anyray-connect 0.11.142 → 0.11.145
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 +209 -209
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`),await fe(o,e),await
|
|
4
|
-
`,{mode:384})}catch(a){throw await
|
|
5
|
-
`,{mode:384}),await Ou(r,384);try{await fe(r,n)}catch(o){throw await
|
|
6
|
-
`)},
|
|
7
|
-
`)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},Xg=async()=>{try{let e=await T();return e.gateway?{origin:new URL(e.gateway).origin,metadata:de({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},nt=async(e="auto")=>e==="profile"?Xg():e==="claude"?Zg():await Zg()??await Xg(),Cc=async(e={})=>{let t=e.readTarget??nt,n=e.loadProfile??T,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a=new Set;try{a.add(new URL(r.gateway).origin)}catch{return"unreadable"}return tt(r)&&r.fallbackPort&&a.add(`http://${pt}:${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},Ac=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),lO);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 xn=()=>Sc(vc(),".claude","settings.json"),is=()=>Sc(vc(),".claude.json"),dO=gc,or="anyray",uO=()=>({type:"stdio",...je("claude"),alwaysLoad:!0}),Br=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pO=e=>{if("mcpServers"in e&&!Br(e.mcpServers))return"conflict";let t=Br(e.mcpServers)?{...e.mcpServers}:{},n=t[or];return n!==void 0&&!Jt(n,"claude")?"conflict":(t[or]=uO(),e.mcpServers=t,"installed")},Jg=e=>{let t=e.mcpServers;return!t||!(or in t)||!Jt(t[or],"claude")?!1:(delete t[or],Object.keys(t).length===0&&delete e.mcpServers,!0)},fO=e=>{hc(e,"PostToolUse",Ze,En(Tt(Ze),{matcher:"*"})),hc(e,"UserPromptSubmit",tr,En(Tt(tr)))},hO=e=>{hc(e,"SessionStart",nr,En(Tt(nr),{async:!0}))},Qg=e=>Mo(e,"SessionStart",nr),qg=e=>{let t=Mo(e,"PostToolUse",Ze),n=Mo(e,"UserPromptSubmit",tr),r=Qg(e);return t||n||r},mO="print-key",yO=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Re()),Hr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===mO&&yO(t)},gO=async(e,t)=>{let n=(await Nr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of dO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},wO=e=>typeof e.apiKeyHelper=="string"&&!Hr(e),ew=async e=>{let t=await Zu(),n=async()=>t,[r,o,a]=await Promise.all([Ug({userSettings:e,readManaged:n}),jg({userSettings:e,readManaged:n}).catch(()=>[]),Gg({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},zg=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await ew(e),o=Yu(t),a=Yg(n);return{routingOverrides:[...t.map(i=>({problem:Vu(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:Vg(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},ar={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=Sc(vc(),".claude"),t=await R(e);return{installed:t,detail:t?xn():"no ~/.claude directory"}},async apply(e,t){let n=xn(),r=await M(n),o=Dg(r),a=await Ng(e.origin,e.clientKey,o),s=$g(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=un(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await ew(r),h=f.filter(x=>!x.repairable),m=f.filter(x=>x.repairable),w=[...h.map(x=>`WARNING: ${Vu(x)}.`),...h.length?[Yu(h)]:[],...p.state==="fine"?[]:[`WARNING: ${bc(p)}.`,kc(p)],...m.map(x=>Bg(x)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let g=r.env??{};r.env={...g,...i};let y=r.env;for(let{name:x}of In)m.some(P=>P.name===x)?y[x]="":y[x]===""&&(process.env[x]??"").trim()===""&&delete y[x];if(u||delete y.ANTHROPIC_CUSTOM_HEADERS,c&&(g.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete y.ANTHROPIC_AUTH_TOKEN),l)for(let x of Lg)delete y[x];let b=!!e.clientKey,A=ce(),S=wO(r);!c&&!l&&b&&A&&!S?(r.apiKeyHelper=Tg(),delete y.ANTHROPIC_AUTH_TOKEN,w.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):Hr(r)&&delete r.apiKeyHelper,S&&!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?(hO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):Qg(r),ce()?(fO(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.")):(qg(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 X(n,r);let I=[n],C=is();try{let x=await M(C),P=!1;ce()?pO(x)==="conflict"?w.push(`MCP name conflict in ${C}: mcpServers.${or} 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=Jg(x),P&&(await X(C,x),I.push(C))}catch(x){w.push(`Could not register the Anyray MCP server in ${C} (${x instanceof Error?x.message:String(x)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:I}},skillsDir(){return Sc(vc(),".claude","skills")},async watchPaths(){return[xn(),is()]},async pointsAt(e){let t=xn();if(!await R(t))return!1;try{let o=(await M(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await M(xn()).catch(()=>({}));return zg(e)},async routingOverrides(){let e=await M(xn()).catch(()=>({}));return(await zg(e)).routingOverrides},async mcpStatus(){let e=is();if(!await R(e))return{registered:!1,command:null};try{let r=(await M(e)).mcpServers?.[or];return!r||!Jt(r,"claude")?{registered:!1,command:null}:{registered:!0,command:typeof r.command=="string"?r.command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=xn();if(!await R(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!Br(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>er(c,Ze))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>er(c,Ze)&&Br(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Br(l)&&mc(l.command,Ze))))}}catch{e="unreadable"}let r,o=!0,a=is();if(!await R(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!Br(s.mcpServers))r="unreadable";else{let i=s.mcpServers[or];r=i===void 0?"missing":Jt(i,"claude")?"owned":"foreign",r==="owned"&&(o=yc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Fr()?"owned":"missing",beacon_target:await Cc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await M(xn()),t=Br(e.env)?e.env:{},n=typeof t.ANTHROPIC_CUSTOM_HEADERS=="string"?t.ANTHROPIC_CUSTOM_HEADERS:"";if(/^x-anyray-custom-host:/m.test(n))return["byo"];if(/^x-anyray-auth-mode:\s*passthrough$/m.test(n))return["subscription"];if(typeof t.ANTHROPIC_AUTH_TOKEN=="string"||typeof e.apiKeyHelper=="string")return["api_key"]}catch{}return["unknown"]},async revert(e){let t=xn();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await M(t),r=n.env,o=qg(n),a=Hr(n);a&&delete n.apiKeyHelper;let s=r?await gO(t,r):[],i=Mg(typeof n.model=="string"?n.model:void 0,(await Nr(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await X(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=is();try{let d=await M(l);Jg(d)&&(await X(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await ae(t),{status:"reverted",messages:c,changedFiles:[t]}}};var we="0.11.142";var pn=e=>{let{command:t,args:n}=dn([e]);return{command:t,args:n}},sr=()=>Mr();import{homedir as tw,userInfo as bO}from"node:os";var cs=()=>{try{return tw()!==bO().homedir}catch{return!1}},Fo=e=>[`Skipped ${e} \u2014 HOME (${tw()}) is not this account's home directory.`,"The OS registers a per-user service against the account, not against HOME, so","one installed from here would point at a path the real login session cannot use."];var ht=(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,Wr=(e=process.env)=>ht(e)!==null,kt=e=>e==="codespaces"||e==="devcontainer",ir=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var zu="__anyray-fallback-proxy",us="ai.anyray.connect.fallback",cr="anyray-fallback",sw=us,ke=8785,ps=60,Qu="x-anyray-local",ep=()=>pn(zu),nw=sr,Ic=async(e=ke)=>{let t=n=>new Promise(r=>{let o=AO();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)}},Wo=()=>Ho(ds(),"Library","LaunchAgents",`${sw}.plist`),fs=()=>Ho(ds(),".anyray","logs"),ls=()=>Ho(fs(),"connect-daemon.log"),iw=async(e,t=1048576)=>{await ow(e).then(r=>r.size,()=>0)>t&&await CO(e).catch(()=>{})},Ko=()=>Ho(ds(),".config","systemd","user",`${cr}.service`),Xu=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),hs=(e=ep())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${Xu(o)}</string>`).join(`
|
|
2
|
+
var cR="http://localhost:8787",Xa="anyray-placeholder",Ie=e=>{let t=e?.trim();return!!(t&&/^ark_[A-Za-z0-9_-]{20,512}$/.test(t))},Ye=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},ku=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,lR=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),rg=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!lR.has(n)}catch{return!1}},dn=e=>{let t=Ye(e||process.env.ANYRAY_GATEWAY_URL||cR),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},pt="127.0.0.1",En=(e,t)=>{let n=`http://${pt}:${t}`;return{...e,anthropicBaseUrl:n,openaiBaseUrl:`${n}/v1`,viaLocalProxy:!0}},ye=(e={})=>{let t=dn(e.origin),n=e.placeholderKey?.trim()||Xa,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:ku(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:ku(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:ku(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 ds,platform as Wo}from"node:os";import{join as Ho}from"node:path";import{mkdir as Xu,readFile as iw,rename as xO,stat as cw,truncate as RO,writeFile as lw,rm as Bo}from"node:fs/promises";import{spawnSync as hn}from"node:child_process";import{createServer as OO}from"node:net";import{homedir as vc}from"node:os";import{join as Sc}from"node:path";import{access as hR,chmod as mR,mkdir as Cu,open as Iu,readFile as dg,rm as Jt,stat as ag,utimes as yR}from"node:fs/promises";import{createHash as gR,randomUUID as ug}from"node:crypto";import{dirname as xu,join as wR}from"node:path";import{isDeepStrictEqual as Po}from"node:util";import{randomUUID as dR}from"node:crypto";import{lstat as uR,rename as rc,rm as pR}from"node:fs/promises";import{platform as og}from"node:os";var fR=e=>e?.code==="ENOENT",za=async(e,t=og())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},fe=async(e,t,n=og())=>{if(n!=="win32"){await rc(e,t);return}let r=`${t}.anyray-old-${process.pid}-${dR()}`,o=!1;try{let a=await uR(t);if(!a.isFile()&&!a.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await rc(t,r),o=!0}catch(a){if(!fR(a))throw a}try{await rc(e,t)}catch(a){if(o)try{await rc(r,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${r}`)}throw a}o&&await pR(r,{force:!0})};var qa=e=>`${e}.anyray-bak`,pg=async e=>{let t;try{t=await Iu(xu(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},sg=async(e,t)=>{let n,r;try{n=await Iu(e,"wx",384),await n.writeFile(t,"utf-8"),await za(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Jt(e,{force:!0}).catch(()=>{}),r;await pg(e)},bR=async e=>{let t;try{t=await Iu(e,"r"),await za(t)}finally{await t?.close().catch(()=>{})}await pg(e)},R=async e=>{try{return await hR(e),!0}catch{return!1}},M=async e=>{if(!await R(e))return{};let t=await dg(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 Cu(xu(e),{recursive:!0,mode:448});let r=qa(e);if(n.backup!==!1&&await R(e)&&!await R(r))try{await sg(r,await dg(e,"utf-8"))}catch(a){if(a.code!=="EEXIST")throw a}let o=`${e}.anyray-tmp-${process.pid}-${ug()}`;try{await sg(o,`${JSON.stringify(t,null,2)}
|
|
3
|
+
`),await fe(o,e),await mR(e,384),await bR(e)}finally{await Jt(o,{force:!0}).catch(()=>{})}},fg=1,ig=3e4,kR=5e3,CR=/^[a-f0-9]{64}$/,hg=e=>`${e}.pending`,AR=e=>`${e}.lock`,Au=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=>Au(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Au(t[n])}`).join(",")}}`},vu=(e,t)=>({exists:e,sha256:gR("sha256").update(Au(t)).digest("hex")}),Su=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),cg=e=>Su(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&CR.test(e.sha256),vR=e=>Su(e)&&e.transactionVersion===fg&&cg(e.before)&&cg(e.after)&&Su(e.journal),Eu=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,Lo=async(e,t)=>{try{return await M(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},SR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},mg=async e=>{let t=AR(e),n=wR(t,"owner.json");await Cu(xu(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=ug();try{await Cu(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await Lo(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 ag(n)).mtimeMs;i=!SR(c.pid)||l>ig}catch{try{i=Date.now()-(await ag(t)).mtimeMs>ig}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Jt(t,{recursive:!0,force:!0});continue}try{await J(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Jt(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await Lo(n,"ownership journal")).nonce!==o)return;let i=new Date;await yR(n,i,i)}catch{}})()},kR);return a.unref(),async()=>{clearInterval(a);try{(await Lo(n,"ownership journal")).nonce===o&&await Jt(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},yg=async e=>{let t=await R(e),n={};if(t)try{n=await M(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:vu(t,n)}},gg=async(e,t)=>{let n=hg(t);if(!await R(n))return;let r=await Lo(n,"prepared ownership transaction");if(!vR(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await yg(e),a=await R(t),s=await R(qa(e)),i=Eu(o.fingerprint,r.before),c=Eu(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 Jt(n,{force:!0});return}if(i){await Jt(n,{force:!0}),a||await ae(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},oc=async(e,t,n)=>{let r=await mg(t);try{return await gg(e,t),await n()}finally{await r()}},lg=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 Lo(e,"ownership journal");if(!(n&&Po(a,t))){if(!Po(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await J(e,t,{backup:!1}):await Jt(e,{force:!0})}},ac=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await mg(a);try{await gg(n,a);let l=await yg(n),d=vu(i,r),u=await R(a),f=u?await Lo(a,"ownership journal"):void 0,p=f&&typeof f.fileExisted=="boolean"?{...s,fileExisted:f.fileExisted}:s;if(!Eu(l.fingerprint,d)){if(Po(l.value,o)&&f&&Po(f,p))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&Po(l.value,o)&&f&&Po(f,p))return;let h=await R(qa(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=hg(a),w={transactionVersion:fg,before:l.fingerprint,after:vu(!0,o),journal:p};await J(m,w,{backup:!1});try{await J(n,o,f?{backup:!1}:{}),await(t.writeJournal??J)(a,p,{backup:!1}),await Jt(m,{force:!0})}catch(g){try{await lg(n,l.value,l.exists,o)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed and config rollback was incomplete")}try{await lg(a,f??{},u,p),await Jt(m,{force:!0}),!h&&!f&&await ae(n)}catch(y){throw new AggregateError([g,y],"ownership journal publication failed after config rollback")}throw g}}finally{await c()}},Mr=async e=>{try{return await M(qa(e))}catch{return{}}},ae=async e=>{await Jt(qa(e),{force:!0}).catch(()=>{})};import{access as XR}from"node:fs/promises";import{spawnSync as NR}from"node:child_process";import{readFileSync as $R,realpathSync as ts,statSync as xg}from"node:fs";import{access as MR,cp as Rg,mkdir as Eg,readdir as FR,readFile as $u,realpath as UR,rename as BR,rm as Du,writeFile as WR}from"node:fs/promises";import{tmpdir as HR}from"node:os";import{basename as No,dirname as Ke,join as xe,resolve as KR}from"node:path";import{writeFile as sc,readFile as Qa,chmod as Ou,stat as _u,mkdir as bg,rm as Fr,access as ER}from"node:fs/promises";import{randomUUID as IR}from"node:crypto";import{homedir as kg}from"node:os";import{join as In}from"node:path";var ee=()=>In(kg(),".anyray"),Do=async()=>{let e=ee();try{if((await _u(e)).isDirectory())return In(e,"connect.json")}catch{}return e},Tu=()=>In(ee(),"dev-key.pem"),bt=async()=>{let e=ee(),t;try{if(!(await _u(e)).isDirectory())t=await Qa(e,"utf-8").catch(()=>{}),await Fr(e,{force:!0});else return}catch{}if(await bg(e,{recursive:!0,mode:448}),t!==void 0){let n=In(e,"connect.json");await sc(n,t,{mode:384}),await Ou(n,384)}},ic=async e=>{await bt();let t=Tu();await sc(t,e,{mode:384}),await Ou(t,384)},Ue=async()=>{try{let e=await Qa(Tu(),"utf-8");return e.trim()?e:void 0}catch{return}},es=async()=>{await Fr(Tu(),{force:!0}).catch(()=>{})},xR=e=>{let{fallbackEnabled:t,fallbackGatewayTimeoutMs:n,fallbackBreaker:r,...o}=e,a=o;return t===!0&&(a.keyRefreshEnabled=!0),a},P=async()=>{try{let e=await Qa(await Do(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:xR(t)}catch{return{}}},RR=0,OR=3e4,_R=5e3,TR=25,PR=()=>In(kg(),".anyray-connect-profile.lock"),LR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},DR=async e=>{try{let t=JSON.parse(await Qa(In(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!LR(t.pid)}catch{}return Date.now()-(await _u(e)).mtimeMs>OR},Cg=async()=>{let e=PR(),t=In(e,"owner.json"),n=Date.now()+_R;for(;;){let r=IR();try{await bg(e,{mode:448});try{await sc(t,`${JSON.stringify({pid:process.pid,nonce:r})}
|
|
4
|
+
`,{mode:384})}catch(a){throw await Fr(e,{recursive:!0,force:!0}).catch(()=>{}),a}return async()=>{try{JSON.parse(await Qa(t,"utf-8")).nonce===r&&await Fr(e,{recursive:!0,force:!0})}catch{}}}catch(a){if(a.code!=="EEXIST")throw a}if(!(await DR(e).catch(()=>!1)&&await Fr(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,TR))}}},Ag=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Do(),r=`${n}.${process.pid}.${RR++}.tmp`;await sc(r,`${JSON.stringify(t,null,2)}
|
|
5
|
+
`,{mode:384}),await Ou(r,384);try{await fe(r,n)}catch(o){throw await Fr(r,{force:!0}).catch(()=>{}),o}},re=async e=>{let t=await Cg();try{await Ag(e)}finally{await t()}},vg=async e=>{let t=await Cg();try{let n=await P(),{next:r,result:o}=e(n);return r&&await Ag(r),o}finally{await t()}},Ru=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],wg="ssoLink",Pu=async()=>{let e=await P();return Ru.some(t=>e[t]!==void 0)?!0:await Ue()!==void 0},cc=async()=>{let e=await P(),t=Ru.some(a=>e[a]!==void 0),n=e[wg]!==void 0,r=e.byoUpstream!==void 0,o=await Ue()!==void 0;if(!t&&!n&&!r&&!o)return!1;if(t||n||r){let a={...e};for(let s of Ru)delete a[s];delete a[wg],delete a.byoUpstream,delete a.anyrayFleetManaged,await re(a)}if(await es(),await Ue())throw new Error(`could not remove the dev key from ${ee()}`);return!0},Sg=["fallback-bundle.enc","fallback-key","fallback-usage-queue.jsonl"],lc=async()=>{let e=ee();for(let t of Sg)await Fr(In(e,t),{force:!0}).catch(()=>{})},Lu=async()=>{let e=ee(),t=[];for(let n of Sg){let r=In(e,n);try{await ER(r),t.push(r)}catch{}}return t},Qn=async(e,t,n=!1)=>{let r=await P(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=r.offboardedAt;for(let h of e){let m=h.status==="configured"||h.status==="queued";!t&&m&&(o.add(h.id),a.delete(h.id),s=void 0),t&&(h.status==="reverted"||h.status==="queued")&&(o.delete(h.id),a.add(h.id))}n&&o.clear();let i=[...o].sort(),c=[...r.managedTools??[]].sort(),l=[...a].sort(),d=[...r.revertedTools??[]].sort();if(i.length===c.length&&i.every((h,m)=>h===c[m])&&r.revertedTools!=null&&l.length===d.length&&l.every((h,m)=>h===d[m])&&s===r.offboardedAt)return;let{offboardedAt:f,...p}=r;await re({...p,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},dc=async(e=new Date().toISOString())=>{await re({...await P(),offboardedAt:e})};var $o=e=>KR(e).replace(/\\/g,"/").toLowerCase(),Nu=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",ns=e=>`${e}.source`,Og=e=>/(^|\/)_npx(\/|$)/.test($o(e)),Mu=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test($o(e)),Fu=e=>{let t=$o(e),n=[HR(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map($o);return Og(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},ft=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),rs=e=>/[\\/](node|node\.exe)$/i.test(e),er=(e=ft())=>rs(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,Ig=e=>{try{let t=xg(e);return t.isFile()?t.size:void 0}catch{return}},Uu=e=>{let t=Ke(e);if(No(t)==="versions")return t;let n=Ke(t);return No(n)==="versions"?n:void 0},pc=(e,t)=>t!==void 0&&(Ke(e)===t||Ke(Ke(e))===t),GR=e=>{let t=Uu(e);if(!t)return;let n=xe(Ke(t),"bin",Nu());try{let r=ts(n);return r===ts(e)||pc(r,ts(t))?n:void 0}catch{return}},Mo=(e=ee(),t=process.platform)=>{let n=xe(e,"bin",Nu(t));try{let r=ts(n),o=ts(xe(e,"versions"));if(pc(r,o))return n;if(t==="win32"){let a=$R(ns(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=Ig(xe(o,a,Nu(t)))??Ig(xe(o,a));if(s!==void 0&&s===xg(n).size)return n}}catch{return}},Ur=(e=ft())=>{let t=er(e),n=Mu(t)||Wu(t)?Mo():void 0;return GR(e.execPath)??n??t},_g=(e=ft())=>Ur(e)!==er(e),un=(e,t=ft())=>{let n=Ur(t);return rs(t.execPath)&&t.scriptPath!==void 0&&n===er(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},Tg=(e=ft())=>{let t=Ur(e);return!rs(e.execPath)&&!Fu(t)?Ke(t):xe(ee(),"bin")},uc=async e=>{try{return await MR(e),!0}catch{return!1}},jR=async e=>{let t=await UR(e),n=Ke(t),r=Ke(n),o=xe(r,"package.json"),a=await $u(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 uc(xe(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},VR=async(e,t)=>{let n=t;for(;;){let r=xe(n,"node_modules",e);if(await uc(xe(r,"package.json")))return r;let o=Ke(n);if(o===n)return;n=o}},YR=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await $u(xe(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await VR(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await Rg(i,xe(t,s),{recursive:!0}),r.push(i)}}},ZR=async(e=ft())=>{let t=Mo();if(t)return{command:t,args:[],entryPath:t};if(!rs(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await jR(e.scriptPath);await bt();let r=xe(ee(),"bin",`connect-runtime-${n.version}`),o=xe(r,"dist","index.js");if(!await uc(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await Du(a,{recursive:!0,force:!0}),await Eg(a,{recursive:!0,mode:448});try{await Rg(n.dist,xe(a,"dist"),{recursive:!0}),await WR(xe(a,"package.json"),await $u(n.packageJson),{mode:384}),await YR(n.root,xe(a,"node_modules")),await Eg(Ke(r),{recursive:!0,mode:448});try{await BR(a,r)}catch(s){if(!await uc(o))throw s}}finally{await Du(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Bu=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,JR=e=>{let t=No(Ke(Ke(e)));return Bu.test(t)?t:void 0},Wu=(e,t=ee())=>{let n=Ke(Ke(e));return $o(Ke(n))===$o(xe(t,"bin"))&&Bu.test(No(n))&&No(Ke(e))==="dist"&&No(e)==="index.js"},fc=async(e=ft())=>{let t=xe(ee(),"bin"),n=JR(er(e)),r=[];for(let o of await FR(t).catch(()=>[])){if(!Bu.test(o)||o===n)continue;let a=xe(t,o);await Du(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},Pg=async(e,t=ft())=>{let n=er(t);if(!rs(t.execPath)||!Og(n)||Mo())return;let r=await ZR(t),o=NR(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var Hu=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,os=(e,t)=>[e,...t].map(Hu).join(" "),xn=(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}:{}}]}),tr=(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))},hc=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!tr(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},Fo=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!tr(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)},Ku=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=>!tr(s,"__anyray-"));a.length!==o.length&&(n=!0,a.length?t[r]=a:delete t[r])}return n&&Object.keys(t).length===0&&delete e.hooks,n};var Ze="__anyray-hook",Lg="__anyray-codex-hook",nr="__anyray-prompt-hook",Dg="__anyray-shell-pretool",Gu="__anyray-shell-run",Ng="__anyray-read-pretool",rr="__anyray-refresh",as=(e,t=[])=>{let{command:n,args:r}=un([e,...t]);return{command:n,args:r}},Pt=(e,t=[])=>{let n=as(e,t);return[n.command,...n.args].map(Hu).join(" ")},mc=(e,t,n=[])=>typeof e=="string"&&e.trim()===Pt(t,n),$g=()=>Pt("print-key"),Re=()=>Ur(),Ge=Fu,ce=()=>!Ge(Re()),Br=async()=>{if(!ce())return!1;try{return await XR(Re()),!0}catch{return!1}},or="__anyray-mcp-server",je=e=>as(or,[e]),zR=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),yc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=je(t);return n.command===r.command&&zR(n.args,r.args)},Xt=(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)===or&&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 Wr=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Mg=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],gc=[...Wr,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],qR=(e,t,n,r)=>{let o=[];return(t||r)&&(o.push("x-anyray-provider: anthropic"),o.push("x-anyray-auth-mode: passthrough"),r&&o.push(`x-anyray-custom-host: ${r}`),n&&o.push(`x-anyray-api-key: ${n}`)),e&&o.push(`x-anyray-metadata: ${e}`),o.join(`
|
|
6
|
+
`)},pn=(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=qR(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 ju}from"zod";var QR=5e3,eO=1e3,tO=1e8,nO=ju.object({modelContext:ju.object({contextTokens:ju.number().int().min(eO).max(tO)}).optional()}),Fg=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},Ug=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??QR,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=nO.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var rO=1e6,ss="[1m]",oO=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},Bg=(e,t)=>!e||t===void 0?{}:oO(e)?{envTokens:t}:t<rO?{}:e.toLowerCase().endsWith(ss)?{}:{model:`${e}${ss}`},Wg=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(ss))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(ss))return e.slice(0,-ss.length)};import{platform as aO}from"node:os";var Lt=(e=aO())=>{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 Rn=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],wc=e=>typeof e=="string"&&e.trim()!=="",sO=(e,t)=>typeof e[t]=="string"&&!wc(e[t]),Hg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},iO=()=>M(Lt()).catch(()=>({})),Kg=async(e={})=>{let t=e.env??process.env,n=Hg(e.userSettings??{}),r=Hg(await(e.readManaged??iO)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of Rn)wc(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Lt()})`,repairable:!1}):wc(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!sO(n,a)&&wc(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},Vu=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`,Yu=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.",Gg=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 cO=Rn.map(e=>e.name),lO=gc.filter(e=>!cO.includes(e)),jg=e=>typeof e=="string"&&e.trim()!=="",Vg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},dO=(e,t,n)=>{if(typeof e!="string"||typeof t!="string")return!1;let r=o=>n?o.trim().replace(/\/+$/,""):o.trim();return r(e)===r(t)},uO=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},Zu=()=>M(Lt()).catch(()=>({})),Yg=Zu,pO=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=>tr(r,Ze))},Zg=async(e={})=>{let t=await(e.readManaged??Yg)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!pO(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},bc=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",kc=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.",Jg=async(e={})=>{let t=Vg(e.userSettings??{}),n=Vg(await(e.readManaged??Yg)().catch(()=>({}))),r=[];for(let o of lO){if(!jg(n[o])||!jg(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(dO(n[o],t[o],a))continue;let s=a?uO(n[o]):void 0;r.push({name:o,source:`managed settings (${Lt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},Xg=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`,zg=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 fO}from"node:os";import{join as hO}from"node:path";import{readFile as mO}from"node:fs/promises";var tt=e=>!!e.keyRefreshEnabled;var yO=400,qg=async()=>{try{let e=hO(fO(),".claude","settings.json"),n=JSON.parse(await mO(e,"utf-8"))?.env,r=n?.ANTHROPIC_BASE_URL;if(!r)return null;let o=new URL(r).origin,a=n?.ANTHROPIC_CUSTOM_HEADERS??"",s=l=>{for(let d of a.split(`
|
|
7
|
+
`)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},Qg=async()=>{try{let e=await P();return e.gateway?{origin:new URL(e.gateway).origin,metadata:de({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},nt=async(e="auto")=>e==="profile"?Qg():e==="claude"?qg():await qg()??await Qg(),Cc=async(e={})=>{let t=e.readTarget??nt,n=e.loadProfile??P,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a=new Set;try{a.add(new URL(r.gateway).origin)}catch{return"unreadable"}return tt(r)&&r.fallbackPort&&a.add(`http://${pt}:${r.fallbackPort}`),a.has(o.origin)?"owned":"foreign"},zt=e=>{let t={"content-type":"application/json"};return e.metadata&&(t["x-anyray-metadata"]=e.metadata),e.apiKey&&(t["x-anyray-api-key"]=e.apiKey),t},Ac=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),yO);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:zt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var On=()=>Sc(vc(),".claude","settings.json"),is=()=>Sc(vc(),".claude.json"),gO=gc,ar="anyray",wO=()=>({type:"stdio",...je("claude"),alwaysLoad:!0}),Hr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bO=e=>{if("mcpServers"in e&&!Hr(e.mcpServers))return"conflict";let t=Hr(e.mcpServers)?{...e.mcpServers}:{},n=t[ar];return n!==void 0&&!Xt(n,"claude")?"conflict":(t[ar]=wO(),e.mcpServers=t,"installed")},ew=e=>{let t=e.mcpServers;return!t||!(ar in t)||!Xt(t[ar],"claude")?!1:(delete t[ar],Object.keys(t).length===0&&delete e.mcpServers,!0)},kO=e=>{hc(e,"PostToolUse",Ze,xn(Pt(Ze),{matcher:"*"})),hc(e,"UserPromptSubmit",nr,xn(Pt(nr)))},CO=e=>{hc(e,"SessionStart",rr,xn(Pt(rr),{async:!0}))},rw=e=>Fo(e,"SessionStart",rr),tw=e=>{let t=Fo(e,"PostToolUse",Ze),n=Fo(e,"UserPromptSubmit",nr),r=rw(e);return t||n||r},AO="print-key",vO=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Re()),Kr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===AO&&vO(t)},SO=async(e,t)=>{let n=(await Mr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of gO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},EO=e=>typeof e.apiKeyHelper=="string"&&!Kr(e),ow=async e=>{let t=await Zu(),n=async()=>t,[r,o,a]=await Promise.all([Kg({userSettings:e,readManaged:n}),Jg({userSettings:e,readManaged:n}).catch(()=>[]),Zg({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},nw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await ow(e),o=Yu(t),a=zg(n);return{routingOverrides:[...t.map(i=>({problem:Vu(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:Xg(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},sr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=Sc(vc(),".claude"),t=await R(e);return{installed:t,detail:t?On():"no ~/.claude directory"}},async apply(e,t){let n=On(),r=await M(n),o=Fg(r),a=await Ug(e.origin,e.clientKey,o),s=Bg(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=pn(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:p}=await ow(r),h=f.filter(x=>!x.repairable),m=f.filter(x=>x.repairable),w=[...h.map(x=>`WARNING: ${Vu(x)}.`),...h.length?[Yu(h)]:[],...p.state==="fine"?[]:[`WARNING: ${bc(p)}.`,kc(p)],...m.map(x=>Gg(x)),`${n} \u2192 env.ANTHROPIC_BASE_URL = ${e.anthropicBaseUrl}`,l?`BYO-upstream mode: your personal upstream key passes through the gateway to ${e.byoUpstream.url} (never the org key).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:c?`Subscription mode: Claude Code keeps your seat sign-in; its OAuth token passes through the gateway (never stored).${e.clientKey?" Your personal gateway key rides x-anyray-api-key.":""}`:e.clientKey?"Auth: personal gateway key (not shown here; see below for where it lives)":"Auth: placeholder token (gateway swaps in the server-held key)",`Attribution: ${d??"(none)"}`,...l?[]:["Restored on-demand MCP tool loading (env.ENABLE_TOOL_SEARCH) that Claude Code otherwise disables behind a non-first-party gateway. Deferred servers stay out of context until used; the first-party AnyRay retrieval server stays always loaded so capability is visible per request."],...s.envTokens!==void 0?[`Context window: env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = ${s.envTokens} \u2014 your model's real window, so Claude Code stops budgeting the 200k it assumes behind any custom base URL.`]:[],...s.model!==void 0?[`Context window: model = ${s.model} \u2014 same model, its long-context variant. Claude Code ignores CLAUDE_CODE_MAX_CONTEXT_TOKENS for claude-* ids, so the [1m] alias is what actually gets you your ${a} window back instead of the 200k it assumes behind any custom base URL. A --model flag on your launch command, or picking a model in-app, overrides this \u2014 add [1m] there too (quote it in zsh).`]:[],"Claude Code settings.json routing covers the CLI and VS Code extension. Claude Desktop is separate: its verified macOS automatic setup supports either the Claude Code subscription-backed Gateway lane or API billing; other Desktop lanes fail closed or use the documented API setup.","Restart Claude Code (or open a new session) to pick up the change."];if(t.dryRun)return{status:"configured",messages:w};s.model!==void 0&&(r.model=s.model);let g=r.env??{};r.env={...g,...i};let y=r.env;for(let{name:x}of Rn)m.some(T=>T.name===x)?y[x]="":y[x]===""&&(process.env[x]??"").trim()===""&&delete y[x];if(u||delete y.ANTHROPIC_CUSTOM_HEADERS,c&&(g.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete y.ANTHROPIC_AUTH_TOKEN),l)for(let x of Mg)delete y[x];let b=!!e.clientKey,A=ce(),v=EO(r);!c&&!l&&b&&A&&!v?(r.apiKeyHelper=$g(),delete y.ANTHROPIC_AUTH_TOKEN,w.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):Kr(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?(CO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):rw(r),ce()?(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.")):(tw(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await J(n,r);let I=[n],C=is();try{let x=await M(C),T=!1;ce()?bO(x)==="conflict"?w.push(`MCP name conflict in ${C}: mcpServers.${ar} is not owned by Anyray Connect, so it was left untouched.`):(T=!0,w.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context \u2014 always loaded so retrieval capability is visible on every request.")):T=ew(x),T&&(await J(C,x),I.push(C))}catch(x){w.push(`Could not register the Anyray MCP server in ${C} (${x instanceof Error?x.message:String(x)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:I}},skillsDir(){return Sc(vc(),".claude","skills")},async watchPaths(){return[On(),is()]},async pointsAt(e){let t=On();if(!await R(t))return!1;try{let o=(await M(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await M(On()).catch(()=>({}));return nw(e)},async routingOverrides(){let e=await M(On()).catch(()=>({}));return(await nw(e)).routingOverrides},async mcpStatus(){let e=is();if(!await R(e))return{registered:!1,command:null};try{let r=(await M(e)).mcpServers?.[ar];return!r||!Xt(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=On();if(!await R(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!Hr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>tr(c,Ze))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>tr(c,Ze)&&Hr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Hr(l)&&mc(l.command,Ze))))}}catch{e="unreadable"}let r,o=!0,a=is();if(!await R(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!Hr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[ar];r=i===void 0?"missing":Xt(i,"claude")?"owned":"foreign",r==="owned"&&(o=yc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Br()?"owned":"missing",beacon_target:await Cc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await M(On()),t=Hr(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=On();if(!await R(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await M(t),r=n.env,o=tw(n),a=Kr(n);a&&delete n.apiKeyHelper;let s=r?await SO(t,r):[],i=Wg(typeof n.model=="string"?n.model:void 0,(await Mr(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=is();try{let d=await M(l);ew(d)&&(await J(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await ae(t),{status:"reverted",messages:c,changedFiles:[t]}}};var we="0.11.145";var fn=e=>{let{command:t,args:n}=un([e]);return{command:t,args:n}},ir=()=>Ur();import{homedir as aw,userInfo as IO}from"node:os";var cs=()=>{try{return aw()!==IO().homedir}catch{return!1}},Uo=e=>[`Skipped ${e} \u2014 HOME (${aw()}) 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 ht=(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,Gr=(e=process.env)=>ht(e)!==null,kt=e=>e==="codespaces"||e==="devcontainer",cr=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var qu="__anyray-fallback-proxy",us="ai.anyray.connect.fallback",lr="anyray-fallback",dw=us,ke=8785,ps=60,Qu="x-anyray-local",ep=()=>fn(qu),sw=ir,Ic=async(e=ke)=>{let t=n=>new Promise(r=>{let o=OO();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)}},Ko=()=>Ho(ds(),"Library","LaunchAgents",`${dw}.plist`),fs=()=>Ho(ds(),".anyray","logs"),ls=()=>Ho(fs(),"connect-daemon.log"),uw=async(e,t=1048576)=>{await cw(e).then(r=>r.size,()=>0)>t&&await RO(e).catch(()=>{})},Go=()=>Ho(ds(),".config","systemd","user",`${lr}.service`),Ju=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),hs=(e=ep())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${Ju(o)}</string>`).join(`
|
|
8
8
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
9
9
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
10
10
|
<plist version="1.0">
|
|
11
11
|
<dict>
|
|
12
|
-
<key>Label</key><string>${
|
|
12
|
+
<key>Label</key><string>${dw}</string>
|
|
13
13
|
<key>ProgramArguments</key>
|
|
14
14
|
<array>
|
|
15
15
|
${r}
|
|
@@ -18,8 +18,8 @@ ${r}
|
|
|
18
18
|
<key>KeepAlive</key><true/>
|
|
19
19
|
<key>ProcessType</key><string>Background</string>
|
|
20
20
|
<key>ExitTimeOut</key><integer>${ps}</integer>
|
|
21
|
-
<key>StandardOutPath</key><string>${
|
|
22
|
-
<key>StandardErrorPath</key><string>${
|
|
21
|
+
<key>StandardOutPath</key><string>${Ju(ls())}</string>
|
|
22
|
+
<key>StandardErrorPath</key><string>${Ju(ls())}</string>
|
|
23
23
|
</dict>
|
|
24
24
|
</plist>
|
|
25
25
|
`},ms=(e=ep())=>{let{command:t,args:n}=e;return`[Unit]
|
|
@@ -34,13 +34,13 @@ TimeoutStopSec=${ps}
|
|
|
34
34
|
|
|
35
35
|
[Install]
|
|
36
36
|
WantedBy=default.target
|
|
37
|
-
`},Ec=()=>{let{command:e,args:t}=ep();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)."]},
|
|
38
|
-
`,"utf-8")}catch{}},rp=()=>{try{
|
|
37
|
+
`},Ec=()=>{let{command:e,args:t}=ep();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)."]},pw=async()=>{let e=Wo();if(e!=="darwin"&&e!=="linux")return!1;let t=e==="darwin"?Ko():Go();try{return await cw(t),!0}catch{return!1}},fw=async()=>{let e=Wo();if(e!=="darwin"&&e!=="linux")return!0;let t=e==="darwin"?Ko():Go(),n=e==="darwin"?hs():ms();return await iw(t,"utf-8").catch(()=>null)===n},zu=async e=>{await Xu(Ho(ds(),"Library","LaunchAgents"),{recursive:!0}),await Xu(fs(),{recursive:!0,mode:448}),await lw(e,hs())},hw=async()=>{let e=Wo();return e==="darwin"?(await zu(Ko()),!0):e==="linux"?(await Xu(Ho(ds(),".config","systemd","user"),{recursive:!0}),await lw(Go(),ms()),!0):!1},mw=async()=>hw().catch(()=>!1),_O=async(e,t)=>{let n=Wo();if(n!=="darwin"&&n!=="linux")return!1;let r=n==="darwin"?Ko():Go(),o=n==="darwin"?hs():ms();if(await iw(r,"utf-8").catch(()=>null)!==o)return!1;let s=await be(e);return s?.version!==we?!1:typeof s.remoteOrigin=="string"&&Ye(s.remoteOrigin)===Ye(t)},Dt=async e=>{if(Ge(sw()))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 anyray-connect is running from a temporary path (${sw()}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(cs())return{ok:!1,messages:Uo("key-refresh auto-start")};{let n=ht();if(kt(n))return{ok:!1,messages:[`Skipped key-refresh auto-start \u2014 ${cr(n)} has no per-user service manager to supervise the daemon.`]}}if(await _O(e.port,e.remoteOrigin))return{ok:!0,messages:["Key-refresh service already current \u2014 left running."]};let t=Wo();try{if(t==="darwin"){let n=Ko(),r=String(process.getuid?.()??""),o=`${n}.new-${process.pid}`;await Bo(o,{force:!0}).catch(()=>{}),await zu(o),hn("launchctl",["bootout",`gui/${r}`,n]),await Bo(n,{force:!0}).catch(()=>{});try{await xO(o,n)}catch{await zu(n),await Bo(o,{force:!0}).catch(()=>{})}return hn("launchctl",["bootstrap",`gui/${r}`,n]).status===0||hn("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.`,...Ec()]}}if(t==="linux"){let n=Go();return await hw(),hn("systemctl",["--user","daemon-reload"]),hn("systemctl",["--user","enable",`${lr}.service`]),hn("systemctl",["--user","restart",`${lr}.service`]).status!==0?{ok:!1,messages:[`Wrote ${n} but \`systemctl --user restart\` failed.`,...Ec()]}:{ok:!0,messages:[`Installed systemd user unit ${n}.`]}}return{ok:!1,messages:Ec()}}catch(n){return{ok:!1,messages:[`Could not install the key-refresh service: ${n instanceof Error?n.message:String(n)}`,...Ec()]}}},tp=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:{[Qu]:"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},qt=async(e=ke)=>{let t=Wo();await Bo(ls(),{force:!0}).catch(()=>{});let n=[],r=cs();try{if(r)n.push(...Uo("key-refresh service teardown"));else if(t==="darwin"){let o=Ko(),a=String(process.getuid?.()??"");hn("launchctl",["bootout",`gui/${a}`,o]),hn("launchctl",["unload",o]),await Bo(o,{force:!0}),n.push("Removed the launchd key-refresh agent.")}else t==="linux"&&(hn("systemctl",["--user","disable","--now",`${lr}.service`]),await Bo(Go(),{force:!0}),hn("systemctl",["--user","daemon-reload"]),n.push("Removed the systemd key-refresh unit."))}catch{}try{await tp(e)&&n.push("Stopped the running key-refresh proxy daemon.")}catch{}return{ok:!0,messages:n}};import{stat as VZ}from"node:fs/promises";import{readFileSync as TO,rmSync as PO,writeFileSync as LO,mkdirSync as DO}from"node:fs";import{join as NO}from"node:path";var np=()=>NO(ee(),"draining"),yw=e=>{try{DO(ee(),{recursive:!0}),LO(np(),`${Math.floor(e)}
|
|
38
|
+
`,"utf-8")}catch{}},rp=()=>{try{PO(np(),{force:!0})}catch{}},$O=16*6e4,op=(e=Date.now())=>{let t;try{t=TO(np(),"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+$O};import{homedir as cp,platform as lp}from"node:os";import{join as jo}from"node:path";import{mkdir as ap,readFile as MO,rename as FO,writeFile as xc,rm as jr}from"node:fs/promises";import{spawnSync as UO}from"node:child_process";var ip=()=>jo(fs(),"connect-refresh.log"),Oc=1800,ws="ai.anyray.connect.refresh",Vr="anyray-refresh",_c="\\AnyrayConnectKeyRefresh",Tc=ws,bs=Vr,gs=_c,BO=String(Oc/60),dp=(e,t)=>{let n=UO(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},up=()=>jo(cp(),"Library","LaunchAgents",`${Tc}.plist`),pp=()=>jo(cp(),".config","systemd","user"),gw=()=>jo(pp(),`${bs}.service`),Rc=()=>jo(pp(),`${bs}.timer`),sp=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Pc=()=>fn(rr),WO=(e=Pc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${sp(o)}</string>`).join(`
|
|
39
39
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
40
40
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
41
41
|
<plist version="1.0">
|
|
42
42
|
<dict>
|
|
43
|
-
<key>Label</key><string>${
|
|
43
|
+
<key>Label</key><string>${Tc}</string>
|
|
44
44
|
<key>ProgramArguments</key>
|
|
45
45
|
<array>
|
|
46
46
|
${r}
|
|
@@ -53,14 +53,14 @@ ${r}
|
|
|
53
53
|
<key>StandardErrorPath</key><string>${sp(ip())}</string>
|
|
54
54
|
</dict>
|
|
55
55
|
</plist>
|
|
56
|
-
`},
|
|
56
|
+
`},HO=(e=Pc())=>{let{command:t,args:n}=e;return`[Unit]
|
|
57
57
|
Description=Anyray connect gateway key refresh
|
|
58
58
|
After=network-online.target
|
|
59
59
|
|
|
60
60
|
[Service]
|
|
61
61
|
Type=oneshot
|
|
62
62
|
ExecStart=${[t,...n].map(o=>/\s/.test(o)?JSON.stringify(o):o).join(" ")}
|
|
63
|
-
`}
|
|
63
|
+
`},KO=()=>`[Unit]
|
|
64
64
|
Description=Anyray connect gateway key refresh (every ${Oc/60}m)
|
|
65
65
|
|
|
66
66
|
[Timer]
|
|
@@ -70,53 +70,53 @@ Persistent=true
|
|
|
70
70
|
|
|
71
71
|
[Install]
|
|
72
72
|
WantedBy=timers.target
|
|
73
|
-
`,MO=(e=Tc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),ys=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(" ")}`],hw=e=>!e.run&&cs(),FO=async(e,t)=>await _O(up(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Pc]).ok,lr=async(e={})=>{let t=e.os??lp(),n=e.invocation??Tc(),r=e.run??dp,o=e.binaryPath??sr();if(Ge(o))return{ok:!1,messages:[`Skipped auto-refresh scheduling \u2014 anyray-connect is running from a temporary path (${o}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(hw(e))return{ok:!1,messages:Fo("auto-refresh scheduling")};let a=ht(e.env??(e.run?{}:process.env));if(kt(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${ir(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=up(),i=DO(n);if(await FO(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await ap(fs(),{recursive:!0,mode:448}),await ap(Go(cp(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=`${s}.new-${process.pid}`;await Kr(l,{force:!0}).catch(()=>{}),await xc(l,i),r("launchctl",["bootout",`gui/${c}`,s]),await Kr(s,{force:!0}).catch(()=>{});try{await PO(l,s)}catch{await xc(s,i),await Kr(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.`,...ys(n)]}}if(t==="linux")return await ap(pp(),{recursive:!0}),await xc(fw(),NO(n)),await xc(Rc(),$O()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${bs}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${Rc()}).`]}:{ok:!1,messages:[`Wrote ${Rc()} but \`systemctl --user enable --now\` failed.`,...ys(n)]};if(t==="win32"){let s=MO(n);return r("schtasks",["/Create","/TN",gs,"/TR",s,"/SC","MINUTE","/MO",LO,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",gs]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${gs}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...ys(n)]}}return{ok:!1,messages:ys(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...ys(n)]}}},dr=async(e={})=>{await Kr(ip(),{force:!0}).catch(()=>{});let t=e.os??lp(),n=e.run??dp,r=[];if(hw(e))return{ok:!0,messages:Fo("scheduler teardown")};try{if(t==="darwin"){let o=up(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Kr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.")}else t==="linux"?(n("systemctl",["--user","disable","--now",`${bs}.timer`]),await Kr(Rc(),{force:!0}),await Kr(fw(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",gs,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},Lc=async(e=lp(),t=dp)=>e==="win32"?t("schtasks",["/Query","/TN",gs]).ok:e==="darwin"?t("launchctl",["list",Pc]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${bs}.timer`]).ok:!1;import L1 from"node:http";import{spawn as KU}from"node:child_process";import{createHash as GU}from"node:crypto";import{homedir as jU}from"node:os";import{join as xS}from"node:path";import{readFile as VU,writeFile as RS,chmod as YU,stat as ZU,unlink as gS}from"node:fs/promises";import{homedir as Mc,platform as xw}from"node:os";import{join as ot}from"node:path";import{execFile as YO}from"node:child_process";import{readFile as ZO,readdir as XO}from"node:fs/promises";import{homedir as UO,platform as BO}from"node:os";import{join as Dc}from"node:path";var rt=e=>{let t=UO();switch(BO()){case"darwin":return Dc(t,"Library","Application Support",e);case"win32":return Dc(process.env.APPDATA??Dc(t,"AppData","Roaming"),e);default:return Dc(t,".config",e)}};import{readFile as gw}from"node:fs/promises";import{homedir as jr,platform as jo}from"node:os";import{join as Rn,posix as HO,win32 as WO}from"node:path";var ks=["Code","Code - Insiders","VSCodium"],fp="1.121.0",mw=1,KO=121,ww="1.102.0",yw=1,GO=102,jO={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},Nc=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},hp=e=>{let t=Nc(e);return t?t.major!==mw?t.major>mw:t.minor>=KO:!1},bw=e=>{let t=Nc(e);return t?t.major!==yw?t.major>yw:t.minor>=GO:!1},VO=async e=>{if(jo()!=="darwin")return;let t=Rn("/Applications",`${jO[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await gw(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},kw=(e,t=jo(),n=jr(),r=process.env)=>{switch(t){case"darwin":return Rn(n,"Library","Application Support",e);case"win32":return Rn(r.APPDATA??Rn(n,"AppData","Roaming"),e);default:return Rn(n,".config",e)}},mp=(e,t)=>e?t==="win32"?WO.join:HO.join:Rn,Vo=(e,t=!1,n=jo(),r=jr(),o=process.env)=>t?mp(t,n)(r,Cs[e],"data","User"):Rn(kw(e,n,r,o),"User"),Cw=async(e,t=!1,n=jo(),r=jr(),o=process.env)=>{try{let a=mp(t,n)(Vo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await gw(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[]}},Aw=async(e,t=jo(),n=jr(),r=process.env)=>{let a=(await Cw(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},vw=async(e,t=!1,n=jo(),r=jr(),o=process.env)=>{let a=mp(t,n),s=Vo(e,t,n,r,o),i=await Cw(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},$c=async()=>{for(let e of ks)if(await R(kw(e)))return e},Cs={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},Sw=(e,t=jr())=>Rn(t,Cs[e],"extensions"),yp=async(e=jr())=>{for(let t of ks)if(await R(Rn(e,Cs[t])))return t},Ew=async e=>{let t=e??await $c();if(!t)return{status:"unknown"};let n=await VO(t);return n?{variant:t,version:n,status:hp(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var JO=3e3,qO="Claude Code-credentials",zO=["copilot-cli","CopilotCLI"],Rw=e=>new Promise(t=>{try{YO("security",["find-generic-password","-s",e],{timeout:JO},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),QO=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=ot(Mc(),".claude");return!!(await R(ot(e,".oauth_token"))||await R(ot(e,".credentials.json"))||xw()==="darwin"&&await Rw(qO))},e_=async()=>{let e=ot(process.env.CODEX_HOME?.trim()||ot(Mc(),".codex"),"auth.json");if(!await R(e))return!1;try{let t=JSON.parse(await ZO(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},Iw=async e=>{try{return(await XO(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},gp=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of ks){let n=ot(rt(t),"User","globalStorage");if(await R(ot(n,"github.copilot-chat"))||await R(ot(n,"github.copilot")))return!0}let e=ot(Mc(),".config","github-copilot");if(await R(ot(e,"apps.json"))||await R(ot(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await Iw(ot(Mc(),t,"extensions")))return!0;for(let t of ks){if(await Iw(Sw(t)))return!0;let n=ot(Vo(t,!0),"globalStorage");if(await R(ot(n,"github.copilot-chat"))||await R(ot(n,"github.copilot")))return!0}if(xw()==="darwin"){for(let t of zO)if(await Rw(t))return!0}return!1},Nt=async()=>{let[e,t,n]=await Promise.all([QO(),e_(),gp()]);return{anthropic:e,openai:t,copilot:n}};var Oe=async(e=T,t=Nt,n)=>{let r=await e();if(!r.gateway||!r.clientKey)return;let o=await t().catch(()=>{}),a=ye({origin:r.gateway,clientKey:r.clientKey,subscription:r.authMode==="subscription",placeholder:r.authMode==="placeholder",byoUpstream:r.byoUpstream,seat:o,user:r.name,team:r.team});if(!tt(r))return{target:a,toolOrigin:a.origin};if(!(!Number.isInteger(r.fallbackPort)||r.fallbackPort<1||r.fallbackPort>65535))return n&&await n(r.fallbackPort)===null?{target:a,toolOrigin:a.origin}:{target:vn(a,r.fallbackPort),toolOrigin:`http://${pt}:${r.fallbackPort}`}};import{homedir as c_}from"node:os";import{join as jc}from"node:path";import{chmod as l_,readFile as As,rm as Dw,copyFile as d_}from"node:fs/promises";var Vr="# >>> anyray connect >>>",Bc="# <<< anyray connect <<<",wp="# restore: ",Ow=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Hc=e=>{let t=new RegExp(`\\n*${Ow(Vr)}[\\s\\S]*?${Ow(Bc)}\\n?`,"g");return e.replace(t,"")},bp=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},Fc=(e,t)=>e.split(t).length-1,_w=e=>Fc(e,"[")-Fc(e,"]"),t_=e=>e.replace(/^['"]|['"]$/g,""),Uc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Fc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+_w(bp(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=bp(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Fc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+_w(l)))}return t},kp=e=>e.findIndex(t=>t.kind==="table"),Cp=e=>e.includes(Vr),Pw=(e,t)=>{let n=`[${t}]`;return e.split(`
|
|
74
|
-
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},Ap=(e,t)=>
|
|
75
|
-
`),o=Uc(r),a=kp(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=bp(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}},
|
|
73
|
+
`,GO=(e=Pc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),ys=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(" ")}`],ww=e=>!e.run&&cs(),jO=async(e,t)=>await MO(up(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Tc]).ok,dr=async(e={})=>{let t=e.os??lp(),n=e.invocation??Pc(),r=e.run??dp,o=e.binaryPath??ir();if(Ge(o))return{ok:!1,messages:[`Skipped auto-refresh scheduling \u2014 anyray-connect is running from a temporary path (${o}).`,"Install it durably (the installer persists it under ~/.anyray/bin) and re-run."]};if(ww(e))return{ok:!1,messages:Uo("auto-refresh scheduling")};let a=ht(e.env??(e.run?{}:process.env));if(kt(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${cr(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=up(),i=WO(n);if(await jO(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await ap(fs(),{recursive:!0,mode:448}),await ap(jo(cp(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=`${s}.new-${process.pid}`;await jr(l,{force:!0}).catch(()=>{}),await xc(l,i),r("launchctl",["bootout",`gui/${c}`,s]),await jr(s,{force:!0}).catch(()=>{});try{await FO(l,s)}catch{await xc(s,i),await jr(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.`,...ys(n)]}}if(t==="linux")return await ap(pp(),{recursive:!0}),await xc(gw(),HO(n)),await xc(Rc(),KO()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${bs}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${Rc()}).`]}:{ok:!1,messages:[`Wrote ${Rc()} but \`systemctl --user enable --now\` failed.`,...ys(n)]};if(t==="win32"){let s=GO(n);return r("schtasks",["/Create","/TN",gs,"/TR",s,"/SC","MINUTE","/MO",BO,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",gs]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${gs}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...ys(n)]}}return{ok:!1,messages:ys(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...ys(n)]}}},ur=async(e={})=>{await jr(ip(),{force:!0}).catch(()=>{});let t=e.os??lp(),n=e.run??dp,r=[];if(ww(e))return{ok:!0,messages:Uo("scheduler teardown")};try{if(t==="darwin"){let o=up(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await jr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.")}else t==="linux"?(n("systemctl",["--user","disable","--now",`${bs}.timer`]),await jr(Rc(),{force:!0}),await jr(gw(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",gs,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},Lc=async(e=lp(),t=dp)=>e==="win32"?t("schtasks",["/Query","/TN",gs]).ok:e==="darwin"?t("launchctl",["list",Tc]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${bs}.timer`]).ok:!1;import WW from"node:http";import{spawn as zU}from"node:child_process";import{createHash as qU}from"node:crypto";import{homedir as QU}from"node:os";import{join as TS}from"node:path";import{readFile as eB,writeFile as PS,chmod as tB,stat as nB,unlink as CS}from"node:fs/promises";import{homedir as Mc,platform as Tw}from"node:os";import{join as ot}from"node:path";import{execFile as e_}from"node:child_process";import{readFile as t_,readdir as n_}from"node:fs/promises";import{homedir as VO,platform as YO}from"node:os";import{join as Dc}from"node:path";var rt=e=>{let t=VO();switch(YO()){case"darwin":return Dc(t,"Library","Application Support",e);case"win32":return Dc(process.env.APPDATA??Dc(t,"AppData","Roaming"),e);default:return Dc(t,".config",e)}};import{readFile as Cw}from"node:fs/promises";import{homedir as Yr,platform as Vo}from"node:os";import{join as _n,posix as ZO,win32 as JO}from"node:path";var ks=["Code","Code - Insiders","VSCodium"],fp="1.121.0",bw=1,XO=121,Aw="1.102.0",kw=1,zO=102,qO={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},Nc=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},hp=e=>{let t=Nc(e);return t?t.major!==bw?t.major>bw:t.minor>=XO:!1},vw=e=>{let t=Nc(e);return t?t.major!==kw?t.major>kw:t.minor>=zO:!1},QO=async e=>{if(Vo()!=="darwin")return;let t=_n("/Applications",`${qO[e]}.app`,"Contents","Resources","app","package.json");if(await R(t))try{let n=JSON.parse(await Cw(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},Sw=(e,t=Vo(),n=Yr(),r=process.env)=>{switch(t){case"darwin":return _n(n,"Library","Application Support",e);case"win32":return _n(r.APPDATA??_n(n,"AppData","Roaming"),e);default:return _n(n,".config",e)}},mp=(e,t)=>e?t==="win32"?JO.join:ZO.join:_n,Yo=(e,t=!1,n=Vo(),r=Yr(),o=process.env)=>t?mp(t,n)(r,Cs[e],"data","User"):_n(Sw(e,n,r,o),"User"),Ew=async(e,t=!1,n=Vo(),r=Yr(),o=process.env)=>{try{let a=mp(t,n)(Yo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await Cw(a,"utf8"))?.userDataProfiles;if(!Array.isArray(i))return[];let c=i.map(l=>l).filter(l=>typeof l.name=="string"&&l.name.trim().length>0&&l.name.length<=128&&!/[\u0000-\u001f\u007f]/.test(l.name)&&typeof l.location=="string"&&/^[A-Za-z0-9._-]{1,128}$/.test(l.location)&&l.location!=="."&&l.location!=="..").map(({name:l,location:d})=>({name:l,location:d}));return c.filter((l,d)=>c.findIndex(u=>u.location===l.location)===d)}catch{return[]}},Iw=async(e,t=Vo(),n=Yr(),r=process.env)=>{let a=(await Ew(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},xw=async(e,t=!1,n=Vo(),r=Yr(),o=process.env)=>{let a=mp(t,n),s=Yo(e,t,n,r,o),i=await Ew(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},$c=async()=>{for(let e of ks)if(await R(Sw(e)))return e},Cs={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},Rw=(e,t=Yr())=>_n(t,Cs[e],"extensions"),yp=async(e=Yr())=>{for(let t of ks)if(await R(_n(e,Cs[t])))return t},Ow=async e=>{let t=e??await $c();if(!t)return{status:"unknown"};let n=await QO(t);return n?{variant:t,version:n,status:hp(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var r_=3e3,o_="Claude Code-credentials",a_=["copilot-cli","CopilotCLI"],Pw=e=>new Promise(t=>{try{e_("security",["find-generic-password","-s",e],{timeout:r_},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),s_=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=ot(Mc(),".claude");return!!(await R(ot(e,".oauth_token"))||await R(ot(e,".credentials.json"))||Tw()==="darwin"&&await Pw(o_))},i_=async()=>{let e=ot(process.env.CODEX_HOME?.trim()||ot(Mc(),".codex"),"auth.json");if(!await R(e))return!1;try{let t=JSON.parse(await t_(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},_w=async e=>{try{return(await n_(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},gp=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of ks){let n=ot(rt(t),"User","globalStorage");if(await R(ot(n,"github.copilot-chat"))||await R(ot(n,"github.copilot")))return!0}let e=ot(Mc(),".config","github-copilot");if(await R(ot(e,"apps.json"))||await R(ot(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await _w(ot(Mc(),t,"extensions")))return!0;for(let t of ks){if(await _w(Rw(t)))return!0;let n=ot(Yo(t,!0),"globalStorage");if(await R(ot(n,"github.copilot-chat"))||await R(ot(n,"github.copilot")))return!0}if(Tw()==="darwin"){for(let t of a_)if(await Pw(t))return!0}return!1},Nt=async()=>{let[e,t,n]=await Promise.all([s_(),i_(),gp()]);return{anthropic:e,openai:t,copilot:n}};var Oe=async(e=P,t=Nt,n)=>{let r=await e();if(!r.gateway||!r.clientKey)return;let o=await t().catch(()=>{}),a=ye({origin:r.gateway,clientKey:r.clientKey,subscription:r.authMode==="subscription",placeholder:r.authMode==="placeholder",byoUpstream:r.byoUpstream,seat:o,user:r.name,team:r.team});if(!tt(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:En(a,r.fallbackPort),toolOrigin:`http://${pt}:${r.fallbackPort}`}};import{homedir as m_}from"node:os";import{join as jc}from"node:path";import{chmod as y_,readFile as As,rm as Fw,copyFile as g_}from"node:fs/promises";var Zr="# >>> anyray connect >>>",Bc="# <<< anyray connect <<<",wp="# restore: ",Lw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Wc=e=>{let t=new RegExp(`\\n*${Lw(Zr)}[\\s\\S]*?${Lw(Bc)}\\n?`,"g");return e.replace(t,"")},bp=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},Fc=(e,t)=>e.split(t).length-1,Dw=e=>Fc(e,"[")-Fc(e,"]"),c_=e=>e.replace(/^['"]|['"]$/g,""),Uc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Fc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+Dw(bp(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?c_(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=bp(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Fc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+Dw(l)))}return t},kp=e=>e.findIndex(t=>t.kind==="table"),Cp=e=>e.includes(Zr),Nw=(e,t)=>{let n=`[${t}]`;return e.split(`
|
|
74
|
+
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},Ap=(e,t)=>Nw(Wc(e),t),vp=e=>{let t=e.indexOf(Zr);if(t<0)return;let n=e.indexOf(Bc,t+Zr.length);if(!(n<0))return e.slice(t,n)},$w=(e,t)=>{let n=e.indexOf(Zr);if(n<0)return!1;let r=e.indexOf(Bc,n+Zr.length);return r<0?!1:Nw(e.slice(n,r),t)},Sp=(e,t)=>{let r=Wc(e).split(`
|
|
75
|
+
`),o=Uc(r),a=kp(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=bp(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}},Hc=(e,t,n)=>{let r=Mw(e),a=Wc(e).split(`
|
|
76
76
|
`),s=Uc(a),i=kp(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=Uc(d),p=kp(f),h=(p===-1?d:d.slice(0,p)).join(`
|
|
77
77
|
`),m=p===-1?"":d.slice(p).join(`
|
|
78
|
-
`),w=[...u.entries()].sort(([b],[A])=>b.localeCompare(A)).map(([,b])=>`${wp}${b}`),g=[
|
|
78
|
+
`),w=[...u.entries()].sort(([b],[A])=>b.localeCompare(A)).map(([,b])=>`${wp}${b}`),g=[Zr,...w,...t,Bc].join(`
|
|
79
79
|
`);return[h.replace(/\s*$/,""),g,m.replace(/^\s*/,"")].filter(b=>b.length>0).join(`
|
|
80
80
|
|
|
81
81
|
`).replace(/\s*$/,"")+`
|
|
82
|
-
`},
|
|
83
|
-
`)){let o=r.trim();if(!o.startsWith(wp))continue;let a=o.slice(wp.length).trim(),[s]=Uc([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},Kc=e=>{if(!Cp(e))return null;let t=[...
|
|
82
|
+
`},Mw=e=>{let t=new Map,n=vp(e);if(n===void 0)return t;for(let r of n.split(`
|
|
83
|
+
`)){let o=r.trim();if(!o.startsWith(wp))continue;let a=o.slice(wp.length).trim(),[s]=Uc([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},Kc=e=>{if(!Cp(e))return null;let t=[...Mw(e).entries()].sort(([a],[s])=>a.localeCompare(s)).map(([,a])=>a),n=Wc(e).replace(/^\s*/,"").replace(/\s*$/,""),o=[t.join(`
|
|
84
84
|
`),n].filter(a=>a.length>0).join(`
|
|
85
85
|
|
|
86
86
|
`);return o.length>0?o+`
|
|
87
|
-
`:""};import{randomUUID as
|
|
87
|
+
`:""};import{randomUUID as l_}from"node:crypto";import{chmod as d_,mkdir as u_,rm as p_,writeFile as f_}from"node:fs/promises";import{dirname as h_}from"node:path";var he=async(e,t)=>{await u_(h_(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${l_()}`;try{await f_(n,t,{flag:"wx",mode:384}),await fe(n,e),await d_(e,384)}finally{await p_(n,{force:!0}).catch(()=>{})}};var w_="codex",b_="Codex app / CLI / IDE",k_="https://chatgpt.com/backend-api/codex",C_="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",A_="x-anyray-client-context-window",v_="x-anyray-client-auto-compact-limit",Vc=()=>process.env.CODEX_HOME?.trim()||jc(m_(),".codex"),Jr=()=>jc(Vc(),"config.toml"),Gc=()=>`${Jr()}.anyray-bak`,Ep=()=>jc(Vc(),"hooks.json"),Tn=()=>jc(Vc(),"anyray.config.toml"),Uw=e=>Fo(e,"PostToolUse",Lg),Bw=(e,t=!1)=>de({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||w_,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||b_}),at=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Ip=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,vs=(e,t={})=>{let n=Bw(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:Ip(),i=e.clientKey&&!e.viaLocalProxy,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${at(k_)}`,`"x-anyray-forward-headers" = ${at(C_)}`,...i?[`"x-anyray-api-key" = ${at(e.clientKey)}`]:[]]:o?[]:[`"Authorization" = ${at(`Bearer ${e.clientKey??e.placeholderKey}`)}`];return n&&c.push(`"x-anyray-metadata" = ${at(n)}`),a&&c.push(`"x-anyray-provider" = ${at(a)}`),t.modelContextWindow&&c.push(`"${A_}" = ${at(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${v_}" = ${at(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 = ${at(s)}`]:[],"","[model_providers.anyray]",'name = "Anyray Gateway"',`base_url = ${at(e.openaiBaseUrl)}`,'wire_api = "responses"',...r?["requires_openai_auth = true"]:[],...c.length>0?[`http_headers = { ${c.join(", ")} }`]:[],...o?["","[model_providers.anyray.auth]",`command = ${at(t.authCommand??"")}`,...t.authArgs&&t.authArgs.length>0?[`args = [${t.authArgs.map(l=>at(l)).join(", ")}]`]:[]]:[],...t.mcpServer?["","[mcp_servers.anyray]",`command = ${at(t.mcpServer.command)}`,`args = [${t.mcpServer.args.map(at).join(", ")}]`]:[]]},S_=()=>Ip()?["model_provider","model"]:["model_provider"],Ww={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=Vc(),t=await R(e);return{installed:t,detail:t?Jr():`no ${e} directory`}},async apply(e,t){let n=Jr(),r=Ep(),o=Bw(e),a=X(e,"openai"),s=Ip(),i=ce(),c={},l=await R(r);try{l&&(c=await M(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=Uw(c),u=await R(n),f=u?await As(n,"utf-8"):"";if(Ap(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=Ap(f,"mcp_servers.anyray"),h=Sp(f,"model_context_window"),m=Sp(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 ae(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(Gc())&&(await g_(n,Gc()),await y_(Gc(),384),w.push(`Backed up your original config to ${Gc()}.`));let y=i&&!p?je("profile"):void 0;w.push(p?`MCP name conflict in ${n}: mcp_servers.anyray is not owned by Anyray Connect, so it was left untouched.`:y?"Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.":`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer or a global install to enable retrieval.`);let b=Hc(f,vs(e,{mcpServer:y,modelContextWindow:h,modelAutoCompactTokenLimit:m}),S_());return await he(n,b),g.push(n),await R(Tn())&&(await Fw(Tn(),{force:!0}),g.push(Tn()),w.push(`Removed the old opt-in profile ${Tn()} (the default route replaces it).`)),{status:"configured",messages:w,changedFiles:g}},async pointsAt(e){let t=Jr();if(!await R(t))return!1;try{let n=await As(t,"utf-8"),r=`base_url = ${at(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async mcpStatus(){let e=Jr();if(!await R(e))return{registered:!1,command:null};try{let t=await As(e,"utf-8");if(!$w(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 As(Jr(),"utf-8"),t=vp(e);if(!t||!t.includes("[model_providers.anyray]"))return["unknown"];if(/^requires_openai_auth = true$/m.test(t)||t.includes('"x-anyray-auth-mode" = "passthrough"'))return["subscription"];if(t.includes('"Authorization" = "Bearer ')||t.includes("[model_providers.anyray.auth]"))return["api_key"]}catch{}return["unknown"]},async revert(e){let t=Jr(),n=await R(t),r=await R(Tn()),o=await R(Ep());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=Ep(),c;try{c=await M(i)}catch(l){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${i} (${l instanceof Error?l.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run --revert.`]}}Uw(c)&&(e.dryRun||(await J(i,c,{backup:!1}),await ae(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=Kc(await As(t,"utf-8"));i!==null&&(e.dryRun||await he(t,i),s.push(t),a.push(e.dryRun?`would remove the Anyray default route from ${t}`:`removed the Anyray default route from ${t}`))}return r&&(e.dryRun||await Fw(Tn(),{force:!0}),s.push(Tn()),a.push(e.dryRun?`would remove the old opt-in profile ${Tn()}`:`removed the old opt-in profile ${Tn()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await ae(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as __}from"node:os";import{join as T_}from"node:path";import{readFile as jw,rm as Rp}from"node:fs/promises";import{readFile as E_,writeFile as Hw,access as I_}from"node:fs/promises";import{homedir as x_}from"node:os";import{join as xp}from"node:path";var R_="# >>> anyray connect >>>",O_="# <<< anyray connect <<<",Ss=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:R_,end:O_},Ct=()=>{let e=x_(),t=process.env.SHELL||"";return t.includes("zsh")?xp(e,".zshrc"):t.includes("bash")?xp(e,".bashrc"):xp(e,".profile")},Yc=async e=>{try{return await I_(e),await E_(e,"utf-8")}catch{return""}},Kw=(e,t)=>{let{begin:n,end:r}=Ss(t),o=e.indexOf(n);if(o===-1)return e;let a=e.indexOf(r,o+n.length);if(a===-1)return e;let s=o;for(;s>0&&e[s-1]===`
|
|
88
88
|
`;)s-=1;let i=a+r.length;return e[i]===`
|
|
89
|
-
`&&(i+=1),e.slice(0,s)+e.slice(i)},Zc=async(e,t,n)=>{let r=await Yc(e),{begin:o,end:a}=Ss(n),s=
|
|
89
|
+
`&&(i+=1),e.slice(0,s)+e.slice(i)},Zc=async(e,t,n)=>{let r=await Yc(e),{begin:o,end:a}=Ss(n),s=Kw(r,n).replace(/\s*$/,""),i=[o,...t,a].join(`
|
|
90
90
|
`),c=s?`${s}
|
|
91
91
|
|
|
92
92
|
${i}
|
|
93
93
|
`:`${i}
|
|
94
|
-
`;return await
|
|
95
|
-
`).filter(c=>c.trim().length>0)},
|
|
96
|
-
`),!0):!1};var $t=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,"'\\''")}'`,
|
|
97
|
-
`)):w&&y&&await Rp(d,{force:!0}),await Zc(n,f)}catch(b){try{g!==void 0&&y?await he(d,g):y&&await Rp(d,{force:!0})}catch{throw new Error("shell environment update failed and credential rollback could not be completed")}throw b}return{status:"configured",messages:m,changedFiles:[n,...c.length>0||w&&y?[d]:[]]}},async revert(e){let t=Ct(),n=Op(),r=await R(n),o=r?
|
|
94
|
+
`;return await Hw(e,c),e},Jc=async(e,t)=>{let n=await Yc(e),{begin:r,end:o}=Ss(t),a=n.indexOf(r);if(a===-1)return;let s=a+r.length,i=n.indexOf(o,s);if(i!==-1)return n.slice(s,i).split(`
|
|
95
|
+
`).filter(c=>c.trim().length>0)},Gw=async(e,t)=>(await Yc(e)).includes(Ss(t).begin),Es=async(e,t)=>{let n=await Yc(e);return n.includes(Ss(t).begin)?(await Hw(e,Kw(n,t).replace(/\s*$/,"")+`
|
|
96
|
+
`),!0):!1};var $t=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,"'\\''")}'`,P_=e=>{let t=ve(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},Vw=(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'"]]},L_=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],D_=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],Op=()=>T_(__(),".anyray","shell-env.sh"),Zw="# Managed by anyray-connect. Do not source this file anywhere else.",Yw=e=>e.split(/\r?\n/,1)[0]===Zw,_p=e=>D_.some(t=>e.startsWith(`export ${t}=`)),Jw=(e,t=process.env)=>Tp([e],t),Tp=(e,t=process.env)=>e.some(r=>t.ANTHROPIC_BASE_URL===r.anthropicBaseUrl||t.OPENAI_BASE_URL===r.openaiBaseUrl)?L_.filter(r=>(t[r]??"")!==""):[],Xw={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=Ct();return{installed:!0,detail:await R(e)?e:`${e} (will be created)`}},async inferenceAuthLanes(){try{let e=await Jc(Ct());return e?e.some(n=>_p(n)||n.includes(Op()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=Ct(),r=X(e,"openai"),o=X(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=Vw(e,s,r,o),c=i.filter(_p),l=i.filter(b=>!_p(b)),d=Op(),u=Tg(),f=[P_(u),...l,...c.length>0?[`[ -r ${ve(d)} ] && . ${ve(d)}`]:[]],p=e.clientKey?Vw(e,$t(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 jw(d,"utf8"):void 0,y=g===void 0||Yw(g);if(c.length>0&&!y)return{status:"manual",messages:[`Refused to overwrite user-managed ${d}; move or rename that file, then run Connect again.`]};if(y||m.push(`Preserved unrelated existing ${d}.`),t.dryRun)return{status:"configured",messages:m};try{c.length>0?await he(d,[Zw,...c,""].join(`
|
|
97
|
+
`)):w&&y&&await Rp(d,{force:!0}),await Zc(n,f)}catch(b){try{g!==void 0&&y?await he(d,g):y&&await Rp(d,{force:!0})}catch{throw new Error("shell environment update failed and credential rollback could not be completed")}throw b}return{status:"configured",messages:m,changedFiles:[n,...c.length>0||w&&y?[d]:[]]}},async revert(e){let t=Ct(),n=Op(),r=await R(n),o=r?Yw(await jw(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 Es(t);o&&await Rp(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 mT}from"node:child_process";import{closeSync as yT,copyFileSync as gT,existsSync as Se,mkdirSync as wT,openSync as bT,readFileSync as Rb,readSync as kT,renameSync as CT,rmSync as mn,writeFileSync as Vp}from"node:fs";import{homedir as Ob,platform as AT}from"node:os";import{dirname as _b,join as zo,resolve as vT}from"node:path";import{isIP as Up}from"node:net";import{execFileSync as qc}from"node:child_process";import{mkdtempSync as N_,rmSync as $_,writeFileSync as M_}from"node:fs";import{createRequire as F_}from"node:module";import{tmpdir as U_}from"node:os";import{join as zw}from"node:path";var Is=class extends Error{},xs=e=>e instanceof Is?`: ${e.message}`:"",qw=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new Is("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new Is(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},Qw=()=>{try{return qc("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Lp=64*1024*1024,B_=Lp*2+64,zc=e=>`'${e.replace(/'/g,"''")}'`,W_=(e,t)=>qc("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:B_,stdio:["ignore","pipe","pipe"]}),H_=(e,t)=>qc("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Lp,stdio:["pipe","pipe","pipe"]}),eb=(e,t,n=W_)=>{let r=zc(t),o=`SELECT 'present:' || COALESCE(hex(CAST(value AS BLOB)), '') FROM ItemTable WHERE key=${r} UNION ALL SELECT 'absent:' WHERE NOT EXISTS (SELECT 1 FROM ItemTable WHERE key=${r});`,a=n(e,o),s=a.endsWith(`\r
|
|
98
98
|
`)?a.slice(0,-2):a.endsWith(`
|
|
99
|
-
`)?a.slice(0,-1):a;if(s==="absent:")return;if(!s.startsWith("present:"))throw new Error("state DB returned an unexpected item encoding");let i=s.slice(8);if(i.length%2!==0||!/^[0-9a-f]*$/i.test(i))throw new Error("state DB returned an unexpected item encoding");return Buffer.from(i,"hex").toString("utf-8")},
|
|
99
|
+
`)?a.slice(0,-1):a;if(s==="absent:")return;if(!s.startsWith("present:"))throw new Error("state DB returned an unexpected item encoding");let i=s.slice(8);if(i.length%2!==0||!/^[0-9a-f]*$/i.test(i))throw new Error("state DB returned an unexpected item encoding");return Buffer.from(i,"hex").toString("utf-8")},tb=(e,t=H_)=>{let r=t(e,`.bail on
|
|
100
100
|
.timeout 5000
|
|
101
101
|
PRAGMA wal_checkpoint(TRUNCATE);
|
|
102
|
-
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");
|
|
103
|
-
`);
|
|
104
|
-
`,{mode:384}),await fe(n,t)},
|
|
105
|
-
`),
|
|
106
|
-
`,{encoding:"utf-8",flag:"wx",mode:384})},
|
|
107
|
-
`,{encoding:"utf-8",flag:"wx",mode:384});try{hP(n,e)}catch(r){throw hn(n,{force:!0}),r}},LP=(e,t)=>{let n=Yo(e);_b(e,{...n,lastWritten:t})},oe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ab=e=>oe(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Yo=e=>{let t=Sb(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(oe(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||oe(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(!oe(n)||n.version!==1||!oe(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Xe],o=n.rows[it];if(!Ab(r)||!Ab(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}},vb=e=>{let t=Buffer.alloc(16),n=pP(e,"r");try{return fP(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{lP(n)}},DP=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return oe(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Pb=e=>{let t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".lan")||t.endsWith(".internal")||t.endsWith(".home")||!t.includes(".")&&Up(t)===0||t==="0.0.0.0")return!0;if(Up(t)===4){let[n,r,o]=t.split(".").map(Number);return n===10||n===0||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===192&&r===0&&(o===0||o===2)||n===198&&(r===18||r===19)||n===198&&r===51&&o===100||n===203&&r===0&&o===113||n>=224}if(Up(t)===6){let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(n){let r=Number.parseInt(n[1],16),o=Number.parseInt(n[2],16);return Pb(`${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},Wp=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Pb(t.hostname)}catch{return!1}},NP=e=>{try{let t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"}catch{return!1}},$P=e=>({...e,openaiBaseUrl:(()=>{try{let t=new URL(e.openaiBaseUrl);return t.protocol==="http:"&&t.hostname==="127.0.0.1"?`${Ye(e.origin)}/v1${Hp}`:`${e.openaiBaseUrl.replace(/\/+$/,"")}${Hp}`}catch{return e.openaiBaseUrl.replace(/\/+$/,"")}})()}),Zo=(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."],Tb=()=>{let e=Xr();if(!Se(e))return"clear";let t=Rs();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Xe)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return oe(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},MP=(e,t)=>{if(!Wp(e))return{routed:!1,problem:"gateway-not-public-https"};let n=Xr();if(!Se(n))return{routed:!1,problem:"state-db-missing"};let r=Rs();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Xe),a=r.readItem(n,it)}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(!oe(s))return{routed:!1,problem:"settings-malformed"};let i=`${Ye(e)}/v1${Hp}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Ie(a)||!Ie(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},FP=(e,t=[])=>({command:Tt(e,[...t,cl])}),Zp=(e,t,n)=>{if(!oe(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Tt(t,[...n,cl])||r===Tt(t,n)||r.endsWith(` ${cl}`)&&r.includes(` ${t} `)},UP=(e,t)=>oe(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),Lb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Zp(a,t,n)){r=!0;continue}if(!oe(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!UP(c,t));if(s.length===a.hooks.length){o.push(a);continue}r=!0;let i=Object.keys(a).every(c=>c==="matcher"||c==="hooks");s.length===0&&i||o.push({...a,hooks:s})}return{entries:o,changed:r}},Xp=(e,t)=>{let n=e[t];if(n===void 0)return[];if(!Array.isArray(n))throw new Error(`Cursor hook event ${t} is not an array`);return n},Db=(e,t,n,r,o)=>oe(e.hooks)&&Xp(e.hooks,t).some(a=>oe(a)&&a.matcher===o&&Zp(a,n,r)),BP=(e,t,n,r,o)=>oe(e.hooks)&&Xp(e.hooks,t).some(a=>oe(a)&&a.matcher===o&&Zp(a,n,r)&&mc(a.command,n,[...r,cl])),Nb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!oe(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=oe(e.hooks)?{...e.hooks}:{},{entries:s}=Lb(Xp(a,t),n,r);return s.push({...FP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},HP=(e,t,n,r=[])=>{if(!oe(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=Lb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},WP=async()=>{let e=Qt();if(!ce()){let t=await Mb();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 M(e);for(let n of Jr)t=Nb(t,n.event,n.flag,n.trailingArgs,n.matcher);return await X(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}}},il=()=>{let e=je("profile");return{command:e.command,args:[...e.args,Ob]}},Kp=e=>oe(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===il().command&&e.args.length===il().args.length&&e.args.every((t,n)=>t===il().args[n]),KP=e=>{if(!oe(e)||Object.keys(e).some(o=>o!=="command"&&o!=="args")||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(o=>typeof o=="string")||Ge(e.command))return!1;let t=e.args;if(t.at(-2)!==rr||t.at(-1)!=="profile")return!1;let n=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(n))return t.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(n)||t.length!==3)return!1;let r=t[0].replaceAll("\\","/");return!Ge(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},ll=e=>oe(e)&&Array.isArray(e.args)&&e.args.at(-1)===Ob||KP(e),GP=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,jP=async()=>{if(!ce())return $b();let e=en();try{let t=await M(e);if(t.mcpServers!==void 0&&!oe(t.mcpServers))throw new Error("mcpServers is not an object");let n=oe(t.mcpServers)?{...t.mcpServers}:{},r=n[Mt];return r!==void 0&&!ll(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Mt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Mt]=il(),await X(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}}},$b=async()=>{let e=en();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e);if(!oe(t.mcpServers)||!(Mt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!ll(t.mcpServers[Mt]))return{changedFiles:[],messages:[`Preserved the foreign ${Mt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Mt];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await X(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}}},Mb=async()=>{let e=Qt();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e),n=t;for(let r of Jr)n=HP(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await X(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}}},VP=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=kP(e);if(!n)return t;let r=Jo(n,Ts),o=bP();try{if(Se(r)){let a=Sb(r,"utf8");if(a===o)return t;if(!a.includes(Rb))return{...t,messages:[`Left ${Ts} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Yp}"`]}}return uP(Ib(r),{recursive:!0}),Vp(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Ts} 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 ${Ts} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Fb=async()=>{let e=await WP(),t=await jP(),n=await VP();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Gp=async()=>{let e=await Mb(),t=await $b();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},Ub=async()=>{if(!ce()){let e=await Gp();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 M(Qt());for(let r of Jr)e=Nb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await M(en());if(t.mcpServers!==void 0&&!oe(t.mcpServers))throw new Error("mcpServers is not an object");let n=oe(t.mcpServers)?t.mcpServers[Mt]:void 0;return n!==void 0&&!ll(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${en()} already contains a foreign ${Mt} 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 ${Qt()} and ${en()}, then re-run Connect.`],complete:!1}}},YP=async()=>{if(!ce())return!1;try{let e=await M(Qt());if(!oe(e.hooks)||!Jr.every(r=>Db(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await M(en()),n=oe(t.mcpServers)?t.mcpServers[Mt]:void 0;return Kp(n)}catch{return!1}},Bb=["openAIBaseUrl","useOpenAIKey"],Ds=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!oe(t))throw new Error("Cursor application-user settings are not an object");return t},ZP=(e,t,n)=>{let r=Ds(e),o=Ds(t??void 0),a=n===void 0?void 0:Ds(n),s={...r},i=[];for(let c of Bb){let l=Object.prototype.hasOwnProperty.call(r,c),d=a!==void 0&&Object.prototype.hasOwnProperty.call(a,c);if(a===void 0||l!==d||l&&!Object.is(r[c],a[c])){i.push(c);continue}Object.prototype.hasOwnProperty.call(o,c)?s[c]=o[c]:delete s[c]}return{mutation:Object.keys(s).length===0?{key:Xe}:{key:Xe,value:JSON.stringify(s)},conflicts:i}},Bp=(e,t)=>{let n=Ds(e),r=Ds(t??void 0),o={...n};for(let a of Bb)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Xe}:{key:Xe,value:JSON.stringify(o)}},ol=e=>typeof e=="string"&&e.startsWith("ark_"),al=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);oe(o)&&(n=o)}catch{}let r=ol(t)||n!==null&&(ol(n.useOpenAIKey)||ol(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,ol(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}},st=(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.",...Zo(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.",...Zo(e)]},jp=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!ce())return n;if(t.dryRun)return{status:"queued",messages:[`Cursor is running \u2014 would queue the ${o} and complete it automatically when Cursor quits.`]};let a;try{a=await _s("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]}},XP=async(e,t)=>{if(!Ie(e.clientKey))return{status:"manual",messages:["Cursor native subscription mode was not changed: a valid personal ark_ gateway key is required for Anyray hooks and MCP retrieval."]};if(!t.dryRun&&!t.preservePendingOp)try{await pr("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 Ub();if(!n.complete)return{status:"manual",messages:n.messages};let r=Se(Ls())||Se(Xo());if(r&&sl())return jp("native",t,{status:"manual",messages:["Cursor is running \u2014 fully quit it and re-run so Connect can restore the journaled BYOK override before enabling native subscription mode."]},["No native Claude/Opus request will be redirected: the queued operation restores Cursor\u2019s prior settings, then installs only Anyray hooks/MCP."]);if(!r){let c=Tb();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(Xo())?Xo():Ls()}, 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 ${Qt()}, and register the Anyray retrieval MCP server in ${en()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Ns.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 Fb(),s=[];if(!t.preservePendingOp)try{await pr("cursor")}catch{s.push("Could not clear Cursor's stale queue marker.")}return{status:a.complete&&s.length===0?"configured":"manual",changedFiles:[...new Set([...o?.changedFiles??[],...a.changedFiles])],messages:[...o?.messages??[],"Kept Cursor's native Team sign-in and Claude/Opus model route; no Anyray OpenAI override or model credential was written.",...a.messages,...s,"Claude/Opus inference remains Cursor-hosted and will not produce gateway inference traces. Anyray records content-free hook savings only when a supported oversized Shell/MCP result is actually reduced.",`Make it seamless org-wide: paste this into Cursor's dashboard Team Rules and mark it Required, so every member's agent uses Anyray's tools without being asked -- "${Yp}" (connect already writes ${Ts} 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."]}},Ns={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>sl(),quitTarget:gP,needsTarget:e=>e!=="revert",async complete(e,t,n){return wP(e)?e!=="revert"&&t?Ns.apply(t,n):Ns.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=xb(),t=Se(e);return{installed:t,detail:t?Xr():"Cursor user dir not found"}},async watchPaths(){return[Qt(),en()]},async mcpStatus(){let e=en();if(!await R(e))return{registered:!1,command:null};try{let t=await M(e),n=oe(t.mcpServers)?t.mcpServers[Mt]:void 0;return Kp(n)?{registered:!0,command:GP(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=Qt();if(!await R(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!oe(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(Jr.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Jr.every(c=>Db(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Jr.every(c=>BP(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=en();if(!await R(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!oe(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Mt];r=i===void 0?"missing":ll(i)?"owned":"foreign",r==="owned"&&(o=Kp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Fr()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await T();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(CP(e))return XP(e,t);let n=$P(e),r=NP(e.openaiBaseUrl),o=Xr(),a=Ls(),s=Xo();if(!Ie(e.clientKey))return{status:"manual",messages:st(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(!Wp(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.",...Zo(n)]});let l=await Ub();if(!l.complete)return{status:"manual",messages:l.messages};let d=Rs();if(!d)return c({status:"manual",messages:st(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:st(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:st(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{vb(s)?u="sqlite":(Yo(s),u="value")}catch{u=null}if(!u)return c({status:"manual",messages:st(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=Yo(a)}catch{return c({status:"manual",messages:st(n,`Existing Cursor backup at ${a} is invalid \u2014 refusing to write or replace recovery data.`)})}if(sl())return c(await jp("apply",t,{status:"manual",messages:st(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Zo(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 ${Qt()}, and register the Anyray retrieval MCP server in ${en()}.`,...Zo(n,r)]};if(u){try{d.checkpointWal(o)}catch(b){return c({status:"manual",messages:st(n,`Couldn't checkpoint Cursor's state DB at ${o} while migrating the legacy Anyray backup at ${s}${xs(b)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(u==="sqlite")y=al(d.readItem(s,Xe)??null,d.readItem(s,it)??null);else{let b=Yo(s);y=al(b.applicationUser,b.openAIKey)}}catch{return c({status:"manual",messages:st(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,[Bp(d.readItem(o,Xe),y.applicationUser),y.openAIKey===null?{key:it}:{key:it,value:y.openAIKey}])}catch{return c({status:"manual",messages:st(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${s} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{hn(s,{force:!0}),hn(`${s}-wal`,{force:!0}),hn(`${s}-shm`,{force:!0}),f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held and removed it.`}catch{f=`Migrated the legacy Anyray backup at ${s}: restored the pre-Anyray values it held, but couldn't remove the file \u2014 delete it by hand or the next apply will refuse as ambiguous.`}}try{d.checkpointWal(o)}catch(y){return c({status:"manual",messages:st(n,`Couldn't checkpoint Cursor's state DB at ${o}${xs(y)} \u2014 refusing to write; set it by hand:`)})}let h;try{h=d.readItem(o,Xe)}catch{return c({status:"manual",messages:st(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let m=DP(h,n);if(!m)return c({status:"manual",messages:st(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{LP(a,w)}catch{return c({status:"manual",messages:st(n,`Couldn't update three-way ownership in the protected Cursor backup at ${a} \u2014 refusing to write; set it by hand:`)})}else try{TP(d,a,o,w)}catch{return c({status:"manual",messages:st(n,`Couldn't create the protected Cursor value backup at ${a} \u2014 refusing to write; set it by hand:`)})}try{d.mutateRows(o,[{key:Xe,value:m.value},{key:it,value:e.clientKey}])}catch{let y=!0;if(p)try{_b(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 Fb();let g=[];if(!t.preservePendingOp)try{await pr("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,...Zo(n,r),"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await T().catch(()=>{}),n=e;if(!Wp(n)){let o=t&&tt(t)&&Number.isInteger(t.fallbackPort)?`http://127.0.0.1:${t.fallbackPort}`:void 0;t?.gateway&&o&&Ye(n)===o&&(n=t.gateway)}let r=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Se(Ls())||Se(Xo())||Tb()!=="clear"?!1:YP():MP(n,r).routed},async revert(e){let t=Xr(),n=Ls(),r=Xo(),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 ${Qt()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${Qt()} and unregister its owned retrieval MCP server.`]};if((o||a)&&sl()){if(e.fullRevert){let h=await Gp(),m=!0;try{await pr("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 jp("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=Rs(),i=!1,c=!1,l,d=[];if(a)try{if(vb(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=al(s.readItem(r,Xe)??null,s.readItem(r,it)??null);s.mutateRows(t,[Bp(s.readItem(t,Xe),h.applicationUser),h.openAIKey===null?{key:it}:{key:it,value:h.openAIKey}]),c=!0}else i=!0,dP(r,t),hn(`${t}-wal`,{force:!0}),hn(`${t}-shm`,{force:!0});else{let h=Yo(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=al(h.applicationUser,h.openAIKey);s.mutateRows(t,[Bp(s.readItem(t,Xe),m.applicationUser),m.openAIKey===null?{key:it}:{key:it,value:m.openAIKey}]),c=!0}}catch(h){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${xs(h)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Yo(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=ZP(s.readItem(t,Xe),l.applicationUser,l.lastWritten?.applicationUser);d.push(...h.conflicts);let m=[h.mutation],w=s.readItem(t,it);l.lastWritten&&w===l.lastWritten.openAIKey?m.push(l.openAIKey===null?{key:it}:{key:it,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,m)}catch(h){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${xs(h)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{hn(r,{force:!0}),hn(`${r}-wal`,{force:!0}),hn(`${r}-shm`,{force:!0}),hn(n,{force:!0})}catch{f=!1,u.push("Cursor values were restored, but a recovery sidecar could not be removed; retain it until a later revert can finish cleanup.")}if(!e.preservePendingOp)try{await pr("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let p=await Gp();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 PT,mkdir as TT,readFile as pk,rm as LT,writeFile as DT}from"node:fs/promises";import{randomUUID as NT}from"node:crypto";import{dirname as $T,join as fk}from"node:path";var JP=e=>{let t="",n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){t+=o,o==="\\"&&r+1<e.length?(t+=e[r+1],r+=1):o==='"'&&(n=!1);continue}if(o==='"'){n=!0,t+=o;continue}if(o==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
|
|
108
|
-
`;)r+=1;r-=1;continue}if(o==="/"&&e[r+1]==="*"){let a=e.indexOf("*/",r+2);r=a===-1?e.length:a+1,t+=" ";continue}t+=o}return t},qP=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},mr=e=>JSON.parse(qP(JP(e)));import{spawnSync as zP}from"node:child_process";import{platform as QP}from"node:os";var Hb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},eT=(e,t,n)=>zP(e,t,n),Wb=eT,tT,nT=()=>{let e=tT??QP();if(e==="win32"){let n=Wb(Ps("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],Hb);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=Wb("pgrep",[n,r],Hb);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},rT=nT,$s=()=>rT();var dl={darwinAppName:"Visual Studio Code",darwinBundleId:"com.microsoft.VSCode",win32Image:"Code.exe",linuxProcess:"code",win32Install:[{root:"localAppData",path:"Programs\\Microsoft VS Code\\Code.exe"},{root:"programFiles",path:"Microsoft VS Code\\Code.exe"},{root:"programFilesX86",path:"Microsoft VS Code\\Code.exe"}]};import{execFile as oT}from"node:child_process";import{readdirSync as aT,statSync as sT}from"node:fs";import{createHash as Yb,randomBytes as iT,randomUUID as Zb}from"node:crypto";import{chmod as cT,lstat as lT,mkdir as qp,readFile as zr,rm as Xb,unlink as Jb,writeFile as zp}from"node:fs/promises";import{homedir as zo,platform as Qp}from"node:os";import{dirname as qb,join as Pn,posix as Gb,win32 as dT}from"node:path";import{promisify as uT}from"node:util";var _n="0.1.22";var qr="c54d0b27bafcd2354da44f92b2948626317adfa555a7390a13eaefe449263e54",ul="597617932b51304b5aaf83939f3bc965b152216f5859b63ae3e1eabd28eb5e4d",Kb="UEsDBBQAAAgIANyKDF3wGpfWBwMAALQJAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeoqWlU+GuNhAUOxEqBSrk+hhgRI5WU1MkweHKUn99sbv6spKmlV3ktsuZeY/zwUfm7zcrK9YYmbzry252IwU67Q25si+rtOj8It8X11f5FPQTlDgBRwvkJB73Ib3spg7arKzjvlymFG6VYr3EFXC2Ih09+0XKtF8pg2u0PmBUa950Wh/Vu+l2d+G35hUAHYNMpWtxiuurq3yCCQwkqH+u8pFBlyhtxRhcWUGJfYmu88dMipHpS3DbCNvOmrU3KI9Z3WTdrNeTYlrNLfES495VCtXifiAOFrafYYXFoDGJhY/icSaG3mCuTu1tALKOFBJ5V6d7ywE09mWIyBjXKIuBMQI3wZKmJHaQJSR8hq1YeYOWhY87Q+c5QghoxNAHsj4JruZH+J13WkZflcv9nn6G4PlXFn6xIE1ghd1VpNP4ixD9mgxGMZiOslyd7LdN4AFKLl7GcK6a1cY+hISlj4RcDEbvJqCX5FCMEaIjV+bqxN74fwRrMW7vbY3QFFrn6sVi7da4TmPd9bQPP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YKo94zdzb00l4lgVz09laLujdNeS4mE/C9gqvVL7QOv+Xxh0Z+rkFmDkLz9kHITSa2I7HqrdeQIBDOAQaH25dIqu643Sx/CX5AJb2C1O/lxsH+jT7HQUZ4sxJTdF9D3t70vIoAlZuj3tmOWaQWqHcl+y7leUHLcDVVD+9K5m05denUPFVRR8FBM1G+W+1c7Yx3b1+c0rTMpm/ACb8KF9HvC1oukc67qa64DyALU+AuN7g1k3JLwznOjWb+Vs8/TOe+syehe3eXO51an7deCiSelh5Zv1ywAk6rquGedaaXoqe9JqyHH6jAM5/vwekvLYBiL83Kw71KQL3S5lWd6vzRvZLulwt17jVrZ2NW8KcI4G17NyR2ZMaI7p27A+fQ1AZXuazCeysyt7pUTK+Ltkwsilyd629oySZLhQTB6T5chOJQ1e7GbLx7j/86cicLUe2kBCFCtKohSd1MQIKciN7pC5xXaSbZTQrOMNQ+1mj0l/8LUEsHCPGPq0qnOAAAB6gAAFBLAQI/AxQAAAgIANyKDF3wGpfWBwMAALQJAAAWAAAAAAAAAAAAAAC0gQAAAABleHRlbnNpb24udnNpeG1hbmlmZXN0UEsBAj8DFAAACAgA3IoMXd+jDd+8AAAAZQEAABMAAAAAAAAAAAAAALSBOwMAAFtDb250ZW50X1R5cGVzXS54bWxQSwECPwMUAAgICABnigxdsylTaJoCAACkBQAAFgAAAAAAAAAAAAAApIEoBAAAZXh0ZW5zaW9uL3BhY2thZ2UuanNvblBLAQI/AxQACAgIABtt8FyyhnqNeQIAACcEAAAVAAAAAAAAAAAAAACkgQYHAABleHRlbnNpb24vTElDRU5TRS50eHRQSwECPwMUAAgICADcigxd8Y+rSqc4AAAHqAAAGwAAAAAAAAAAAAAApIHCCQAAZXh0ZW5zaW9uL2Rpc3QvZXh0ZW5zaW9uLmpzUEsFBgAAAAAFAAUAVQEAALJCAAAAAA==";var le="anyray.anyray-vscode",pT="vscode-handoffs",zb="vscode-receipts",Ms=2,fT=uT(oT),Tn={Code:{slug:"code",scheme:"vscode",macAppName:"Visual Studio Code",commands:["code","/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"]},"Code - Insiders":{slug:"code-insiders",scheme:"vscode-insiders",macAppName:"Visual Studio Code - Insiders",commands:["code-insiders","/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin/code-insiders"]},VSCodium:{slug:"vscodium",scheme:"vscodium",macAppName:"VSCodium",commands:["codium","/Applications/VSCodium.app/Contents/Resources/app/bin/codium"]}},hT={Code:{directory:"Microsoft VS Code",executable:"Code.exe"},"Code - Insiders":{directory:"Microsoft VS Code Insiders",executable:"Code - Insiders.exe"},VSCodium:{directory:"VSCodium",executable:"VSCodium.exe"}},mT=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),Qb=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&mT(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Fs=e=>{if(Qb(e))try{return new URL(e.trim()).origin}catch{return}},yT=(e,t)=>{if(!e.endsWith(".app"))return!1;let n=e.slice(0,-4);if(n===t)return!0;if(!n.startsWith(`${t} `))return!1;let r=n.slice(t.length+1);return r.length>0&&/^\d+$/.test(r)},gT=e=>{try{return aT(e)}catch{return[]}},wT=e=>{try{return sT(e).mtimeMs}catch{return}},bT=(e,t,n,r,o)=>{if(!Wr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=Tn[e].commands[0],s=Pn(t,Cs[e]),i=[];for(let{directory:c,suffix:l}of[{directory:Pn(s,"bin"),suffix:["bin","remote-cli"]},{directory:Pn(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=Pn(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)},kT=(e,t,n)=>{let{macAppName:r,commands:o}=Tn[e],a=o[0],s=[];for(let i of["/Applications",Gb.join(t,"Applications")])for(let c of n(i))yT(c,r)&&s.push(Gb.join(i,c,"Contents/Resources/app/bin",a));return s},CT=(e,t=Qp(),n=zo(),r=process.env,o=gT,a=wT)=>{let s=bT(e,n,r,o,a);if(t==="darwin")return[...new Set([...Tn[e].commands,...kT(e,n,o),...s])];if(t!=="win32"){let u=Tn[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=hT[e],c=dT.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)),Tn[e].commands[0],...s])]},ek={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:()=>iT(24).toString("base64url"),home:"",commandCandidates:e=>CT(e)},qo=(e,t)=>Pn(e,".anyray",zb,`${t}.json`),ef=(e,t)=>Pn(e,".anyray",zb,`${t}.applied.json`),tk=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&Nc(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},nk=async(e,t)=>{let n=await tk(e,t);if(n)try{let r=await t.run(n.command,["--list-extensions","--show-versions"]);if(typeof r?.stdout!="string")return;let o=r.stdout.split(/\r?\n/).map(a=>a.trim()).flatMap(a=>{let s=a.lastIndexOf("@");return s<=0?[]:a.slice(0,s).toLowerCase()===le.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===_n}catch{return}},rk=250,AT=9e4,vT=AT/rk,ST=async(e,t,n,r)=>{for(let o=0;o<vT;o++){try{let a=JSON.parse(await zr(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Ms&&a.action===n?"confirmed":a.extensionVersion!==_n||a.extensionDistSha256!==qr?"reload-required":a.version===Ms&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(rk)}return"timeout"},ET=200,jb=(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,ET))}return r.join(": ")},IT=async e=>{try{let t=await lT(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},Vb=e=>Yb("sha256").update(e).digest("hex"),xT=async(e=zo())=>{let t=Buffer.from(Kb,"base64");if(t.length<4||t[0]!==80||t[1]!==75||Vb(t)!==ul)throw new Error("bundled VS Code extension failed integrity validation");let n=Pn(e,".anyray","vscode-extension"),r=Pn(n,`anyray-vscode-${_n}-${ul.slice(0,12)}.vsix`);try{if(Vb(await zr(r))===ul)return r}catch{}await qp(n,{recursive:!0,mode:448});let o=`${r}.${Zb()}.tmp`;try{await zp(o,t,{mode:384}),await fe(o,r),Qp()!=="win32"&&await cT(r,384)}finally{await Xb(o,{force:!0})}return r},Jp=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=>Jp(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Jp(t[n])}`).join(",")}}`},ok=(e,t,n)=>Yb("sha256").update(Jp({gatewayUrl:Fs(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:_n,extensionDistSha256:qr,profiles:[...n].sort()})).digest("hex"),RT=async(e,t,n,r,o,a)=>{let s=JSON.parse(await zr(ef(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==ok(t,n,r))return!1;let i=JSON.parse(await zr(qo(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===_n&&i.extensionDistSha256===qr&&i.gatewayUrl===Fs(t.origin)?await nk(e,a)===!0:!1},OT=async(e,t,n,r)=>{let o=ef(e,t),a=`${o}.${Zb()}.tmp`;try{await qp(qb(o),{recursive:!0,mode:448}),await zp(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
109
|
-
`,{mode:384}),await fe(a,o)}catch{}finally{await
|
|
110
|
-
`,{mode:384});let
|
|
111
|
-
`,{flag:"wx",mode:384}),await fe(n,e),await PT(e,384)}finally{await LT(n,{force:!0}).catch(()=>{})}},tf=e=>{if(!At(e))return!1;let t=e,n=Object.keys(t).sort(),r=["apiType",...t.apiKey===void 0?[]:["apiKey"],"models","name","vendor"].sort();return n.length!==r.length||!n.every((o,a)=>o===r[a])||t.name!==yr||t.vendor!=="customendpoint"||t.apiType!=="chat-completions"||!(t.apiKey===void 0||typeof t.apiKey=="string"&&t.apiKey.length>0&&t.apiKey.length<=512&&!/[\u0000-\u001f\u007f]/.test(t.apiKey))||!Array.isArray(t.models)||t.models.length===0||t.models.length>64?!1:t.models.every(o=>{if(!At(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!==yk(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!At(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}})},nf=e=>{let t=e.filter(n=>!tf(n));return{next:t,removed:t.length!==e.length}},UT=async(e,t)=>{let n=Us(e),r=await pl(n);if(r.kind==="missing")return{changedFiles:[],messages:[],manual:!1};if(r.kind==="unrecognized")return{changedFiles:[],manual:!0,messages:[`Could not recognize ${n}; left it untouched. Remove the legacy "${yr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=nf(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${yr}" Custom Endpoint from ${n}.`]};try{return await gk(n,o),await ae(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${yr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${yr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},BT=async e=>{try{let t=mr(await pk(e,"utf-8"));if(At(t))return mk(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Bs}.${fl} 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 ${Bs}.${fl} value manually if present.`]}},wk=async(e,t)=>{let n=MT(e),r;try{r=await M(n)}catch{return BT(n)}let{next:o,removed:a}=mk(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 X(n,o,{backup:!1}),await ae(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.`]}}},HT=async(e,t)=>{let n=await UT(e,t),r=await wk(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},bk=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,hk]}},kk=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},Ck=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),WT=e=>Array.isArray(e.args)&&e.args.at(-1)===hk,Ak=(e,t)=>{if(!t.hookBinaryIsDurable()||!At(e)||!kk(e,["type","command","args"]))return!1;let n=bk(t);return e.type==="stdio"&&e.command===n.command&&Ck(e.args,n.args)},KT=(e,t)=>{if(!At(e)||!kk(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&&Ck(e.args,n.args))return!0;if(Ge(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===rr&&r.at(-1)==="profile"))return!1;let a=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(a))return r.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(a)||r.length!==3)return!1;let s=r[0].replaceAll("\\","/");return!Ge(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},rf=(e,t)=>Ak(e,t)?"exact":At(e)&&WT(e)||KT(e,t)?"stale-owned":"foreign",lk=e=>`MCP name conflict in ${e}: servers.${mn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,GT=async(e,t,n,r,o)=>{let a=await o.vscodeUserMcpConfigPaths(e,r),s=o.hookBinaryIsDurable(),i=n&&s,c=[],l=[],d=0,u=!1,f=[];for(let p of a)try{let h=await M(p);if(i){if("servers"in h&&!At(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=At(h.servers)?{...h.servers}:{},b=bk(o),A=y[mn],S=A===void 0?void 0:rf(A,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(lk(p));continue}if(t){d+=1;continue}y[mn]=b,f.push({path:p,next:{...h,servers:y},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!At(h.servers)||!(mn in h.servers))continue;if(rf(h.servers[mn],o)==="foreign"){u=!0,l.push(lk(p));continue}if(t)continue;let w={...h.servers};delete w[mn];let g={...h};Object.keys(w).length===0?delete g.servers:g.servers=w,f.push({path:p,next:g,backup:!1,clearBackupAfter:!0})}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${p} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let p of f)try{await X(p.path,p.next,p.backup?{}:{backup:!1}),p.clearBackupAfter&&await ae(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 (${ww}+).`),{changedFiles:c,messages:l,manual:u}},jT=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await R(c))try{let l=await M(c);if(!At(l.servers)||!(mn in l.servers)||rf(l.servers[mn],r)==="foreign"||(i+=1,t))continue;let d={...l.servers};delete d[mn];let u={...l};Object.keys(d).length===0?delete u.servers:u.servers=d,await X(c,u,{backup:!1}),await ae(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}},vk=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.`]:[]],Sk=()=>`${le} 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.)`,dk=e=>[`${le} 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."],Ek=(e,t,n,r)=>({runMcp:o=>GT(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):HT(e,o)}),Ik=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${le} 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 ${le} 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 ${le} 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 ${le} 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 ${fp} 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 ${le} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${le} 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.`:`${le} 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 ${le} ${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 ${le} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},VT=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${le} 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 ${le} 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 ${le} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${le} 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 ${le} 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 ${le} 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 ${le} 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 ${le} 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 ${le} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},YT=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Ek(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required for the authenticated Anyray VS Code provider. Re-run anyray-connect with --enroll, then apply Copilot again."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${le} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...dk(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${le}; 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:[Ik(d.reason,e,a,"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?[Sk()]:[],...dk(t),...d.alreadyCurrent?[]:vk(d.profiles),...f.messages,...u.messages]}},uk=e=>[`${le} 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: ${Ws().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."],ZT=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Ek(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 ${le} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...uk(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${le}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Ws().map(p=>({id:p,name:yk(p)}))});if(!d.ok)return{status:"manual",messages:[Ik(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?[Sk()]:[],...uk(t),...d.alreadyCurrent?[]:vk(d.profiles),...f.messages,...u.messages]}},XT=async(e,t,n)=>{let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null};let o=[];for(let s of r){if(!await R(s))return{registered:!1,command:null};try{let i=await M(s),c=At(i.servers)?i.servers[mn]:void 0;if(!Ak(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 JT=async(e={installedVariant:$c,remoteServerVariant:yp,isRemoteDevContext:Wr})=>{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}},qT={installedVariant:$c,remoteServerVariant:yp,detectVscodeLmProviderEligibility:Ew,configureVscodeExtension:ak,vscodeExtensionPointsAt:ck,vscodeExtensionAwaitingReload:sk,vscodeExtensionReceiptMode:ik,hookBinaryIsDurable:ce,hookBinaryPath:Re,mcpServerCommand:je,vscodeUserMcpConfigPaths:vw,isRemoteDevContext:Wr},zT=(e={})=>{let t={...qT,...e},n=()=>JT(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:$s,quitTarget:dl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Vo(r,!0)}`:Us(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Ie(r.clientKey))return{status:"manual",messages:["Enrollment required: Copilot setup needs a personal ark_ gateway key. Re-run anyray-connect with --enroll or --sso; no VS Code configuration was written."]};let{variant:a,remote:s}=await n();if(!a)return{status:"manual",messages:[t.isRemoteDevContext()?"No VS Code server found here yet \u2014 this looks like a dev container, Codespace, or SSH remote. `--tools copilot` now configures the Anyray provider directly in a remote VS Code window, but only after VS Code has attached to this machine and installed its server. Open this machine with the VS Code Remote-SSH (or Dev Containers) extension, then re-run anyray-connect --tools copilot in that window\u2019s integrated terminal. To route this shell through Anyray without the Copilot UI, use an in-container tool instead: anyray-connect --tools opencode --sso <link> --subscription.":"No VS Code install found. Install VS Code, then re-run anyray-connect; the personal key will be transferred directly into SecretStorage."]};let i=await t.detectVscodeLmProviderEligibility(a);if(i.status==="needs-update")return{status:"manual",messages:[`${a} ${i.version??""} cannot expose public third-party models in Chat's picker. Upgrade to VS Code ${fp} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||bw(i.version);return J(r,"copilot")?YT(a,r,o,t.configureVscodeExtension,c,s,t):ZT(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?XT(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Fs(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await pl(Us(o));if(s.kind==="array"){let c=s.entries.find(tf)?.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 pl(Us(r));if(o.kind==="array"&&o.entries.some(tf))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 jT(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await wk(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${le} 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 ${le} gateway configuration and secret.`)):(l=!0,u.push(VT(y.reason,o,a,y.detail)))}let f=Us(o),p=await pl(f),h=p.kind==="missing"||p.kind==="array"&&!nf(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 "${yr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=nf(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${yr} Custom Endpoint from ${f}`]};await gk(f,w);let g=[...u,`Removed the ${yr} Custom Endpoint from ${f}.`];return await ae(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...m,f],messages:g}}}},xk=zT();import{accessSync as kL,constants as Fk,statSync as CL}from"node:fs";import{readFile as Uk,rm as Gs}from"node:fs/promises";import{homedir as hf,platform as Vk}from"node:os";import{delimiter as AL,join as mf,resolve as vL}from"node:path";import{execFile as rL}from"node:child_process";import{readFile as oL}from"node:fs/promises";import{homedir as sf,platform as aL}from"node:os";import{join as Ks}from"node:path";import{join as QT}from"node:path";var of="Iv1.b507a08c87ecfe98",eL="https://github.com/login/device/code",tL="https://github.com/login/oauth/access_token",nL="read:user",Rk=1e4,Qo=()=>QT(ee(),"copilot-seat-login.json"),Ok={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},af=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_k=async(e={})=>{let t={...Ok,...e};try{let n=await t.fetch(eL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:of,scope:nL}),signal:AbortSignal.timeout(Rk)});if(!n.ok)return;let r=await n.json();if(!af(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}},Pk=async(e,t={})=>{let n={...Ok,...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(tL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:of,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(Rk)})).json();if(!af(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"}},Tk=async(e,t)=>{let n=Qo();return await he(n,`${JSON.stringify({token:e,clientId:of,mintedAtIso:t},null,2)}
|
|
112
|
-
`),n},hl=async()=>{try{let e=await M(Qo());if(!
|
|
113
|
-
`))}`]:[],`export ${wl}=${ve(n)}`]},
|
|
114
|
-
`).map(
|
|
115
|
-
`)):Y&&
|
|
102
|
+
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");qw(o?.slice(1).map(Number))},K_=(e,t)=>{let n=N_(zw(U_(),"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=${zc(a.key)};`;let i=zw(n,`value-${s}`);return M_(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${zc(a.key)}, CAST(readfile(${zc(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
|
|
103
|
+
`);qc("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Lp,stdio:["pipe","ignore","pipe"]})}finally{try{$_(n,{recursive:!0,force:!0})}catch{}}},G_={kind:"sqlite3-cli",readItem:(e,t)=>eb(e,t),checkpointWal:e=>tb(e),mutateRows:K_},j_=()=>{try{let t=F_(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},Pp=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},V_=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),Y_=e=>({kind:"node-sqlite",readItem:(t,n)=>Pp(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:V_(o.value)}),checkpointWal:t=>Pp(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);qw(o)}),mutateRows:(t,n)=>Pp(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}})}),Xc,Rs=()=>{if(Xc!==void 0)return Xc;let e=j_();return Xc=e?Y_(e):Qw()?G_:null,Xc};import{spawn as Z_}from"node:child_process";import{randomUUID as nb}from"node:crypto";import{constants as rb}from"node:fs";import{chmod as J_,copyFile as ob,mkdir as X_,readdir as z_,readFile as q_,rename as Q_,rm as Os,writeFile as eT}from"node:fs/promises";import{join as Dp}from"node:path";var Np=/^[a-z0-9][a-z0-9-]{0,31}$/,tT=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,ab=/^[a-z0-9][a-z0-9-]{0,31}$/,nT=/^[0-9TZ:.+-]{1,40}$/,$p=()=>Dp(ee(),"pending"),el=e=>{if(!Np.test(e)||tT.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Dp($p(),`${e}.json`)},sb=()=>Dp(ee(),"cursor-pending.json"),rT=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),oT=(e,t)=>{if(!rT(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!Np.test(n)||typeof e.op!="string"||!ab.test(e.op)||typeof e.requestedAt!="string"||!nT.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}:{}}},Mp=async(e,t)=>{try{return oT(JSON.parse(await q_(e,"utf-8")),t)}catch{return}},ib=async()=>{let e=sb(),t=await Mp(e,"cursor");if(!t)return;let n=!1;try{await cb(),await ob(e,el("cursor"),rb.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await Os(e,{force:!0})}catch{}return t},tl=async e=>{let t=await Mp(el(e),e);return t||(e==="cursor"?ib():void 0)},pr=async()=>{let e;try{e=await z_($p())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!Np.test(r))continue;let o=await tl(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await ib();n&&t.push(n)}return t},cb=async()=>{await bt();let e=$p();await X_(e,{recursive:!0,mode:448});try{await J_(e,448)}catch{}},Qc=async e=>{await cb();let t=el(e.adapter),n=`${t}.${process.pid}.tmp`;await eT(n,`${JSON.stringify(e)}
|
|
104
|
+
`,{mode:384}),await fe(n,t)},aT=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,fr=async(e,t)=>await Fp(e,t)==="claimed",Fp=async(e,t)=>{let n=el(e);if(t){let o=`${n}.${process.pid}.${nb()}.claimed`;try{await Q_(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Mp(o,e);if(a&&aT(a,t))return await Os(o,{force:!0}),"claimed";let s=!1;try{await ob(o,n,rb.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await Os(o,{force:!0})}return"superseded"}let r=!1;try{await Os(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await Os(sb(),{force:!0})}catch{}return r?"claimed":"absent"},hr=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},sT=e=>{let{command:t,args:n}=fn("__anyray-quit-watch");return{exe:t,args:[...n,e]}},iT=e=>{let{exe:t,args:n}=sT(e),r=Z_(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},lb=iT;var db=async()=>{let e=[],t;try{t=await pr()}catch{return e}for(let n of t)if(!hr(n.watcherPid))try{let r=lb(n.adapter);if(!r)continue;await Qc({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},_s=async(e,t)=>{if(!ab.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await tl(e),r=new Date().toISOString(),o=nb();if(n&&hr(n.watcherPid))return await Qc({...n,adapter:e,op:t,requestedAt:r,generation:o}),{watcherPid:n.watcherPid,alreadyWatching:!0};await Qc({version:1,adapter:e,op:t,requestedAt:r,generation:o});let a;try{a=lb(e)}catch{a=void 0}return a&&await Qc({version:1,adapter:e,op:t,requestedAt:r,watcherPid:a,generation:o}),{watcherPid:a,alreadyWatching:!1}};import{spawn as cT,spawnSync as pb}from"node:child_process";import{existsSync as nl}from"node:fs";import{homedir as lT,platform as mr}from"node:os";import{join as fb,win32 as ub}from"node:path";var hb=(e,t={})=>{let n=t.env??process.env,r=t.exists??nl,o=(t.home??lT)(),a={localAppData:n.LOCALAPPDATA??ub.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=ub.join(i,s.path);if(r(c))return c}},Xr=/^[A-Za-z0-9 ._-]{1,64}$/,dT=/^[A-Za-z0-9.-]{1,128}$/,rl=e=>e.darwinBundleId&&dT.test(e.darwinBundleId)?e.darwinBundleId:void 0,mb=(e,t=mr())=>t==="darwin"?rl(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",yb=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",gb=(e,t=mr(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return hb(e,r)!==void 0;let o=e.linuxProcess;return!o||!Xr.test(o)?!1:n.split(":").filter(Boolean).some(a=>nl(fb(a,o)))},wb=(e,t=mr())=>{if(t==="darwin"&&rl(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Xr.test(n))},bb=1e4,Ts=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=fb(t,"System32",e);return nl(n)?n:e},uT=e=>{let t=`/usr/bin/${e}`;return nl(t)?t:e},pT=(e,t)=>{try{let n=pb(e,t,{encoding:"utf-8",timeout:bb,windowsHide:!0,...mr()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:mr()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},fT=e=>new Promise(t=>setTimeout(t,e)),kb=(e,t={})=>{let n=t.runtimePlatform??mr(),r=t.run??pT;if(n==="darwin"){let a=rl(e);if(a&&r("/usr/bin/osascript",["-e",`if application id "${a}" is running then tell application id "${a}" to quit`]))return!0;let s=e.darwinAppName;return!s||!Xr.test(s)?!1:r("/usr/bin/osascript",["-e",`if application "${s}" is running then tell application "${s}" to quit`])}if(n==="win32"){let a=e.win32Image;return!a||!Xr.test(a)?!1:r(Ts("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Xr.test(o)?!1:r(uT("pkill"),["-TERM","-o","-x",o])},Cb=async(e,t=2e4,n={})=>{let r=n.sleep??fT,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},hT=(e,t,n={})=>{let r=mr();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=pb(e,t,{stdio:"ignore",timeout:bb,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=cT(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},Ab=(e,t={})=>{let n=t.runtimePlatform??mr(),r=t.launch??hT;if(n==="darwin"){let a=rl(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!Xr.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=hb(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!Xr.test(o)?!1:r(o,[])};var ST={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"}]},ET=e=>e==="apply"||e==="native"||e==="revert",Tb=()=>rt("Cursor"),zr=()=>zo(Tb(),"User","globalStorage","state.vscdb"),Ls=()=>`${zr()}.anyray-bak.json`,Xo=()=>`${zr()}.anyray-bak`,Je="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",it="cursorAuth/openAIKey";var Wp="/seat/cursor",Yp="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.",Ps=zo(".cursor","rules","anyray.mdc"),Pb="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",IT=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",Pb,"",Yp,""].join(`
|
|
105
|
+
`),xT=e=>{let t=vT(e);for(;;){if(Se(zo(t,".git")))return t;let n=_b(t);if(n===t)return null;t=n}},RT=e=>e.authMode!=="placeholder",Qt=()=>zo(Ob(),".cursor","hooks.json"),en=()=>zo(Ob(),".cursor","mcp.json"),Mt="anyray",Lb="--anyray-owner=cursor-v1",OT="postToolUse",_T="beforeSubmitPrompt",vb="preToolUse",TT="^MCP:",PT="UserPromptSubmit",LT="Shell",DT="^(Read|Grep)$",cl="--anyray-owner=cursor-hook-v1",qr=[{event:OT,flag:Ze,trailingArgs:["cursor"],matcher:TT},{event:_T,flag:nr,trailingArgs:[],matcher:PT},{event:vb,flag:Dg,trailingArgs:[],matcher:LT},{event:vb,flag:Ng,trailingArgs:[],matcher:DT}];var Sb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},NT=(e,t,n)=>mT(e,t,n),Eb=NT,$T,MT=()=>{let e=$T??AT();if(e==="win32"){let t=Eb(Ts("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],Sb);return t.error||t.signal||t.status!==0?!0:/(?:^|\r?\n)"Cursor\.exe",/iu.test(t.stdout??"")}for(let t of e==="linux"?["cursor","Cursor"]:["Cursor"]){let n=Eb("pgrep",["-x",t],Sb);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},FT=MT,sl=()=>FT();var UT=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,Je)??null,openAIKey:e.readItem(n,it)??null,lastWritten:r};Vp(t,`${JSON.stringify(o,null,2)}
|
|
106
|
+
`,{encoding:"utf-8",flag:"wx",mode:384})},Db=(e,t)=>{let n=`${e}.${process.pid}.tmp`;Vp(n,`${JSON.stringify(t,null,2)}
|
|
107
|
+
`,{encoding:"utf-8",flag:"wx",mode:384});try{CT(n,e)}catch(r){throw mn(n,{force:!0}),r}},BT=(e,t)=>{let n=Zo(e);Db(e,{...n,lastWritten:t})},oe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ib=e=>oe(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Zo=e=>{let t=Rb(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(oe(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||oe(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(!oe(n)||n.version!==1||!oe(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Je],o=n.rows[it];if(!Ib(r)||!Ib(o))throw new Error("Cursor value backup is missing an exact managed row");return{applicationUser:r.exists?r.value:null,openAIKey:o.exists?o.value:null}},xb=e=>{let t=Buffer.alloc(16),n=bT(e,"r");try{return kT(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{yT(n)}},WT=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return oe(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Nb=e=>{let t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".lan")||t.endsWith(".internal")||t.endsWith(".home")||!t.includes(".")&&Up(t)===0||t==="0.0.0.0")return!0;if(Up(t)===4){let[n,r,o]=t.split(".").map(Number);return n===10||n===0||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===192&&r===0&&(o===0||o===2)||n===198&&(r===18||r===19)||n===198&&r===51&&o===100||n===203&&r===0&&o===113||n>=224}if(Up(t)===6){let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(n){let r=Number.parseInt(n[1],16),o=Number.parseInt(n[2],16);return Nb(`${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},Hp=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Nb(t.hostname)}catch{return!1}},HT=e=>{try{let t=new URL(e);return t.protocol==="http:"&&t.hostname==="127.0.0.1"}catch{return!1}},KT=e=>({...e,openaiBaseUrl:(()=>{try{let t=new URL(e.openaiBaseUrl);return t.protocol==="http:"&&t.hostname==="127.0.0.1"?`${Ye(e.origin)}/v1${Wp}`:`${e.openaiBaseUrl.replace(/\/+$/,"")}${Wp}`}catch{return e.openaiBaseUrl.replace(/\/+$/,"")}})()}),Jo=(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."],$b=()=>{let e=zr();if(!Se(e))return"clear";let t=Rs();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Je)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return oe(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},GT=(e,t)=>{if(!Hp(e))return{routed:!1,problem:"gateway-not-public-https"};let n=zr();if(!Se(n))return{routed:!1,problem:"state-db-missing"};let r=Rs();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Je),a=r.readItem(n,it)}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(!oe(s))return{routed:!1,problem:"settings-malformed"};let i=`${Ye(e)}/v1${Wp}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Ie(a)||!Ie(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},jT=(e,t=[])=>({command:Pt(e,[...t,cl])}),Zp=(e,t,n)=>{if(!oe(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Pt(t,[...n,cl])||r===Pt(t,n)||r.endsWith(` ${cl}`)&&r.includes(` ${t} `)},VT=(e,t)=>oe(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),Mb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Zp(a,t,n)){r=!0;continue}if(!oe(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!VT(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}},Jp=(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},Fb=(e,t,n,r,o)=>oe(e.hooks)&&Jp(e.hooks,t).some(a=>oe(a)&&a.matcher===o&&Zp(a,n,r)),YT=(e,t,n,r,o)=>oe(e.hooks)&&Jp(e.hooks,t).some(a=>oe(a)&&a.matcher===o&&Zp(a,n,r)&&mc(a.command,n,[...r,cl])),Ub=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!oe(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=oe(e.hooks)?{...e.hooks}:{},{entries:s}=Mb(Jp(a,t),n,r);return s.push({...jT(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},ZT=(e,t,n,r=[])=>{if(!oe(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=Mb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},JT=async()=>{let e=Qt();if(!ce()){let t=await Wb();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 M(e);for(let n of qr)t=Ub(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}}},il=()=>{let e=je("profile");return{command:e.command,args:[...e.args,Lb]}},Kp=e=>oe(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===il().command&&e.args.length===il().args.length&&e.args.every((t,n)=>t===il().args[n]),XT=e=>{if(!oe(e)||Object.keys(e).some(o=>o!=="command"&&o!=="args")||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(o=>typeof o=="string")||Ge(e.command))return!1;let t=e.args;if(t.at(-2)!==or||t.at(-1)!=="profile")return!1;let n=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(n))return t.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(n)||t.length!==3)return!1;let r=t[0].replaceAll("\\","/");return!Ge(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},ll=e=>oe(e)&&Array.isArray(e.args)&&e.args.at(-1)===Lb||XT(e),zT=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,qT=async()=>{if(!ce())return Bb();let e=en();try{let t=await M(e);if(t.mcpServers!==void 0&&!oe(t.mcpServers))throw new Error("mcpServers is not an object");let n=oe(t.mcpServers)?{...t.mcpServers}:{},r=n[Mt];return r!==void 0&&!ll(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Mt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Mt]=il(),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}}},Bb=async()=>{let e=en();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e);if(!oe(t.mcpServers)||!(Mt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!ll(t.mcpServers[Mt]))return{changedFiles:[],messages:[`Preserved the foreign ${Mt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Mt];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}}},Wb=async()=>{let e=Qt();if(!await R(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e),n=t;for(let r of qr)n=ZT(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}}},QT=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=xT(e);if(!n)return t;let r=zo(n,Ps),o=IT();try{if(Se(r)){let a=Rb(r,"utf8");if(a===o)return t;if(!a.includes(Pb))return{...t,messages:[`Left ${Ps} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Yp}"`]}}return wT(_b(r),{recursive:!0}),Vp(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Ps} 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 ${Ps} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Hb=async()=>{let e=await JT(),t=await qT(),n=await QT();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Gp=async()=>{let e=await Wb(),t=await Bb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},Kb=async()=>{if(!ce()){let e=await Gp();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 M(Qt());for(let r of qr)e=Ub(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await M(en());if(t.mcpServers!==void 0&&!oe(t.mcpServers))throw new Error("mcpServers is not an object");let n=oe(t.mcpServers)?t.mcpServers[Mt]:void 0;return n!==void 0&&!ll(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${en()} already contains a foreign ${Mt} 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 ${Qt()} and ${en()}, then re-run Connect.`],complete:!1}}},eP=async()=>{if(!ce())return!1;try{let e=await M(Qt());if(!oe(e.hooks)||!qr.every(r=>Fb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await M(en()),n=oe(t.mcpServers)?t.mcpServers[Mt]:void 0;return Kp(n)}catch{return!1}},Gb=["openAIBaseUrl","useOpenAIKey"],Ds=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!oe(t))throw new Error("Cursor application-user settings are not an object");return t},tP=(e,t,n)=>{let r=Ds(e),o=Ds(t??void 0),a=n===void 0?void 0:Ds(n),s={...r},i=[];for(let c of Gb){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:Je}:{key:Je,value:JSON.stringify(s)},conflicts:i}},Bp=(e,t)=>{let n=Ds(e),r=Ds(t??void 0),o={...n};for(let a of Gb)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Je}:{key:Je,value:JSON.stringify(o)}},ol=e=>typeof e=="string"&&e.startsWith("ark_"),al=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);oe(o)&&(n=o)}catch{}let r=ol(t)||n!==null&&(ol(n.useOpenAIKey)||ol(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,ol(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}},st=(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.",...Jo(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.",...Jo(e)]},jp=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!ce())return n;if(t.dryRun)return{status:"queued",messages:[`Cursor is running \u2014 would queue the ${o} and complete it automatically when Cursor quits.`]};let a;try{a=await _s("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]}},nP=async(e,t)=>{if(!Ie(e.clientKey))return{status:"manual",messages:["Cursor native subscription mode was not changed: a valid personal ark_ gateway key is required for Anyray hooks and MCP retrieval."]};if(!t.dryRun&&!t.preservePendingOp)try{await fr("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 Kb();if(!n.complete)return{status:"manual",messages:n.messages};let r=Se(Ls())||Se(Xo());if(r&&sl())return jp("native",t,{status:"manual",messages:["Cursor is running \u2014 fully quit it and re-run so Connect can restore the journaled BYOK override before enabling native subscription mode."]},["No native Claude/Opus request will be redirected: the queued operation restores Cursor\u2019s prior settings, then installs only Anyray hooks/MCP."]);if(!r){let c=$b();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(Xo())?Xo():Ls()}, 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 ${Qt()}, and register the Anyray retrieval MCP server in ${en()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Ns.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 Hb(),s=[];if(!t.preservePendingOp)try{await fr("cursor")}catch{s.push("Could not clear Cursor's stale queue marker.")}return{status:a.complete&&s.length===0?"configured":"manual",changedFiles:[...new Set([...o?.changedFiles??[],...a.changedFiles])],messages:[...o?.messages??[],"Kept Cursor's native Team sign-in and Claude/Opus model route; no Anyray OpenAI override or model credential was written.",...a.messages,...s,"Claude/Opus inference remains Cursor-hosted and will not produce gateway inference traces. Anyray records content-free hook savings only when a supported oversized Shell/MCP result is actually reduced.",`Make it seamless org-wide: paste this into Cursor's dashboard Team Rules and mark it Required, so every member's agent uses Anyray's tools without being asked -- "${Yp}" (connect already writes ${Ps} 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."]}},Ns={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>sl(),quitTarget:ST,needsTarget:e=>e!=="revert",async complete(e,t,n){return ET(e)?e!=="revert"&&t?Ns.apply(t,n):Ns.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=Tb(),t=Se(e);return{installed:t,detail:t?zr():"Cursor user dir not found"}},async watchPaths(){return[Qt(),en()]},async mcpStatus(){let e=en();if(!await R(e))return{registered:!1,command:null};try{let t=await M(e),n=oe(t.mcpServers)?t.mcpServers[Mt]:void 0;return Kp(n)?{registered:!0,command:zT(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=Qt();if(!await R(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!oe(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(qr.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=qr.every(c=>Fb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=qr.every(c=>YT(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=en();if(!await R(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!oe(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Mt];r=i===void 0?"missing":ll(i)?"owned":"foreign",r==="owned"&&(o=Kp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Br()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await P();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(RT(e))return nP(e,t);let n=KT(e),r=HT(e.openaiBaseUrl),o=zr(),a=Ls(),s=Xo();if(!Ie(e.clientKey))return{status:"manual",messages:st(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(!Hp(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.",...Jo(n)]});let l=await Kb();if(!l.complete)return{status:"manual",messages:l.messages};let d=Rs();if(!d)return c({status:"manual",messages:st(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:st(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:st(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{xb(s)?u="sqlite":(Zo(s),u="value")}catch{u=null}if(!u)return c({status:"manual",messages:st(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=Zo(a)}catch{return c({status:"manual",messages:st(n,`Existing Cursor backup at ${a} is invalid \u2014 refusing to write or replace recovery data.`)})}if(sl())return c(await jp("apply",t,{status:"manual",messages:st(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Jo(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 ${Qt()}, and register the Anyray retrieval MCP server in ${en()}.`,...Jo(n,r)]};if(u){try{d.checkpointWal(o)}catch(b){return c({status:"manual",messages:st(n,`Couldn't checkpoint Cursor's state DB at ${o} while migrating the legacy Anyray backup at ${s}${xs(b)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(u==="sqlite")y=al(d.readItem(s,Je)??null,d.readItem(s,it)??null);else{let b=Zo(s);y=al(b.applicationUser,b.openAIKey)}}catch{return c({status:"manual",messages:st(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,[Bp(d.readItem(o,Je),y.applicationUser),y.openAIKey===null?{key:it}:{key:it,value:y.openAIKey}])}catch{return c({status:"manual",messages:st(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{mn(s,{force:!0}),mn(`${s}-wal`,{force:!0}),mn(`${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:st(n,`Couldn't checkpoint Cursor's state DB at ${o}${xs(y)} \u2014 refusing to write; set it by hand:`)})}let h;try{h=d.readItem(o,Je)}catch{return c({status:"manual",messages:st(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let m=WT(h,n);if(!m)return c({status:"manual",messages:st(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{BT(a,w)}catch{return c({status:"manual",messages:st(n,`Couldn't update three-way ownership in the protected Cursor backup at ${a} \u2014 refusing to write; set it by hand:`)})}else try{UT(d,a,o,w)}catch{return c({status:"manual",messages:st(n,`Couldn't create the protected Cursor value backup at ${a} \u2014 refusing to write; set it by hand:`)})}try{d.mutateRows(o,[{key:Je,value:m.value},{key:it,value:e.clientKey}])}catch{let y=!0;if(p)try{Db(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 Hb();let g=[];if(!t.preservePendingOp)try{await fr("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,...Jo(n,r),"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await P().catch(()=>{}),n=e;if(!Hp(n)){let o=t&&tt(t)&&Number.isInteger(t.fallbackPort)?`http://127.0.0.1:${t.fallbackPort}`:void 0;t?.gateway&&o&&Ye(n)===o&&(n=t.gateway)}let r=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Se(Ls())||Se(Xo())||$b()!=="clear"?!1:eP():GT(n,r).routed},async revert(e){let t=zr(),n=Ls(),r=Xo(),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 ${Qt()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${Qt()} and unregister its owned retrieval MCP server.`]};if((o||a)&&sl()){if(e.fullRevert){let h=await Gp(),m=!0;try{await fr("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 jp("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=Rs(),i=!1,c=!1,l,d=[];if(a)try{if(xb(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=al(s.readItem(r,Je)??null,s.readItem(r,it)??null);s.mutateRows(t,[Bp(s.readItem(t,Je),h.applicationUser),h.openAIKey===null?{key:it}:{key:it,value:h.openAIKey}]),c=!0}else i=!0,gT(r,t),mn(`${t}-wal`,{force:!0}),mn(`${t}-shm`,{force:!0});else{let h=Zo(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=al(h.applicationUser,h.openAIKey);s.mutateRows(t,[Bp(s.readItem(t,Je),m.applicationUser),m.openAIKey===null?{key:it}:{key:it,value:m.openAIKey}]),c=!0}}catch(h){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${xs(h)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Zo(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=tP(s.readItem(t,Je),l.applicationUser,l.lastWritten?.applicationUser);d.push(...h.conflicts);let m=[h.mutation],w=s.readItem(t,it);l.lastWritten&&w===l.lastWritten.openAIKey?m.push(l.openAIKey===null?{key:it}:{key:it,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,m)}catch(h){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${xs(h)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{mn(r,{force:!0}),mn(`${r}-wal`,{force:!0}),mn(`${r}-shm`,{force:!0}),mn(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 fr("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let p=await Gp();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 UP,mkdir as BP,readFile as yk,rm as WP,writeFile as HP}from"node:fs/promises";import{randomUUID as KP}from"node:crypto";import{dirname as GP,join as gk}from"node:path";var rP=e=>{let t="",n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){t+=o,o==="\\"&&r+1<e.length?(t+=e[r+1],r+=1):o==='"'&&(n=!1);continue}if(o==='"'){n=!0,t+=o;continue}if(o==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
|
|
108
|
+
`;)r+=1;r-=1;continue}if(o==="/"&&e[r+1]==="*"){let a=e.indexOf("*/",r+2);r=a===-1?e.length:a+1,t+=" ";continue}t+=o}return t},oP=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},yr=e=>JSON.parse(oP(rP(e)));import{spawnSync as aP}from"node:child_process";import{platform as sP}from"node:os";var jb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},iP=(e,t,n)=>aP(e,t,n),Vb=iP,cP,lP=()=>{let e=cP??sP();if(e==="win32"){let n=Vb(Ts("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],jb);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=Vb("pgrep",[n,r],jb);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},dP=lP,$s=()=>dP();var dl={darwinAppName:"Visual Studio Code",darwinBundleId:"com.microsoft.VSCode",win32Image:"Code.exe",linuxProcess:"code",win32Install:[{root:"localAppData",path:"Programs\\Microsoft VS Code\\Code.exe"},{root:"programFiles",path:"Microsoft VS Code\\Code.exe"},{root:"programFilesX86",path:"Microsoft VS Code\\Code.exe"}]};import{execFile as uP}from"node:child_process";import{readdirSync as pP,statSync as fP}from"node:fs";import{createHash as zb,randomBytes as hP,randomUUID as qb}from"node:crypto";import{chmod as mP,lstat as Qb,mkdir as Qp,readdir as yP,readFile as Ln,rm as ek,unlink as ef,writeFile as tf}from"node:fs/promises";import{homedir as qo,platform as nf}from"node:os";import{dirname as Xp,join as tn,posix as Zb,win32 as gP}from"node:path";import{promisify as wP}from"node:util";var yn="0.1.23";var gr="31112ab5ee55ece527cade12d2845cf6016ca0d94eb733727e7045af98442ea1",ul="7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1xITzuznDYmCn+KJp63N0hshqbt6s5R3Lc+Tm14pRcrvDdSdKtLyQe7eEv5osjkUf+WlvlkKbHAGd2Hu1Esrtrd6L34oEZABfOkAaqt4MB5gFY15K2bcciZE9J7dafzKklFfpuAfww1jzUa/uX/AlBLBwhJWCqlszgAABqoAABQSwECPwMUAAAICABHqQxdO1mCNAgDAAC0CQAAFgAAAAAAAAAAAAAAtIEAAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdFBLAQI/AxQAAAgIAEepDF3fow3fvAAAAGUBAAATAAAAAAAAAAAAAAC0gTwDAABbQ29udGVudF9UeXBlc10ueG1sUEsBAj8DFAAICAgARakMXbkkqLuaAgAApAUAABYAAAAAAAAAAAAAAKSBKQQAAGV4dGVuc2lvbi9wYWNrYWdlLmpzb25QSwECPwMUAAgICABppwxdsoZ6jXkCAAAnBAAAFQAAAAAAAAAAAAAApIEHBwAAZXh0ZW5zaW9uL0xJQ0VOU0UudHh0UEsBAj8DFAAICAgAR6kMXUlYKqWzOAAAGqgAABsAAAAAAAAAAAAAAKSBwwkAAGV4dGVuc2lvbi9kaXN0L2V4dGVuc2lvbi5qc1BLBQYAAAAABQAFAFUBAAC/QgAAAAA=";var le="anyray.anyray-vscode",tk="vscode-handoffs",nk="vscode-receipts",Ms=2,bP=wP(uP),Pn={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"]}},kP={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"}},CP=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),rk=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&CP(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Fs=e=>{if(rk(e))try{return new URL(e.trim()).origin}catch{return}},AP=(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)},vP=e=>{try{return pP(e)}catch{return[]}},SP=e=>{try{return fP(e).mtimeMs}catch{return}},EP=(e,t,n,r,o)=>{if(!Gr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=Pn[e].commands[0],s=tn(t,Cs[e]),i=[];for(let{directory:c,suffix:l}of[{directory:tn(s,"bin"),suffix:["bin","remote-cli"]},{directory:tn(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=tn(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)},IP=(e,t,n)=>{let{macAppName:r,commands:o}=Pn[e],a=o[0],s=[];for(let i of["/Applications",Zb.join(t,"Applications")])for(let c of n(i))AP(c,r)&&s.push(Zb.join(i,c,"Contents/Resources/app/bin",a));return s},xP=(e,t=nf(),n=qo(),r=process.env,o=vP,a=SP)=>{let s=EP(e,n,r,o,a);if(t==="darwin")return[...new Set([...Pn[e].commands,...IP(e,n,o),...s])];if(t!=="win32"){let u=Pn[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=kP[e],c=gP.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)),Pn[e].commands[0],...s])]},ok={run:async(e,t)=>({stdout:(await bP(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>hP(24).toString("base64url"),home:"",commandCandidates:e=>xP(e)},Qr=(e,t)=>tn(e,".anyray",nk,`${t}.json`),rf=(e,t)=>tn(e,".anyray",nk,`${t}.applied.json`),ak=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&Nc(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},zp=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()===le.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===yn}catch{return}},sk=async(e,t)=>{let n=await ak(e,t);if(n)return zp(n.command,t)},RP=async(e,t,n)=>{let r=tn(e,".anyray",tk);for(let o of n){if(!o.endsWith(".json"))continue;let a=tn(r,o);try{if(!(await Qb(a)).isFile()||JSON.parse(await Ln(a,"utf8")).variant!==t)continue;await ef(a)}catch{}}},OP=async(e,t)=>{try{let n=JSON.parse(await Ln(Qr(e,t),"utf8"));return n.extensionVersion===yn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==gr}catch{return!1}},ik=250,_P=9e4,TP=_P/ik,PP=async(e,t,n,r)=>{for(let o=0;o<TP;o++){try{let a=JSON.parse(await Ln(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Ms&&a.action===n?"confirmed":a.extensionVersion!==yn||a.extensionDistSha256!==gr?"reload-required":a.version===Ms&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(ik)}return"timeout"},LP=200,Jb=(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,LP))}return r.join(": ")},DP=async e=>{try{let t=await Qb(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},Xb=e=>zb("sha256").update(e).digest("hex"),NP=async(e=qo())=>{let t=Buffer.from(Yb,"base64");if(t.length<4||t[0]!==80||t[1]!==75||Xb(t)!==ul)throw new Error("bundled VS Code extension failed integrity validation");let n=tn(e,".anyray","vscode-extension"),r=tn(n,`anyray-vscode-${yn}-${ul.slice(0,12)}.vsix`);try{if(Xb(await Ln(r))===ul)return r}catch{}await Qp(n,{recursive:!0,mode:448});let o=`${r}.${qb()}.tmp`;try{await tf(o,t,{mode:384}),await fe(o,r),nf()!=="win32"&&await mP(r,384)}finally{await ek(o,{force:!0})}return r},qp=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=>qp(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${qp(t[n])}`).join(",")}}`},ck=(e,t,n)=>zb("sha256").update(qp({gatewayUrl:Fs(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:yn,extensionDistSha256:gr,profiles:[...n].sort()})).digest("hex"),$P=async(e,t,n,r,o,a)=>{let s=JSON.parse(await Ln(rf(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==ck(t,n,r))return!1;let i=JSON.parse(await Ln(Qr(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===yn&&i.extensionDistSha256===gr&&i.gatewayUrl===Fs(t.origin)?await sk(e,a)===!0:!1},MP=async(e,t,n,r)=>{let o=rf(e,t),a=`${o}.${qb()}.tmp`;try{await Qp(Xp(o),{recursive:!0,mode:448}),await tf(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
109
|
+
`,{mode:384}),await fe(a,o)}catch{}finally{await ek(a,{force:!0})}},FP=async(e,t)=>{await ef(rf(e,t)).catch(()=>{})},lk=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...ok,...r,home:r.home??qo()},s=Pn[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!rk(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 ak(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!hp(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,d=a.listProfiles??(b=>Iw(b,nf(),a.home)),u=n==="configure"?await d(e).catch(()=>[]):[];if(n==="configure"&&await $P(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:Qr(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let f=a.extensionPath;if(n==="configure"){try{f??=await NP(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await DP(f))return{ok:!1,reason:"extension-missing"}}let p=a.nonce(),h=tn(a.home,".anyray",tk,`${p}.json`),m=Qr(a.home,s.slug);await Qp(Xp(h),{recursive:!0,mode:448});let w=await yP(Xp(h)).catch(()=>[]);await tf(h,`${JSON.stringify({version:Ms,action:n,nonce:p,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:yn,expectedExtensionDistSha256:gr})}
|
|
110
|
+
`,{mode:384}),await RP(a.home,s.slug,w).catch(()=>{});let g={installed:[],failed:[]},y=!1;try{if(n==="configure"){let A=await OP(a.home,s.slug);if(A||await zp(l,a)!==!0)try{await a.run(l,["--install-extension",f,"--force"])}catch(v){return y=!0,{ok:!1,reason:"install-failed",detail:Jb(v,p)}}for(let v of u)try{(A||await zp(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}://${le}/configure?nonce=${encodeURIComponent(p)}`])}catch(A){return{ok:!1,reason:"handoff-undeliverable",detail:Jb(A,p)}}let b=await PP(m,p,n,a);return b!=="confirmed"?{ok:!1,reason:b==="reload-required"?"reload-required":"activation-timeout"}:(y=!0,n==="configure"?g.failed.length===0&&await MP(a.home,s.slug,ck(t,o,u),p):await FP(a.home,s.slug),{ok:!0,receipt:m,profiles:g})}catch{return{ok:!1,reason:"failed"}}finally{y&&await ef(h).catch(()=>{})}},dk=async(e,t=qo())=>{try{let n=JSON.parse(await Ln(Qr(t,Pn[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==yn||n.extensionDistSha256!==gr)}catch{return!1}},uk=async(e,t=qo())=>{try{let n=JSON.parse(await Ln(Qr(t,Pn[e].slug),"utf8"));return n.version!==Ms||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},pk=async(e,t,n=qo(),r={})=>{try{let o=Fs(t);if(!o)return!1;let a=JSON.parse(await Ln(Qr(n,Pn[e].slug),"utf8"));if(!(a.version===Ms&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===yn&&a.extensionDistSha256===gr))return!1;let i={...ok,...r,home:n};return await sk(e,i)===!0}catch{return!1}};var wr="Anyray",gn="anyray",wk="--anyray-owner=vscode-profile-v1",Us=e=>gk(rt(e),"User","chatLanguageModels.json"),jP=e=>gk(rt(e),"User","settings.json"),Bs="github.copilot.advanced",fl="debug.overrideCapiUrl",At=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),VP=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}},bk=e=>{let t=e[Bs];if(!At(t)||!VP(t[fl]))return{next:e,removed:!1};let n={...t};delete n[fl];let r={...e};return Object.keys(n).length>0?r[Bs]=n:delete r[Bs],{next:r,removed:!0}},Ws="anyray-default",Hs=()=>{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:[Ws]},kk=e=>e===Ws?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),pl=async e=>{if(!await R(e))return{kind:"missing"};try{let t=await yk(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"}}},Ck=async(e,t)=>{await BP(GP(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${KP()}`;try{await HP(n,`${JSON.stringify(t,null,2)}
|
|
111
|
+
`,{flag:"wx",mode:384}),await fe(n,e),await UP(e,384)}finally{await WP(n,{force:!0}).catch(()=>{})}},of=e=>{if(!At(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!==wr||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(!At(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!==kk(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!At(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}})},af=e=>{let t=e.filter(n=>!of(n));return{next:t,removed:t.length!==e.length}},YP=async(e,t)=>{let n=Us(e),r=await pl(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 "${wr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=af(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${wr}" Custom Endpoint from ${n}.`]};try{return await Ck(n,o),await ae(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${wr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${wr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},ZP=async e=>{try{let t=yr(await yk(e,"utf-8"));if(At(t))return bk(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Bs}.${fl} 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 ${Bs}.${fl} value manually if present.`]}},Ak=async(e,t)=>{let n=jP(e),r;try{r=await M(n)}catch{return ZP(n)}let{next:o,removed:a}=bk(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 ae(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.`]}}},JP=async(e,t)=>{let n=await YP(e,t),r=await Ak(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},vk=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,wk]}},Sk=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},Ek=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),XP=e=>Array.isArray(e.args)&&e.args.at(-1)===wk,Ik=(e,t)=>{if(!t.hookBinaryIsDurable()||!At(e)||!Sk(e,["type","command","args"]))return!1;let n=vk(t);return e.type==="stdio"&&e.command===n.command&&Ek(e.args,n.args)},zP=(e,t)=>{if(!At(e)||!Sk(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&&Ek(e.args,n.args))return!0;if(Ge(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===or&&r.at(-1)==="profile"))return!1;let a=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(a))return r.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(a)||r.length!==3)return!1;let s=r[0].replaceAll("\\","/");return!Ge(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},sf=(e,t)=>Ik(e,t)?"exact":At(e)&&XP(e)||zP(e,t)?"stale-owned":"foreign",fk=e=>`MCP name conflict in ${e}: servers.${gn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,qP=async(e,t,n,r,o)=>{let a=await o.vscodeUserMcpConfigPaths(e,r),s=o.hookBinaryIsDurable(),i=n&&s,c=[],l=[],d=0,u=!1,f=[];for(let p of a)try{let h=await M(p);if(i){if("servers"in h&&!At(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=At(h.servers)?{...h.servers}:{},b=vk(o),A=y[gn],v=A===void 0?void 0:sf(A,o);if(v==="exact"){d+=1;continue}if(v==="foreign"){u=!0,l.push(fk(p));continue}if(t){d+=1;continue}y[gn]=b,f.push({path:p,next:{...h,servers:y},backup:v!=="stale-owned",clearBackupAfter:!1});continue}if(!At(h.servers)||!(gn in h.servers))continue;if(sf(h.servers[gn],o)==="foreign"){u=!0,l.push(fk(p));continue}if(t)continue;let w={...h.servers};delete w[gn];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 ae(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 (${Aw}+).`),{changedFiles:c,messages:l,manual:u}},QP=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await R(c))try{let l=await M(c);if(!At(l.servers)||!(gn in l.servers)||sf(l.servers[gn],r)==="foreign"||(i+=1,t))continue;let d={...l.servers};delete d[gn];let u={...l};Object.keys(d).length===0?delete u.servers:u.servers=d,await J(c,u,{backup:!1}),await ae(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}},xk=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.`]:[]],Rk=()=>`${le} 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.)`,hk=e=>[`${le} 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."],Ok=(e,t,n,r)=>({runMcp:o=>qP(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):JP(e,o)}),_k=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${le} 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 ${le} 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 ${le} 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 ${le} 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 ${fp} 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 ${le} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${le} 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.`:`${le} 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 ${le} ${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 ${le} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},eL=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${le} 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 ${le} 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 ${le} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${le} 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 ${le} 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 ${le} 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 ${le} 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 ${le} 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 ${le} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},tL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Ok(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required for the authenticated Anyray VS Code provider. Re-run anyray-connect with --enroll, then apply Copilot again."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${le} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...hk(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${le}; 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:[_k(d.reason,e,a,"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?[Rk()]:[],...hk(t),...d.alreadyCurrent?[]:xk(d.profiles),...f.messages,...u.messages]}},mk=e=>[`${le} 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: ${Hs().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."],nL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=Ok(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 ${le} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...mk(t),...h.messages,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${le}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Hs().map(p=>({id:p,name:kk(p)}))});if(!d.ok)return{status:"manual",messages:[_k(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?[Rk()]:[],...mk(t),...d.alreadyCurrent?[]:xk(d.profiles),...f.messages,...u.messages]}},rL=async(e,t,n)=>{let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null};let o=[];for(let s of r){if(!await R(s))return{registered:!1,command:null};try{let i=await M(s),c=At(i.servers)?i.servers[gn]:void 0;if(!Ik(c,n))return{registered:!1,command:null};o.push(c.command)}catch{return{registered:!1,command:null}}}let a=o[0]||null;return{registered:!0,command:o.every(s=>s===a)?a:null}};var oL=async(e={installedVariant:$c,remoteServerVariant:yp,isRemoteDevContext:Gr})=>{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}},aL={installedVariant:$c,remoteServerVariant:yp,detectVscodeLmProviderEligibility:Ow,configureVscodeExtension:lk,vscodeExtensionPointsAt:pk,vscodeExtensionAwaitingReload:dk,vscodeExtensionReceiptMode:uk,hookBinaryIsDurable:ce,hookBinaryPath:Re,mcpServerCommand:je,vscodeUserMcpConfigPaths:xw,isRemoteDevContext:Gr},sL=(e={})=>{let t={...aL,...e},n=()=>oL(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:$s,quitTarget:dl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Yo(r,!0)}`:Us(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Ie(r.clientKey))return{status:"manual",messages:["Enrollment required: Copilot setup needs a personal ark_ gateway key. Re-run anyray-connect with --enroll or --sso; no VS Code configuration was written."]};let{variant:a,remote:s}=await n();if(!a)return{status:"manual",messages:[t.isRemoteDevContext()?"No VS Code server found here yet \u2014 this looks like a dev container, Codespace, or SSH remote. `--tools copilot` now configures the Anyray provider directly in a remote VS Code window, but only after VS Code has attached to this machine and installed its server. Open this machine with the VS Code Remote-SSH (or Dev Containers) extension, then re-run anyray-connect --tools copilot in that window\u2019s integrated terminal. To route this shell through Anyray without the Copilot UI, use an in-container tool instead: anyray-connect --tools opencode --sso <link> --subscription.":"No VS Code install found. Install VS Code, then re-run anyray-connect; the personal key will be transferred directly into SecretStorage."]};let i=await t.detectVscodeLmProviderEligibility(a);if(i.status==="needs-update")return{status:"manual",messages:[`${a} ${i.version??""} cannot expose public third-party models in Chat's picker. Upgrade to VS Code ${fp} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||vw(i.version);return X(r,"copilot")?tL(a,r,o,t.configureVscodeExtension,c,s,t):nL(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?rL(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Fs(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await pl(Us(o));if(s.kind==="array"){let c=s.entries.find(of)?.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 pl(Us(r));if(o.kind==="array"&&o.entries.some(of))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 QP(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await Ak(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${le} 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 ${le} gateway configuration and secret.`)):(l=!0,u.push(eL(y.reason,o,a,y.detail)))}let f=Us(o),p=await pl(f),h=p.kind==="missing"||p.kind==="array"&&!af(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 "${wr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=af(p.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${wr} Custom Endpoint from ${f}`]};await Ck(f,w);let g=[...u,`Removed the ${wr} Custom Endpoint from ${f}.`];return await ae(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...m,f],messages:g}}}},Tk=sL();import{accessSync as RL,constants as Hk,statSync as OL}from"node:fs";import{readFile as Kk,rm as Gs}from"node:fs/promises";import{homedir as gf,platform as Xk}from"node:os";import{delimiter as _L,join as wf,resolve as TL}from"node:path";import{execFile as uL}from"node:child_process";import{readFile as pL}from"node:fs/promises";import{homedir as df,platform as fL}from"node:os";import{join as Ks}from"node:path";import{join as iL}from"node:path";var cf="Iv1.b507a08c87ecfe98",cL="https://github.com/login/device/code",lL="https://github.com/login/oauth/access_token",dL="read:user",Pk=1e4,Qo=()=>iL(ee(),"copilot-seat-login.json"),Lk={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},lf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Dk=async(e={})=>{let t={...Lk,...e};try{let n=await t.fetch(cL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:cf,scope:dL}),signal:AbortSignal.timeout(Pk)});if(!n.ok)return;let r=await n.json();if(!lf(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}},Nk=async(e,t={})=>{let n={...Lk,...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(lL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:cf,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(Pk)})).json();if(!lf(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"}},$k=async(e,t)=>{let n=Qo();return await he(n,`${JSON.stringify({token:e,clientId:cf,mintedAtIso:t},null,2)}
|
|
112
|
+
`),n},hl=async()=>{try{let e=await M(Qo());if(!lf(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var hL=5e3,uf=5e3,mL=["copilot-cli","CopilotCLI"],yL="https://api.github.com/copilot_internal/user",Fk="~/.copilot/config.json",Uk="macOS Keychain (Copilot CLI)",Bk=e=>e===Fk||e===Uk,ea=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),nn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gL=()=>process.env.XDG_CONFIG_HOME?.trim()||Ks(df(),".config"),wL=()=>process.env.XDG_DATA_HOME?.trim()||Ks(df(),".local","share"),bL=async()=>{try{let e=await pL(Ks(df(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return ea(t)?t:void 0}catch{}},kL=async e=>{try{let t=await M(Ks(gL(),"github-copilot",e));if(!nn(t))return;for(let n of Object.values(t))if(nn(n)&&ea(n.oauth_token))return n.oauth_token}catch{}},CL=async()=>{try{let e=await M(Ks(wL(),"opencode","auth.json")),t=nn(e)?e["github-copilot"]:void 0;if(!nn(t)||t.type!=="oauth")return;if(ea(t.access))return t.access;if(ea(t.refresh))return t.refresh}catch{}},AL=(e,t)=>new Promise((n,r)=>{try{uL(e,[...t],{timeout:hL},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),vL=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return ea(r)?r:void 0}catch{return}},SL=async(e=AL)=>{for(let t of mL){let n=await vL(t,e);if(n)return n}};var ml={env:process.env,platform:fL,tokenFromDeviceLogin:hl,tokenFromCopilotCliConfig:bL,tokenFromSharedConfig:kL,tokenFromOpenCode:CL,tokenFromKeychain:SL,fetch:(...e)=>fetch(...e)},EL=new Set([401,403,404]),Wk=/^[a-z][a-z0-9-]{0,30}$/,IL=e=>e!=="default"&&Wk.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",xL=e=>typeof e!="string"?"default":/^https:\/\/api\.([a-z][a-z0-9-]{0,30})\.githubcopilot\.com\/?$/.exec(e.trim())?.[1]??"default",pf=async(e,t={})=>{let n={...ml,...t},r=new AbortController,o=setTimeout(()=>r.abort(),uf);try{let a=await n.fetch(yL,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=nn(i)&&nn(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:xL(s)}}return{verdict:EL.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var ta=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${Wk.test(n)?n:"default"}/header/models`,a=await Mk(o,e,r.clientKey,t);if(a.length>0)return a}return Mk(`${IL(n)}/models`,e,void 0,t)},Mk=async(e,t,n,r={})=>{let o={...ml,...r},a=new AbortController,s=setTimeout(()=>a.abort(),uf);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=nn(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!nn(u))continue;let f=u.id;if(typeof f!="string"||f.length===0||u.model_picker_enabled!==!0)continue;let p=u.policy;if(nn(p)&&p.state!=="enabled")continue;let h=u.supported_endpoints,m=Array.isArray(h)?h.filter(E=>typeof E=="string"):[],w=u.capabilities,g=nn(w)?w.limits:void 0,y=E=>{let I=nn(g)?g[E]:void 0;return typeof I=="number"&&Number.isFinite(I)&&I>0?Math.floor(I):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)}},yl=async(e,t,n,r={})=>{let o={...ml,...r},a=new AbortController,s=setTimeout(()=>a.abort(),uf);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)}},gl=async(e={},t={})=>{let n={...ml,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return ea(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:Uk,read:()=>n.tokenFromKeychain()}]:[],{source:Fk,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await pf(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 no="copilot-cli",wn="copilot-cli",PL=$s,LL=()=>PL()?["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."]:[],zk=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],bf=()=>Object.fromEntries(zk.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),ff=()=>wf(gf(),".anyray","copilot-cli.sh"),qk="# Managed by anyray-connect. Do not source this file anywhere else.",Gk=e=>e.split(/\r?\n/,1)[0]===qk,DL=["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"],wl="COPILOT_PROVIDER_API_KEY",jk=e=>e.startsWith(`export ${wl}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Nn=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",NL=()=>Hs()[0],js=(e="default")=>`/copilot/${e}/header`,nq=js(),eo=e=>e.replace(/\/+$/,""),$L=(e,t="default")=>`${eo(e.openaiBaseUrl)}${js(t)}`,hf=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),yf="claude-sonnet-5",ML=()=>{let e=Hs()[0];return e===Ws?yf:e},Qk=e=>e.endpoints.includes(Nn(e.id)==="responses"?"/responses":"/chat/completions"),kf=e=>{let t=e.filter(Qk),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)=>Vk(a.version,s.version)?-1:Vk(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var Vk=(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},Yk=(e,t,n,r,o,a="default")=>{let s=de({...e.metadata,tool:no}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...zk];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve($L(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${Nn(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(`
|
|
113
|
+
`))}`]:[],`export ${wl}=${ve(n)}`]},mf=(e,t,n)=>{let r=de({...e.metadata,tool:no});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Nn(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${ve(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${wl}=${ve(n)}`]:[]]},FL=(e,t)=>t||!X(e,"copilot"),Zk=()=>{let e=DL.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).`]},Jk=(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 ${no}\`), 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`."],UL=(e=process.env.PATH,t=Xk())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(_L)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=TL(o,n);try{if(!OL(a).isFile())continue;return RL(a,t==="win32"?Hk.F_OK:Hk.X_OK),a}catch{}}},BL=()=>wf(gf(),".copilot","config.json"),Dn=()=>wf(gf(),".copilot","mcp-config.json"),to="anyray",WL=()=>({type:"local",...je("profile"),tools:["*"]}),br=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),HL=async()=>{let e=Dn(),t;try{t=await M(e)}catch{return{status:"skipped",message:`Skipped the Anyray retrieval MCP server because ${e} could not be parsed; it was left unchanged.`}}if("mcpServers"in t&&!br(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=(br(t.mcpServers)?t.mcpServers:{})[to];return r!==void 0&&!Xt(r,"profile")?{status:"skipped",message:`MCP name conflict in ${e}: mcpServers.${to} is not owned by Anyray Connect, so retrieval was skipped and the existing server was left untouched.`}:{status:"installable",json:t}},KL=async e=>{let t=Dn(),n=e.json,r=br(n.mcpServers)?n.mcpServers:{};r[to]=WL(),n.mcpServers=r,await J(t,n)},GL=async()=>{let e=Dn(),t;try{let r=await M(e);if(!br(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!br(n)||!(to in n)||!Xt(n[to],"profile")?!1:(delete n[to],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await Gs(e,{force:!0}):await J(e,t,{backup:!1}),await ae(e),!0)},jL={resolveCopilotCommand:UL,platform:Xk,detectCopilotSeat:gp,discoverSeatToken:gl,readDeviceLoginToken:hl,fetchSeatModelCatalog:ta,probeSeatChatModel:yl},VL=e=>`'${e.replace(/'/g,"''")}'`,YL=e=>e.split(`
|
|
114
|
+
`).map(VL).join(" + [Environment]::NewLine + "),ZL=(e={})=>{let t={...jL,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await Jc(Ct(),wn))?.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&&eo(s)===`${eo(i)}/v1`,a=(s,i)=>s!==void 0&&hf(s)&&eo(s).startsWith(`${eo(i)}/v1/copilot/`);return{id:no,title:"GitHub Copilot CLI",automatic:!0,changesBilling:!1,quitGated:{isRunning:$s,quitTarget:dl},async usesDynamicCredential(s){let i=await r();return a(i,s)||!o(i,s)?!1:!await R(ff())},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=Ct(),l=async(E,I,C)=>{let x=E.filter(jk),T=E.filter(Le=>!jk(Le)),U=ff(),Z=[...T,...x.length>0?[`[ -r ${ve(U)} ] && . ${ve(U)}`]:[]],Y=await R(U),W=Y?await Kk(U,"utf8"):void 0,z=W===void 0||Gk(W);if(x.length>0&&!z)return{status:"manual",messages:[`Refused to overwrite user-managed ${U}; move or rename that file, then run Connect again.`]};let me=ce(),Pe=me?await HL():void 0,ne=[`${c} \u2190 managed Anyray block (${wn})`,...I.map(Le=>` ${Le}`),...x.length>0?[`${U} \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,Pe?.status==="skipped"?Pe.message:me?`${Dn()} \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.`,...LL()];if(i.dryRun)return{status:"configured",messages:ne};let He=!1;Pe?.status==="installable"&&(await KL(Pe),He=!0);try{x.length>0?await he(U,[qk,...x,""].join(`
|
|
115
|
+
`)):Y&&z&&await Gs(U,{force:!0}),await Zc(c,Z,wn)}catch(Le){try{W!==void 0&&z?await he(U,W):z&&await Gs(U,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw Le}return{status:"configured",messages:ne,changedFiles:[c,...x.length>0||Y&&z?[U]:[],...He?[Dn()]:[]]}},d=await r(),u=d!==void 0&&!hf(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",I=ML(),C=I!==yf||!!process.env.ANYRAY_COPILOT_MODEL,x=await t.fetchSeatModelCatalog(g.token,{},E,{laneOrigin:eo(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),T=x.find(ne=>ne.id===I);if(!C){let ne=kf(x);if(T=ne[0],!i.dryRun&&ne.length>0){let He=H=>`${eo(s.origin)}/v1${js(E)}/${Nn(H)==="responses"?"responses":"chat/completions"}`,Le={...bf(),authorization:`Bearer ${g.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},O=new Set,L;for(let H of ne.slice(0,4)){let pe=await t.probeSeatChatModel(He(H.id),Le,H.id);if(pe==="ok"){L=H;break}if(pe==="unreachable")break;O.add(H.id)}T=L??ne.find(H=>!O.has(H.id))??ne[0]}I=T?.id??yf}let U=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,Z=U&&s.clientKey?$t(U):U,Y=Yk(s,I,g.token,U,T,E),W=Yk(s,I,$t(g.token),Z,T,E),z=Nn(I),me=x.filter(ne=>Qk(ne)&&Nn(ne.id)===z).map(ne=>ne.id).filter(ne=>ne!==I),Pe=[`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: ${I}${C?" (pinned via ANYRAY_COPILOT_MODEL)":x.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...x.length===0&&Bk(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(ne=>{let He=ne.indexOf("="),Le=ne.slice(7,He),O=ne.slice(He+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${Le}', ${YL(O)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${g.source}, and the gateway key from \`anyray-connect print-key\`.)`,...Pe]}:l(Y,W,Pe)}if(!FL(s,h)){if(p&&!i.dryRun){let E=Ct();if(await Es(E,wn))return{status:"reverted",changedFiles:[E],messages:[`removed a stale Anyray ${wn} 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:",...Jk(t.platform(),y),...Zk()]}}return{status:"held",messages:[...p&&i.dryRun?[`would remove a stale Anyray ${wn} block from ${Ct()} (org lane, not chosen)`]:[],...Jk(t.platform(),y)]}}let b=NL(),A=s.viaLocalProxy?void 0:s.clientKey??s.placeholderKey,v=A&&s.clientKey?$t(A):A;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...mf(s,b,v).map(E=>{let[I,...C]=E.replace(/^export /,"").split("=");return` setx ${I} "${C.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${wl} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(mf(s,b,A),mf(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===Ws?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=Ct(),c=ff(),l=await R(c),d=l?Gk(await Kk(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${wn} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${Dn()} if registered`,...await R(Qo())?[`would remove the Copilot sign-in Connect minted (${Qo()})`]:[]]};let u=await Es(i,wn);d&&await Gs(c,{force:!0});let f=await GL(),p=Qo(),h=await R(p);h&&await Gs(p,{force:!0});let m=[...u?[i]:[],...d?[c]:[],...f?[Dn()]:[],...h?[p]:[]];return{status:m.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${wn} block from ${i}`:`no Anyray ${wn} 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 ${Dn()}`]:[],...Zk()],changedFiles:m.length>0?m:void 0}},async pointsAt(s){let i=await r();return o(i,s)||a(i,s)},async mcpStatus(){try{let s=await M(Dn()),i=br(s)?s.mcpServers:void 0,c=br(i)?i[to]:void 0;return!br(c)||!Xt(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"]:hf(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(no)?!0:!await t.detectCopilotSeat()}}},eC=ZL();import{homedir as cC}from"node:os";import{join as Cr}from"node:path";import{constants as zL,chmod as qL,copyFile as QL,readFile as Cl}from"node:fs/promises";import{applyEdits as eD,modify as tD}from"jsonc-parser";import{readFile as tC,rm as JL}from"node:fs/promises";var nC="// Managed by anyray-connect: OpenCode trim carrier v1",XL=5e3,Cf=e=>`${nC}
|
|
116
116
|
import { spawn } from "node:child_process"
|
|
117
117
|
|
|
118
118
|
const hookCommand = ${JSON.stringify([e.command,...e.args])}
|
|
119
|
-
const hookTimeoutMs = ${
|
|
119
|
+
const hookTimeoutMs = ${XL}
|
|
120
120
|
|
|
121
121
|
const invokeHook = (payload) =>
|
|
122
122
|
new Promise((resolve) => {
|
|
@@ -183,38 +183,38 @@ export const AnyrayTrimPlugin = async () => ({
|
|
|
183
183
|
}
|
|
184
184
|
},
|
|
185
185
|
})
|
|
186
|
-
`,Vs=async e=>await R(e)?(await
|
|
187
|
-
`)?"owned":"foreign":"absent",
|
|
188
|
-
`,r=n.trim()?
|
|
186
|
+
`,Vs=async e=>await R(e)?(await tC(e,"utf-8")).startsWith(`${nC}
|
|
187
|
+
`)?"owned":"foreign":"absent",rC=async(e,t)=>{let n=Cf(t),r=await Vs(e);return r==="foreign"?"foreign":r==="owned"&&await tC(e,"utf-8")===n?"unchanged":(await he(e,n),"installed")},Af=async e=>{let t=await Vs(e);return t!=="owned"?t:(await JL(e,{force:!0}),"removed")};var vf="https://opencode.ai/config.json",Fn="x-anyray-metadata",Ft="x-anyray-api-key",Sf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],$n="Authorization",kr=["anthropic","openai"],Un="github-copilot",nD="header",Mn="anyray",rD=()=>process.env.XDG_CONFIG_HOME?.trim()||Cr(cC(),".config"),oD=()=>process.env.XDG_DATA_HOME?.trim()||Cr(cC(),".local","share"),Al=()=>Cr(rD(),"opencode"),bl=()=>Cr(Al(),"plugins","anyrayTrim.js"),lC=()=>Cr(oD(),"opencode"),dC=async()=>{try{let e=await Cl(Cr(lC(),"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}}},oC=async()=>(await dC()).chatGptOAuth,aD=["opencode.jsonc","opencode.json","config.json"],ra=async()=>{let e=Al(),t=[];for(let n of aD){let r=Cr(e,n);await R(r)&&t.push(r)}return t},aC=async()=>(await ra())[0]??Cr(Al(),"opencode.json"),na=async e=>{let t=await R(e),n=t?await Cl(e,"utf8"):`{}
|
|
188
|
+
`,r=n.trim()?yr(n):{};if(!B(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},uC=(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(...uC(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}]},sC=async(e,t,n,r)=>{let o=uC(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await QL(e,`${e}.anyray-bak`,zL.COPYFILE_EXCL),await qL(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await he(`${e}.anyray-bak`,`{}
|
|
189
189
|
`);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
|
|
190
190
|
`)?`\r
|
|
191
191
|
`:`
|
|
192
|
-
`},s=t.raw;for(let i of o)s=
|
|
192
|
+
`},s=t.raw;for(let i of o)s=eD(s,tD(s,i.path,i.value,{formattingOptions:a}));return await he(e,s.endsWith(`
|
|
193
193
|
`)?s:`${s}
|
|
194
|
-
`),!0},zL=async e=>{try{let t=mr(await Cl(`${e}.anyray-bak`,"utf8"));return B(t)?t:void 0}catch{return}},Af=()=>["individual","business","enterprise"].includes(process.env.ANYRAY_COPILOT_PLAN?.trim()??"")?process.env.ANYRAY_COPILOT_PLAN.trim():"default",vf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${Af()}/${ZL}`,B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},QL=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===wr[0]||n===wr[1]||n===Fn?[]:B(r)&&B(r.options)&&Rf(r.options.baseURL,t)?[n]:[]),Sf=/claude/i,Of=["model","small_model"],cC=(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)||!Sf.test(o)))return`${wr[0]}/${o}`},Ef=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Ef(n,t);return t}if(!B(e))return t;for(let[n,r]of Object.entries(e))Of.includes(n)&&typeof r=="string"?t.push(r):Ef(r,t);return t},eD=(e,t,n)=>{if(!B(e)||!B(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>Sf.test(a)))return!1;let o=`${n}/`;return Ef(t).filter(a=>a.startsWith(o)).every(a=>Sf.test(a.slice(o.length)))},If=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>If(o,t,n));if(!B(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Of.includes(o)?cC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=If(a,t,n)}return r},xf=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>xf(o,t[a],n));if(!B(e)||!B(t))return e;let r={};for(let[o,a]of Object.entries(e))Of.includes(o)&&typeof a=="string"&&cC(t[o],n)===a?r[o]=t[o]:r[o]=xf(a,t[o],n);return r},tD=e=>{if(B(e))for(let t of wr){let n=e[t];if(B(n)&&B(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Ys=e=>{if(!B(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Jt({command:t,args:n},"profile")},kl=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),nD=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return B(t)&&t.tool==="opencode"}catch{return!1}},_f=e=>J(e,"copilot")&&!!e.clientKey,rD=e=>e.byoUpstream?[]:J(e,"anthropic")?[`Note: OpenCode can't route your personal Claude subscription \u2014 its Anthropic provider is api-key only, so this uses the gateway's server-held provider key (API billing). For your personal subscription use Claude Code; otherwise make sure an org provider key is set on the gateway, or requests will fail upstream with "invalid x-api-key".`]:[],oD=(e,t)=>J(e,"openai")?[`OpenAI subscription: OpenCode's built-in ChatGPT Pro/Plus OAuth is ${t?"detected":"not signed in yet (run `opencode auth login`)"}. Its Codex endpoint is hard-coded to chatgpt.com, so provider.baseURL cannot redirect it. Connect leaves machine networking untouched. Use the Codex app/CLI/IDE for ChatGPT subscription pass-through, or sign OpenCode into an API-key/Copilot provider that Connect can route.`]:[],aD=e=>_f(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."]:[],sD=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=kf);let o=!1;if(n)if("mcp"in r&&!B(r.mcp))o=!0;else{let y=B(r.mcp)?{...r.mcp}:{},b=y[$n];b!==void 0&&!Ys(b)?o=!0:(y[$n]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=y)}else if(B(r.mcp)&&Ys(r.mcp[$n])){let y={...r.mcp};delete y[$n],Object.keys(y).length===0?delete r.mcp:r.mcp=y}let a=B(r.provider)?{...r.provider}:{},s=QL(a,t.origin),i=s.every(y=>eD(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=If(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 S=B(A.headers)?{...A.headers}:{},E=!1;for(let[I,C]of[[Ft,p],...h?[[Mn,h]]:[]])I in S?(typeof S[I]!="string"||S[I].trim()==="")&&u.push(`${y}.${I}`):(S[I]=C,d.push(`${y}.${I}`),E=!0);E&&(A.headers=S,b.options=A,a[y]=b)}let m=c.length>0?[]:wr.filter(y=>y!=="openai"||!J(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 S=B(A.headers)?{...A.headers}:{};if(y==="anthropic"&&w)A.apiKey=w.key,S[Nn]=`Bearer ${w.key}`,S["x-anyray-provider"]="anthropic",S["x-anyray-auth-mode"]="passthrough",S["x-anyray-custom-host"]=w.url;else{A.apiKey=p,"x-anyray-custom-host"in S&&delete S[Nn];for(let E of Cf)delete S[E]}S[Ft]=p,h&&(S[Mn]=h),A.headers=S,b.options=A,a[y]=b}let g=c.length===0&&_f(t);if(g){let y=B(a[Fn])?{...a[Fn]}:{},b=B(y.options)?{...y.options}:{};b.baseURL=vf(t);let A=B(b.headers)?{...b.headers}:{};A[Ft]=t.clientKey,h&&(A[Mn]=h),b.headers=A,y.options=b,a[Fn]=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}},iD=["baseURL","apiKey"],rC=(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=kl(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,Mn])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[Mn]=="string"||Cf.some(h=>h in f);if(!o&&!p)return!1;for(let h of iD)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&&Nn in h&&(Nn in m?h[Nn]!==m[Nn]&&(h[Nn]=m[Nn],l=!0):(delete h[Nn],l=!0));for(let w of[Ft,Mn,...Cf])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},cD=(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)&&kl(a[Ft])&&(delete a[Ft],i=!0),!(Mn in s)&&nD(a[Mn])&&(delete a[Mn],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},lD=(e,t)=>{let n={...e},r=!1,o=tD(e.provider);if(B(n.mcp)&&Ys(n.mcp[$n])){let c={...n.mcp};delete c[$n],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===kf&&wr.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 wr)rC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...wr,Fn]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;cD(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&B(u)&&B(u.options)&&Rf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=xf(n,t,l))}return rC(a,Fn,!0,s[Fn])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===kf&&(delete n.$schema,r=!0),{next:n,removed:r}},lC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=Al(),t=aC(),n=await R(e)||await R(t),r=n&&await eC();return{installed:n,detail:n?`${await tC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await tC(),r=e.openaiBaseUrl,o=de({...e.metadata,tool:"opencode"}),a=_f(e),s=J(e,"openai"),i=await eC(),c;try{c=await na(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(vf(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 Fr()?je("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:p,customHeadersAdded:h,customHeaderConflicts:m,mcpConflict:w}=sD(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)"}`,...rD(e),...oD(e,i),a?`provider.github-copilot options.baseURL \u2192 ${vf(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. ${Af()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${Af()} 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).",...aD(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${$n} 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 nC(n,c,d,!0)?[n]:[],I=bl();if(ce())try{let C=await Qk(I,as(Ze,["opencode"]));C==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${I} already exists and is not owned by Anyray.`):(C==="installed"&&E.push(I),b.push(`The OpenCode tool.execute.after carrier is active in ${I}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${I}. Gateway-side optimization remains active.`)}else{try{await bf(I)==="removed"&&E.push(I)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:A,messages:b,changedFiles:E}},async pointsAt(e){for(let t of await ra())try{let{data:n}=await na(t);if(!B(n.provider))continue;for(let r of Object.values(n.provider))if(!(!B(r)||!B(r.options))&&Rf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await ra())try{let{data:t}=await na(e);if(!B(t.mcp))continue;let n=t.mcp[$n];if(!Ys(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 Vs(bl());e=i==="absent"?"missing":i,e==="owned"&&(t=await Cl(bl(),"utf-8")===wf(as(Ze,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await ra()){let c;try{c=await na(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[$n];if(l!==void 0)if(Ys(l))if(n=!0,!B(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;yc({command:d,args:u},"profile")||(a=!1)}else r=!0}return{hook_registration:e,mcp_registration:o?"unreadable":r?"foreign":n?"owned":"missing",hook_binary:t&&a&&await Fr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await sC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await ra()){let{data:o}=await na(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===Fn&&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===Fn&&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(kl(c[Ft])||kl(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 ra(),n=bl(),r="absent";try{r=await Vs(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 na(i)}catch{s.push(i);continue}let{next:l,removed:d}=lD(c.data,await zL(i));d&&(await nC(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await ae(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 bf(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 hC}from"node:os";import{join as Sl}from"node:path";import{constants as hD,chmod as mD,copyFile as yD,readFile as mC}from"node:fs/promises";import{applyEdits as gD,modify as wD}from"jsonc-parser";import{homedir as dD}from"node:os";import{dirname as uD,join as Zs}from"node:path";import{mkdir as pD,readFile as uC,rm as fD}from"node:fs/promises";var Pf="82c607644bafc47826c5c245835eb4d0a51e1ada632653742f3c14bf31932598",dC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfQogICAgfQogIH0sCiAgImNvbmZpZ1NjaGVtYSI6IHsKICAgICJ0eXBlIjogIm9iamVjdCIsCiAgICAiYWRkaXRpb25hbFByb3BlcnRpZXMiOiBmYWxzZSwKICAgICJyZXF1aXJlZCI6IFsiZ2F0ZXdheVVybCJdLAogICAgInByb3BlcnRpZXMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkFueXJheSBnYXRld2F5IG9yaWdpbiwgZS5nLiBodHRwczovL2dhdGV3YXkuZXhhbXBsZS5hbnlyYXkuYWkgKG5vIC92MSBzdWZmaXgpLiIKICAgICAgfSwKICAgICAgImFwaUtleSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJQZXJzb25hbCBBbnlyYXkgY2xpZW50IGtleSAoYXJrX+KApikuIFN1cHBvcnRzICR7RU5WX1ZBUn0gc3Vic3RpdHV0aW9uOyBkZWZhdWx0cyB0byAke0FOWVJBWV9DTElFTlRfS0VZfS4iCiAgICAgIH0sCiAgICAgICJ1c2VyIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkF0dHJpYnV0aW9uIHVzZXIgKGNvbnRlbnQtZnJlZTsgdXN1YWxseSBhbiBlbWFpbCkuIE9wdGlvbmFsIOKAlCB0aGUgY2xpZW50IGtleSBhbHJlYWR5IGF0dHJpYnV0ZXMgdGhlIGVucm9sbGVkIHVzZXIuIgogICAgICB9LAogICAgICAidGVhbSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB0ZWFtIChjb250ZW50LWZyZWUpLiBPcHRpb25hbC4iCiAgICAgIH0KICAgIH0sCiAgICAidWlIaW50cyI6IHsKICAgICAgImdhdGV3YXlVcmwiOiB7CiAgICAgICAgImxhYmVsIjogIkdhdGV3YXkgVVJMIiwKICAgICAgICAiaGVscCI6ICJZb3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IG9yaWdpbi4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgImxhYmVsIjogIkNsaWVudCBrZXkiLAogICAgICAgICJoZWxwIjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudC4gTGVhdmUgdW5zZXQgdG8gcmVhZCAkQU5ZUkFZX0NMSUVOVF9LRVkuIgogICAgICB9CiAgICB9CiAgfQp9Cg=="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjEuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIj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gc3RyaW5nIHwgdW5kZWZpbmVkPiA9IHByb2Nlc3MuZW52Cik6IE1vZGVsUHJvdmlkZXJDb25maWcgPT4gewogIGNvbnN0IGdhdGV3YXlVcmwgPSB0cmltbWVkU3RyaW5nKGNvbmZpZy5nYXRld2F5VXJsKTsKICBpZiAoIWdhdGV3YXlVcmwpIHsKICAgIHRocm93IG5ldyBFcnJvcigKICAgICAgJ2FueXJheSBwbHVnaW46IHBsdWdpbnMuZW50cmllcy5hbnlyYXkuY29uZmlnLmdhdGV3YXlVcmwgaXMgcmVxdWlyZWQnCiAgICApOwogIH0KICBjb25zdCBhcGlLZXkgPSB0cmltbWVkU3RyaW5nKGNvbmZpZy5hcGlLZXkpID8/IGVudltLRVlfRU5WXTsKICBjb25zdCBhdHRyaWJ1dGlvbiA9IGF0dHJpYnV0aW9uSGVhZGVyVmFsdWUoY29uZmlnKTsKICByZXR1cm4gewogICAgLy8gQmFyZSBvcmlnaW46IHRoZSBhbnRocm9waWMtbWVzc2FnZXMgdHJhbnNwb3J0IGFwcGVuZHMgL3YxL21lc3NhZ2VzLgogICAgYmFzZVVybDogZ2F0ZXdheVVybC5yZXBsYWNlKC9cLyskLywgJycpLAogICAgYXBpOiAnYW50aHJvcGljLW1lc3NhZ2VzJywKICAgIC4uLihhcGlLZXkgPyB7IGFwaUtleSB9IDoge30pLAogICAgaGVhZGVyczogewogICAgICAnYW50aHJvcGljLWJldGEnOiBBTlRIUk9QSUNfQkVUQSwKICAgICAgLi4uKGFwaUtleSA/IHsgJ3gtYW55cmF5LWFwaS1rZXknOiBhcGlLZXkgfSA6IHt9KSwKICAgICAgLi4uKGF0dHJpYnV0aW9uID8geyAneC1hbnlyYXktbWV0YWRhdGEnOiBhdHRyaWJ1dGlvbiB9IDoge30pLAogICAgfSwKICAgIG1vZGVsczogTU9ERUxTLAogIH07Cn07Cg=="},{path:"src/sessionIdentity.ts",contentBase64:"LyoqCiAqIFBlci1zZXNzaW9uIGlkZW50aXR5IGZvciB0aGU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S1rZXknXSA9PT0gdW5kZWZpbmVkICYmCiAgICAgIHR5cGVvZiBvcHRzLmFwaUtleSA9PT0gJ3N0cmluZycgJiYKICAgICAgb3B0cy5hcGlLZXkuc3RhcnRzV2l0aCgnYXJrXycpCiAgICApIHsKICAgICAgaGVhZGVyc1sneC1hbnlyYXktYXBpLWtleSddID0gb3B0cy5hcGlLZXk7CiAgICB9CiAgICBvcHRzLmhlYWRlcnMgPSBoZWFkZXJzOwogICAgY29uc3Qgc2Vzc2lvbklkID0KICAgICAgdHlwZW9mIG9wdHMuc2Vzc2lvbklkID09PSAnc3RyaW5nJyA/IG9wdHMuc2Vzc2lvbklkIDogdW5kZWZpbmVkOwogICAgY29uc3QgY2FsbGVyT25QYXlsb2FkID0gb3B0cy5vblBheWxvYWQ7CiAgICBvcHRzLm9uUGF5bG9hZCA9IGFzeW5jIChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpID0+IHsKICAgICAgaWYgKHBheWxvYWQgJiYgdHlwZW9mIHBheWxvYWQgPT09ICdvYmplY3QnICYmICFBcnJheS5pc0FycmF5KHBheWxvYWQpKSB7CiAgICAgICAgcGF0Y2hQYXlsb2FkU2Vzc2lvbklkZW50aXR5KAogICAgICAgICAgcGF5bG9hZCBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPiwKICAgICAgICAgIHNlc3Npb25JZAogICAgICAgICk7CiAgICAgIH0KICAgICAgcmV0dXJuIGNhbGxlck9uUGF5bG9hZCA/IGNhbGxlck9uUGF5bG9hZChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpIDogcGF5bG9hZDsKICAgIH07CiAgICByZXR1cm4gaW5uZXIobW9kZWwsIGNvbnRleHQsIG9wdHMpOwogIH07CiAgcmV0dXJuIHdyYXBwZWQ7Cn07Cg=="}];var Tf=".anyray-source-sha",nn=()=>Zs(dD(),".anyray","openclaw-plugin"),pC=async(e=nn())=>{try{if((await uC(Zs(e,Tf),"utf8")).trim()===Pf)return"current"}catch{}for(let t of dC){let n=Zs(e,t.path);await pD(uD(n),{recursive:!0,mode:448}),await he(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await he(Zs(e,Tf),`${Pf}
|
|
195
|
-
`),"installed"},vl=async(e=
|
|
196
|
-
`,r=n.trim()?
|
|
194
|
+
`),!0},sD=async e=>{try{let t=yr(await Cl(`${e}.anyray-bak`,"utf8"));return B(t)?t:void 0}catch{return}},Ef=()=>["individual","business","enterprise"].includes(process.env.ANYRAY_COPILOT_PLAN?.trim()??"")?process.env.ANYRAY_COPILOT_PLAN.trim():"default",If=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${Ef()}/${nD}`,B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Tf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},iD=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===kr[0]||n===kr[1]||n===Un?[]:B(r)&&B(r.options)&&Tf(r.options.baseURL,t)?[n]:[]),xf=/claude/i,Pf=["model","small_model"],pC=(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)||!xf.test(o)))return`${kr[0]}/${o}`},Rf=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Rf(n,t);return t}if(!B(e))return t;for(let[n,r]of Object.entries(e))Pf.includes(n)&&typeof r=="string"?t.push(r):Rf(r,t);return t},cD=(e,t,n)=>{if(!B(e)||!B(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>xf.test(a)))return!1;let o=`${n}/`;return Rf(t).filter(a=>a.startsWith(o)).every(a=>xf.test(a.slice(o.length)))},Of=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>Of(o,t,n));if(!B(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Pf.includes(o)?pC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=Of(a,t,n)}return r},_f=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>_f(o,t[a],n));if(!B(e)||!B(t))return e;let r={};for(let[o,a]of Object.entries(e))Pf.includes(o)&&typeof a=="string"&&pC(t[o],n)===a?r[o]=t[o]:r[o]=_f(a,t[o],n);return r},lD=e=>{if(B(e))for(let t of kr){let n=e[t];if(B(n)&&B(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Ys=e=>{if(!B(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Xt({command:t,args:n},"profile")},kl=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),dD=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return B(t)&&t.tool==="opencode"}catch{return!1}},Lf=e=>X(e,"copilot")&&!!e.clientKey,uD=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".`]:[],pD=(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.`]:[],fD=e=>Lf(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."]:[],hD=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=vf);let o=!1;if(n)if("mcp"in r&&!B(r.mcp))o=!0;else{let y=B(r.mcp)?{...r.mcp}:{},b=y[Mn];b!==void 0&&!Ys(b)?o=!0:(y[Mn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=y)}else if(B(r.mcp)&&Ys(r.mcp[Mn])){let y={...r.mcp};delete y[Mn],Object.keys(y).length===0?delete r.mcp:r.mcp=y}let a=B(r.provider)?{...r.provider}:{},s=iD(a,t.origin),i=s.every(y=>cD(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=Of(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,p=t.clientKey??t.placeholderKey,h=de({...t.metadata,tool:"opencode"});for(let y of c){let b={...a[y]},A={...b.options};if("headers"in A&&!B(A.headers)){u.push(y);continue}let v=B(A.headers)?{...A.headers}:{},E=!1;for(let[I,C]of[[Ft,p],...h?[[Fn,h]]:[]])I in v?(typeof v[I]!="string"||v[I].trim()==="")&&u.push(`${y}.${I}`):(v[I]=C,d.push(`${y}.${I}`),E=!0);E&&(A.headers=v,b.options=A,a[y]=b)}let m=c.length>0?[]:kr.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[$n]=`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[$n];for(let E of Sf)delete v[E]}v[Ft]=p,h&&(v[Fn]=h),A.headers=v,b.options=A,a[y]=b}let g=c.length===0&&Lf(t);if(g){let y=B(a[Un])?{...a[Un]}:{},b=B(y.options)?{...y.options}:{};b.baseURL=If(t);let A=B(b.headers)?{...b.headers}:{};A[Ft]=t.clientKey,h&&(A[Fn]=h),b.headers=A,y.options=b,a[Un]=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}},mD=["baseURL","apiKey"],iC=(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=kl(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,Fn])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[Fn]=="string"||Sf.some(h=>h in f);if(!o&&!p)return!1;for(let h of mD)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&&$n in h&&($n in m?h[$n]!==m[$n]&&(h[$n]=m[$n],l=!0):(delete h[$n],l=!0));for(let w of[Ft,Fn,...Sf])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},yD=(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)&&kl(a[Ft])&&(delete a[Ft],i=!0),!(Fn in s)&&dD(a[Fn])&&(delete a[Fn],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},gD=(e,t)=>{let n={...e},r=!1,o=lD(e.provider);if(B(n.mcp)&&Ys(n.mcp[Mn])){let c={...n.mcp};delete c[Mn],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===vf&&kr.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 kr)iC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...kr,Un]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;yD(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&B(u)&&B(u.options)&&Tf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=_f(n,t,l))}return iC(a,Un,!0,s[Un])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===vf&&(delete n.$schema,r=!0),{next:n,removed:r}},fC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=Al(),t=lC(),n=await R(e)||await R(t),r=n&&await oC();return{installed:n,detail:n?`${await aC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await aC(),r=e.openaiBaseUrl,o=de({...e.metadata,tool:"opencode"}),a=Lf(e),s=X(e,"openai"),i=await oC(),c;try{c=await na(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(If(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 Br()?je("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:p,customHeadersAdded:h,customHeaderConflicts:m,mcpConflict:w}=hD(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)"}`,...uD(e),...pD(e,i),a?`provider.github-copilot options.baseURL \u2192 ${If(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. ${Ef()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${Ef()} 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).",...fD(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Mn} 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 sC(n,c,d,!0)?[n]:[],I=bl();if(ce())try{let C=await rC(I,as(Ze,["opencode"]));C==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${I} already exists and is not owned by Anyray.`):(C==="installed"&&E.push(I),b.push(`The OpenCode tool.execute.after carrier is active in ${I}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${I}. Gateway-side optimization remains active.`)}else{try{await Af(I)==="removed"&&E.push(I)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${Re()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:A,messages:b,changedFiles:E}},async pointsAt(e){for(let t of await ra())try{let{data:n}=await na(t);if(!B(n.provider))continue;for(let r of Object.values(n.provider))if(!(!B(r)||!B(r.options))&&Tf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await ra())try{let{data:t}=await na(e);if(!B(t.mcp))continue;let n=t.mcp[Mn];if(!Ys(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 Vs(bl());e=i==="absent"?"missing":i,e==="owned"&&(t=await Cl(bl(),"utf-8")===Cf(as(Ze,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await ra()){let c;try{c=await na(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[Mn];if(l!==void 0)if(Ys(l))if(n=!0,!B(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;yc({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 Br()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await dC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await ra()){let{data:o}=await na(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===Un&&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===Un&&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(kl(c[Ft])||kl(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 ra(),n=bl(),r="absent";try{r=await Vs(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 na(i)}catch{s.push(i);continue}let{next:l,removed:d}=gD(c.data,await sD(i));d&&(await sC(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await ae(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 Af(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 wC}from"node:os";import{join as Sl}from"node:path";import{constants as AD,chmod as vD,copyFile as SD,readFile as bC}from"node:fs/promises";import{applyEdits as ED,modify as ID}from"jsonc-parser";import{homedir as wD}from"node:os";import{dirname as bD,join as Zs}from"node:path";import{mkdir as kD,readFile as mC,rm as CD}from"node:fs/promises";var Df="82c607644bafc47826c5c245835eb4d0a51e1ada632653742f3c14bf31932598",hC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfQogICAgfQogIH0sCiAgImNvbmZpZ1NjaGVtYSI6IHsKICAgICJ0eXBlIjogIm9iamVjdCIsCiAgICAiYWRkaXRpb25hbFByb3BlcnRpZXMiOiBmYWxzZSwKICAgICJyZXF1aXJlZCI6IFsiZ2F0ZXdheVVybCJdLAogICAgInByb3BlcnRpZXMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkFueXJheSBnYXRld2F5IG9yaWdpbiwgZS5nLiBodHRwczovL2dhdGV3YXkuZXhhbXBsZS5hbnlyYXkuYWkgKG5vIC92MSBzdWZmaXgpLiIKICAgICAgfSwKICAgICAgImFwaUtleSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJQZXJzb25hbCBBbnlyYXkgY2xpZW50IGtleSAoYXJrX+KApikuIFN1cHBvcnRzICR7RU5WX1ZBUn0gc3Vic3RpdHV0aW9uOyBkZWZhdWx0cyB0byAke0FOWVJBWV9DTElFTlRfS0VZfS4iCiAgICAgIH0sCiAgICAgICJ1c2VyIjogewogICAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIkF0dHJpYnV0aW9uIHVzZXIgKGNvbnRlbnQtZnJlZTsgdXN1YWxseSBhbiBlbWFpbCkuIE9wdGlvbmFsIOKAlCB0aGUgY2xpZW50IGtleSBhbHJlYWR5IGF0dHJpYnV0ZXMgdGhlIGVucm9sbGVkIHVzZXIuIgogICAgICB9LAogICAgICAidGVhbSI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB0ZWFtIChjb250ZW50LWZyZWUpLiBPcHRpb25hbC4iCiAgICAgIH0KICAgIH0sCiAgICAidWlIaW50cyI6IHsKICAgICAgImdhdGV3YXlVcmwiOiB7CiAgICAgICAgImxhYmVsIjogIkdhdGV3YXkgVVJMIiwKICAgICAgICAiaGVscCI6IC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VkU3RyaW5nKGNvbmZpZy5nYXRld2F5VXJsKTsKICBpZiAoIWdhdGV3YXlVcmwpIHsKICAgIHRocm93IG5ldyBFcnJvcigKICAgICAgJ2FueXJheSBwbHVnaW46IHBsdWdpbnMuZW50cmllcy5hbnlyYXkuY29uZmlnLmdhdGV3YXlVcmwgaXMgcmVxdWlyZWQnCiAgICApOwogIH0KICBjb25zdCBhcGlLZXkgPSB0cmltbWVkU3RyaW5nKGNvbmZpZy5hcGlLZXkpID8/IGVudltLRVlfRU5WXTsKICBjb25zdCBhdHRyaWJ1dGlvbiA9IGF0dHJpYnV0aW9uSGVhZGVyVmFsdWUoY29uZmlnKTsKICByZXR1cm4gewogICAgLy8gQmFyZSBvcmlnaW46IHRoZSBhbnRocm9waWMtbWVzc2FnZXMgdHJhbnNwb3J0IGFwcGVuZHMgL3YxL21lc3NhZ2VzLgogICAgYmFzZVVybDogZ2F0ZXdheVVybC5yZXBsYWNlKC9cLyskLywgJycpLAogICAgYXBpOiAnYW50aHJvcGljLW1lc3NhZ2VzJywKICAgIC4uLihhcGlLZXkgPyB7IGFwaUtleSB9IDoge30pLAogICAgaGVhZGVyczogewogICAgICAnYW50aHJvcGljLWJldGEnOiBBTlRIUk9QSUNfQkVUQSwKICAgICAgLi4uKGFwaUtleSA/IHsgJ3gtYW55cmF5LWFwaS1rZXknOiBhcGlLZXkgfSA6IHt9KSwKICAgICAgLi4uKGF0dHJpYnV0aW9uID8geyAneC1hbnlyYXktbWV0YWRhdGEnOiBhdHRyaWJ1dGlvbiB9IDoge30pLAogICAgfSwKICAgIG1vZGVsczogTU9ERUxTLAogIH07Cn07Cg=="},{path:"src/sessionIdentity.ts",contentBase64:"LyoqCiAqIFBlci1zZXNzaW9uIGlkZW50aXR5IGZvciB0aGUgQW55cmF5IGdhdGV3YXksIGluamVjdGVkIGludG8gdGhlIEFudGhyb3BpYwogKiBNZXNzYWdlcyBib2R5IGFzIGBtZXRhZGF0YS51c2VyX2lkYC4KICoKICogVGhlI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2l0aCgnYXJrXycpCiAgICApIHsKICAgICAgaGVhZGVyc1sneC1hbnlyYXktYXBpLWtleSddID0gb3B0cy5hcGlLZXk7CiAgICB9CiAgICBvcHRzLmhlYWRlcnMgPSBoZWFkZXJzOwogICAgY29uc3Qgc2Vzc2lvbklkID0KICAgICAgdHlwZW9mIG9wdHMuc2Vzc2lvbklkID09PSAnc3RyaW5nJyA/IG9wdHMuc2Vzc2lvbklkIDogdW5kZWZpbmVkOwogICAgY29uc3QgY2FsbGVyT25QYXlsb2FkID0gb3B0cy5vblBheWxvYWQ7CiAgICBvcHRzLm9uUGF5bG9hZCA9IGFzeW5jIChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpID0+IHsKICAgICAgaWYgKHBheWxvYWQgJiYgdHlwZW9mIHBheWxvYWQgPT09ICdvYmplY3QnICYmICFBcnJheS5pc0FycmF5KHBheWxvYWQpKSB7CiAgICAgICAgcGF0Y2hQYXlsb2FkU2Vzc2lvbklkZW50aXR5KAogICAgICAgICAgcGF5bG9hZCBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPiwKICAgICAgICAgIHNlc3Npb25JZAogICAgICAgICk7CiAgICAgIH0KICAgICAgcmV0dXJuIGNhbGxlck9uUGF5bG9hZCA/IGNhbGxlck9uUGF5bG9hZChwYXlsb2FkLCBwYXlsb2FkTW9kZWwpIDogcGF5bG9hZDsKICAgIH07CiAgICByZXR1cm4gaW5uZXIobW9kZWwsIGNvbnRleHQsIG9wdHMpOwogIH07CiAgcmV0dXJuIHdyYXBwZWQ7Cn07Cg=="}];var Nf=".anyray-source-sha",rn=()=>Zs(wD(),".anyray","openclaw-plugin"),yC=async(e=rn())=>{try{if((await mC(Zs(e,Nf),"utf8")).trim()===Df)return"current"}catch{}for(let t of hC){let n=Zs(e,t.path);await kD(bD(n),{recursive:!0,mode:448}),await he(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await he(Zs(e,Nf),`${Df}
|
|
195
|
+
`),"installed"},vl=async(e=rn())=>{try{await mC(Zs(e,Nf),"utf8")}catch{return!1}return await CD(e,{recursive:!0,force:!0}),!0};var Uf="x-anyray-metadata",oa="x-anyray-api-key",Bf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],oo="Authorization",ao="anthropic-beta",El="interleaved-thinking-2025-05-14",Il=["anthropic","openai"],kC="short",Hf="anthropic-messages",Kf=32e3,xl="anthropic/claude-sonnet-4-5",Gf=["anthropic/claude-haiku-4-5"],jf="anyray/claude-sonnet-4-5",Vf=["anyray/claude-haiku-4-5"],xD=[xl,jf],RD=[Gf,Vf],Xe="anyray",Ar="ANYRAY_API_KEY",Xs="openclaw",CC=()=>process.env.OPENCLAW_STATE_DIR?.trim()||Sl(wC(),".openclaw"),ro=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||Sl(CC(),"openclaw.json"),N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Js=async e=>{let t=await R(e),n=t?await bC(e,"utf8"):`{}
|
|
196
|
+
`,r=n.trim()?yr(n):{};if(!N(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},AC=(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(...AC(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}]},$f=async(e,t,n,r)=>{let o=AC(t.data,n);if(o.length===0)return!1;if(r&&!await R(`${e}.anyray-bak`))if(t.existed)try{await SD(e,`${e}.anyray-bak`,AD.COPYFILE_EXCL),await vD(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await he(`${e}.anyray-bak`,`{}
|
|
197
197
|
`);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
|
|
198
198
|
`)?`\r
|
|
199
199
|
`:`
|
|
200
|
-
`},s=t.raw;for(let i of o)s=
|
|
200
|
+
`},s=t.raw;for(let i of o)s=ED(s,ID(s,i.path,i.value,{formattingOptions:a}));return await he(e,s.endsWith(`
|
|
201
201
|
`)?s:`${s}
|
|
202
|
-
`),!0},Df=async e=>{try{let t=mr(await mC(`${e}.anyray-bak`,"utf8"));return N(t)?t:void 0}catch{return}},Ff=e=>{if(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},CD=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=de({...t.metadata,tool:Js}),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 S=N(l.plugins)?{...l.plugins}:{},E=N(S.load)?{...S.load}:{},I=N(S.entries)?{...S.entries}:{},C=N(I[Je])?{...I[Je]}:{},x=N(C.config)?{...C.config}:{};if("plugins"in l&&!N(l.plugins)||"load"in S&&!N(S.load)||"paths"in E&&!Array.isArray(E.paths)||"entries"in S&&!N(S.entries)||Je in I&&!N(I[Je])||"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,S.load=E,C.enabled=!0,x.gatewayUrl=t.anthropicBaseUrl,x.apiKey=r;let U=t.metadata.user,Z=t.metadata.team;U&&(x.user=U),Z&&(x.team=Z),C.config=x,I[Je]=C,S.entries=I,l.plugins=S;let Y=N(l.env)?{...l.env}:{};Y[kr]=r,l.env=Y,p=!0}}let h=Il.filter(S=>S!=="openai"||!J(t,"openai"));for(let S of h){if(S in f&&!N(f[S])){d.push(`models.providers.${S}`);continue}let E=N(f[S])?{...f[S]}:{};if("headers"in E&&!N(E.headers)){i.push(S);continue}let I=N(E.headers)?{...E.headers}:{};if(E.baseUrl=S==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,S==="anthropic"&&(E.api=Uf,(typeof E.maxTokens!="number"||E.maxTokens<=0)&&(E.maxTokens=Bf)),S==="anthropic"&&a)E.apiKey=a.key,I[ro]=`Bearer ${a.key}`,I["x-anyray-provider"]="anthropic",I["x-anyray-auth-mode"]="passthrough",I["x-anyray-custom-host"]=a.url;else{E.apiKey=r,"x-anyray-custom-host"in I&&delete I[ro];for(let C of Mf)delete I[C]}I[oa]=r,o&&(I[$f]=o),S==="anthropic"&&(oo in I?c=I[oo]!==El:I[oo]=El),E.headers=I,f[S]=E,s.push(S)}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 S=N(l.agents)?{...l.agents}:{},E=N(S.defaults)?{...S.defaults}:{},I=N(E.params)?{...E.params}:{};"cacheRetention"in I||(I.cacheRetention=yC,m=!0,E.params=I);let C=N(E.model)?{...E.model}:{},x=p?[...s,Je]:s,P=U=>typeof U=="string"&&x.some(Z=>U.startsWith(`${Z}/`));typeof C.primary!="string"||C.primary.trim()===""?(C.primary=p?Wf:xl,w=!0,E.model=C,"fallbacks"in C||(C.fallbacks=p?[...Kf]:[...Hf],g=!0)):P(C.primary)||(y=C.primary),b=(Array.isArray(C.fallbacks)?C.fallbacks:[]).filter(U=>typeof U=="string"&&!P(U)),(m||w)&&(S.defaults=E,l.agents=S)}return{next:l,routed:s,cacheRetentionSeeded:m,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:g,unroutedPrimary:y,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:p}},AD=["baseUrl","apiKey","api","maxTokens"],Nf=(e,t,n=Il,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=Ff(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[oa]=="string"||typeof h[$f]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||Mf.some(S=>S in h)))continue;let w=N(c[u])?c[u]:{},g=N(w.headers)?w.headers:{},y="x-anyray-custom-host"in h,b=S=>S==="api"?p.api===Uf:S==="maxTokens"?p.maxTokens===Bf:S==="apiKey"?y||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let S of AD)b(S)&&(S in w?p[S]!==w[S]&&(p[S]=w[S],l=!0):S in p&&(delete p[S],l=!0));let A=[oa,$f,...Mf,..."x-anyray-custom-host"in h?[ro]:[]];h[oo]===El&&A.push(oo);for(let S of A)S in g?h[S]!==g[S]&&(h[S]=g[S],l=!0):S in h&&(delete h[S],l=!0);ro in g&&!(ro in h)&&(h[ro]=g[ro],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[Je];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:{};Je in b?JSON.stringify(p[Je])!==JSON.stringify(b[Je])&&(p[Je]=b[Je],l=!0):(delete p[Je],l=!0)}}if(Object.keys(f).length===0?delete u.load:u.load=f,Object.keys(p).length===0?delete u.entries:u.entries=p,Object.keys(u).length===0?delete o.plugins:o.plugins=u,N(o.env)){let w={...o.env},g=w[kr];if(typeof g=="string"&&g.startsWith("ark_")){let y=N(t?.env)?t.env:{};kr in y?w[kr]!==y[kr]&&(w[kr]=y[kr],l=!0):(delete w[kr],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===yC&&("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:{};bD.includes(g.primary)&&("primary"in y?g.primary!==y.primary&&(g.primary=y.primary,l=!0):(delete g.primary,l=!0)),kD.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}},bC={id:Js,title:"OpenClaw",automatic:!0,async detect(){let e=await R(no())||await R(gC());return{installed:e,detail:e?no():`no ${Sl(hC(),".openclaw")} state dir`}},async apply(e,t){let n=no();if(!e.byoUpstream&&J(e,"anthropic")){let E=["OpenClaw stays on its native Claude sign-in \u2014 the Anyray seat","passthrough lane for OpenClaw is not yet supported, and routing it","would move inference onto the org API bill. Opt in explicitly with",`\`--org --tools ${Js}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],I;try{I=await Xs(n)}catch{return{status:"held",messages:E}}let{next:C,removed:x}=Nf(I.data,await Df(n),Il,nn());return x?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...E]}:(await Lf(n,I,C,!1),await ae(n),await vl(),{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 vl(),{status:"held",messages:E})}let r=nn(),o=!1;if(!t.dryRun)try{await pC(r)}catch{r=void 0,o=!0}let a;try{a=await Xs(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Uf}", "maxTokens": ${Bf}, "apiKey": "<your personal ark_ key>", "headers": { "${oa}": "<your personal ark_ key>", "${oo}": "${El}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${oa}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${xl}") 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}=CD(a.data,e,r),g=s,y=!1;if(!i.includes("openai")){let E=Nf(g,await Df(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:Js})??"(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 ${oo} 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?Wf:xl} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(w?Kf:Hf).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 (${nn()}) and registered it under plugins.entries.${Je}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${nn()}; 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 S=await Lf(n,a,g,!0);return{status:A,messages:b,changedFiles:S?[n]:[]}},async pointsAt(e){try{let{data:t}=await Xs(no());for(let a of Object.values(Ff(t)))if(N(a)&&fC(a.baseUrl,e))return!0;let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[Je];if(N(o)&&N(o.config)&&fC(o.config.gatewayUrl,e))return!0}catch{}return!1},async watchPaths(){return[no(),Sl(nn(),".anyray-source-sha")]},async routingExpected(e){return e.includes(Js)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Xs(no());for(let a of Object.values(Ff(t))){if(!N(a))continue;let s=N(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[oa]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[Je];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=no();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 Xs(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}=Nf(n.data,await Df(t),Il,nn()),a=await vl();return o?(await Lf(t,n,r,!1),await ae(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${nn()}`]:[]],changedFiles:[t]}):(await ae(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${nn()}`]:[]]})}};import{execFile as dM}from"node:child_process";import{readFile as uM}from"node:fs/promises";import{homedir as mi,platform as Ar}from"node:os";import{join as kn}from"node:path";import{isDeepStrictEqual as Oh,promisify as pM}from"node:util";var qs=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},Rl=(e,t)=>{let n=qs(e),r=qs(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 x$}from"node:crypto";import{promises as _A}from"node:fs";import{platform as R$,tmpdir as O$}from"node:os";import{join as Vl}from"node:path";import{execFile as vD}from"node:child_process";import{promises as zs}from"node:fs";import{homedir as SD,platform as ED}from"node:os";import{delimiter as ID,join as Ol}from"node:path";import{promisify as xD}from"node:util";var RD=xD(vD),OD=15*6e4,_D=64*1024*1024,PD=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],kC=async(e={})=>{let t=(e.home??SD)(),n=e.env??process.env,r=PD(e.runtimePlatform??ED()),o=[Ol(t,".local","bin"),Ol(t,".claude","local"),...(n.PATH??"").split(ID).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Ol(a,`claude${s}`);try{return await zs.access(i),i}catch{}}return null},TD=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let{uuid:r,name:o,dirName:a}=n;typeof r!="string"||typeof a!="string"||a.length===0||a.includes("/")||a.includes("\\")||a==="."||a===".."||t.push({uuid:r,name:typeof o=="string"&&o.length>0?o:"Project",dirName:a})}return t},LD=async e=>{let t=Ol(e,"projects"),n;try{n=(await zs.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return[]}let r=[];for(let o of n){let a=o.slice(-36);if(!$D.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},DD=e=>{if(!e||!e.startsWith("{"))return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t,r=n.sessionIds,o=n.jsonlPaths;if(!Array.isArray(r)||!Array.isArray(o))return null;let a=Array.isArray(n.titles)?n.titles:[],s=Array.isArray(n.createdAts)?n.createdAts:[],i=Array.isArray(n.updatedAts)?n.updatedAts:[],c=d=>typeof d=="number"&&Number.isFinite(d)?d:void 0,l=[];for(let d=0;d<r.length;d+=1){let u=r[d],f=o[d];if(typeof u!="string"||typeof f!="string"||u.length===0||f.length===0)continue;let p=a[d];l.push({sessionId:u,transcriptPath:f,title:typeof p=="string"&&p.length>0?p:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:TD(n.projectList)}},ND=async e=>{let t,n;try{let r=await zs.readFile(e,"utf8");for(let o of r.split(`
|
|
203
|
-
`)){if(o.length===0)continue;let a;try{a=JSON.parse(o).timestamp}catch{continue}if(typeof a!="string")continue;let s=Date.parse(a);Number.isFinite(s)&&(t??=s,n=s)}}catch{return{}}return{createdAt:t,lastActivityAt:n??t}}
|
|
204
|
-
`).filter(d=>d.trim().length>0),i=DD(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 ND(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await LD(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as UD}from"node:crypto";import{promises as Un}from"node:fs";import{homedir as BD,platform as HD}from"node:os";import{join as vt}from"node:path";var AC=448,Bn="local_",WD="local-agent-mode-sessions",Gf="-3p",KD="cowork_account_settings.json",ao=(e={})=>{let t=(e.home??BD)(),n=e.runtimePlatform??HD(),r=e.env??process.env;if(n==="darwin")return vt(t,"Library","Application Support",`Claude${Gf}`);if(n==="win32"){let o=r.LOCALAPPDATA??vt(t,"AppData","Local");return vt(o,`Claude${Gf}`)}return null},Qs=(e={})=>{let t=ao(e);return t?t.slice(0,-Gf.length):null},jf=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)}`},_l=async e=>{let t=vt(e,WD),n;try{n=(await Un.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 Un.readdir(vt(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=vt(t,o,s);try{await Un.access(vt(i,KD)),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]}},Vf=async e=>{try{let t=await Un.readdir(e);return new Set(t.filter(n=>n.startsWith(Bn)&&n.endsWith(".json")).map(n=>n.slice(Bn.length,-5)))}catch{return new Set}},aa=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),GD=async(e,t)=>{let n=`${Bn}${t.sessionId}`,r=vt(e,n),o=vt(r,"outputs"),a=vt(r,".claude"),s=vt(a,"projects",jf(o));await Un.mkdir(o,{recursive:!0,mode:AC}),await Un.mkdir(s,{recursive:!0,mode:AC});let i=vt(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${UD()}`;await Un.copyFile(t.transcriptPath,c),await Un.chmod(c,384),await Un.rename(c,i);let l=t.createdAt??Date.now();await X(vt(e,`${n}.json`),{sessionId:n,cliSessionId:t.sessionId,processName:"claude-ai-import",cwd:o,hostLoopMode:!0,title:t.title,createdAt:l,lastActivityAt:t.lastActivityAt??l,isArchived:!1,userSelectedFolders:[],pendingNotifications:[]},{backup:!1})},vC=async(e,t)=>{let n=await Vf(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!aa(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await GD(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as sa}from"node:fs";import{homedir as jD}from"node:os";import{dirname as VD,join as ei}from"node:path";var YD=448,ZD=["Documents","Claude","Projects"],XD="spaces.json",JD=(e={})=>ei((e.home??jD)(),...ZD),qD=async e=>{try{let t=JSON.parse(await sa.readFile(e,"utf8"));if(!t||typeof t!="object")return{spaces:[],readable:!1};let n=t.spaces;return Array.isArray(n)?{spaces:n.filter(r=>!!r&&typeof r=="object"&&typeof r.id=="string"),readable:!0}:{spaces:[],readable:!1}}catch(t){return t.code==="ENOENT"?{spaces:[],readable:!0}:{spaces:[],readable:!1}}},zD=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},Yf=async e=>{try{return await sa.access(e),!0}catch{return!1}},QD=async(e,t,n)=>{let r=ei(t,zD(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await Yf(r)?o:r;return a===o&&await Yf(o)?null:(await sa.mkdir(VD(a),{recursive:!0}),await sa.cp(e,a,{recursive:!0}),a)},eN=async e=>{try{let t=(await sa.readFile(ei(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},SC=async e=>{let t=JD({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=ei(e.storageDir,XD),{spaces:a,readable:s}=await qD(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=ei(e.stagedProjectsDir,l.dirName);try{if(!await Yf(d)){n.failed+=1;continue}let u=await QD(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await eN(u);c.push({id:l.uuid,name:l.name,folders:[{path:u}],projects:[],links:[],...f?{instructions:f}:{},origin:"user",createdAt:e.now,updatedAt:e.now}),n.imported+=1}catch{n.failed+=1}}return c.length>0&&(await sa.mkdir(e.storageDir,{recursive:!0,mode:YD}),await X(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as oN}from"node:crypto";import{execFile as aN,spawnSync as NC}from"node:child_process";import{constants as $C}from"node:fs";import{access as $l,chmod as sN,mkdir as iN,readFile as Xf,rename as cN,rm as ca,stat as MC,writeFile as lN}from"node:fs/promises";import{homedir as dN,platform as uN,userInfo as pN}from"node:os";import{dirname as fN,isAbsolute as la,join as Ut,resolve as OC}from"node:path";import{isDeepStrictEqual as ni,promisify as hN}from"node:util";var ti="__anyray-claude-desktop-credential";var Pl=["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>`."],Tl=["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."],EC="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 Ll=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],IC=["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"],tN=new Set(IC),nN=new Set(IC.map(e=>e.toLowerCase())),rN=new Set(Ll.map(e=>e.toLowerCase())),Dl=(e,t=!1)=>(t?nN:tN).has(t?e.toLowerCase():e),xC=(e,t=!1)=>t?rN.has(e.toLowerCase()):Ll.some(n=>n===e),RC=["*"],so=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...RC]}),ia=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var ri=/^[a-f0-9-]{36}$/,FC="Anyray",Jf=4,si=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],ii=["deploymentMode","awaitingSignIn"],UC=[...si,...ii,"configLibrary","_meta.json"],gn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ct=e=>structuredClone(e),oi=async e=>{try{return await $l(e),!0}catch{return!1}},mN=async e=>{try{return await $l(e),"present"}catch(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"?"absent":"unreadable"}},rn=(e={})=>{let t=(e.home??dN)(),n=(e.username??(()=>pN().username))(),r=Ut(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Ut("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Ut(r,"configLibrary"),meta:Ut(r,"configLibrary","_meta.json"),appConfig:Ut(r,"claude_desktop_config.json"),helper:Ut(t,".anyray","bin","claude-desktop-credential-helper"),journal:Ut(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Ml=()=>{let e=NC("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},BC=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],yN=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...BC(t)]}},qf=(e="json")=>{let t=dn(BC(e)),n=OC(t.command),r=OC(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:ce()&&(!o||r!==n)}},gN=e=>`'${e.replace(/'/g,`'"'"'`)}'`,zf=e=>[e.command,...e.args].map(gN).join(" "),wN=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!la(e.command))throw new Error("the credential helper executable is not absolute")},HC=(e,t)=>{wN(e);let n=Fl(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!la(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},WC=e=>(HC(e,"--json"),`#!/bin/sh
|
|
205
|
-
exec ${
|
|
206
|
-
`),
|
|
207
|
-
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,
|
|
208
|
-
`)},
|
|
202
|
+
`),!0},Mf=async e=>{try{let t=yr(await bC(`${e}.anyray-bak`,"utf8"));return N(t)?t:void 0}catch{return}},Wf=e=>{if(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},OD=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=de({...t.metadata,tool:Xs}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!N(l.models)&&d.push("models");let u=N(l.models)?{...l.models}:{};if("providers"in u&&!N(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let f=N(u.providers)?{...u.providers}:{},p=!1;if(n){let v=N(l.plugins)?{...l.plugins}:{},E=N(v.load)?{...v.load}:{},I=N(v.entries)?{...v.entries}:{},C=N(I[Xe])?{...I[Xe]}:{},x=N(C.config)?{...C.config}:{};if("plugins"in l&&!N(l.plugins)||"load"in v&&!N(v.load)||"paths"in E&&!Array.isArray(E.paths)||"entries"in v&&!N(v.entries)||Xe in I&&!N(I[Xe])||"config"in C&&!N(C.config)||"env"in l&&!N(l.env))d.push("plugins");else{let T=Array.isArray(E.paths)?[...E.paths]:[];T.includes(n)||T.push(n),E.paths=T,v.load=E,C.enabled=!0,x.gatewayUrl=t.anthropicBaseUrl,x.apiKey=r;let U=t.metadata.user,Z=t.metadata.team;U&&(x.user=U),Z&&(x.team=Z),C.config=x,I[Xe]=C,v.entries=I,l.plugins=v;let Y=N(l.env)?{...l.env}:{};Y[Ar]=r,l.env=Y,p=!0}}let h=Il.filter(v=>v!=="openai"||!X(t,"openai"));for(let v of h){if(v in f&&!N(f[v])){d.push(`models.providers.${v}`);continue}let E=N(f[v])?{...f[v]}:{};if("headers"in E&&!N(E.headers)){i.push(v);continue}let I=N(E.headers)?{...E.headers}:{};if(E.baseUrl=v==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,v==="anthropic"&&(E.api=Hf,(typeof E.maxTokens!="number"||E.maxTokens<=0)&&(E.maxTokens=Kf)),v==="anthropic"&&a)E.apiKey=a.key,I[oo]=`Bearer ${a.key}`,I["x-anyray-provider"]="anthropic",I["x-anyray-auth-mode"]="passthrough",I["x-anyray-custom-host"]=a.url;else{E.apiKey=r,"x-anyray-custom-host"in I&&delete I[oo];for(let C of Bf)delete I[C]}I[oa]=r,o&&(I[Uf]=o),v==="anthropic"&&(ao in I?c=I[ao]!==El:I[ao]=El),E.headers=I,f[v]=E,s.push(v)}u.providers=f,l.models=u;let m=!1,w=!1,g=!1,y,b=[],A="agents"in l&&!N(l.agents)||N(l.agents)&&"defaults"in l.agents&&!N(l.agents.defaults)||N(l.agents)&&N(l.agents.defaults)&&("params"in l.agents.defaults&&!N(l.agents.defaults.params)||"model"in l.agents.defaults&&!N(l.agents.defaults.model));if(A&&d.push("agents.defaults"),s.includes("anthropic")&&!A){let v=N(l.agents)?{...l.agents}:{},E=N(v.defaults)?{...v.defaults}:{},I=N(E.params)?{...E.params}:{};"cacheRetention"in I||(I.cacheRetention=kC,m=!0,E.params=I);let C=N(E.model)?{...E.model}:{},x=p?[...s,Xe]:s,T=U=>typeof U=="string"&&x.some(Z=>U.startsWith(`${Z}/`));typeof C.primary!="string"||C.primary.trim()===""?(C.primary=p?jf:xl,w=!0,E.model=C,"fallbacks"in C||(C.fallbacks=p?[...Vf]:[...Gf],g=!0)):T(C.primary)||(y=C.primary),b=(Array.isArray(C.fallbacks)?C.fallbacks:[]).filter(U=>typeof U=="string"&&!T(U)),(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}},_D=["baseUrl","apiKey","api","maxTokens"],Ff=(e,t,n=Il,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=Wf(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[oa]=="string"||typeof h[Uf]=="string"||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_")||Bf.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===Hf:v==="maxTokens"?p.maxTokens===Kf:v==="apiKey"?y||typeof p.apiKey=="string"&&p.apiKey.startsWith("ark_"):!0;for(let v of _D)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=[oa,Uf,...Bf,..."x-anyray-custom-host"in h?[oo]:[]];h[ao]===El&&A.push(ao);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);oo in g&&!(oo in h)&&(h[oo]=g[oo],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[Xe];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:{};Xe in b?JSON.stringify(p[Xe])!==JSON.stringify(b[Xe])&&(p[Xe]=b[Xe],l=!0):(delete p[Xe],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[Ar];if(typeof g=="string"&&g.startsWith("ark_")){let y=N(t?.env)?t.env:{};Ar in y?w[Ar]!==y[Ar]&&(w[Ar]=y[Ar],l=!0):(delete w[Ar],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===kC&&("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:{};xD.includes(g.primary)&&("primary"in y?g.primary!==y.primary&&(g.primary=y.primary,l=!0):(delete g.primary,l=!0)),RD.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}},vC={id:Xs,title:"OpenClaw",automatic:!0,async detect(){let e=await R(ro())||await R(CC());return{installed:e,detail:e?ro():`no ${Sl(wC(),".openclaw")} state dir`}},async apply(e,t){let n=ro();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 ${Xs}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],I;try{I=await Js(n)}catch{return{status:"held",messages:E}}let{next:C,removed:x}=Ff(I.data,await Mf(n),Il,rn());return x?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...E]}:(await $f(n,I,C,!1),await ae(n),await vl(),{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 vl(),{status:"held",messages:E})}let r=rn(),o=!1;if(!t.dryRun)try{await yC(r)}catch{r=void 0,o=!0}let a;try{a=await Js(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Hf}", "maxTokens": ${Kf}, "apiKey": "<your personal ark_ key>", "headers": { "${oa}": "<your personal ark_ key>", "${ao}": "${El}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${oa}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${xl}") 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}=OD(a.data,e,r),g=s,y=!1;if(!i.includes("openai")){let E=Ff(g,await Mf(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:Xs})??"(none \u2014 pass --user, or --enroll for a per-user key)"}`,...c?['Seeded agents.defaults.params.cacheRetention = "short": OpenClaw',"skips its prompt-cache auto-seed on custom hosts, and an unset","value would leave the provider cache permanently cold."]:["Kept your existing cacheRetention setting."],...l?[`Kept your existing ${ao} header value (OpenClaw suppresses its implicit beta headers off-host; yours replaces our default restore).`]:[],...d.length>0?[`Could not add headers on models.providers.${d.join(", ")}: the existing "headers" value is not an object. Fix it manually; nothing there was replaced.`]:[],...u?[`Seeded agents.defaults.model.primary = ${w?jf:xl} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(w?Vf:Gf).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 (${rn()}) and registered it under plugins.entries.${Xe}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${rn()}; 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 $f(n,a,g,!0);return{status:A,messages:b,changedFiles:v?[n]:[]}},async pointsAt(e){try{let{data:t}=await Js(ro());for(let a of Object.values(Wf(t)))if(N(a)&&gC(a.baseUrl,e))return!0;let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[Xe];if(N(o)&&N(o.config)&&gC(o.config.gatewayUrl,e))return!0}catch{}return!1},async watchPaths(){return[ro(),Sl(rn(),".anyray-source-sha")]},async routingExpected(e){return e.includes(Xs)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Js(ro());for(let a of Object.values(Wf(t))){if(!N(a))continue;let s=N(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[oa]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[Xe];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=ro();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 Js(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}=Ff(n.data,await Mf(t),Il,rn()),a=await vl();return o?(await $f(t,n,r,!1),await ae(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${rn()}`]:[]],changedFiles:[t]}):(await ae(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${rn()}`]:[]]})}};import{execFile as wM}from"node:child_process";import{readFile as bM}from"node:fs/promises";import{homedir as mi,platform as Sr}from"node:os";import{join as An}from"node:path";import{isDeepStrictEqual as Ph,promisify as kM}from"node:util";var zs=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},Rl=(e,t)=>{let n=zs(e),r=zs(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 N$}from"node:crypto";import{promises as DA}from"node:fs";import{platform as $$,tmpdir as M$}from"node:os";import{join as Vl}from"node:path";import{execFile as TD}from"node:child_process";import{promises as qs}from"node:fs";import{homedir as PD,platform as LD}from"node:os";import{delimiter as DD,join as Ol}from"node:path";import{promisify as ND}from"node:util";var $D=ND(TD),MD=15*6e4,FD=64*1024*1024,UD=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],SC=async(e={})=>{let t=(e.home??PD)(),n=e.env??process.env,r=UD(e.runtimePlatform??LD()),o=[Ol(t,".local","bin"),Ol(t,".claude","local"),...(n.PATH??"").split(DD).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Ol(a,`claude${s}`);try{return await qs.access(i),i}catch{}}return null},BD=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},WD=async e=>{let t=Ol(e,"projects"),n;try{n=(await qs.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(!GD.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},HD=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:BD(n.projectList)}},KD=async e=>{let t,n;try{let r=await qs.readFile(e,"utf8");for(let o of r.split(`
|
|
203
|
+
`)){if(o.length===0)continue;let a;try{a=JSON.parse(o).timestamp}catch{continue}if(typeof a!="string")continue;let s=Date.parse(a);Number.isFinite(s)&&(t??=s,n=s)}}catch{return{}}return{createdAt:t,lastActivityAt:n??t}},GD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,jD=/\.(?:cmd|bat)$/i,VD=(e,t)=>jD.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},EC=async(e,t={})=>{let n=t.exec??$D,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 qs.mkdir(e.configDir,{recursive:!0,mode:448}),await qs.mkdir(e.workDir,{recursive:!0,mode:448});let o=VD(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:MD,maxBuffer:FD,windowsVerbatimArguments:o.verbatim})).stdout}catch(d){let u=d.code;return{ok:!1,reason:typeof u=="number"?`the Claude Code importer exited with status ${u}`:"the Claude Code importer could not be run"}}let s=a.split(`
|
|
204
|
+
`).filter(d=>d.trim().length>0),i=HD(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 KD(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await WD(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as YD}from"node:crypto";import{promises as Bn}from"node:fs";import{homedir as ZD,platform as JD}from"node:os";import{join as vt}from"node:path";var IC=448,Wn="local_",XD="local-agent-mode-sessions",Yf="-3p",zD="cowork_account_settings.json",so=(e={})=>{let t=(e.home??ZD)(),n=e.runtimePlatform??JD(),r=e.env??process.env;if(n==="darwin")return vt(t,"Library","Application Support",`Claude${Yf}`);if(n==="win32"){let o=r.LOCALAPPDATA??vt(t,"AppData","Local");return vt(o,`Claude${Yf}`)}return null},Qs=(e={})=>{let t=so(e);return t?t.slice(0,-Yf.length):null},Zf=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)}`},_l=async e=>{let t=vt(e,XD),n;try{n=(await Bn.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return{ok:!1,reason:"no-profile",found:[]}}let r=[];for(let o of n){let a;try{a=(await Bn.readdir(vt(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=vt(t,o,s);try{await Bn.access(vt(i,zD)),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]}},Jf=async e=>{try{let t=await Bn.readdir(e);return new Set(t.filter(n=>n.startsWith(Wn)&&n.endsWith(".json")).map(n=>n.slice(Wn.length,-5)))}catch{return new Set}},aa=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),qD=async(e,t)=>{let n=`${Wn}${t.sessionId}`,r=vt(e,n),o=vt(r,"outputs"),a=vt(r,".claude"),s=vt(a,"projects",Zf(o));await Bn.mkdir(o,{recursive:!0,mode:IC}),await Bn.mkdir(s,{recursive:!0,mode:IC});let i=vt(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${YD()}`;await Bn.copyFile(t.transcriptPath,c),await Bn.chmod(c,384),await Bn.rename(c,i);let l=t.createdAt??Date.now();await J(vt(e,`${n}.json`),{sessionId:n,cliSessionId:t.sessionId,processName:"claude-ai-import",cwd:o,hostLoopMode:!0,title:t.title,createdAt:l,lastActivityAt:t.lastActivityAt??l,isArchived:!1,userSelectedFolders:[],pendingNotifications:[]},{backup:!1})},xC=async(e,t)=>{let n=await Jf(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!aa(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await qD(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as sa}from"node:fs";import{homedir as QD}from"node:os";import{dirname as eN,join as ei}from"node:path";var tN=448,nN=["Documents","Claude","Projects"],rN="spaces.json",oN=(e={})=>ei((e.home??QD)(),...nN),aN=async e=>{try{let t=JSON.parse(await sa.readFile(e,"utf8"));if(!t||typeof t!="object")return{spaces:[],readable:!1};let n=t.spaces;return Array.isArray(n)?{spaces:n.filter(r=>!!r&&typeof r=="object"&&typeof r.id=="string"),readable:!0}:{spaces:[],readable:!1}}catch(t){return t.code==="ENOENT"?{spaces:[],readable:!0}:{spaces:[],readable:!1}}},sN=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},Xf=async e=>{try{return await sa.access(e),!0}catch{return!1}},iN=async(e,t,n)=>{let r=ei(t,sN(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await Xf(r)?o:r;return a===o&&await Xf(o)?null:(await sa.mkdir(eN(a),{recursive:!0}),await sa.cp(e,a,{recursive:!0}),a)},cN=async e=>{try{let t=(await sa.readFile(ei(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},RC=async e=>{let t=oN({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=ei(e.storageDir,rN),{spaces:a,readable:s}=await aN(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=ei(e.stagedProjectsDir,l.dirName);try{if(!await Xf(d)){n.failed+=1;continue}let u=await iN(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await cN(u);c.push({id:l.uuid,name:l.name,folders:[{path:u}],projects:[],links:[],...f?{instructions:f}:{},origin:"user",createdAt:e.now,updatedAt:e.now}),n.imported+=1}catch{n.failed+=1}}return c.length>0&&(await sa.mkdir(e.storageDir,{recursive:!0,mode:tN}),await J(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as pN}from"node:crypto";import{execFile as fN,spawnSync as UC}from"node:child_process";import{constants as BC}from"node:fs";import{access as $l,chmod as hN,mkdir as mN,readFile as qf,rename as yN,rm as ca,stat as WC,writeFile as gN}from"node:fs/promises";import{homedir as wN,platform as bN,userInfo as kN}from"node:os";import{dirname as CN,isAbsolute as la,join as Ut,resolve as LC}from"node:path";import{isDeepStrictEqual as ni,promisify as AN}from"node:util";var ti="__anyray-claude-desktop-credential";var Tl=["Heads up: Claude Desktop's third-party mode uses its own app profile, so it opens signed out with empty conversation lists. Nothing is deleted and your Claude account is unchanged \u2014 sign back in with the account you already use.","Your Claude Code sessions and Cowork tasks come across on their own once this new profile has been signed in to and the app is fully quit \u2014 no second command.","Your claude.ai chats live on your Claude account rather than this machine, so those need your data export: `anyray-connect migrate --export <file.zip>`."],Pl=["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."],OC="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 Ll=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],_C=["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"],lN=new Set(_C),dN=new Set(_C.map(e=>e.toLowerCase())),uN=new Set(Ll.map(e=>e.toLowerCase())),Dl=(e,t=!1)=>(t?dN:lN).has(t?e.toLowerCase():e),TC=(e,t=!1)=>t?uN.has(e.toLowerCase()):Ll.some(n=>n===e),PC=["*"],io=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...PC]}),ia=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var ri=/^[a-f0-9-]{36}$/,HC="Anyray",Qf=4,si=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],ii=["deploymentMode","awaitingSignIn"],KC=[...si,...ii,"configLibrary","_meta.json"],bn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ct=e=>structuredClone(e),oi=async e=>{try{return await $l(e),!0}catch{return!1}},vN=async e=>{try{return await $l(e),"present"}catch(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"?"absent":"unreadable"}},on=(e={})=>{let t=(e.home??wN)(),n=(e.username??(()=>kN().username))(),r=Ut(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Ut("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Ut(r,"configLibrary"),meta:Ut(r,"configLibrary","_meta.json"),appConfig:Ut(r,"claude_desktop_config.json"),helper:Ut(t,".anyray","bin","claude-desktop-credential-helper"),journal:Ut(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Ml=()=>{let e=UC("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},GC=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],SN=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...GC(t)]}},eh=(e="json")=>{let t=un(GC(e)),n=LC(t.command),r=LC(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:ce()&&(!o||r!==n)}},EN=e=>`'${e.replace(/'/g,`'"'"'`)}'`,th=e=>[e.command,...e.args].map(EN).join(" "),IN=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!la(e.command))throw new Error("the credential helper executable is not absolute")},jC=(e,t)=>{IN(e);let n=Fl(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!la(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},VC=e=>(jC(e,"--json"),`#!/bin/sh
|
|
205
|
+
exec ${th(e)}
|
|
206
|
+
`),xN=`#!/bin/sh
|
|
207
|
+
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,YC=e=>{jC(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),ti]};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 ${th(t)}`,""].join(`
|
|
208
|
+
`)},RN=e=>e.args.at(-1)==="--passthrough-headers"?YC(e):VC(e),Fl=e=>/[\\/](node|node\.exe)$/i.test(e),nh=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++}},ON=e=>{let t=`#!/bin/sh
|
|
209
209
|
exec `;if(!e.startsWith(t)||!e.endsWith(`
|
|
210
210
|
`))return;let n=e.slice(t.length,-1);if(n.includes(`
|
|
211
|
-
`)||n.includes("\r"))return;let r=
|
|
212
|
-
# Anyray subscription pass-through credential helper`,
|
|
213
|
-
`)},
|
|
214
|
-
`,384)},
|
|
215
|
-
`,384)},ai=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!ri.test(t)||!Array.isArray(n))throw new Error("Claude config-library metadata has an invalid shape");let r=new Set;for(let o of n){if(!gn(o)||typeof o.id!="string"||!ri.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},MN=async(e,t,n)=>{let r=await wn(e.meta);if(t){if(!r.present){if(t.metaFileExisted)throw new Error("Claude config-library metadata disappeared after apply");return{configId:t.configId,meta:r,metaFileExisted:!1,metaEntry:ct(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[ct(t.metaEntry)]}}}let c=ai(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!ni(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:ct(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...ct(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=ai(r.value);let c=Ut(e.library,`${o}.json`);if(!await oi(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=ct(r.value.entries)}let s=n();if(!ri.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await oi(Ut(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:FC};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?ct(r.value):{},appliedId:s,entries:[...a,i]}}},FN=(e,t)=>{let n=so(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},VC=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),UN=async(e,t,n,r,o,a,s)=>{let i=VC(),c=Object.fromEntries(si.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(ii.map(d=>[d,{original:s?.deployment[d].original??jC(r.value,d),lastWritten:i[d]}]));return{version:Jf,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??ct(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await ci(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Nl=e=>({status:"manual",messages:[e]}),BN=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}`)]}},HN=hN(aN),WN=new Set(Ll),KN=async e=>{try{let{stdout:t}=await HN("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return gn(n)?Object.keys(n):void 0}catch{return}},io=async(e,t={})=>{let n=t.readManagedPolicyKeys??KN;for(let r of e.managedPolicies){let o=await mN(r);if(o==="absent")continue;if(o==="unreadable")return{path:r,keys:[],unreadable:!0};let a=await n(r);if(a===void 0)return{path:r,keys:[],unreadable:!0};let s=a.filter(i=>Dl(i)&&!WN.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},nh=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.`},rh=e=>(e.platform??uN)()==="darwin",YC=async(e,t,n={})=>{if(!rh(n))return Nl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Ml)()&&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=rn(n),a=await io(o,n);if(a&&r.push({audience:"admin",message:nh(a)}),r.length>0)return BN(r);let s=!1,i=!1,c=[o.journal];try{let l=J(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??IN)())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=yN((n.credentialCommand??(()=>qf(d)))(),d),f=kN(u),p=await th(o),h=await ci(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 MN(o,p,n.randomUUID??oN),w=Ut(o.library,`${m.configId}.json`);c=[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig];let g=await wn(w),y=await wn(o.appConfig),b=FN(e,o.helper),A=await UN(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 LC(o.journal,A),i=!0,await Ul(o.helper,f,448),A.helper.previousWritten!==void 0&&(delete A.helper.previousWritten,await LC(o.journal,A));let S=ct(g.value);for(let C of si)Zf(S,C,b[C]);await Hn(w,S),m.metaToWrite&&await Hn(o.meta,m.metaToWrite);let E=ct(y.value),I=VC();for(let C of ii)Zf(E,C,I[C]);return await Hn(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.",...Pl]}}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.`]}:Nl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},DC=(e,t,n,r)=>{let o=ct(e);for(let a of n){let s=t[a];ni(jC(e,a),s.lastWritten)?Zf(o,a,s.original):r.push(a)}return o},ZC=async(e,t={})=>{if(!rh(t))return{status:"not-found",messages:[]};if((t.appRunning??Ml)())return Nl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=rn(t);try{let r=await th(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Ut(n.library,`${r.configId}.json`);if(e.dryRun)return{status:"reverted",messages:[`Would restore Anyray-owned Claude Desktop fields from ${n.journal}, preserving user changes.`]};let a=[],s=await wn(o),i=s.value;s.present&&(i=DC(s.value,r.config,si,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await wn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let h=ai(l.value),m=ct(l.value.entries),w=m.findIndex(b=>b.id===r.configId),g=w>=0?m[w]:void 0,y=g!==void 0&&ni(g,r.metaEntry);if(g!==void 0&&!y&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=ct(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=ni(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&h!==r.configId?(y&&m.splice(w,1),d={...ct(l.value),entries:m}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await ca(o,{force:!0}):await Hn(o,i)),l.present&&(u?await ca(n.meta,{force:!0}):ni(l.value,d)||await Hn(n.meta,d));let f=await wn(n.appConfig);if(f.present){let h=DC(f.value,r.deployment,ii,a);!r.deploymentFileExisted&&Object.keys(h).length===0?await ca(n.appConfig,{force:!0}):await Hn(n.appConfig,h)}else r.deploymentFileExisted&&a.push("deployment config file");let p=await ci(n.helper);return p.present&&(p.content===r.helper.lastWritten||p.content===r.helper.previousWritten)?r.helper.original.present?await Ul(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await ca(n.helper,{force:!0}):(p.present||r.helper.original.present)&&a.push("credential helper"),await ca(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?[]:Tl]}}catch(r){return Nl(`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.`)}},oh=async(e,t={})=>{if(!rh(t))return!1;let n=rn(t);if(await io(n,t))return!1;try{let r=await wn(n.meta);if(!r.present)return!1;let o=ai(r.value),a=await wn(Ut(n.library,`${o}.json`)),s=await wn(n.appConfig);if(!a.present||!s.present)return!1;await $l(n.helper,$C.X_OK);let i=Ye(e);return a.value.inferenceProvider==="gateway"&&a.value.inferenceGatewayBaseUrl===i&&a.value.inferenceGatewayAuthScheme==="bearer"&&a.value.inferenceCredentialKind==="helper-script"&&a.value.inferenceCredentialHelper===n.helper&&!Object.prototype.hasOwnProperty.call(a.value,"inferenceGatewayApiKey")&&s.value.deploymentMode==="3p"&&!Object.prototype.hasOwnProperty.call(s.value,"awaitingSignIn")}catch{return!1}},XC=async(e={})=>{try{let t=rn(e),n=await ci(t.helper);if(!n.present||typeof n.content!="string")return;let r=GC(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},JC=async(e,t={})=>{if(!await oh(e,t))return!1;let n=rn(t);try{let r=await th(n);if(!r)return!1;let o=await wn(n.meta);if(!o.present||ai(o.value)!==r.configId)return!1;let a=await ci(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=GC(a.content??"");return s?await(t.helperLauncherAvailable??xN)(s):!1}catch{return!1}};import{createHash as pA,randomUUID as fA}from"node:crypto";import{spawn as GN,spawnSync as jN}from"node:child_process";import{link as uh,mkdir as ah,open as hA,readFile as sh,readdir as mA,rename as yA,rm as on,stat as gA}from"node:fs/promises";import{homedir as ph}from"node:os";import{basename as wA,dirname as di,join as ya,win32 as VN}from"node:path";import{isDeepStrictEqual as da}from"node:util";var _e="HKCU\\SOFTWARE\\Policies\\Claude",li="HKLM\\SOFTWARE\\Policies\\Claude",Kl=5,ga="inferenceGatewayApiKey",Ne=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ga],qC=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ga],zC=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ga],QC=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ga],bA="Managed by anyray-connect; dynamic credential only.",YN=e=>/^[A-Za-z]:[\\/]/.test(e)&&VN.isAbsolute(e),eA=e=>{if(!YN(e)||/[\0\r\n"]/u.test(e))return!1;let t=e.replace(/\\/g,"/").toLowerCase();return!/(^|\/)_npx(\/|$)/u.test(t)&&!/\/appdata\/local\/temp(\/|$)/u.test(t)&&!/(^|\/)temp(\/|$)/u.test(t)},kA=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!eA(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&&!eA(e.args[0]))throw new Error("the credential helper does not use print-key --json")},fh=(e={})=>ya((e.home??ph)(),".anyray","bin","claude-desktop-credential-helper.cmd"),ZN=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},XN=e=>(kA(e),["@echo off",`REM ${bA}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(ZN).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
216
|
-
`)),
|
|
217
|
-
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${
|
|
211
|
+
`)||n.includes("\r"))return;let r=nh(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Fl(o);if(!la(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!la(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return VC(i)===e?i:void 0}catch{return}},_N=e=>{if(!e.startsWith(xN))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=nh(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==ti)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return YC(a)===e?a:void 0}catch{return}},TN=`#!/bin/sh
|
|
212
|
+
# Anyray subscription pass-through credential helper`,PN=e=>{let t=Fl(e.command);if(!(!la(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!la(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=$(${th(e)})`,'if [ -z "${headers}" ]; then'," echo 'Anyray: could not resolve gateway headers; is this machine enrolled? Run: anyray-connect' >&2"," exit 1","fi","token=$(security find-generic-password -s 'Claude Code-credentials' -w 2>/dev/null | grep -oE 'sk-ant-oat[0-9A-Za-z._-]+' | head -n1)",'if [ -z "${token}" ]; then'," echo 'Anyray: no Claude subscription sign-in found; run: claude' >&2"," exit 1","fi",'printf \'{"token":"%s","headers":%s}\\n\' "${token}" "${headers}"',""].join(`
|
|
213
|
+
`)},LN=e=>{if(!e.startsWith(TN))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=nh(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return PN(a)===e?a:void 0},ZC=e=>ON(e)??_N(e)??LN(e),DN=async()=>{let e=UC("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},NN=async e=>{let t=[e.command,...Fl(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>WC(r)))).every(r=>r.isFile())?(await $l(e.command,BC.X_OK),!0):!1}catch{return!1}},$N=0,Ul=async(e,t,n)=>{await mN(CN(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${$N++}.tmp`;try{await gN(r,t,{mode:n}),await hN(r,n),await yN(r,e)}catch(o){throw await ca(r,{force:!0}).catch(()=>{}),o}},Hn=async(e,t)=>{await Ul(e,`${JSON.stringify(t,null,2)}
|
|
214
|
+
`,384)},kn=async e=>{if(!await oi(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await qf(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!bn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},ci=async e=>{if(!await oi(e))return{present:!1};let t=await WC(e);return{present:!0,content:await qf(e,"utf-8"),mode:t.mode&511}},JC=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:ct(e[t])}:{present:!1},zf=(e,t,n)=>{n.present?e[t]=ct(n.value):delete e[t]},DC=e=>bn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),MN=e=>bn(e)&&DC(e.original)&&DC(e.lastWritten),FN=e=>bn(e)&&typeof e.present=="boolean"&&(!e.present||typeof e.content=="string"&&typeof e.mode=="number"&&Number.isInteger(e.mode)&&e.mode>=0&&e.mode<=511),NC=(e,t)=>bn(e)&&t.every(n=>MN(e[n])),UN=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],BN=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],rh=(e,t,n,r)=>!(!bn(e)||e.version!==n||typeof e.configId!="string"||!ri.test(e.configId)||typeof e.metaFileExisted!="boolean"||e.originalAppliedId!==void 0&&(typeof e.originalAppliedId!="string"||!ri.test(e.originalAppliedId))||e.metaFileExisted!==(e.originalAppliedId!==void 0)||!bn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==HC||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!NC(e.config,r)||r.some(o=>e.config[o].original.present)||!NC(e.deployment,ii)||!bn(e.helper)||e.helper.path!==t.helper||!FN(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),WN=(e,t)=>rh(e,t,Qf,si),HN=(e,t)=>rh(e,t,2,UN),KN=(e,t)=>rh(e,t,3,BN),GN=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),$C=e=>({...e,version:Qf,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),oh=async e=>{if(!await oi(e.journal))return;let t;try{t=JSON.parse(await qf(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(WN(t,e))return t;if(KN(t,e))return $C(t);if(HN(t,e))return $C(GN(t));throw new Error(`${e.journal} is not a valid ownership journal`)},MC=async(e,t)=>{await Ul(e,`${JSON.stringify(t,null,2)}
|
|
215
|
+
`,384)},ai=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!ri.test(t)||!Array.isArray(n))throw new Error("Claude config-library metadata has an invalid shape");let r=new Set;for(let o of n){if(!bn(o)||typeof o.id!="string"||!ri.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},jN=async(e,t,n)=>{let r=await kn(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:ct(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[ct(t.metaEntry)]}}}let c=ai(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!ni(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:ct(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...ct(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=ai(r.value);let c=Ut(e.library,`${o}.json`);if(!await oi(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=ct(r.value.entries)}let s=n();if(!ri.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await oi(Ut(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:HC};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?ct(r.value):{},appliedId:s,entries:[...a,i]}}},VN=(e,t)=>{let n=io(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},XC=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),YN=async(e,t,n,r,o,a,s)=>{let i=XC(),c=Object.fromEntries(si.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(ii.map(d=>[d,{original:s?.deployment[d].original??JC(r.value,d),lastWritten:i[d]}]));return{version:Qf,configId:t.configId,metaFileExisted:s?.metaFileExisted??t.metaFileExisted,originalAppliedId:s?.originalAppliedId??t.originalAppliedId,metaEntry:s?.metaEntry??ct(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await ci(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Nl=e=>({status:"manual",messages:[e]}),ZN=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}`)]}},JN=AN(fN),XN=new Set(Ll),zN=async e=>{try{let{stdout:t}=await JN("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return bn(n)?Object.keys(n):void 0}catch{return}},co=async(e,t={})=>{let n=t.readManagedPolicyKeys??zN;for(let r of e.managedPolicies){let o=await vN(r);if(o==="absent")continue;if(o==="unreadable")return{path:r,keys:[],unreadable:!0};let a=await n(r);if(a===void 0)return{path:r,keys:[],unreadable:!0};let s=a.filter(i=>Dl(i)&&!XN.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},ah=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.`},sh=e=>(e.platform??bN)()==="darwin",zC=async(e,t,n={})=>{if(!sh(n))return Nl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Ml)()&&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=on(n),a=await co(o,n);if(a&&r.push({audience:"admin",message:ah(a)}),r.length>0)return ZN(r);let s=!1,i=!1,c=[o.journal];try{let l=X(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??DN)())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=SN((n.credentialCommand??(()=>eh(d)))(),d),f=RN(u),p=await oh(o),h=await ci(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 jN(o,p,n.randomUUID??pN),w=Ut(o.library,`${m.configId}.json`);c=[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig];let g=await kn(w),y=await kn(o.appConfig),b=VN(e,o.helper),A=await YN(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 MC(o.journal,A),i=!0,await Ul(o.helper,f,448),A.helper.previousWritten!==void 0&&(delete A.helper.previousWritten,await MC(o.journal,A));let v=ct(g.value);for(let C of si)zf(v,C,b[C]);await Hn(w,v),m.metaToWrite&&await Hn(o.meta,m.metaToWrite);let E=ct(y.value),I=XC();for(let C of ii)zf(E,C,I[C]);return await Hn(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.",...Tl]}}catch(l){let d=l instanceof Error?l.message:String(l);return s?{status:"manual",changedFiles:c,messages:[i?`Claude Desktop setup stopped after its ownership journal was written (${d}). Some listed files may contain a partial Anyray configuration.`:`Claude Desktop setup stopped while writing its ownership journal (${d}). No app configuration write was attempted, but the journal path may need cleanup.`,i?"Re-run connect to converge the journaled setup, or run --revert to restore the pre-Anyray values.":`Inspect ${o.journal}, then re-run connect.`]}:Nl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},FC=(e,t,n,r)=>{let o=ct(e);for(let a of n){let s=t[a];ni(JC(e,a),s.lastWritten)?zf(o,a,s.original):r.push(a)}return o},qC=async(e,t={})=>{if(!sh(t))return{status:"not-found",messages:[]};if((t.appRunning??Ml)())return Nl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=on(t);try{let r=await oh(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Ut(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 kn(o),i=s.value;s.present&&(i=FC(s.value,r.config,si,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await kn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let h=ai(l.value),m=ct(l.value.entries),w=m.findIndex(b=>b.id===r.configId),g=w>=0?m[w]:void 0,y=g!==void 0&&ni(g,r.metaEntry);if(g!==void 0&&!y&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=ct(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=ni(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&h!==r.configId?(y&&m.splice(w,1),d={...ct(l.value),entries:m}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await ca(o,{force:!0}):await Hn(o,i)),l.present&&(u?await ca(n.meta,{force:!0}):ni(l.value,d)||await Hn(n.meta,d));let f=await kn(n.appConfig);if(f.present){let h=FC(f.value,r.deployment,ii,a);!r.deploymentFileExisted&&Object.keys(h).length===0?await ca(n.appConfig,{force:!0}):await Hn(n.appConfig,h)}else r.deploymentFileExisted&&a.push("deployment config file");let p=await ci(n.helper);return p.present&&(p.content===r.helper.lastWritten||p.content===r.helper.previousWritten)?r.helper.original.present?await Ul(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await ca(n.helper,{force:!0}):(p.present||r.helper.original.present)&&a.push("credential helper"),await ca(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?[]:Pl]}}catch(r){return Nl(`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.`)}},ih=async(e,t={})=>{if(!sh(t))return!1;let n=on(t);if(await co(n,t))return!1;try{let r=await kn(n.meta);if(!r.present)return!1;let o=ai(r.value),a=await kn(Ut(n.library,`${o}.json`)),s=await kn(n.appConfig);if(!a.present||!s.present)return!1;await $l(n.helper,BC.X_OK);let i=Ye(e);return a.value.inferenceProvider==="gateway"&&a.value.inferenceGatewayBaseUrl===i&&a.value.inferenceGatewayAuthScheme==="bearer"&&a.value.inferenceCredentialKind==="helper-script"&&a.value.inferenceCredentialHelper===n.helper&&!Object.prototype.hasOwnProperty.call(a.value,"inferenceGatewayApiKey")&&s.value.deploymentMode==="3p"&&!Object.prototype.hasOwnProperty.call(s.value,"awaitingSignIn")}catch{return!1}},QC=async(e={})=>{try{let t=on(e),n=await ci(t.helper);if(!n.present||typeof n.content!="string")return;let r=ZC(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},eA=async(e,t={})=>{if(!await ih(e,t))return!1;let n=on(t);try{let r=await oh(n);if(!r)return!1;let o=await kn(n.meta);if(!o.present||ai(o.value)!==r.configId)return!1;let a=await ci(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=ZC(a.content??"");return s?await(t.helperLauncherAvailable??NN)(s):!1}catch{return!1}};import{createHash as yA,randomUUID as gA}from"node:crypto";import{spawn as qN,spawnSync as QN}from"node:child_process";import{link as hh,mkdir as ch,open as wA,readFile as lh,readdir as bA,rename as kA,rm as an,stat as CA}from"node:fs/promises";import{homedir as mh}from"node:os";import{basename as AA,dirname as di,join as ya,win32 as e$}from"node:path";import{isDeepStrictEqual as da}from"node:util";var _e="HKCU\\SOFTWARE\\Policies\\Claude",li="HKLM\\SOFTWARE\\Policies\\Claude",Kl=5,ga="inferenceGatewayApiKey",Ne=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ga],tA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ga],nA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ga],rA=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ga],vA="Managed by anyray-connect; dynamic credential only.",t$=e=>/^[A-Za-z]:[\\/]/.test(e)&&e$.isAbsolute(e),oA=e=>{if(!t$(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)},SA=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!oA(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&&!oA(e.args[0]))throw new Error("the credential helper does not use print-key --json")},yh=(e={})=>ya((e.home??mh)(),".anyray","bin","claude-desktop-credential-helper.cmd"),n$=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},r$=e=>(SA(e),["@echo off",`REM ${vA}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(n$).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
216
|
+
`)),o$=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},EA=e=>{let t=e.split(`\r
|
|
217
|
+
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${vA}`||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(o$);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return SA(s),s}catch{return}},a$=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>CA(r)))).every(r=>r.isFile())}catch{return!1}},s$=async(e,t)=>{let n=EA(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??a$)(n)}catch{return!1}},dh=e=>({sha256:lo(e),content:e}),aA=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Bt(t,["sha256","content"])&&h$(t.sha256)&&typeof t.content=="string"&&lo(t.content)===t.sha256&&EA(t.content)!==void 0},gh=()=>{let e=QN("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??"")},i$=async(e,t)=>{await ch(di(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await wA(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await hh(n,e)}finally{await an(n,{force:!0}).catch(()=>{})}},c$=e=>`${AA(e)}.anyray-old-`,l$=e=>`${e}.anyray-old-${process.pid}-${gA()}`,IA=async(e,t)=>{try{await hh(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await an(t,{force:!0}),!0},Wl=async(e,t,n,r,o)=>{let a=l$(e),s=n===void 0?void 0:lo(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${gA()}`,c=!1;try{if(i&&n!==void 0){let d=await wA(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 kA(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await ha(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await hh(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await ma(e)!==s))throw new Error("credential helper publication verification failed");await an(a,{force:!0}),c=!1}catch(l){throw c&&await IA(e,a).catch(()=>!1),l}finally{i&&await an(i,{force:!0}).catch(()=>{})}},uh=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,d$=String.raw`
|
|
218
218
|
$ErrorActionPreference = 'Stop'
|
|
219
219
|
try {
|
|
220
220
|
$request = ConvertFrom-Json ([Console]::In.ReadToEnd())
|
|
@@ -283,29 +283,29 @@ try {
|
|
|
283
283
|
exit 5
|
|
284
284
|
} catch {
|
|
285
285
|
exit 6
|
|
286
|
-
}`,
|
|
287
|
-
`)}catch(a){if(a.code!=="EEXIST")throw await
|
|
288
|
-
`;t.writeJournalFile?await t.writeJournalFile(n,r):await he(n,r)},h$=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,m$=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),y$=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),g$=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),w$=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===g$(t).toUpperCase(),dA=(e,t,n,r,o)=>{let a=Ne.find(i=>i.toLowerCase()===t.toLowerCase());if(!a)return!1;let s=n==="String"?"REG_SZ":n==="ExpandString"?"REG_EXPAND_SZ":n;if(s!=="REG_SZ"&&s!=="REG_EXPAND_SZ"){if(o)throw new Error("an owned Claude policy value has an unsupported type");return!1}if(e[a].present)throw new Error("a Claude policy value was returned more than once");return e[a]={present:!0,type:s,value:r},!0},b$=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,k$=(e,t)=>{if(!Dl(e,!0))return!1;let n=b$(t);if(y$.has(n))return!1;if(m$.has(n))return n==="REG_EXPAND_SZ"?!0:!xC(e,!0)},C$=(e,t)=>{let n=vA(),r=!1,o=!1,a=!1,s=t.toUpperCase()===li.toUpperCase(),i=(l,d)=>{if(!s)return;let u=k$(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),dA(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||w$(d,t))continue;let u=h$.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),dA(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Wn=async(e,t=_e)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:vA(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return C$(n.stdout,t)},Cr=async e=>{let t=await Wn(e,li);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...Ne.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},bh=e=>e.unparsed?`This machine may have a Claude policy under ${li} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${li} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${li} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var jl=(e,t)=>ia(so(e,t)),SA=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],A$=(e,t)=>{let n=jl(e,t);return Object.fromEntries(Ne.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},v$=(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}}),S$=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,lh=e=>Object.fromEntries(Ne.map(t=>[t,a$(t,e[t])])),uA=(e,t,n,r)=>({version:Kl,registryKey:_e,keyExisted:e,lastWritten:lh(t),helper:{path:n,lastWritten:ih(r)}}),E$=(e,t,n,r,o,a)=>({version:Kl,registryKey:_e,keyExisted:e,lastWritten:lh(t),pending:lh(n),helper:{path:r,...o?{lastWritten:ih(o)}:{},pending:ih(a)}}),dh=(e,t,n)=>ua(n,e.lastWritten[t])||e.pending!==void 0&&ua(n,e.pending[t]),ha=async e=>{try{let t=await sh(e,"utf8");return{content:t,sha256:co(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},ma=async e=>(await ha(e))?.sha256,pa=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Wl=async(e,t)=>{let n=e$(e),r;try{r=await mA(di(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>ya(di(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([ha(e),ha(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!pa(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await AA(e,a))throw new Error("credential helper changed during recovery");return}if(t&&pa(t,s.sha256)&&pa(t,i.sha256)){await on(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},kh=async(e,t,n)=>(n.present?await e(SA(_e,t,n.value??"",n.type??"REG_SZ")):await e(["delete",_e,"/v",t,"/f"])).code===0,I$=async(e,t,n)=>{let r=!0,o=await Wn(e);for(let a of Ne)if(!da(o.values[a],t[a])){if(!da(o.values[a],n[a])){r=!1;continue}await kh(e,a,t[a])||(r=!1),o=await Wn(e)}return r&&Ne.every(a=>da(o.values[a],t[a]))},qe=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Ht(n)]}}),EA=async(e,t,n,r={})=>{if(!Ie(t))return qe("A valid personal ark_ gateway key is required.",!1,r);let o=fh(r),a;try{a=XN((r.credentialCommand??qf)())}catch{return qe("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=co(a),i=r.runReg??Kn,c=Ht(r),l;if(!n.dryRun)try{l=await mh(r)}catch(m){return qe(m instanceof fa?"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 Cr(i);if(m)return qe(bh(m),!1,r);let w=await wh(r,!n.dryRun);n.dryRun||await Wl(o,w);let g=await Wn(i),y=A$(e,o),b=await ha(o),A=b?.sha256,S=!1;if(d=w,u=g,f=y,w){let C=Ne.find(x=>!dh(w,x,g.values[x]));if(C)return qe(`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&&!pa(w,A))return qe(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);S=S$(w)}else{if(A!==void 0&&A!==s)return qe(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let C=g.foreignState||Ne.some(U=>g.values[U].present),x=Ne.every(U=>da(g.values[U],y[U])),P=Ne.every(U=>da(g.values[U],v$(e,t.trim())[U]));if(C&&!x&&!P)return qe(`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(S=P,x&&A===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${_e} into an owner-only journal without rewriting them.`]}:(await Bl(uA(g.keyPresent,y,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${_e} into the ownership journal.`]})}if(S){let C=!0;try{C=(r.appRunning??hh)()}catch{}if(C)return qe("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let E=E$(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 Bl(E,r),h=!0;for(let C of Ne){let x=await Wn(i);if(!ua(x.values[C],E.lastWritten[C])&&!ua(x.values[C],E.pending[C]))throw new Error("registry value changed during apply");if(!da(x.values[C],y[C])&&!await kh(i,C,y[C]))throw new Error("registry write failed")}let I=await Wn(i);if(!Ne.every(C=>ua(I.values[C],E.pending[C])))throw new Error("registry verification failed");if(A!==s&&(A===void 0?await QN(o,a):await Hl(o,A,a,"apply",r)),await ma(o)!==s)throw new Error("credential helper verification failed");return await Bl(uA(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.",...Pl]}}catch{if(!h||!u||!f||!p)return qe("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Wl(o,p);let m=!0,w=await ha(o),g=p.helper.pending;if(w?.sha256!==p.helper.lastWritten?.sha256&&(g!==void 0&&w?.sha256===g.sha256?p.helper.lastWritten?(await Hl(o,g.sha256,p.helper.lastWritten.content,"rollback",r),m=await ma(o)===p.helper.lastWritten.sha256):await Hl(o,g.sha256,void 0,"rollback",r):m=w===void 0&&p.helper.lastWritten===void 0),m&&await I$(i,u.values,f))return d?await Bl(d,r):await on(c,{force:!0}),qe("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return qe("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?.()}},IA=async(e,t={})=>{let n=t.runReg??Kn,r=Ht(t),o;if(!e.dryRun)try{o=await mh(t)}catch(a){return qe(a instanceof fa?"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 wh(t,!e.dryRun);a&&!e.dryRun&&await Wl(a.helper.path,a);let s=await Wn(n);if(!a)return Ne.filter(h=>s.values[h].present).length>0?qe(`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=Ne.filter(p=>s.values[p].present&&!dh(a,p,s.values[p])),c=await ma(a.helper.path),l=c!==void 0&&!pa(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 Ne){let m=(await Wn(n)).values[p];if(m.present){if(!dh(a,p,m)){u.add(p);continue}await kh(n,p,{present:!1})||(d=!0)}}let f=await ma(a.helper.path);if(f!==void 0)if(pa(a,f))try{await Hl(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?qe(`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 on(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?[]:Tl]})}catch{return qe(`Could not safely inspect or revert ${_e}; no unproven value was removed.`,!1,t)}finally{await o?.()}},xA=async(e,t={})=>{let n=t.runReg??Kn;if(!await R(Ht(t)))return;let r;try{r=await mh(t);let o=await wh(t);if(o&&await Wl(o.helper.path,o),!o||o.pending||await Cr(n)!==void 0)return;let a=await Wn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Ye(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&Ne.every(l=>ua(a.values[l],o.lastWritten[l]))))return;let i=await ma(o.helper.path),c=o.helper.lastWritten;return a.values.inferenceCredentialKind.value==="helper-script"&&a.values.inferenceCredentialHelper.value===o.helper.path&&!a.values.inferenceGatewayApiKey.present&&c!==void 0&&i===c.sha256&&await zN(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?.()}},RA=async(e,t={})=>await xA(e,t)!==void 0,OA=async(e,t={})=>await xA(e,t)==="dynamic";var wa=(e=R$())=>e==="win32"?hh:Ml,Ch="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",Yl=async(e,t={})=>{let n=(t.profileRoot??ao)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Ch};if((t.appRunning??wa(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await _A.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 _l(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 "+Ch}:{ok:!1,reason:"no Claude Desktop third-party session store found \u2014 the app has not run in this mode yet",remedy:"Open Claude Desktop with Anyray configured, sign in with your usual Claude account, quit it, then run this again."};let o=await(t.findBinary??kC)();if(!o)return{ok:!1,reason:"the Claude Code CLI was not found",remedy:"Install Claude Code (the conversion step uses its importer), then run this again."};let a=Vl(t.stagingRoot??O$(),`anyray-history-${process.pid}-${x$()}`);try{let s=await(t.runImporter??CC)({binary:o,exportPath:e,configDir:Vl(a,"config"),workDir:Vl(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. "+Ch};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 vC(r.dir,s.conversations),c=await SC({stagedProjectsDir:Vl(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 _A.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as Et}from"node:fs";import{homedir as q$}from"node:os";import{join as sn,sep as z$}from"node:path";import{isDeepStrictEqual as ql}from"node:util";import{constants as _$}from"node:fs";import{promises as G}from"node:fs";import{dirname as ba,isAbsolute as vh,join as te,relative as Zl,resolve as an,sep as ui}from"node:path";import{randomUUID as zl}from"node:crypto";var bn=448,pi=384,DA=448,P$=4,Sh=3e4,NA=5e3,T$=10*6e4,Ah=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),lt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fi=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),$A=(e,t)=>{let n=Zl(an(e),an(t));return n===""||!n.startsWith(`..${ui}`)&&n!==".."&&!vh(n)},lo=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return lt(n)?{raw:t,value:n}:void 0}catch(t){return St(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},St=e=>e instanceof Error&&"code"in e,L$=e=>{try{return process.kill(e,0),!0}catch(t){return St(t)&&t.code==="EPERM"}},MA=e=>e===0?"owner.json":`owner.${e}.json`,Xl=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=te(e,r.name),a,s,i;try{let d=JSON.parse(await G.readFile(o,"utf8"));lt(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}},FA=e=>{if(e.pid===void 0||!L$(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Sh&&t-e.createdAtMs>T$},D$=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(ba(t),{recursive:!0,mode:bn});let n=zl(),r,o=!1;try{await G.mkdir(t,{mode:bn}),o=!0}catch(i){if(!St(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Xl(t);if(d){if(!FA(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)<=Sh)return}let l=te(t,MA(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
289
|
-
`,{flag:"wx",mode:pi}),r=l}catch(d){if(St(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(!lt(i)||i.nonce!==n)return;let c=new Date;await G.utimes(a,c,c)}catch{}})()},
|
|
290
|
-
`,{mode:pi,flag:"wx"}),await G.rename(a,e)}catch(s){try{await G.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},Ql=async(e,t)=>{for(let n=0;n<
|
|
291
|
-
`,{flag:"wx",mode:pi}),o=u}catch(f){if(St(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(!lt(l)||l.nonce!==r)return;let d=new Date;await G.utimes(a,d,d)}catch{}})()},
|
|
292
|
-
`)}},xh=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),qA=async e=>{let t=[];for(let n of tM)t.push({lane:n,sources:await rM(e,n)});return t},zA=async(e={})=>{let t=(e.firstPartyRoot??(()=>Qs()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([qA(t),Eh(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=xh(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}},uo=async(e={})=>{let t=(e.home??q$)(),n=(e.firstPartyRoot??(()=>Qs()))(),r=(e.thirdPartyRoot??(()=>ao()))();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??wa())())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([qA(n),Eh(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=xh(o);for(let w of h)m.add(w);if(m.size>1)return ZA(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${m.size} accounts`,h);s=[...m]}else if(!e.allAccounts){let p=xh(o);for(let h of a.accounts)p.add(h);if(p.size>1)return ZA(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 Q$(r),l=await VA(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(Ih(p));continue}let m=await oM(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(Ih(p));continue}d.push(await iM(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:Rh(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 lM=e=>[rt(e)],QA=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...lM(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 ev="1.21459.0",fM=pM(dM),hM=async e=>{try{let{stdout:t}=await fM("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},mM=async e=>{try{return await uM(e)}catch{return}},tv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",yM=["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."],ka=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(nv??=rv({}),nv):rv(e),nv,rv=async e=>{let t=(e.home??mi)(),n=["/Applications/Claude.app",kn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??hM,o=e.readClaudeAppBundle??mM;for(let a of n){let s=await r(kn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${tv}`}),c=Rl(s,ev);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${ev} or newer.`);let l=await o(kn(a,"Contents","Resources","app.asar"));return l?UC.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. ${tv}`}},td="anyray",sv="--anyray-owner=claude-desktop-v1",nd=(e={})=>{let t=(e.platform??Ar)(),n=(e.home??mi)();return t==="darwin"?rn(e).appConfig:t==="win32"?kn(process.env.APPDATA??kn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):kn(n,".config","Claude","claude_desktop_config.json")},Lh=(e={})=>kn((e.home??mi)(),"Library","Application Support","Claude","claude_desktop_config.json"),iv=()=>{let e=je("profile");return{command:e.command,args:[...e.args,sv]}},po=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),cv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},gM=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),wM=e=>{if(!po(e)||!cv(e,["command","args"]))return!1;let t=iv();return e.command===t.command&&gM(e.args,t.args)},bM=e=>po(e)&&Array.isArray(e.args)&&e.args.at(-1)===sv,kM=e=>{if(!po(e)||!cv(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||Ge(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===rr&&t.at(-1)==="profile"))return!1;let r=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(r))return t.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(r)||t.length!==3)return!1;let o=t[0].replaceAll("\\","/");return!Ge(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},CM=e=>e===void 0?"absent":wM(e)?"exact":bM(e)||kM(e)?"stale-owned":"foreign",Be=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},fo=async e=>{let t=await R(e),n;try{n=await M(e)}catch{throw new Be(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!po(n.mcpServers))throw new Be(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(po(n.mcpServers)?n.mcpServers:void 0)?.[td];return{path:e,fileExisted:t,json:n,entry:o,ownership:CM(o)}},rd=e=>{if(e.ownership==="foreign")throw new Be(`MCP name conflict in ${e.path}: mcpServers.${td} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},lv=(e,t)=>{let n={...e},r=po(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[td]:r[td]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},_h=async(e,t)=>{if(Oh(e.entry,t))return;let n=await fo(e.path);if(!Oh(n.entry,e.entry))throw new Be(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Hn(e.path,lv(n.json,t)),{reading:e,afterEntry:t}},Ph=async e=>{let t=await fo(e.reading.path);if(!Oh(t.entry,e.afterEntry))throw new Be(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=lv(t.json,e.reading.entry);await Hn(e.reading.path,n)},AM=async e=>{if(!ce())throw new Be(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Re()} is temporary); no inference setting was changed.`);let t=await fo(nd(e));rd(t);let n=Lh(e),r=(e.platform??Ar)()==="darwin"&&n!==t.path?await fo(n):void 0;return r&&rd(r),{active:t,...r?{legacy:r}:{}}},ov=async e=>{let t=await fo(nd(e));rd(t);let n=Lh(e),r=(e.platform??Ar)()==="darwin"&&n!==t.path?await fo(n):void 0;return r&&rd(r),{active:t,...r?{legacy:r}:{}}},vM=async e=>{let t=[];try{let n=await _h(e.active,iv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await _h(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Ph(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Be(`Claude Desktop MCP setup failed and could not restore ${r.join(", ")}. Re-run \`anyray-connect desktop disconnect\` to recover safely.`,r):n}return{changedFiles:t.map(n=>n.reading.path),async rollback(){let n=[];for(let r of[...t].reverse())await Ph(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Be(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},SM=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await _h(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Ph(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Be(`Claude Desktop MCP cleanup failed and could not restore ${r.join(", ")}. Re-run revert after resolving the file conflict.`,r):n}return t.map(n=>n.reading.path)},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)."]},EM={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},od="claude-desktop",Th="migrate",dv=new Set(["app-running","store-missing"]),IM={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},xM={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"}},RM="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",uv=e=>{let t=(e.platform??Ar)(),n=e.home??mi;return{home:n,appRunning:e.appRunning??wa(t),firstPartyRoot:()=>Qs({home:n,runtimePlatform:t}),thirdPartyRoot:()=>ao({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},pv=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=IM[a.lane];return`${a.migrated} ${a.migrated===1?s.one:s.many}`}).join(", ")}.`+(n>0?` ${n} skipped \u2014 the transcript is no longer on disk.`:"")+(r>0?` ${r} could not be copied.`:"")},fv=e=>{let t=e.filter(s=>s.migrated>0),n=e.reduce((s,i)=>s+i.conflicts,0),r=e.reduce((s,i)=>s+i.invalid,0),o=e.reduce((s,i)=>s+i.failed,0);if(t.length===0&&n+r+o===0)return;let a=t.map(s=>{let i=xM[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.`:"")},hi=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=uv(e),r=await(e.pendingDesktopMigrationCount??zA)(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??uo)(n);if(a.ok){let c=pv(a.lanes),l=fv(a.portableAssets),d=a.ambiguousAssets??[],u=d.length>0?`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`:void 0,f=(a.blocked??[]).filter(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 _s(od,Th);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(!dv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
|
|
293
|
-
${a.remedy}`];if(t.preservePendingOp)return[];await _s(od,Th);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."]}},OM=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await pr(od),[]}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."]}},_M=e=>QA({id:od,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??Ar)(),n=(e.home??mi)();return t==="darwin"?["/Applications/Claude.app",kn(n,"Applications","Claude.app")]:t==="win32"?[kn(process.env.LOCALAPPDATA??kn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>J(t,"anthropic")?["Claude Desktop subscription routing requires automatic setup on a verified macOS build and a Claude Code sign-in in Keychain.","This platform/build has no verified subscription helper seam, so Connect left inference unchanged instead of silently switching you to API billing.","To opt into the API-billed Gateway lane instead, re-run Connect in org/API mode and use:",...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`."]}),PM=(e={})=>{let t=_M(e),n=()=>(e.platform??Ar)()==="darwin",r=()=>(e.platform??Ar)()==="win32",o=(s,i)=>n()?YC(s,i,e):EA(s,s.clientKey??"",i,e),a=s=>n()?ZC(s,e):IA(s,e);return{...t,automatic:!0,quitGated:{isRunning:()=>(e.appRunning??wa((e.platform??Ar)()))(),quitTarget:EM,needsTarget:()=>!1,async complete(s){if(s!==Th)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??uo)(uv(e));if(i.ok){let c=pv(i.lanes),l=fv(i.portableAssets),d=i.ambiguousAssets??[];if(d.length>0)return{status:"manual",messages:[...c?[c]:[],...l?[l]:[],`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`]};let f=(i.blocked??[]).filter(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 dv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?JC(s,e):r()?OA(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=rn(e),p=await io(f,e);if(p)return{status:"manual",manualAudience:"admin",messages:[nh(p),...await hi(e,i)]}}if(r()){let f;try{f=await Cr(e.runReg??Kn)}catch{return{status:"manual",manualAudience:"admin",messages:[RM,...await hi(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[bh(f),...await hi(e,i)]}}if(r()&&J(s,"anthropic"))return{status:"manual",messages:["Claude Desktop subscription routing is not available on Windows: Connect could not verify a supported Claude subscription credential source, so inference was left unchanged instead of switching to API billing.","Use org/API mode for the Windows Gateway lane, or run subscription mode on a verified macOS build after signing in to Claude Code."]};if(n()){let f=await ka(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await AM(e)}catch(f){let p=f instanceof Be?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Be?f.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no inference setting was changed."]}}let l=await o(s,{dryRun:!0});if(l.status!=="configured")return l;if(i.dryRun){let f=c.legacy;return{...l,messages:[...l.messages,`Would register the ownership-marked Anyray retrieval MCP server in ${c.active.path}.`,...f&&f.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${f.path}.`]:[],...await hi(e,i)]}}let d;try{d=await vM(c)}catch(f){let p=f instanceof Be?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Be?f.message:"Could not safely register Claude Desktop retrieval; the inference route was left unchanged."]}}let u;try{u=await o(s,{dryRun:!1})}catch{u={status:"manual",messages:["Claude Desktop inference setup failed before it returned a result."]}}if(u.status!=="configured")try{return await d.rollback(),{...u,changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])],messages:[...u.messages,"Restored the prior Claude Desktop MCP registration because inference setup did not complete. A config file that was absent before setup may remain as an inert object to avoid racing unrelated concurrent writes."]}}catch{return{status:"manual",changedFiles:[...u.changedFiles??[],...d.changedFiles],messages:[...u.messages,"Inference setup did not complete, and the prior MCP registration could not be fully restored. Re-run `anyray-connect desktop disconnect` to recover safely."]}}return{...u,messages:[...u.messages,"Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) with an ownership marker.",...await hi(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?yM:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=nd(e),c=await OM(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 ov(e)}catch(m){return l({status:"manual",messages:[m instanceof Be?m.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no setting was removed."]})}let u=await a({dryRun:!0});if(s.dryRun){let m=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...m&&m.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${m.path}.`]:[]]})}let f=await a({dryRun:!1});if(f.status==="manual"){let m=r()?Ht(e):void 0;if(!(m!==void 0&&f.changedFiles?.includes(m)===!0&&!await R(m)))return l(f)}let p;try{p=await SM(await ov(e))}catch(m){let w=m instanceof Be?m.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...w])],messages:[...f.messages,m instanceof Be?m.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await ae(i);let h=Lh(e);return n()&&h!==i&&await ae(h),l({...f,messages:[...f.messages,...p.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...f.changedFiles??[],...p])]})},async mcpStatus(){if(!ce())return{registered:!1,command:null};try{let s=await fo(nd(e));return s.ownership!=="exact"||!po(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 ka(e)).supported?oh(s,e):!1:r()?RA(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await ka(e)).supported)return["unknown"];let s=await XC(e);return s?[s]:["unknown"]}if(r())return await R(Ht(e))?await Cr(e.runReg??Kn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=rn(e);return!await R(s.journal)||await io(s,e)?!1:(await ka(e)).supported}return r()&&await R(Ht(e))?!await Cr(e.runReg??Kn):!1}catch{return!1}}}},hv=PM();import{homedir as aF}from"node:os";import{join as sF}from"node:path";import{rm as fd}from"node:fs/promises";import{constants as mv,accessSync as TM,statSync as LM}from"node:fs";import{platform as Dh}from"node:os";import{delimiter as DM,posix as NM,resolve as $M,win32 as MM}from"node:path";var FM="0.59.0",UM="1.1.4",Gn="Anyray \xB7 Claude",jn="Anyray \xB7 Codex",ad="__anyray-acp-agent",yv=(e,t,n)=>{let{command:r,args:o}=dn([ad,e,t,n]);return{command:r,args:o,env:{}}},sd=(e=Dh())=>e==="win32"?"npx.cmd":"npx",id=(e=process.env.PATH,t=Dh())=>{if(!e)return;let n=sd(t);for(let r of e.split(DM)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=$M(o,n);try{if(!LM(a).isFile())continue;return TM(a,t==="win32"?mv.F_OK:mv.X_OK),a}catch{}}},cd=(e,t=Dh())=>{let n=t==="win32"?MM:NM;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==sd(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},BM="https://chatgpt.com/backend-api/codex",HM="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",gv="ANYRAY_ACP_CODEX_AUTHORIZATION",wv="ANYRAY_ACP_CODEX_CLIENT_KEY",bv="ANYRAY_ACP_CODEX_METADATA",kv=e=>de({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),WM=(e,t={})=>{let n=J(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":BM,"x-anyray-forward-headers":HM}:{},o=n?{...e.clientKey?{"x-anyray-api-key":wv}:{}}:{Authorization:gv};return kv(e)&&(o["x-anyray-metadata"]=bv),{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}}}:{}}},KM=e=>{let t=J(e,"openai"),n=kv(e);return{...t?e.clientKey?{[wv]:e.clientKey}:{}:{[gv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[bv]:n}:{}}},Cv=(e,t=sd(),n={})=>({[Gn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${FM}`],env:un(e).env},[jn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${UM}`],env:{CODEX_CONFIG:JSON.stringify(WM(e,n)),...KM(e)}}}),yi=(e=sd(),t="jetbrains")=>({[Gn]:yv("claude",e,t),[jn]:yv("codex",e,t)}),ho=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ld=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as GM}from"node:zlib";import{open as jM,readFile as Uh,readdir as pd}from"node:fs/promises";import{dirname as Av,join as ue}from"node:path";import{homedir as Iv,platform as Bh}from"node:os";var dd="2025.3.2",Ca="253.30387.147",gi="com.intellij.ml.llm",Nh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),VM=1e4,YM=256*1024*1024,ZM=16*1024*1024,$h=1024*1024,Mh=22,XM=Mh+65535,Fh=Rl,JM=()=>{let e=Iv(),t=ue(e,".cache","JetBrains","RemoteDev");switch(Bh()){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"}]}},qM=()=>Bh()==="linux"?ue(Iv(),".local","share","JetBrains"):rt("JetBrains"),zM=()=>Bh()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),QM=async(e,t=VM)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await pd(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 pd(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)]},eF=e=>{let t=Av(e);return t.endsWith(`${ue("Contents","Resources")}`)?Av(t):t},tF=async e=>{try{let t=JSON.parse(await Uh(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!qs(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:eF(e)}}catch{return}},ud=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},nF=async(e,t)=>{let n;try{n=await jM(e,"r");let{size:r}=await n.stat();if(r<Mh||r>YM)return;let o=Math.min(r,XM),a=await ud(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Mh;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>ZM||c+i>r)return;let l=await ud(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>$h||p>$h)return;let A=await ud(n,30,g);if(!A||A.readUInt32LE(0)!==67324752)return;let S=A.readUInt16LE(26),E=A.readUInt16LE(28),I=await ud(n,f,g+30+S+E);return I?u===0?I.toString("utf8"):u===8?GM(I,{maxOutputLength:$h}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},vv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!qs(n)))return{id:t,version:n}},rF=async(e,t)=>{let n=ue(e,"META-INF","plugin.xml");if(await R(n))try{let o=vv(await Uh(n,"utf8"));return{present:o?.id===gi||t,descriptor:o?.id===gi?o:void 0}}catch{return{present:t}}let r=[];try{r=(await pd(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 nF(o,"META-INF/plugin.xml"),s=a?vv(a):void 0;if(s?.id===gi)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},Sv=async e=>{let t;try{t=await pd(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Nh.has(o.name.toLowerCase()),i=Nh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Nh.has(o.name.toLowerCase());if(!a){let i=ue(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await rF(ue(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},oF=async e=>{try{return(await Uh(ue(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(gi)}catch{return!1}},Ev=e=>e.reduce((t,n)=>t?(Fh(n,t)??-1)>0?n:t:n,void 0),xv=async(e={})=>{let t=e.configRoot??rt("JetBrains"),n=e.userPluginsRoot??qM(),r=await QM(e.productRoots?e.productRoots.map(h=>({path:h,layout:"recursive"})):JM(),e.scanBudget),o=(await Promise.all(r.map(h=>tF(h)))).filter(h=>h!==void 0),a=o.length>0||await R(t);if(e.wsl??zM())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=>(Fh(h.version,dd)??-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 Sv(y);if(b.present){g=b;break}}if(g??=await Sv(ue(h.root,"plugins")),g.present&&!g.descriptor){l=!0;continue}if(!(!g.descriptor||g.descriptor.id!==gi)){if(i.push(g.descriptor.version),await oF(m)){c=!0;continue}if(!((Fh(g.descriptor.version,Ca)??-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=Ev(o.map(h=>h.version)),f=Ev(i),p;return a?u?s.length===0?p=`JetBrains IDE ${u} is below the ACP minimum ${dd}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${dd}+ once, enable AI Assistant ${Ca}+, then run Connect again. No ACP config was written.`:c?p=`JetBrains AI Assistant is disabled; enable version ${Ca}+ and run Connect again. No ACP config was written.`:f?p=`JetBrains AI Assistant ${f} is below the ACP minimum ${Ca}; no ACP config was written.`:l?p=`Could not verify the local JetBrains AI Assistant version; require ${Ca}+ before running Connect. No ACP config was written.`:p=`JetBrains AI Assistant ${Ca}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:p=`Could not prove JetBrains IDE ${dd}+ 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 iF=[Gn,jn],Hh=()=>sF(aF(),".jetbrains","acp.json"),mo=()=>`${Hh()}.anyray-state`,cF=(e,t,n="npx")=>{let r=ho(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,yi(n,"jetbrains")),{...e,agent_servers:r}},lF=(e,t,n)=>{if(!ho(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=ho(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of iF)if(c in r){if(!ld(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}},dF=(e=xv)=>({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=Hh(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=id();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await R(r),c;try{c=await M(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=yi(a,"jetbrains");return await ac({configPath:r,current:c,next:cF(c,t,a),journalPath:mo(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,mo()]}},async revert(t){let n=Hh(),r=async()=>{if(!await R(n))return t.dryRun||(await ae(n),await fd(mo(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await M(n)}catch{return t.dryRun||(await ae(n),await fd(mo(),{force:!0}).catch(()=>{})),{status:"manual",messages:[`Could not parse ${n}; remove the two \u201CAnyray \xB7 \u2026\u201D agent entries manually.`]}}let a={},s=!1,i=!1;try{let u=await M(mo());(u.version===1||u.version===2)&&ho(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await R(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await M(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await Nr(n);let l=lF(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 fd(n,{force:!0}):await X(n,l.next,{backup:!1})),t.dryRun||(await ae(n),await fd(mo(),{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():oc(n,mo(),r)}}),Rv=dF();import{homedir as md}from"node:os";import{join as yd}from"node:path";import{rm as Wh}from"node:fs/promises";var Kh="1.0.0",gd=["anyray-claude-acp","anyray-codex-acp"],uF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Gh=()=>yd(md(),".windsurf","acp","registry.json"),jh=()=>yd(md(),".windsurf-next","acp","registry.json"),Aa=e=>`${e}.anyray-state`,Ov=e=>({binary:Object.fromEntries(uF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Pv=(e="npx")=>{let t=yi(e,"windsurf");return[{id:gd[0],name:Gn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Ov(t[Gn])},{id:gd[1],name:jn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Ov(t[jn])}]},hd=e=>!Array.isArray(e)||e.some(t=>!ho(t)||typeof t.id!="string")?null:e,pF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Kh||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:hd(e.agents);if(!n)return null;let r=new Set(gd);return{...e,version:typeof e.version=="string"?e.version:Kh,agents:[...n.filter(o=>!r.has(o.id)),...Pv(t)],extensions:e.extensions??[]}},fF=(e,t,n)=>{let r=hd(e.agents);if(!r)return null;let o=hd(t.agents)??[],a=new Map((hd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!gd.includes(u.id)){l.push(u);continue}if(!ld(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===Kh&&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}},_v=async()=>{let e=[];return(await R(jh())||await R(yd(md(),".windsurf-next")))&&e.push(jh()),(await R(Gh())||await R(yd(md(),".windsurf"))||await R(rt("Devin"))||await R(rt("Windsurf")))&&e.push(Gh()),e},Tv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await _v();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await _v();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=id();if(!r)return{status:"manual",messages:["Devin ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP registry was written."]};let o=[],a=[];for(let s of n){let i;try{i=await M(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=pF(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=Pv(r);await ac({configPath:s,current:i,next:c,journalPath:Aa(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,Aa(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=[Gh(),jh()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await ae(a),await Wh(Aa(a),{force:!0}).catch(()=>{}));return}let i;try{i=await M(a)}catch{n.push(`Could not parse ${a}; remove the anyray-* ACP agents manually.`),o=!0;return}let c=[],l=!1,d=!1;try{let p=await M(Aa(a));(p.version===1||p.version===2)&&Array.isArray(p.agents)&&(c=p.agents,l=p.version===2&&p.fileExisted===!1,d=p.version===2&&p.fileExisted===!0)}catch{}let u;if(d){let p=`${a}.anyray-bak`;if(!await R(p)){n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is missing. Restore it or remove the agents manually.`),o=!0;return}try{u=await M(p)}catch{n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is malformed. Repair it or remove the agents manually.`),o=!0;return}}else u=await Nr(a);let f=fF(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 Wh(a,{force:!0}):await X(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 ae(a),await Wh(Aa(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await oc(a,Aa(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var se=[ar,Mw,Ns,xk,Jk,lC,bC,Rv,hv,Tv,Vw],Wt=e=>se.find(t=>t.id===e);var hF=["hook_registration","mcp_registration","hook_binary","beacon_target"],yo=e=>e.status==="configured"||e.status==="queued",go=async(e,t=se)=>{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},vr=async(e,t,n=se)=>{let r=[];for(let o of await go(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},Vh=async(e,t=se)=>{let n=[];for(let r of await go(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(hF.map(o=>[o,"unreadable"]))})}return n},Lv=e=>e.filter(t=>!t.integrationStatus),mF=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},mt=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=mF(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 vF,writeFile as SF}from"node:fs/promises";import{join as Bv}from"node:path";import{z as He}from"zod";var yF=["HTTPS_PROXY","https_proxy"],Dv=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"]),Nv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),$v=new Set(["ENOTFOUND","EAI_AGAIN"]),Mv=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Fv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),gF=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 wF(e)},wF=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...Dv,...Nv,...$v,...Mv,...Fv])if(t.includes(n))return n}},bF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",kF=e=>yF.filter(t=>(e[t]??"").trim()!==""),CF=(e,t=process.env)=>{let n=gF(e),r=kF(t);return{kind:n&&Dv.has(n)?"tls-unknown-issuer":n&&Nv.has(n)?"tls-invalid-cert":n&&$v.has(n)?"dns":bF(e)||n&&Fv.has(n)?"timeout":n&&Mv.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},AF=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}},yt=(e,t=process.env)=>AF(CF(e,t));var va="required",Uv=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team;return{routingUpdated:n,teamUpdated:r,...n?{gateway:t.routingOrigin}:{},...r?{team:t.team}:{}}},wd=(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]??va,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 EF=1e4,IF=1,xF=He.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),RF=He.object({id:xF,name:He.string().min(1),version:He.string().min(1),body:He.string()}),OF=He.object({version:He.literal(IF).optional(),skills:He.array(RF),updatedAt:He.string().min(1).optional(),routing:He.object({origin:He.string().min(1)}).optional(),team:He.string().min(1).optional(),tools:He.object({enabled:He.array(He.string().min(1)),tiers:He.record(He.string().min(1),He.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),_F=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",bd=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",kd=async(e,t,n={})=>{let r=n.timeoutMs??EF,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.`:yt(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=bd(l),d}return OF.parse(c)},Hv=/^[a-z0-9][a-z0-9-]{0,31}$/,Wv=64,PF=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>Hv.test(o)).slice(0,Wv).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>Hv.test(o)).slice(0,Wv).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},wi=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??va)==="locked":!1},Cd=async(e,t={})=>{let n=t.loadProfile??T,r=t.saveProfile??re,o=t.targetFromProfile??Oe,a=t.adapters??se,s=t.repairTools??mt,i=t.recordManaged??zn,c=await n(),l={...c},d=Uv(c,{routingOrigin:e.routing?.origin?ln(e.routing.origin):void 0,team:e.team}),{routingUpdated:u,teamUpdated:f}=d;(u||f)&&(l={...await n()},d.gateway!=null&&(l.gateway=d.gateway),d.team!=null&&(l.team=d.team),await r(l));let p=wd(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||f),{candidateIds:h,freshIds:m}=p,w=0,g=0,y=0;if(h.length>0||m.length>0){let S=await o(async()=>l);if(S){let E;if(u||f){let x=new Set(h);E=[];for(let P of a)if(x.has(P.id))try{(await P.detect()).installed&&E.push(P)}catch{}}else E=await vr(h,S.toolOrigin,a);let I=new Set(m),C=[];for(let x of a)if(I.has(x.id))try{(await x.detect()).installed&&C.push(x)}catch{}if(w=E.length+C.length,w>0){let x=await s([...E,...C],S.target);g=x.filter(yo).length;let P=x.filter(U=>I.has(U.id));if(y=P.filter(yo).length,P.length>0)try{await i(P,!1)}catch{}}}}let b=PF(e),A=await n();if(JSON.stringify(b??null)!==JSON.stringify(A.fleetToolPolicy??null)){let{fleetToolPolicy:S,...E}=A;await r({...E,...b?{fleetToolPolicy:b}:{}})}return{routingUpdated:u,teamUpdated:f,toolsRequested:w,toolsApplied:g,toolsEnrolled:y,toolsTombstoned:p.tombstonedIds,profileUpdated:u||f}},Kv=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!_F(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=Bv(d,i.id),f=Bv(u,"SKILL.md");await vF(u,{recursive:!0}),await SF(f,TF(i.body),"utf-8"),l.push(f)}a+=1,r.push({id:i.id,name:i.name,version:i.version,written:!0,files:l})}return{results:r,changed:a,unchanged:s,versions:o,updatedAt:e.updatedAt}},TF=e=>e.endsWith(`
|
|
286
|
+
}`,Gn=async e=>new Promise((t,n)=>{let r=qN("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",d$],{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(uh(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(uh({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),Wt=(e={})=>ya((e.home??mh)(),".anyray","claude-desktop-windows.json"),u$=e=>ya((e.home??mh)(),".anyray","claude-desktop-windows.lock"),fa=class extends Error{},p$=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},wh=async e=>{let t=u$(e);await ch(di(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=yA("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=ya(t,"owner.json");try{await ch(t,{mode:448}),await he(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
287
|
+
`)}catch(a){if(a.code!=="EEXIST")throw await an(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await lh(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!p$(i.pid)}catch{try{s=Date.now()-(await CA(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new fa;await an(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await lh(o,"utf8")).nonce===r&&await an(t,{recursive:!0,force:!0})}catch{}}}throw new fa},xA=()=>Object.fromEntries(Ne.map(e=>[e,{present:!1}])),lo=e=>yA("sha256").update(e).digest("hex"),f$=(e,t)=>t.present?e===ga?{present:!0,type:t.type,sha256:lo(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},ua=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?lo(e.value??"")===t.sha256:e.value===t.value:!0,Bt=(e,t)=>Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),Gl=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.present!="boolean"?!1:n.present?n.type!=="REG_SZ"&&n.type!=="REG_EXPAND_SZ"?!1:t===ga?Bt(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:Bt(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},sA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,Ne)&&Ne.every(t=>Gl(e[t],t)),iA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,tA)&&tA.every(t=>Gl(e[t],t)),h$=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),bh=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=["path",...n.lastWritten===void 0?[]:["lastWritten"],...n.pending===void 0?[]:["pending"]];return Bt(n,r)&&n.path===yh(t)&&(n.lastWritten===void 0||aA(n.lastWritten))&&(n.pending===void 0||aA(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},m$=(e,t)=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Kl&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&sA(e.lastWritten)&&(e.pending===void 0||sA(e.pending))&&bh(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),y$=e=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&iA(e.lastWritten)&&(e.pending===void 0||iA(e.pending)),cA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,nA)&&nA.every(t=>Gl(e[t],t)),g$=(e,t)=>Bt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===3&&e.registryKey===_e&&typeof e.keyExisted=="boolean"&&cA(e.lastWritten)&&(e.pending===void 0||cA(e.pending))&&bh(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),lA=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Bt(e,rA)&&rA.every(t=>Gl(e[t],t)),w$=(e,t)=>Bt(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"&&lA(e.lastWritten)&&(e.pending===void 0||lA(e.pending))&&bh(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),dA=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),kh=e=>{let{pending:t,...n}=e;return{...n,version:Kl,lastWritten:dA(e.lastWritten),...t?{pending:dA(t)}:{}}},uA=e=>({...e,chatTabEnabled:{present:!1}}),b$=e=>{let{pending:t,...n}=e;return kh({...n,version:4,lastWritten:uA(e.lastWritten),...t?{pending:uA(t)}:{}})},pA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),k$=(e,t)=>kh({version:4,registryKey:_e,keyExisted:e.keyExisted,lastWritten:pA(e.lastWritten),...e.pending?{pending:pA(e.pending)}:{},helper:{path:yh(t)}}),Ch=async(e,t=!0)=>{let n=Wt(e),r=di(n),o=`${AA(n)}.anyray-old-`,a=(await bA(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>ya(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 kA(a[0],n):s=a[0]}let i=await M(s),c=y$(i)?k$(i,e):g$(i,e)?b$(i):w$(i,e)?kh(i):m$(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>an(l,{force:!0}))),c},fA=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),C$=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:_e,keyExisted:e.keyExisted,lastWritten:fA(e.lastWritten),...e.pending?{pending:fA(e.pending)}:{}}:e,Bl=async(e,t)=>{let n=Wt(t),r=`${JSON.stringify(C$(e),null,2)}
|
|
288
|
+
`;t.writeJournalFile?await t.writeJournalFile(n,r):await he(n,r)},A$=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,v$=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),S$=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),E$=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),I$=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===E$(t).toUpperCase(),hA=(e,t,n,r,o)=>{let a=Ne.find(i=>i.toLowerCase()===t.toLowerCase());if(!a)return!1;let s=n==="String"?"REG_SZ":n==="ExpandString"?"REG_EXPAND_SZ":n;if(s!=="REG_SZ"&&s!=="REG_EXPAND_SZ"){if(o)throw new Error("an owned Claude policy value has an unsupported type");return!1}if(e[a].present)throw new Error("a Claude policy value was returned more than once");return e[a]={present:!0,type:s,value:r},!0},x$=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,R$=(e,t)=>{if(!Dl(e,!0))return!1;let n=x$(t);if(S$.has(n))return!1;if(v$.has(n))return n==="REG_EXPAND_SZ"?!0:!TC(e,!0)},O$=(e,t)=>{let n=xA(),r=!1,o=!1,a=!1,s=t.toUpperCase()===li.toUpperCase(),i=(l,d)=>{if(!s)return;let u=R$(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),hA(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||I$(d,t))continue;let u=A$.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),hA(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Kn=async(e,t=_e)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:xA(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return O$(n.stdout,t)},vr=async e=>{let t=await Kn(e,li);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...Ne.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},Ah=e=>e.unparsed?`This machine may have a Claude policy under ${li} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${li} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${li} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var jl=(e,t)=>ia(io(e,t)),RA=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],_$=(e,t)=>{let n=jl(e,t);return Object.fromEntries(Ne.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},T$=(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}}),P$=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,ph=e=>Object.fromEntries(Ne.map(t=>[t,f$(t,e[t])])),mA=(e,t,n,r)=>({version:Kl,registryKey:_e,keyExisted:e,lastWritten:ph(t),helper:{path:n,lastWritten:dh(r)}}),L$=(e,t,n,r,o,a)=>({version:Kl,registryKey:_e,keyExisted:e,lastWritten:ph(t),pending:ph(n),helper:{path:r,...o?{lastWritten:dh(o)}:{},pending:dh(a)}}),fh=(e,t,n)=>ua(n,e.lastWritten[t])||e.pending!==void 0&&ua(n,e.pending[t]),ha=async e=>{try{let t=await lh(e,"utf8");return{content:t,sha256:lo(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},ma=async e=>(await ha(e))?.sha256,pa=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Hl=async(e,t)=>{let n=c$(e),r;try{r=await bA(di(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>ya(di(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([ha(e),ha(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!pa(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await IA(e,a))throw new Error("credential helper changed during recovery");return}if(t&&pa(t,s.sha256)&&pa(t,i.sha256)){await an(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},vh=async(e,t,n)=>(n.present?await e(RA(_e,t,n.value??"",n.type??"REG_SZ")):await e(["delete",_e,"/v",t,"/f"])).code===0,D$=async(e,t,n)=>{let r=!0,o=await Kn(e);for(let a of Ne)if(!da(o.values[a],t[a])){if(!da(o.values[a],n[a])){r=!1;continue}await vh(e,a,t[a])||(r=!1),o=await Kn(e)}return r&&Ne.every(a=>da(o.values[a],t[a]))},ze=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Wt(n)]}}),OA=async(e,t,n,r={})=>{if(!Ie(t))return ze("A valid personal ark_ gateway key is required.",!1,r);let o=yh(r),a;try{a=r$((r.credentialCommand??eh)())}catch{return ze("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=lo(a),i=r.runReg??Gn,c=Wt(r),l;if(!n.dryRun)try{l=await wh(r)}catch(m){return ze(m instanceof fa?"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 vr(i);if(m)return ze(Ah(m),!1,r);let w=await Ch(r,!n.dryRun);n.dryRun||await Hl(o,w);let g=await Kn(i),y=_$(e,o),b=await ha(o),A=b?.sha256,v=!1;if(d=w,u=g,f=y,w){let C=Ne.find(x=>!fh(w,x,g.values[x]));if(C)return ze(`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&&!pa(w,A))return ze(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);v=P$(w)}else{if(A!==void 0&&A!==s)return ze(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let C=g.foreignState||Ne.some(U=>g.values[U].present),x=Ne.every(U=>da(g.values[U],y[U])),T=Ne.every(U=>da(g.values[U],T$(e,t.trim())[U]));if(C&&!x&&!T)return ze(`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=T,x&&A===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${_e} into an owner-only journal without rewriting them.`]}:(await Bl(mA(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??gh)()}catch{}if(C)return ze("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let E=L$(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 Bl(E,r),h=!0;for(let C of Ne){let x=await Kn(i);if(!ua(x.values[C],E.lastWritten[C])&&!ua(x.values[C],E.pending[C]))throw new Error("registry value changed during apply");if(!da(x.values[C],y[C])&&!await vh(i,C,y[C]))throw new Error("registry write failed")}let I=await Kn(i);if(!Ne.every(C=>ua(I.values[C],E.pending[C])))throw new Error("registry verification failed");if(A!==s&&(A===void 0?await i$(o,a):await Wl(o,A,a,"apply",r)),await ma(o)!==s)throw new Error("credential helper verification failed");return await Bl(mA(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.",...Tl]}}catch{if(!h||!u||!f||!p)return ze("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Hl(o,p);let m=!0,w=await ha(o),g=p.helper.pending;if(w?.sha256!==p.helper.lastWritten?.sha256&&(g!==void 0&&w?.sha256===g.sha256?p.helper.lastWritten?(await Wl(o,g.sha256,p.helper.lastWritten.content,"rollback",r),m=await ma(o)===p.helper.lastWritten.sha256):await Wl(o,g.sha256,void 0,"rollback",r):m=w===void 0&&p.helper.lastWritten===void 0),m&&await D$(i,u.values,f))return d?await Bl(d,r):await an(c,{force:!0}),ze("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return ze("Could not complete or fully roll back Claude Desktop's HKCU policy transaction. The owner-only journal was preserved; run `anyray-connect desktop disconnect` to recover safely.",!0,r)}finally{await l?.()}},_A=async(e,t={})=>{let n=t.runReg??Gn,r=Wt(t),o;if(!e.dryRun)try{o=await wh(t)}catch(a){return ze(a instanceof fa?"Another Claude Desktop policy operation is already in progress; retry shortly.":"Could not acquire the owner-only Claude Desktop policy lock; no registry value was removed.",!1,t)}try{let a=await Ch(t,!e.dryRun);a&&!e.dryRun&&await Hl(a.helper.path,a);let s=await Kn(n);if(!a)return Ne.filter(h=>s.values[h].present).length>0?ze(`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=Ne.filter(p=>s.values[p].present&&!fh(a,p,s.values[p])),c=await ma(a.helper.path),l=c!==void 0&&!pa(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 Ne){let m=(await Kn(n)).values[p];if(m.present){if(!fh(a,p,m)){u.add(p);continue}await vh(n,p,{present:!1})||(d=!0)}}let f=await ma(a.helper.path);if(f!==void 0)if(pa(a,f))try{await Wl(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?ze(`Could not remove every Anyray-owned Claude policy value or credential-helper file. The ownership journal remains at ${r}; re-run revert.`,!0,t):(await an(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?[]:Pl]})}catch{return ze(`Could not safely inspect or revert ${_e}; no unproven value was removed.`,!1,t)}finally{await o?.()}},TA=async(e,t={})=>{let n=t.runReg??Gn;if(!await R(Wt(t)))return;let r;try{r=await wh(t);let o=await Ch(t);if(o&&await Hl(o.helper.path,o),!o||o.pending||await vr(n)!==void 0)return;let a=await Kn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Ye(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&Ne.every(l=>ua(a.values[l],o.lastWritten[l]))))return;let i=await ma(o.helper.path),c=o.helper.lastWritten;return a.values.inferenceCredentialKind.value==="helper-script"&&a.values.inferenceCredentialHelper.value===o.helper.path&&!a.values.inferenceGatewayApiKey.present&&c!==void 0&&i===c.sha256&&await s$(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?.()}},PA=async(e,t={})=>await TA(e,t)!==void 0,LA=async(e,t={})=>await TA(e,t)==="dynamic";var wa=(e=$$())=>e==="win32"?gh:Ml,Sh="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",Yl=async(e,t={})=>{let n=(t.profileRoot??so)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Sh};if((t.appRunning??wa(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await DA.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 _l(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 "+Sh}:{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??SC)();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=Vl(t.stagingRoot??M$(),`anyray-history-${process.pid}-${N$()}`);try{let s=await(t.runImporter??EC)({binary:o,exportPath:e,configDir:Vl(a,"config"),workDir:Vl(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. "+Sh};if(s.conversations.length===0)return{ok:!1,reason:"that export contains no conversations",remedy:"Check you pointed at the export archive itself."};let i=await xC(r.dir,s.conversations),c=await RC({stagedProjectsDir:Vl(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 DA.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as Et}from"node:fs";import{homedir as aM}from"node:os";import{join as cn,sep as sM}from"node:path";import{isDeepStrictEqual as zl}from"node:util";import{constants as F$}from"node:fs";import{promises as G}from"node:fs";import{dirname as ba,isAbsolute as Ih,join as te,relative as Zl,resolve as sn,sep as ui}from"node:path";import{randomUUID as ql}from"node:crypto";var Cn=448,pi=384,FA=448,U$=4,xh=3e4,UA=5e3,B$=10*6e4,Eh=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),lt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fi=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),BA=(e,t)=>{let n=Zl(sn(e),sn(t));return n===""||!n.startsWith(`..${ui}`)&&n!==".."&&!Ih(n)},uo=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return lt(n)?{raw:t,value:n}:void 0}catch(t){return St(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},St=e=>e instanceof Error&&"code"in e,W$=e=>{try{return process.kill(e,0),!0}catch(t){return St(t)&&t.code==="EPERM"}},WA=e=>e===0?"owner.json":`owner.${e}.json`,Jl=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=te(e,r.name),a,s,i;try{let d=JSON.parse(await G.readFile(o,"utf8"));lt(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}},HA=e=>{if(e.pid===void 0||!W$(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>xh&&t-e.createdAtMs>B$},H$=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(ba(t),{recursive:!0,mode:Cn});let n=ql(),r,o=!1;try{await G.mkdir(t,{mode:Cn}),o=!0}catch(i){if(!St(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Jl(t);if(d){if(!HA(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)<=xh)return}let l=te(t,WA(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
289
|
+
`,{flag:"wx",mode:pi}),r=l}catch(d){if(St(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(!lt(i)||i.nonce!==n)return;let c=new Date;await G.utimes(a,c,c)}catch{}})()},UA);return s.unref(),async()=>{clearInterval(s);try{(await Jl(t))?.nonce===n&&await G.rm(t,{recursive:!0,force:!0})}catch{}}},K$=async(e,t,n)=>{await G.mkdir(ba(e),{recursive:!0,mode:Cn});let r=await H$(e);if(!r)return!1;try{let o;try{o=await G.readFile(e,"utf8")}catch(s){if(!St(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${ql()}`;try{await G.writeFile(a,`${JSON.stringify(n,null,2)}
|
|
290
|
+
`,{mode:pi,flag:"wx"}),await G.rename(a,e)}catch(s){try{await G.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},Ql=async(e,t)=>{for(let n=0;n<U$;n+=1){let r=await uo(e);if(!r)return"failed";let o=t(r.value);if(!o||zl(o,r.value))return"unchanged";try{if(await K$(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},NA=async e=>{try{return(await G.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},ed=async e=>{let t=[];for(let n of await NA(e))for(let r of await NA(te(e,n)))t.push(te(e,n,r));return t},G$=e=>Array.isArray(e.skills)?e.skills.filter(t=>lt(t)&&fi(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],j$=async e=>{let t=te(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await ed(t)){let o=await uo(te(r,"manifest.json"));if(!o)continue;let a=r.split(ui).at(-1)??"";for(let s of G$(o.value))n.push({account:a,packageDir:r,entry:s})}return n},V$=async e=>{let t=await uo(te(e,".claude-plugin","plugin.json"));return!!t&&fi(t.value.name)},Y$=(e,t)=>{let n=Ih(t)?sn(t):sn(e,t);if(!BA(e,n)||n===sn(e))return;let r=Zl(sn(e),n);return r.length>0?{absolute:n,relative:r}:void 0},Z$=async e=>{let t=await ed(te(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(ui).includes("skills-plugin"))continue;let o=te(r,"cowork_plugins"),a=await uo(te(o,"installed_plugins.json"));if(!a||!lt(a.value.plugins))continue;let s=r.split(ui).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!fi(i)||!Array.isArray(c)))for(let l of c){if(!lt(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=Y$(o,l.installPath);!d||!await V$(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:te(r,"cowork_account_settings.json")})}}return n},J$=async e=>{let t=await uo(te(e,"claude_desktop_config.json"));return!t||!lt(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>fi(n)&&n.toLowerCase()!=="anyray"&<(r)))},KA=async e=>{let[t,n,r]=await Promise.all([j$(e),Z$(e),J$(e)]);return{skills:t,plugins:n,localMcpServers:r}},Rh=async e=>{let t=await KA(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)}},$A=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(!fi(o.name))return!1;let a=te(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)},X$=async e=>{let t=async n=>{let r=await G.readdir(n,{withFileTypes:!0});for(let o of r){let a=te(n,o.name);if(o.isDirectory())await t(a),await G.chmod(a,Cn);else if(o.isFile()){let s=await G.stat(a);await G.chmod(a,(s.mode&73)!==0?FA:pi)}}};await t(e),await G.chmod(e,Cn)},GA=async(e,t)=>{try{let[n,r]=await Promise.all([G.readFile(e),G.readFile(t)]);return n.equals(r)}catch{return!1}},Xl=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(!zl(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 Xl(te(e,s),te(t,s)))return!1}else if(!i.isFile()||!await GA(te(e,s),te(t,s)))return!1}return!0}catch{return!1}},jA=e=>`${e}.anyray-incomplete`,VA=async(e,t)=>{let n=!1;if(t){await G.mkdir(ba(e),{recursive:!0,mode:Cn});try{await G.mkdir(e,{mode:Cn}),n=!0}catch(l){if(!St(l)||l.code!=="EEXIST")return}}else try{let l=await G.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=ql(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let f;try{f=await Jl(e)}catch{return}if(f){if(!HA(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)<=xh)return}let u=te(e,WA(d));try{await G.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
291
|
+
`,{flag:"wx",mode:pi}),o=u}catch(f){if(St(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(!lt(l)||l.nonce!==r)return;let d=new Date;await G.utimes(a,d,d)}catch{}})()},UA);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await Jl(e))?.nonce===r&&await G.rm(e,{recursive:!0,force:!0})}catch{}}}},YA=async e=>{let t=await VA(e,!1);t&&await t.complete()},z$=async(e,t,n)=>{let r=jA(t),o=!1;try{let c=await G.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await Xl(e,t))return await YA(r),"present"}catch(c){if(!St(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 VA(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await G.mkdir(t,{mode:Cn})}catch(c){if(!St(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=te(c,u.name),p=te(l,u.name);try{if(u.isDirectory()){try{await G.mkdir(p,{mode:Cn})}catch(m){if(!St(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,F$.COPYFILE_EXCL);let h=await G.stat(f);await G.chmod(p,(h.mode&73)!==0?FA:pi)}catch(h){if(!St(h)||h.code!=="EEXIST")throw h;if(!await GA(f,p))return"conflict"}else return"failed"}catch(h){return St(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 Xl(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},ZA=async(e,t,n,r)=>{if(!await $A(e))return"invalid";try{let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await Xl(e,t))return await YA(jA(t)),"present"}catch(a){if(!St(a)||a.code!=="ENOENT")return"failed"}await G.mkdir(ba(t),{recursive:!0,mode:Cn});let o=te(ba(t),`.anyray-stage-${ql()}`);try{return await G.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await $A(o)?(await X$(o),await n?.(t),await z$(o,t,r)):"invalid"}catch{return"failed"}finally{try{await G.rm(o,{recursive:!0,force:!0})}catch{}}},MA=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),q$=async e=>{let t=await ed(te(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await uo(te(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},Q$=async e=>{let t=await ed(te(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(ui).includes("skills-plugin"))try{await G.access(te(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},eM=async(e,t,n,r,o)=>{let a=te(t,"manifest.json");for(let s of e){let i=te(s.packageDir,"skills",s.entry.name);try{await G.access(te(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=te(t,"skills",s.entry.name),l=await ZA(i,c,r,o);if(l==="conflict"){n.conflicts+=1;continue}if(l==="invalid"){n.invalid+=1;continue}if(l==="failed"){n.failed+=1;continue}let d=!1;await Ql(a,f=>{let p=Array.isArray(f.skills)?f.skills:[];if(p.find(m=>lt(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}},JA=(e,t)=>({...e,installPath:t}),tM=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=Ih(r.installPath)?sn(r.installPath):sn(o,r.installPath),s=JA(e,Zl(sn(t),sn(n))),i={...r,installPath:Zl(sn(o),a)};return zl(s,i)},nM=async(e,t,n)=>{let r=await uo(e);if(!r||!lt(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":Ql(t,a=>{let s=lt(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},rM=async(e,t,n,r,o)=>{let a=te(t,"cowork_plugins"),s=te(a,"installed_plugins.json"),i=te(t,"cowork_account_settings.json");for(let c of e){let l=te(a,c.relativeInstallPath);if(!BA(a,l)){n.invalid+=1;continue}let d=await ZA(c.packageDir,l,r,o);if(d==="conflict"){n.conflicts+=1;continue}if(d==="invalid"){n.invalid+=1;continue}if(d==="failed"){n.failed+=1;continue}let u=!1,f=!1;await Ql(s,h=>{let m=lt(h.plugins)?h.plugins:{},w=m[c.id],g=Array.isArray(w)?w:[],y=g.find(A=>lt(A)&&A.scope==="user");if(y){u=tM(c.entry,ba(c.settingsFile),c.packageDir,y,t),f=!u;return}let b=JA(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 nM(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},oM=async(e,t,n)=>{let r=te(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await Ql(r,c=>{let l=lt(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=zl(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}},XA=async(e,t,n={})=>{let r=await KA(e),o=Eh("skill"),a=Eh("plugin"),s=Eh("local-mcp"),i=[],c=[],l=MA(r.skills,n.account,n.allAccounts),d=MA(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 q$(t);f.state==="found"?await eM(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 Q$(t);f.state==="found"?await rM(d,f.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await oM(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 iM=async e=>{try{return await Et.access(e),!0}catch{return!1}},zA=448,cM=384,QA={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},lM=["code","cowork"],Th=(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.",Oh=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),ev=async e=>{let t;try{t=(await Et.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&aa(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await Et.readdir(cn(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&aa(a.name)).map(a=>a.name);for(let a of o)n.push(cn(e,r,a))}catch{}return n},dM=async e=>{try{return(await Et.readdir(e)).filter(t=>t.startsWith(Wn)&&t.endsWith(".json")).map(t=>t.slice(Wn.length,-5)).filter(aa)}catch{return[]}},uM=async(e,t)=>{let n=await ev(cn(e,QA[t])),r=[];for(let o of n){let a=await dM(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(sM).slice(-2)[0]})}return r},pM=async(e,t)=>{if(t==="cowork"){let r=await _l(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await ev(cn(e,QA.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},fM=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await Et.copyFile(e,n),await Et.chmod(n,cM),await Et.rename(n,t)},hM=async(e,t)=>{try{let n=JSON.parse(await Et.readFile(e,"utf8"));if(!n||typeof n!="object")return!1;let{cwd:r,cliSessionId:o}=n;return typeof r!="string"||typeof o!="string"||r.length===0||!aa(o)?!1:(await Et.access(cn(t,".claude","projects",Zf(r),`${o}.jsonl`)),!0)}catch{return!1}},mM=async(e,t,n,r)=>{let o=Oh(e),a=await Jf(n);for(let s of t)await yM(e,s,n,r,a,o);return o},yM=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${Wn}${s}.json`,c=cn(t.dir,i);try{if(e==="code"){if(!await hM(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=cn(t.dir,`${Wn}${s}`),d=cn(n,`${Wn}${s}`),u=await Et.readdir(l);await Et.mkdir(d,{mode:zA});for(let f of u)await Et.cp(cn(l,f),cn(d,f),{recursive:!0,force:!1,errorOnExist:!0});await Et.chmod(d,zA)}await fM(c,cn(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},qA=(e,t,n,r=[])=>{let o=new Map;for(let{sources:s}of e)for(let i of s){let c=o.get(i.account)??{sessions:0,portable:!1};c.sessions+=i.ids.length,o.set(i.account,c)}for(let s of r){let i=o.get(s)??{sessions:0,portable:!1};i.portable=!0,o.set(s,i)}let a=[...o.entries()].sort((s,i)=>i[1].sessions-s[1].sessions).map(([s,i])=>{let c=i.sessions===0?"portable configuration":`${i.sessions} session${i.sessions===1?"":"s"}${i.portable?" plus portable configuration":""}`;return` ${t} --account ${s.slice(0,8)} (${c})`});return{ok:!1,kind:"account-ambiguous",reason:n,remedy:["Pick the one you want, or take everything:",...a,` ${t} --all-accounts`].join(`
|
|
292
|
+
`)}},_h=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),tv=async e=>{let t=[];for(let n of lM)t.push({lane:n,sources:await uM(e,n)});return t},nv=async(e={})=>{let t=(e.firstPartyRoot??(()=>Qs()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([tv(t),Rh(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=_h(n);for(let s of r.accounts)a.add(s);return{sessions:o,accounts:a.size,userSkills:r.skills,userPlugins:r.plugins,localMcpServers:r.localMcpServers}},po=async(e={})=>{let t=(e.home??aM)(),n=(e.firstPartyRoot??(()=>Qs()))(),r=(e.thirdPartyRoot??(()=>so()))();if(!n||!r)return{ok:!1,kind:"platform-unsupported",reason:"this platform has no Claude Desktop third-party profile",remedy:"Migration applies to macOS and Windows, where Desktop runs third-party mode in its own profile."};if((e.appRunning??wa())())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([tv(n),Rh(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=_h(o);for(let w of h)m.add(w);if(m.size>1)return qA(o,e.command??"anyray-connect desktop --migrate",`"${p}" matches ${m.size} accounts`,h);s=[...m]}else if(!e.allAccounts){let p=_h(o);for(let h of a.accounts)p.add(h);if(p.size>1)return qA(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 iM(r),l=await XA(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(Oh(p));continue}let m=await pM(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(Oh(p));continue}d.push(await mM(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:Th(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 gM=e=>[rt(e)],rv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...gM(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 ov="1.21459.0",CM=kM(wM),AM=async e=>{try{let{stdout:t}=await CM("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},vM=async e=>{try{return await bM(e)}catch{return}},av="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",SM=["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."],ka=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(sv??=iv({}),sv):iv(e),sv,iv=async e=>{let t=(e.home??mi)(),n=["/Applications/Claude.app",An(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??AM,o=e.readClaudeAppBundle??vM;for(let a of n){let s=await r(An(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${av}`}),c=Rl(s,ov);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${ov} or newer.`);let l=await o(An(a,"Contents","Resources","app.asar"));return l?KC.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. ${av}`}},td="anyray",dv="--anyray-owner=claude-desktop-v1",nd=(e={})=>{let t=(e.platform??Sr)(),n=(e.home??mi)();return t==="darwin"?on(e).appConfig:t==="win32"?An(process.env.APPDATA??An(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):An(n,".config","Claude","claude_desktop_config.json")},$h=(e={})=>An((e.home??mi)(),"Library","Application Support","Claude","claude_desktop_config.json"),uv=()=>{let e=je("profile");return{command:e.command,args:[...e.args,dv]}},fo=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),pv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},EM=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),IM=e=>{if(!fo(e)||!pv(e,["command","args"]))return!1;let t=uv();return e.command===t.command&&EM(e.args,t.args)},xM=e=>fo(e)&&Array.isArray(e.args)&&e.args.at(-1)===dv,RM=e=>{if(!fo(e)||!pv(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||Ge(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===or&&t.at(-1)==="profile"))return!1;let r=e.command.replaceAll("\\","/");if(/(?:^|\/)anyray-connect(?:\.exe)?$/.test(r))return t.length===2;if(!/(?:^|\/)node(?:\.exe)?$/.test(r)||t.length!==3)return!1;let o=t[0].replaceAll("\\","/");return!Ge(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},OM=e=>e===void 0?"absent":IM(e)?"exact":xM(e)||RM(e)?"stale-owned":"foreign",Be=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},ho=async e=>{let t=await R(e),n;try{n=await M(e)}catch{throw new Be(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!fo(n.mcpServers))throw new Be(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(fo(n.mcpServers)?n.mcpServers:void 0)?.[td];return{path:e,fileExisted:t,json:n,entry:o,ownership:OM(o)}},rd=e=>{if(e.ownership==="foreign")throw new Be(`MCP name conflict in ${e.path}: mcpServers.${td} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},fv=(e,t)=>{let n={...e},r=fo(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[td]:r[td]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Lh=async(e,t)=>{if(Ph(e.entry,t))return;let n=await ho(e.path);if(!Ph(n.entry,e.entry))throw new Be(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Hn(e.path,fv(n.json,t)),{reading:e,afterEntry:t}},Dh=async e=>{let t=await ho(e.reading.path);if(!Ph(t.entry,e.afterEntry))throw new Be(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=fv(t.json,e.reading.entry);await Hn(e.reading.path,n)},_M=async e=>{if(!ce())throw new Be(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Re()} is temporary); no inference setting was changed.`);let t=await ho(nd(e));rd(t);let n=$h(e),r=(e.platform??Sr)()==="darwin"&&n!==t.path?await ho(n):void 0;return r&&rd(r),{active:t,...r?{legacy:r}:{}}},cv=async e=>{let t=await ho(nd(e));rd(t);let n=$h(e),r=(e.platform??Sr)()==="darwin"&&n!==t.path?await ho(n):void 0;return r&&rd(r),{active:t,...r?{legacy:r}:{}}},TM=async e=>{let t=[];try{let n=await Lh(e.active,uv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Lh(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Dh(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Be(`Claude Desktop MCP setup failed and could not restore ${r.join(", ")}. Re-run \`anyray-connect desktop disconnect\` to recover safely.`,r):n}return{changedFiles:t.map(n=>n.reading.path),async rollback(){let n=[];for(let r of[...t].reverse())await Dh(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Be(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},PM=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Lh(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Dh(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Be(`Claude Desktop MCP cleanup failed and could not restore ${r.join(", ")}. Re-run revert after resolving the file conflict.`,r):n}return t.map(n=>n.reading.path)},lv=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)."]},LM={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},od="claude-desktop",Nh="migrate",hv=new Set(["app-running","store-missing"]),DM={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},NM={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"}},$M="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",mv=e=>{let t=(e.platform??Sr)(),n=e.home??mi;return{home:n,appRunning:e.appRunning??wa(t),firstPartyRoot:()=>Qs({home:n,runtimePlatform:t}),thirdPartyRoot:()=>so({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},yv=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=DM[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.`:"")},gv=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=NM[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.`:"")},hi=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=mv(e),r=await(e.pendingDesktopMigrationCount??nv)(n),o=r.userSkills+r.userPlugins+r.localMcpServers;if(r.sessions+o===0)return[];if(t.dryRun)return[`Would bring ${[r.sessions>0?`${r.sessions} existing Claude Desktop session${r.sessions===1?"":"s"}`:"",o>0?`${o} portable configuration ${o===1?"entry":"entries"}`:""].filter(Boolean).join(" and ")} into Claude Desktop's third-party profile, now or automatically the next time Claude Desktop is fully quit.`];let a=await(e.migrateDesktopProfile??po)(n);if(a.ok){let c=yv(a.lanes),l=gv(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 _s(od,Nh);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(!hv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
|
|
293
|
+
${a.remedy}`];if(t.preservePendingOp)return[];await _s(od,Nh);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."]}},MM=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await fr(od),[]}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."]}},FM=e=>rv({id:od,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??Sr)(),n=(e.home??mi)();return t==="darwin"?["/Applications/Claude.app",An(n,"Applications","Claude.app")]:t==="win32"?[An(process.env.LOCALAPPDATA??An(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:",...lv(t)]:["Claude desktop org/API lane:",...lv(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`."]}),UM=(e={})=>{let t=FM(e),n=()=>(e.platform??Sr)()==="darwin",r=()=>(e.platform??Sr)()==="win32",o=(s,i)=>n()?zC(s,i,e):OA(s,s.clientKey??"",i,e),a=s=>n()?qC(s,e):_A(s,e);return{...t,automatic:!0,quitGated:{isRunning:()=>(e.appRunning??wa((e.platform??Sr)()))(),quitTarget:LM,needsTarget:()=>!1,async complete(s){if(s!==Nh)return{status:"manual",messages:[`Claude Desktop could not service a queued "${s}" operation it does not recognise; the queue entry was dropped.`]};let i=await(e.migrateDesktopProfile??po)(mv(e));if(i.ok){let c=yv(i.lanes),l=gv(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 hv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?eA(s,e):r()?LA(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=on(e),p=await co(f,e);if(p)return{status:"manual",manualAudience:"admin",messages:[ah(p),...await hi(e,i)]}}if(r()){let f;try{f=await vr(e.runReg??Gn)}catch{return{status:"manual",manualAudience:"admin",messages:[$M,...await hi(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[Ah(f),...await hi(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 ka(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await _M(e)}catch(f){let p=f instanceof Be?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Be?f.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no inference setting was changed."]}}let l=await o(s,{dryRun:!0});if(l.status!=="configured")return l;if(i.dryRun){let f=c.legacy;return{...l,messages:[...l.messages,`Would register the ownership-marked Anyray retrieval MCP server in ${c.active.path}.`,...f&&f.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${f.path}.`]:[],...await hi(e,i)]}}let d;try{d=await TM(c)}catch(f){let p=f instanceof Be?f.changedFiles:[];return{status:"manual",...p.length>0?{changedFiles:p}:{},messages:[f instanceof Be?f.message:"Could not safely register Claude Desktop retrieval; the inference route was left unchanged."]}}let u;try{u=await o(s,{dryRun:!1})}catch{u={status:"manual",messages:["Claude Desktop inference setup failed before it returned a result."]}}if(u.status!=="configured")try{return await d.rollback(),{...u,changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])],messages:[...u.messages,"Restored the prior Claude Desktop MCP registration because inference setup did not complete. A config file that was absent before setup may remain as an inert object to avoid racing unrelated concurrent writes."]}}catch{return{status:"manual",changedFiles:[...u.changedFiles??[],...d.changedFiles],messages:[...u.messages,"Inference setup did not complete, and the prior MCP registration could not be fully restored. Re-run `anyray-connect desktop disconnect` to recover safely."]}}return{...u,messages:[...u.messages,"Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) with an ownership marker.",...await hi(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?SM:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=nd(e),c=await MM(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 Be?m.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no setting was removed."]})}let u=await a({dryRun:!0});if(s.dryRun){let m=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...m&&m.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${m.path}.`]:[]]})}let f=await a({dryRun:!1});if(f.status==="manual"){let m=r()?Wt(e):void 0;if(!(m!==void 0&&f.changedFiles?.includes(m)===!0&&!await R(m)))return l(f)}let p;try{p=await PM(await cv(e))}catch(m){let w=m instanceof Be?m.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...w])],messages:[...f.messages,m instanceof Be?m.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await ae(i);let h=$h(e);return n()&&h!==i&&await ae(h),l({...f,messages:[...f.messages,...p.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...f.changedFiles??[],...p])]})},async mcpStatus(){if(!ce())return{registered:!1,command:null};try{let s=await ho(nd(e));return s.ownership!=="exact"||!fo(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 ka(e)).supported?ih(s,e):!1:r()?PA(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await ka(e)).supported)return["unknown"];let s=await QC(e);return s?[s]:["unknown"]}if(r())return await R(Wt(e))?await vr(e.runReg??Gn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=on(e);return!await R(s.journal)||await co(s,e)?!1:(await ka(e)).supported}return r()&&await R(Wt(e))?!await vr(e.runReg??Gn):!1}catch{return!1}}}},wv=UM();import{homedir as fF}from"node:os";import{join as hF}from"node:path";import{rm as fd}from"node:fs/promises";import{constants as bv,accessSync as BM,statSync as WM}from"node:fs";import{platform as Mh}from"node:os";import{delimiter as HM,posix as KM,resolve as GM,win32 as jM}from"node:path";var VM="0.59.0",YM="1.1.4",jn="Anyray \xB7 Claude",Vn="Anyray \xB7 Codex",ad="__anyray-acp-agent",kv=(e,t,n)=>{let{command:r,args:o}=un([ad,e,t,n]);return{command:r,args:o,env:{}}},sd=(e=Mh())=>e==="win32"?"npx.cmd":"npx",id=(e=process.env.PATH,t=Mh())=>{if(!e)return;let n=sd(t);for(let r of e.split(HM)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=GM(o,n);try{if(!WM(a).isFile())continue;return BM(a,t==="win32"?bv.F_OK:bv.X_OK),a}catch{}}},cd=(e,t=Mh())=>{let n=t==="win32"?jM:KM;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==sd(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},ZM="https://chatgpt.com/backend-api/codex",JM="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",Cv="ANYRAY_ACP_CODEX_AUTHORIZATION",Av="ANYRAY_ACP_CODEX_CLIENT_KEY",vv="ANYRAY_ACP_CODEX_METADATA",Sv=e=>de({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),XM=(e,t={})=>{let n=X(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":ZM,"x-anyray-forward-headers":JM}:{},o=n?{...e.clientKey?{"x-anyray-api-key":Av}:{}}:{Authorization:Cv};return Sv(e)&&(o["x-anyray-metadata"]=vv),{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}}}:{}}},zM=e=>{let t=X(e,"openai"),n=Sv(e);return{...t?e.clientKey?{[Av]:e.clientKey}:{}:{[Cv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[vv]:n}:{}}},Ev=(e,t=sd(),n={})=>({[jn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${VM}`],env:pn(e).env},[Vn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${YM}`],env:{CODEX_CONFIG:JSON.stringify(XM(e,n)),...zM(e)}}}),yi=(e=sd(),t="jetbrains")=>({[jn]:kv("claude",e,t),[Vn]:kv("codex",e,t)}),mo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ld=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as qM}from"node:zlib";import{open as QM,readFile as Hh,readdir as pd}from"node:fs/promises";import{dirname as Iv,join as ue}from"node:path";import{homedir as _v,platform as Kh}from"node:os";var dd="2025.3.2",Ca="253.30387.147",gi="com.intellij.ml.llm",Fh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),eF=1e4,tF=256*1024*1024,nF=16*1024*1024,Uh=1024*1024,Bh=22,rF=Bh+65535,Wh=Rl,oF=()=>{let e=_v(),t=ue(e,".cache","JetBrains","RemoteDev");switch(Kh()){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"}]}},aF=()=>Kh()==="linux"?ue(_v(),".local","share","JetBrains"):rt("JetBrains"),sF=()=>Kh()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),iF=async(e,t=eF)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await pd(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 pd(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)]},cF=e=>{let t=Iv(e);return t.endsWith(`${ue("Contents","Resources")}`)?Iv(t):t},lF=async e=>{try{let t=JSON.parse(await Hh(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!zs(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:cF(e)}}catch{return}},ud=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},dF=async(e,t)=>{let n;try{n=await QM(e,"r");let{size:r}=await n.stat();if(r<Bh||r>tF)return;let o=Math.min(r,rF),a=await ud(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Bh;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>nF||c+i>r)return;let l=await ud(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>Uh||p>Uh)return;let A=await ud(n,30,g);if(!A||A.readUInt32LE(0)!==67324752)return;let v=A.readUInt16LE(26),E=A.readUInt16LE(28),I=await ud(n,f,g+30+v+E);return I?u===0?I.toString("utf8"):u===8?qM(I,{maxOutputLength:Uh}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},xv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!zs(n)))return{id:t,version:n}},uF=async(e,t)=>{let n=ue(e,"META-INF","plugin.xml");if(await R(n))try{let o=xv(await Hh(n,"utf8"));return{present:o?.id===gi||t,descriptor:o?.id===gi?o:void 0}}catch{return{present:t}}let r=[];try{r=(await pd(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 dF(o,"META-INF/plugin.xml"),s=a?xv(a):void 0;if(s?.id===gi)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},Rv=async e=>{let t;try{t=await pd(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Fh.has(o.name.toLowerCase()),i=Fh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Fh.has(o.name.toLowerCase());if(!a){let i=ue(e,o.name,"META-INF","plugin.xml");if(!await R(i))continue}let s=await uF(ue(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},pF=async e=>{try{return(await Hh(ue(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(gi)}catch{return!1}},Ov=e=>e.reduce((t,n)=>t?(Wh(n,t)??-1)>0?n:t:n,void 0),Tv=async(e={})=>{let t=e.configRoot??rt("JetBrains"),n=e.userPluginsRoot??aF(),r=await iF(e.productRoots?e.productRoots.map(h=>({path:h,layout:"recursive"})):oF(),e.scanBudget),o=(await Promise.all(r.map(h=>lF(h)))).filter(h=>h!==void 0),a=o.length>0||await R(t);if(e.wsl??sF())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=>(Wh(h.version,dd)??-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 Rv(y);if(b.present){g=b;break}}if(g??=await Rv(ue(h.root,"plugins")),g.present&&!g.descriptor){l=!0;continue}if(!(!g.descriptor||g.descriptor.id!==gi)){if(i.push(g.descriptor.version),await pF(m)){c=!0;continue}if(!((Wh(g.descriptor.version,Ca)??-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=Ov(o.map(h=>h.version)),f=Ov(i),p;return a?u?s.length===0?p=`JetBrains IDE ${u} is below the ACP minimum ${dd}; no ACP config was written.`:d?p=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${dd}+ once, enable AI Assistant ${Ca}+, then run Connect again. No ACP config was written.`:c?p=`JetBrains AI Assistant is disabled; enable version ${Ca}+ and run Connect again. No ACP config was written.`:f?p=`JetBrains AI Assistant ${f} is below the ACP minimum ${Ca}; no ACP config was written.`:l?p=`Could not verify the local JetBrains AI Assistant version; require ${Ca}+ before running Connect. No ACP config was written.`:p=`JetBrains AI Assistant ${Ca}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:p=`Could not prove JetBrains IDE ${dd}+ 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 mF=[jn,Vn],Gh=()=>hF(fF(),".jetbrains","acp.json"),yo=()=>`${Gh()}.anyray-state`,yF=(e,t,n="npx")=>{let r=mo(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,yi(n,"jetbrains")),{...e,agent_servers:r}},gF=(e,t,n)=>{if(!mo(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=mo(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of mF)if(c in r){if(!ld(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}},wF=(e=Tv)=>({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=Gh(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=id();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await R(r),c;try{c=await M(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=yi(a,"jetbrains");return await ac({configPath:r,current:c,next:yF(c,t,a),journalPath:yo(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,yo()]}},async revert(t){let n=Gh(),r=async()=>{if(!await R(n))return t.dryRun||(await ae(n),await fd(yo(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await M(n)}catch{return t.dryRun||(await ae(n),await fd(yo(),{force:!0}).catch(()=>{})),{status:"manual",messages:[`Could not parse ${n}; remove the two \u201CAnyray \xB7 \u2026\u201D agent entries manually.`]}}let a={},s=!1,i=!1;try{let u=await M(yo());(u.version===1||u.version===2)&&mo(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await R(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await M(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await Mr(n);let l=gF(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 fd(n,{force:!0}):await J(n,l.next,{backup:!1})),t.dryRun||(await ae(n),await fd(yo(),{force:!0}).catch(()=>{})),{status:l.conflicts.length?"manual":"reverted",messages:d.length?d:["No Anyray ACP entries found."],changedFiles:!t.dryRun&&l.removed.length?[n]:void 0}};return t.dryRun?r():oc(n,yo(),r)}}),Pv=wF();import{homedir as md}from"node:os";import{join as yd}from"node:path";import{rm as jh}from"node:fs/promises";var Vh="1.0.0",gd=["anyray-claude-acp","anyray-codex-acp"],bF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Yh=()=>yd(md(),".windsurf","acp","registry.json"),Zh=()=>yd(md(),".windsurf-next","acp","registry.json"),Aa=e=>`${e}.anyray-state`,Lv=e=>({binary:Object.fromEntries(bF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Nv=(e="npx")=>{let t=yi(e,"windsurf");return[{id:gd[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:Lv(t[jn])},{id:gd[1],name:Vn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Lv(t[Vn])}]},hd=e=>!Array.isArray(e)||e.some(t=>!mo(t)||typeof t.id!="string")?null:e,kF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Vh||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:hd(e.agents);if(!n)return null;let r=new Set(gd);return{...e,version:typeof e.version=="string"?e.version:Vh,agents:[...n.filter(o=>!r.has(o.id)),...Nv(t)],extensions:e.extensions??[]}},CF=(e,t,n)=>{let r=hd(e.agents);if(!r)return null;let o=hd(t.agents)??[],a=new Map((hd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!gd.includes(u.id)){l.push(u);continue}if(!ld(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===Vh&&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}},Dv=async()=>{let e=[];return(await R(Zh())||await R(yd(md(),".windsurf-next")))&&e.push(Zh()),(await R(Yh())||await R(yd(md(),".windsurf"))||await R(rt("Devin"))||await R(rt("Windsurf")))&&e.push(Yh()),e},$v={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await Dv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await Dv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=id();if(!r)return{status:"manual",messages:["Devin ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP registry was written."]};let o=[],a=[];for(let s of n){let i;try{i=await M(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=kF(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=Nv(r);await ac({configPath:s,current:i,next:c,journalPath:Aa(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,Aa(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=[Yh(),Zh()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await R(a)){e.dryRun||(await ae(a),await jh(Aa(a),{force:!0}).catch(()=>{}));return}let i;try{i=await M(a)}catch{n.push(`Could not parse ${a}; remove the anyray-* ACP agents manually.`),o=!0;return}let c=[],l=!1,d=!1;try{let p=await M(Aa(a));(p.version===1||p.version===2)&&Array.isArray(p.agents)&&(c=p.agents,l=p.version===2&&p.fileExisted===!1,d=p.version===2&&p.fileExisted===!0)}catch{}let u;if(d){let p=`${a}.anyray-bak`;if(!await R(p)){n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is missing. Restore it or remove the agents manually.`),o=!0;return}try{u=await M(p)}catch{n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is malformed. Repair it or remove the agents manually.`),o=!0;return}}else u=await Mr(a);let f=CF(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 jh(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 ae(a),await jh(Aa(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await oc(a,Aa(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var se=[sr,Ww,Ns,Tk,eC,fC,vC,Pv,wv,$v,Xw],Ht=e=>se.find(t=>t.id===e);var AF=["hook_registration","mcp_registration","hook_binary","beacon_target"],go=e=>e.status==="configured"||e.status==="queued",wo=async(e,t=se)=>{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},Er=async(e,t,n=se)=>{let r=[];for(let o of await wo(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},Jh=async(e,t=se)=>{let n=[];for(let r of await wo(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(AF.map(o=>[o,"unreadable"]))})}return n},Mv=e=>e.filter(t=>!t.integrationStatus),vF=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},mt=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=vF(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 TF,writeFile as PF}from"node:fs/promises";import{join as Gv}from"node:path";import{z as We}from"zod";var SF=["HTTPS_PROXY","https_proxy"],Fv=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"]),Uv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Bv=new Set(["ENOTFOUND","EAI_AGAIN"]),Wv=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Hv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),EF=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[...Fv,...Uv,...Bv,...Wv,...Hv])if(t.includes(n))return n}},xF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",RF=e=>SF.filter(t=>(e[t]??"").trim()!==""),OF=(e,t=process.env)=>{let n=EF(e),r=RF(t);return{kind:n&&Fv.has(n)?"tls-unknown-issuer":n&&Uv.has(n)?"tls-invalid-cert":n&&Bv.has(n)?"dns":xF(e)||n&&Hv.has(n)?"timeout":n&&Wv.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},_F=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}},yt=(e,t=process.env)=>_F(OF(e,t));var va="required",Kv=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team;return{routingUpdated:n,teamUpdated:r,...n?{gateway:t.routingOrigin}:{},...r?{team:t.team}:{}}},wd=(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]??va,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 LF=1e4,DF=1,NF=We.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),$F=We.object({id:NF,name:We.string().min(1),version:We.string().min(1),body:We.string()}),MF=We.object({version:We.literal(DF).optional(),skills:We.array($F),updatedAt:We.string().min(1).optional(),routing:We.object({origin:We.string().min(1)}).optional(),team:We.string().min(1).optional(),tools:We.object({enabled:We.array(We.string().min(1)),tiers:We.record(We.string().min(1),We.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),FF=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",bd=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",kd=async(e,t,n={})=>{let r=n.timeoutMs??LF,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.`:yt(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=bd(l),d}return MF.parse(c)},jv=/^[a-z0-9][a-z0-9-]{0,31}$/,Vv=64,UF=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>jv.test(o)).slice(0,Vv).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>jv.test(o)).slice(0,Vv).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},wi=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??va)==="locked":!1},Cd=async(e,t={})=>{let n=t.loadProfile??P,r=t.saveProfile??re,o=t.targetFromProfile??Oe,a=t.adapters??se,s=t.repairTools??mt,i=t.recordManaged??Qn,c=await n(),l={...c},d=Kv(c,{routingOrigin:e.routing?.origin?dn(e.routing.origin):void 0,team:e.team}),{routingUpdated:u,teamUpdated:f}=d;(u||f)&&(l={...await n()},d.gateway!=null&&(l.gateway=d.gateway),d.team!=null&&(l.team=d.team),await r(l));let p=wd(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||f),{candidateIds:h,freshIds:m}=p,w=0,g=0,y=0;if(h.length>0||m.length>0){let v=await o(async()=>l);if(v){let E;if(u||f){let x=new Set(h);E=[];for(let T of a)if(x.has(T.id))try{(await T.detect()).installed&&E.push(T)}catch{}}else E=await Er(h,v.toolOrigin,a);let I=new Set(m),C=[];for(let x of a)if(I.has(x.id))try{(await x.detect()).installed&&C.push(x)}catch{}if(w=E.length+C.length,w>0){let x=await s([...E,...C],v.target);g=x.filter(go).length;let T=x.filter(U=>I.has(U.id));if(y=T.filter(go).length,T.length>0)try{await i(T,!1)}catch{}}}}let b=UF(e),A=await n();if(JSON.stringify(b??null)!==JSON.stringify(A.fleetToolPolicy??null)){let{fleetToolPolicy:v,...E}=A;await r({...E,...b?{fleetToolPolicy:b}:{}})}return{routingUpdated:u,teamUpdated:f,toolsRequested:w,toolsApplied:g,toolsEnrolled:y,toolsTombstoned:p.tombstonedIds,profileUpdated:u||f}},Yv=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!FF(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=Gv(d,i.id),f=Gv(u,"SKILL.md");await TF(u,{recursive:!0}),await PF(f,BF(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}},BF=e=>e.endsWith(`
|
|
294
294
|
`)?e:`${e}
|
|
295
|
-
`;import{createHash as LF,createPrivateKey as DF,generateKeyPairSync as NF,randomBytes as Yh,sign as $F}from"node:crypto";var Zh=1e4,wo=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(wo).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${wo(e[n])}`).join(",")}}`,bi="stable-key-heartbeat-v1",Gv="key-heartbeat",MF=["reapply_config","remint","revert"];var jv=e=>LF("sha256").update(e).digest("hex"),ze=e=>typeof e=="string"&&e.trim()?e.trim():void 0,FF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],Xh=async e=>{try{let t=await e.json(),n=ze(t?.message);if(n)return n}catch{}return`gateway responded ${e.status}`},It=class extends Error{status;constructor(t,n){super(`the gateway rejected this enrollment (HTTP ${t}): ${n}`),this.name="GatewayVerifyError",this.status=t}},Sr=class extends Error{status;constructor(t,n){super(`the gateway rejected this credential heartbeat (HTTP ${t}): ${n}`),this.name="GatewayHeartbeatError",this.status=t}},Jh=(e,t,n)=>{try{let r=DF(t),o=new TextEncoder().encode(wo(e));return $F(null,o,r).toString("base64url")}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},Ad=()=>{let{publicKey:e,privateKey:t}=NF("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},cn=async(e,t,n,r={})=>{let o=r.timeoutMs??Zh,a=`${e}/connect/verify`,s=ze(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:Yh(16).toString("hex")},c=Jh(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.`:yt(y);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:y})}finally{clearTimeout(d)}if(!u.ok)throw new It(u.status,await Xh(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=ze(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=ze(p.user);if(!m)throw new Error("developer verification failed: the gateway response is missing the user");let w=UF(p.directive),g=FF(p.capabilities);return{key:h,user:m,team:ze(p.team),expiresAt:ze(p.expiresAt),...g.length>0?{capabilities:g}:{},...w?{directive:w}:{}}},vd=async(e,t,n,r,o={})=>{let a=o.timeoutMs??Zh,s=`${e}/connect/key/heartbeat`,i=ze(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:Yh(16).toString("hex"),purpose:Gv},l=Jh(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.`:yt(m);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:m})}finally{clearTimeout(u)}if(!f.ok)throw new Sr(f.status,await Xh(f));let p;try{p=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let h=ze(p.expiresAt);if(!h||!Number.isFinite(Date.parse(h))||p.credentialMode!==bi||p.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:h,credentialMode:bi}},Vv=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??Zh,i=`${e.replace(/\/$/,"")}/connect/machine`,c=ze(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Yh(16).toString("hex"),purpose:Gv},d=Jh(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)}},UF=e=>{if(e===null||typeof e!="object")return null;let t=e,n=ze(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!MF.includes(r)?null:{id:n,kind:r}},BF=1e4,HF=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!ze(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!ze(r.deploymentId)&&!!ze(r.user)&&!!ze(r.devPublicKey)&&!!ze(r.issuedAt)&&!!ze(r.expiresAt)},WF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??BF,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.`:yt(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 Xh(l)}`);let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!HF(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},Yv=(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())},Zv=async e=>{let t={timeoutMs:e.timeoutMs},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=Ad();return{cert:await WF(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 cn(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 ZF,randomBytes as XF,sign as JF}from"node:crypto";var KF="https://app.anyray.ai",GF=new Set(["localhost","::1","[::1]"]),jF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,VF=e=>GF.has(e)||jF.test(e),qh=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&VF(t.hostname)},YF=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Vn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!qh(e)?KF:YF(e)};var qF=1e4,zF="machine:",Xv=e=>e.startsWith(zF),QF="cert-renew",eU=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)},Jv=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Vn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:XF(16).toString("hex"),purpose:QF},c;try{let h=ZF(t),m=new TextEncoder().encode(wo(i));c=JF(null,m,h).toString("base64url")}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),qF),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 eU(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var zh=async(e,t=e.origin,n=se)=>{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}},ki=async(e,t=e.origin,n=se)=>(await zh(e,t,n)).complete;var tU=["claude","codex","cursor","opencode"],nU=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],rU=new Set(["missing_key","key_expired"]);var oU=600*1e3,aU=600*1e3,qv=1440*60*1e3,sU=1440*60*1e3,iU=10080*60*1e3,cU=3600*1e3,lU=720*60*1e3,dU=e=>Math.min(lU,cU*2**Math.max(0,e-1)),Ci=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Sa=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,zv=e=>typeof e=="string"&&nU.includes(e),Cn=e=>{if(!Ci(e))return{};let t={};if(Sa(e.watchSince)&&(t.watchSince=e.watchSince),Ci(e.invoked)){let n={};for(let r of tU){let o=e.invoked[r];Sa(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return Ci(e.authFailure)&&Sa(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...zv(e.authFailure.code)?{code:e.authFailure.code}:{}}),Ci(e.repair)&&Sa(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,...Sa(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Sd=e=>{try{let n=JSON.parse(e);if(Ci(n)&&zv(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"},Qh=e=>e!==void 0&&rU.has(e),em=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=oU},Qv=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),tm=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=aU},eS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),tS=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,nS=(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},rS=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>qv||!Qh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<dU(r.failures??1))},Ed=e=>{let t=Object.values(e?.invoked??{}).filter(Sa);return t.length>0?Math.max(...t):null},nm=(e,t)=>{if(Ed(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=iU},oS=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=sU)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=qv)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var rm="x-anyray-retrieve-probe",Id=8e3,uU=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",aS=(e,t)=>{let n=qt(e);return t?.probe&&(n[rm]="1"),n},Ea=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(),Id);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=uU(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)}},xd=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(),Id);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 pU=5e3,fU=2048,hU=e=>{let t=e.toLowerCase();return t.includes("client key required")?!0:["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},Ia=async(e={})=>{let t=e.readTarget??nt,n=e.fetch??fetch,r=e.timeoutMs??pU,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[rm]="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,fU);if(!hU(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=Sd(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)}},om=(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 mU,randomBytes as yU,sign as gU}from"node:crypto";var wU=500,sS=2e3,bU=2e3,kU=250,iS=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),wU);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)}},CU=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},AU=e=>new Promise(t=>setTimeout(t,e)),vU=async(e,t,n=AU)=>{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=CU(i)??kU,s>bU))return!1}finally{clearTimeout(a)}await n(s)}},SU=async e=>{try{let n=(await T()).enrolledCert,r=await Ue(),o=n?.payload?.deploymentId;if(!n||!r||!o)return!1;let a={deploymentId:o,issuedAt:new Date().toISOString(),nonce:yU(16).toString("hex"),events:e},s;try{let i=mU(r),c=new TextEncoder().encode(wo(a));s=gU(null,c,i).toString("base64url")}catch{return!1}return await vU(`${Vn()}/v1/connect-events`,JSON.stringify({cert:n,challenge:a,sig:s}))}catch{return!1}},EU=async(e,t)=>{try{let r=(await T()).enrolledCert,o=await Ue();if(!r||!o)return;await cn(e,r,o,{timeoutMs:sS,health:{events:t},telemetryOnly:!0})}catch{}},cS=async(e,t)=>{if(e.length!==0)try{let n=await nt(),r=n&&await iS(n.origin,qt(n),e,t);if(n&&await EU(n.origin,e),r)return;await SU(e)}catch{}},am=async(e,t,n={readTarget:()=>nt("profile"),post:iS})=>{if(e.length===0)return!1;try{let r=await n.readTarget();return r?await n.post(r.origin,{"content-type":"application/json"},e,t):!1}catch{return!1}};var ko=["hook_registration","mcp_registration","hook_binary","beacon_target"];var dS=128,uS=300*1e3,IU=["repaired","repair_failed","flapping","pending"],xU=["settings_not_writable","apply_unconfirmed","apply_threw"],pS=["rebroke_same_day","repeat_days"],fS=new Set(se.map(e=>e.id)),bo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),hS=e=>vi(e,ko),Rd=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},Er=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,Ai=e=>{if(!(!Array.isArray(e)||!e.every(hS)))return Yn(e)},RU=e=>{if(!bo(e))return;let t=Ai(e.checks);if(!(!Er(e.since)||!vi(e.reason,pS)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},OU=e=>{if(!bo(e))return;let t={};Rd(e.day)&&(t.day=e.day),Er(e.attempts)&&(t.attempts=e.attempts);let n=Ai(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=Ai(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=Ai(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=Ai(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Rd(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Er(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),bo(e.lastRepaired)){let i={};for(let c of ko){let l=e.lastRepaired[c];Er(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=RU(e.flapping);return s&&(t.flapping=s),t},_U=e=>{if(!bo(e)||!Rd(e.day)||!Er(e.sequence)||e.sequence===0||typeof e.tool!="string"||!fS.has(e.tool)||!hS(e.checkId)||!vi(e.status,IU)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!vi(e.errorClass,xU))return;t=e.errorClass}else if(e.status==="flapping"){if(!vi(e.errorClass,pS))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,...Er(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},lS=e=>{if(!bo(e))return{};let t={};if(bo(e.adapters)){let n={};for(let r of fS){let o=OU(e.adapters[r]);o&&(n[r]=o)}Object.keys(n).length>0&&(t.adapters=n)}return Array.isArray(e.events)&&(t.events=e.events.map(_U).filter(n=>n!==void 0).slice(-dS)),Er(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),bo(e.report)&&Rd(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Er(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},PU=e=>new Date(e).toISOString().slice(0,10),TU=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,Yn=e=>[...new Set(e)],Od=(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}:{}}},Si=(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(-dS),nextSequence:r}},LU=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),DU=async e=>await Oe(async()=>e,void 0,be)??null,NU=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=Od(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)},mS=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:TU(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:Yn([...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:Yn([...i?.checks??[],...t])}}:{}},slowFlap:a}},$U=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=Od(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=mS(u,h,n,r);c[l]={...g.adapter,awaiting:w.length>0?w:void 0},i=Si(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)},MU=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Od(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:Yn([...l.brokenReportedChecks??[],...g]),flapping:{since:y?.since??a,reason:"rebroke_same_day",checks:Yn([...y?.checks??[],...g])}},{next:Si({...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:Yn([...d,...f]),confirmedChecks:u.filter(g=>!f.includes(g)),brokenReportedChecks:Yn([...l.brokenReportedChecks??[],...p]),...p.length>0?{flapping:{since:m?.since??a,reason:"rebroke_same_day",checks:Yn([...m?.checks??[],...p])}}:{}},{next:Si({...i,adapters:c},o,p.map(g=>({tool:e,checkId:g,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:p}}},void 0),FU=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Od(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:Yn([...l.awaiting??[],...t])},{next:Si({...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=mS(l,d,o,a);c[e]=f.adapter;let p=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:Si({...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)},UU=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>=uS));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??am)(o.map(LU),n).catch(()=>!1))return;let s=new Set(o.map(i=>`${i.day}:${i.sequence}`));await r.claimState(i=>({next:{...i,events:(i.events??[]).map(c=>s.has(`${c.day}:${c.sequence}`)?{...c,delivered:!0}:c)},result:void 0}),void 0)},BU=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 ko){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??Lc)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??fr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=oS(await a.readHookLane?.().catch(()=>({})),o);return d&&(d.status!=="repaired"&&(i=!0),s.push({tool:"connect",checkId:"hook_lane",status:d.status,...d.errorClass?{errorClass:d.errorClass}:{}})),s.push({tool:"connect",checkId:"selfcheck_report",status:i?"problems":"ok"}),s},HU=async(e,t,n,r,o,a,s)=>{if(!await s.claimState(u=>u.report?.day===r&&u.report.delivered?{result:!1}:u.report?.day===r&&u.report.attemptedAt!==void 0&&u.report.attemptedAt<=o&&o-u.report.attemptedAt<uS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await BU(e,t,n,c,o,s);await(s.report??am)(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)},yS=async(e,t,n)=>{let r=n.now??Date.now,o=PU(r()),a=e.managedTools??[],s={...n,readState:async()=>lS(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(lS(l)),c)};try{let i=await(s.findIntegrations??Vh)(a);await NU(i,o,s);let c=await(s.listPending??ur)().catch(()=>[]),l=new Set(c.map(g=>g.adapter));await $U(i,l,o,r(),s);let d=await(s.resolveTarget??DU)(e),u=d?await(s.findDrifted??vr)(a,d.toolOrigin):[],f=new Set(u.map(g=>g.id)),p=new Map(i.map(g=>[g.adapter.id,g]));for(let g of u)p.has(g.id)||p.set(g.id,{adapter:g,checks:{}});let h=!1,m=(s.runtimeDurable??ce)();if(d)for(let{adapter:g,checks:y}of p.values()){let b=m?ko.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(ko.map(P=>[P,"unreadable"]))}let S=b.filter(P=>A[P]==="missing"),E=f.has(g.id);if(E&&g.pointsAt&&(E=!await g.pointsAt(d.toolOrigin).catch(()=>!0)),S.length===0&&!E)continue;let I=await MU(g.id,S,E,l.has(g.id),o,r(),s);if(!I)continue;let[C]=await(s.repair??mt)([g],d.target);if(!C)continue;h=!0;let x;C.status==="configured"&&g.integrationStatus&&(x=await g.integrationStatus().catch(()=>{})),await FU(g.id,I.checks,C,x,o,r(),s)}await UU(o,r(),t,s),i=await(s.findIntegrations??Vh)(a);let w=await(s.listPending??ur)().catch(()=>[]);return await HU(e,i,w,o,r(),t,s),h}catch{return!1}};var XU=14,JU=.35,qU=900*1e3,wS=360*60*1e3,zU=.2,QU=1800*1e3,bS=3600*1e3,eB=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),tB=300*1e3,nB=30*1e3,rB=900*1e3,oB=(e=0)=>Math.min(rB,nB*2**Math.max(0,e)),kS=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}},aB=720*60*1e3,CS=1440*60*1e3,sB=300*1e3,iB=.25,cB=.5,AS=3600*1e3,lB=720*60*60*1e3,dB=360*60*1e3,uB=1440*60*1e3,pB=4,_d=e=>GU("sha256").update(e).digest("hex").slice(0,32),OS=async(e,t={})=>{if(!e)return!1;let r=(await(t.readState??Kt)().catch(()=>({}))).ownKeys;return!r?.certSig||!r.fingerprints?.length||(await(t.loadProfile??T)().catch(()=>{}))?.enrolledCert?.sig!==r.certSig?!1:r.fingerprints.includes(_d(e))},sm=(e,t,n)=>({certSig:t,fingerprints:[n,...e?.certSig===t?e.fingerprints.filter(r=>r!==n):[]].slice(0,pB)}),fB=()=>xS(jU(),".anyray"),cm=()=>xS(fB(),"refresh-state.json"),lm=e=>process.env?.[e],_S=()=>lm("ANYRAY_REFRESH_DISABLE")==="true",dm=()=>{let e=lm("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:XU)*uB},Ii=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},PS=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),hB=10080*60*1e3,Pd=(e,t,n=Date.now())=>{let r=[],o=Ii(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)<=hB},xi=e=>{let t=dm(),n=e?Ii(e):void 0;if(!n)return t;let r=Math.max(qU,Math.round(n*JU));return Math.min(t,r)},mB=e=>{let t=lm("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(wS,Math.max(QU,Math.round(e*zU))):wS},Kt=async()=>{try{let e=await VU(cm(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Td=async e=>{try{let t=cm(),n=`${t}.${process.pid}.tmp`;await RS(n,JSON.stringify(e),{mode:384}),await fe(n,t),await YU(t,384).catch(()=>{})}catch{}},yB=3e4,gB=()=>`${cm()}.lock`,vS=async e=>{try{return await RS(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},dt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Kt,a=n.writeState??Td,s=gB(),i=!1;try{if(i=await vS(s),!i){if(await ZU(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<yB)return t;await gS(s).catch(()=>{}),i=await vS(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await gS(s).catch(()=>{})}},Ei=async(e,t={})=>{await dt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},xa=async(e={},t={})=>{let n=t.now??Date.now,r=e.expiresAt?Date.parse(e.expiresAt):NaN,o=e.keyTtlMs??(Number.isFinite(r)&&r-n()>0?r-n():void 0),a=await(t.loadProfile??T)().catch(()=>{}),s=a?.enrolledCert?.sig,i=a?.clientKey?_d(a.clientKey):void 0;await dt(({lastError:c,...l})=>({next:{...l,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??l.keyTtlMs,...s&&i?{ownKeys:sm(l.ownKeys,s,i)}:{}},result:void 0}),void 0,t).catch(()=>{})},Co=async(e={})=>{let t=e.now??Date.now;await dt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},wB=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(lB,Math.max(AS,Math.round(o*cB))):AS},im=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,um=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??re,a=n.loadProfile??T,s=n.loadDevKey??Ue,i=n.renew??Jv,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(Xv(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()>wB(e))return{outcome:"not-due",profile:e};if(!await dt(w=>r()-(w.lastCertRenewAt??0)<dB?{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 im(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}},SS=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*iB):CS,r=Math.min(CS,n);return Math.min(r,sB*2**Math.max(0,e-1))},bB=()=>{let{command:e,args:t}=pn(nr);return{exe:e,args:t}},Ir=async(e={})=>{if(_S())return;let t=e.now??Date.now,n=e.readState??Kt,r=e.writeState??Td,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=bB();KU(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await dt(s=>t()-(s.lastSpawnAt??0)<mB(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},kB=ki,CB=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 vr(r,o.toolOrigin),s=n?Lv(a):a;return s.length===0?!1:(await mt(s,o.target),!0)}catch{return!1}},AB=async(e,t,n,r,o,a)=>{try{let s=new Set(e.managedTools??[]),i=se.filter(p=>s.has(p.id));if(i.length===0)return!1;let c=await r().catch(()=>{}),l=ye({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:c,user:e.name,team:e.team}),d=e.fallbackPort,u=tt(e)&&Number.isInteger(d)&&d>0&&d<=65535&&await o(d)!==null,f=await a(u?vn(l,d):l,u?`http://${pt}:${d}`:l.origin,i);return f.matched>0&&f.complete}catch{return!1}},vB=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Kt,a=t.writeState??Td;return yS(e,we,{now:r,deadWatcherObserved:n,readHookLane:()=>Ld({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>dt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Ld=async(e={})=>{let n=await(e.readState??Kt)().catch(()=>({}));return Cn(n.hookLane)},TS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Ld(t);if(!em(r,e,n()))return;await dt(o=>{let a=Cn(o.hookLane);return em(a,e,n())?{next:{...o,hookLane:Qv(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},LS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Ld(t);if(!tm(r,n()))return;await dt(o=>{let a=Cn(o.hookLane);return tm(a,n())?{next:{...o,hookLane:eS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},SB=async(e={})=>{try{let t=e.now??Date.now;if((await Ld(e)).watchSince!==void 0)return;await dt(n=>{let r=Cn(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:tS(r,t())},result:void 0}},void 0,e)}catch{}},ES=async(e,t={})=>{try{let n=t.now??Date.now;await dt(r=>{let o=Cn(r.hookLane),a=nS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},DS=async(e={})=>{try{if((await(e.readState??Kt)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>dt(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??Ig)())return await r()?"stamped":"skipped";let o=await(e.load??T)(),s=await(e.findTools??go)(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??mt)(s,i.target),"repathed")}catch{return"skipped"}},NS=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Kt)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>dt(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??T)(),i=await(e.findTools??go)(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??mt)(i,c.target)).some(d=>d.status==="failed")?(await dt(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"}},EB=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await kd(e.gateway,e.clientKey),n=await Cd(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},IS=async(e,t,n,r)=>{let a=await(t.reconcilePolicy??EB)(e).catch(()=>!1),s=a?await n().catch(()=>e):e,c=await(t.repairDrift??(l=>CB(l,r,t.runAmbientSelfcheck===!0)))(s).catch(()=>!1);return a||c},Qe=async(e={})=>{if(_S())return"disabled";let t=e.now??Date.now,n=e.loadProfile??T,r=e.saveProfile??re,o=e.loadDevKey??Ue,a=e.readState??Kt,s=e.writeState??Td,i=e.remint??cn,c=e.heartbeat??vd,l=e.detectSeat??Nt,d=e.rewriteTools??kB,u=e.rewriteHookLaneTools??zh,f=e.probeHookLane??Ia,p=e.classifyBeacon??Cc,h=e.probe??be,m=e.installProxy??Dt,w=e.pickProxyPort??Ic,g=e.force===!0,y=!1,b=!1,A=!1,S=!1;e.hookLaneRepair===!0&&(g=!0,S=!0);let E=async C=>{if(!S){C==="repaired"&&await ES("none",{now:t,readState:a,writeState:s});return}let x=C;if(C==="repaired"){let P=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));x=P.verdict==="live"?"repaired":P.verdict==="dark"?"repair_failed":"unverified"}await ES(x,{now:t,readState:a,writeState:s})},I=async()=>{if(!e.runAmbientSelfcheck||b||!y)return!1;b=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(P=>vB(P,{now:t,readState:a,writeState:s},A)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(A=await ur().then(O=>O.some(D=>!fr(D.watcherPid))).catch(()=>!1),await SB({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??sb)();let C=await n();if(y=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let x=C.gateway,P=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(P)||P<=t())return"cert-expired";let U=await o();if(!U)return"not-enrolled";let Z=await um(C,U,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=Z.profile;let Y=Z.outcome==="renewed",H=C.enrolledCert;if(!H)return"not-enrolled";let q=Date.parse(C.clientKeyExpiresAt??""),me=Number.isFinite(q)?q-t():0,Te=await a(),ne=!C.clientKey||me<=xi(C),We=C.credentialProtocol!=="stable-heartbeat-v1"&&t()-(Te.lastSuccessAt??0)>=aB;if(!g&&rS(Cn(Te.hookLane),t())&&await p().catch(()=>"unreadable")!=="foreign"&&(g=!0,S=!0),C.credentialProtocol==="stable-heartbeat-v1"&&C.clientKey&&(g||ne)){let O=await dt(D=>{let W=t()-(D.lastAttemptAt??0);return W<bS?{result:"throttled"}:D.failureCount&&W<SS(D.failureCount,D.keyTtlMs)?{result:"backoff"}:{next:{...D,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(O!=="ok")return O;try{let D=await c(x,C.clientKey,H,U),W=await n().catch(()=>C);return W.clientKey!==C.clientKey||W.enrolledCert?.sig!==H.sig?"failed":(await r({...W,clientKeyExpiresAt:D.expiresAt}),await Ei(({lastError:pe,...z})=>({...z,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Ii(C)??z.keyTtlMs}),{now:t,readState:a,writeState:s}),S&&await E(await AB(C,x,C.clientKey,l,h,u)?"repaired":"repair_failed"),"heartbeat-refreshed")}catch(D){let W=D;if(D instanceof Sr&&D.status===404)try{let z=await i(x,H,U),Ve=await l().catch(()=>{}),Me=ye({origin:x,clientKey:z.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Ve,user:C.name,team:C.team}),Q=C.fallbackPort,Fe=Number.isInteger(Q)&&Q>0&&Q<=65535?Q:await w();if(!(await m({port:Fe,remoteOrigin:x})).ok||await h(Fe)===null)throw new Error("key-refresh proxy recovery failed");let V=await n().catch(()=>C);if(!await im(V,H.sig,U,o))throw new Error("enrollment changed during proxy recovery");if(await r({...V,clientKey:z.key,clientKeyExpiresAt:z.expiresAt??V.clientKeyExpiresAt,credentialProtocol:"rotating-proxy-v1",directMigration:"pending",keyRefreshEnabled:!0,fallbackPort:Fe}),await d(vn(Me,Fe),Me.origin)===!1)throw new Error("proxy recovery adapter rewrite incomplete");let Ee=z.expiresAt?Date.parse(z.expiresAt):NaN,wt=Ii(C)??(Number.isFinite(Ee)&&Ee-t()>0?Ee-t():void 0);return await Ei(({lastError:qn,...Ot})=>({...Ot,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:wt??Ot.keyTtlMs,ownKeys:sm(Ot.ownKeys,H.sig,_d(z.key))}),{now:t,readState:a,writeState:s}),await E("repaired"),"proxy-restored"}catch(z){W=z}let pe=kS(W);return await Ei(z=>({...z,lastAttemptAt:t(),failureCount:(z.failureCount??0)+1,lastError:{name:W instanceof Error?W.name:"Error",...pe!==void 0?{code:pe}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),W instanceof Sr?"cert-rejected":"failed"}}if(!g&&C.clientKey&&!ne&&!We){let O=await IS(C,e,n,h),D=await I();return O||D?"repaired":Y?"cert-renewed":"not-due"}let Le=await dt(O=>{let D=t()-(O.lastAttemptAt??0);if(g)return D<oB(O.failureCount)?{result:"throttled"}:{next:{...O,lastAttemptAt:t()},result:"ok"};let W=O.lastError?.code!==void 0&&eB.has(O.lastError.code)?tB:bS;return D<W?{result:"throttled"}:O.failureCount&&D<SS(O.failureCount,O.keyTtlMs)?{result:"backoff"}:{next:{...O,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(Le!=="ok")return Le;try{let O=await i(x,H,U),D=await l().catch(()=>{}),W=ye({origin:x,clientKey:O.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:D,user:C.name,team:C.team}),pe=W,z=W.origin;if(tt(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&&(pe=vn(W,C.fallbackPort),z=`http://${pt}:${C.fallbackPort}`)}let Ve=await d(pe,z);if(C.directMigration==="pending"&&pe.viaLocalProxy===!0){let Ee=await d(pe,W.origin);Ve=Ve!==!1&&Ee!==!1}if(Ve===!1)throw new Error("one or more configured tools rejected the refreshed key");let Me=await n().catch(()=>C),Q=null,Fe;Me.enrolledCert&&await im(Me,H.sig,U,o)&&(Fe=_d(O.key),Q={...Me,clientKey:O.key,clientKeyExpiresAt:O.expiresAt??Me.clientKeyExpiresAt},await r(Q));let De=O.expiresAt?Date.parse(O.expiresAt):NaN,V=Ii(C)??(Number.isFinite(De)&&De-t()>0?De-t():void 0);return await Ei(({lastError:Ee,...wt})=>({...wt,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:V??wt.keyTtlMs,...Fe?{ownKeys:sm(wt.ownKeys,H.sig,Fe)}:{}}),{now:t,readState:a,writeState:s}),Q&&await IS(Q,e,n,h),await E(Q?"repaired":"repair_failed"),await I(),"refreshed"}catch(O){let D=kS(O);return await Ei(W=>({...W,lastAttemptAt:t(),failureCount:(W.failureCount??0)+1,lastError:{name:O instanceof Error?O.name:"Error",...D!==void 0?{code:D}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),O instanceof It?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await I()}catch{}}};import{readFile as TB}from"node:fs/promises";import{isAbsolute as LB,posix as BS,win32 as hm}from"node:path";var pm=1e4,IB=900*1e3,MS="tnt_",xB=/^\/sso\/([^/]+)\/?$/,RB=/^\/i\/([^/]+)\/?$/,OB=e=>{let t=e.match(xB);if(t)return t[1];let n=e.match(RB);return n?.[1].startsWith(MS)?n[1]:void 0},xt=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=OB(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(MS))return{cpOrigin:Vn(),tenantId:t}},Ao=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Gt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},fm=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)}},_B=e=>new Promise(t=>setTimeout(t,e)),Dd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??Ad)(),a;try{a=await fm(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},pm,n)}catch(h){throw new Ao("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${yt(h)}`)}if(a.status!==200){let h=a.status===404,m=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new Ao(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 Ao("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??IB,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}`),PB(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},PB=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Nd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??_B,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 fm(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},pm,o)}catch(c){throw new Gt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${yt(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 Gt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Gt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Gt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var $S="sdc_",FS=e=>{let t=e.trim();if(!t)return;if(t.startsWith($S))return{cpOrigin:Vn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!qh(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith($S)))return{cpOrigin:n.origin,claim:r}},US=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??Ad)(),o;try{o=await fm(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},pm,t)}catch(s){throw new Gt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${yt(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 Gt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Gt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Gt("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};var Ri=(e=process.platform,t=process.env)=>e==="darwin"?BS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?hm.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):BS.join("/etc","anyray","bootstrap.json"),DB=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),HS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(LB(e)||hm.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),NB=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}},jt=async(e=Ri())=>{try{let t=await TB(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!DB(n)||n.v!==1||typeof n.sso!="string")return;let r=xt(n.sso);if(!r)return;let o=NB(n.gateway)?n.gateway:void 0,a=HS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},WS=(e,t,n)=>{let r=xt(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!HS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&hm.isAbsolute(n)&&/^[A-Za-z]:\\/.test(n)&&!/^[A-Za-z]:\\Program Files( \(x86\))?\\/i.test(n))throw new Error("--bin on Windows must live under Program Files (admin-only writable)");return`${JSON.stringify({v:1,sso:`${r.cpOrigin}/sso/${r.tenantId}`,...t?{gateway:t}:{},...n?{bin:n}:{}},null,2)}
|
|
296
|
-
`};import{execFile as
|
|
297
|
-
`,{mode:384}),await
|
|
295
|
+
`;import{createHash as WF,createPrivateKey as HF,generateKeyPairSync as KF,randomBytes as Xh,sign as GF}from"node:crypto";var zh=1e4,bo=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(bo).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${bo(e[n])}`).join(",")}}`,bi="stable-key-heartbeat-v1",Zv="key-heartbeat",jF=["reapply_config","remint","revert"];var Jv=e=>WF("sha256").update(e).digest("hex"),qe=e=>typeof e=="string"&&e.trim()?e.trim():void 0,VF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],qh=async e=>{try{let t=await e.json(),n=qe(t?.message);if(n)return n}catch{}return`gateway responded ${e.status}`},It=class extends Error{status;constructor(t,n){super(`the gateway rejected this enrollment (HTTP ${t}): ${n}`),this.name="GatewayVerifyError",this.status=t}},Ir=class extends Error{status;constructor(t,n){super(`the gateway rejected this credential heartbeat (HTTP ${t}): ${n}`),this.name="GatewayHeartbeatError",this.status=t}},Qh=(e,t,n)=>{try{let r=HF(t),o=new TextEncoder().encode(bo(e));return GF(null,o,r).toString("base64url")}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},Ad=()=>{let{publicKey:e,privateKey:t}=KF("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},ln=async(e,t,n,r={})=>{let o=r.timeoutMs??zh,a=`${e}/connect/verify`,s=qe(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:Xh(16).toString("hex")},c=Qh(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.`:yt(y);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:y})}finally{clearTimeout(d)}if(!u.ok)throw new It(u.status,await qh(u));let f;try{f=await u.text()}catch{f=""}let p;try{p=JSON.parse(f)}catch{let y=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(y)||/^\s*<(?:!doctype|html)/i.test(f);throw new Error(b?`developer verification failed: ${a} returned an HTML page, not the gateway \u2014 /connect/* is being routed to the console/proxy. Ask your admin to route /connect/* to the gateway service (:8787), the same as /v1/*.`:"developer verification failed: the gateway returned a malformed response")}let h=qe(p?.key);if(!h)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(h))throw new Error("developer verification failed: the gateway returned a malformed key");let m=qe(p.user);if(!m)throw new Error("developer verification failed: the gateway response is missing the user");let w=YF(p.directive),g=VF(p.capabilities);return{key:h,user:m,team:qe(p.team),expiresAt:qe(p.expiresAt),...g.length>0?{capabilities:g}:{},...w?{directive:w}:{}}},vd=async(e,t,n,r,o={})=>{let a=o.timeoutMs??zh,s=`${e}/connect/key/heartbeat`,i=qe(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:Xh(16).toString("hex"),purpose:Zv},l=Qh(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.`:yt(m);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:m})}finally{clearTimeout(u)}if(!f.ok)throw new Ir(f.status,await qh(f));let p;try{p=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let h=qe(p.expiresAt);if(!h||!Number.isFinite(Date.parse(h))||p.credentialMode!==bi||p.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:h,credentialMode:bi}},Xv=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??zh,i=`${e.replace(/\/$/,"")}/connect/machine`,c=qe(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Xh(16).toString("hex"),purpose:Zv},d=Qh(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)}},YF=e=>{if(e===null||typeof e!="object")return null;let t=e,n=qe(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!jF.includes(r)?null:{id:n,kind:r}},ZF=1e4,JF=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!qe(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!qe(r.deploymentId)&&!!qe(r.user)&&!!qe(r.devPublicKey)&&!!qe(r.issuedAt)&&!!qe(r.expiresAt)},XF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??ZF,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.`:yt(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 qh(l)}`);let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!JF(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},zv=(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())},qv=async e=>{let t={timeoutMs:e.timeoutMs},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=Ad();return{cert:await XF(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 ln(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 nU,randomBytes as rU,sign as oU}from"node:crypto";var zF="https://app.anyray.ai",qF=new Set(["localhost","::1","[::1]"]),QF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,eU=e=>qF.has(e)||QF.test(e),em=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&eU(t.hostname)},tU=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Yn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!em(e)?zF:tU(e)};var aU=1e4,sU="machine:",Qv=e=>e.startsWith(sU),iU="cert-renew",cU=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)},eS=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Yn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:rU(16).toString("hex"),purpose:iU},c;try{let h=nU(t),m=new TextEncoder().encode(bo(i));c=oU(null,m,h).toString("base64url")}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),aU),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 cU(p)?{ok:!0,cert:p}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var tm=async(e,t=e.origin,n=se)=>{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}},ki=async(e,t=e.origin,n=se)=>(await tm(e,t,n)).complete;var lU=["claude","codex","cursor","opencode"],dU=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],uU=new Set(["missing_key","key_expired"]);var pU=600*1e3,fU=600*1e3,tS=1440*60*1e3,hU=1440*60*1e3,mU=10080*60*1e3,yU=3600*1e3,gU=720*60*1e3,wU=e=>Math.min(gU,yU*2**Math.max(0,e-1)),Ci=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Sa=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,nS=e=>typeof e=="string"&&dU.includes(e),vn=e=>{if(!Ci(e))return{};let t={};if(Sa(e.watchSince)&&(t.watchSince=e.watchSince),Ci(e.invoked)){let n={};for(let r of lU){let o=e.invoked[r];Sa(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return Ci(e.authFailure)&&Sa(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...nS(e.authFailure.code)?{code:e.authFailure.code}:{}}),Ci(e.repair)&&Sa(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,...Sa(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Sd=e=>{try{let n=JSON.parse(e);if(Ci(n)&&nS(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"},nm=e=>e!==void 0&&uU.has(e),rm=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=pU},rS=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),om=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=fU},oS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),aS=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,sS=(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},iS=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>tS||!nm(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<wU(r.failures??1))},Ed=e=>{let t=Object.values(e?.invoked??{}).filter(Sa);return t.length>0?Math.max(...t):null},am=(e,t)=>{if(Ed(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=mU},cS=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=hU)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=tS)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var sm="x-anyray-retrieve-probe",Id=8e3,bU=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",lS=(e,t)=>{let n=zt(e);return t?.probe&&(n[sm]="1"),n},Ea=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(),Id);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:lS(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=bU(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)}},xd=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(),Id);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:lS(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 kU=5e3,CU=2048,AU=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}"`))},Ia=async(e={})=>{let t=e.readTarget??nt,n=e.fetch??fetch,r=e.timeoutMs??kU,o=null;try{o=await t()}catch{o=null}if(!o)return{verdict:"dark",reason:"target_null"};let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let i=zt(o);i["content-type"]="application/json",i[sm]="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,CU);if(!AU(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=Sd(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)}},im=(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 vU,randomBytes as SU,sign as EU}from"node:crypto";var IU=500,dS=2e3,xU=2e3,RU=250,uS=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),IU);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)}},OU=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},_U=e=>new Promise(t=>setTimeout(t,e)),TU=async(e,t,n=_U)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),dS),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=OU(i)??RU,s>xU))return!1}finally{clearTimeout(a)}await n(s)}},PU=async e=>{try{let n=(await P()).enrolledCert,r=await Ue(),o=n?.payload?.deploymentId;if(!n||!r||!o)return!1;let a={deploymentId:o,issuedAt:new Date().toISOString(),nonce:SU(16).toString("hex"),events:e},s;try{let i=vU(r),c=new TextEncoder().encode(bo(a));s=EU(null,c,i).toString("base64url")}catch{return!1}return await TU(`${Yn()}/v1/connect-events`,JSON.stringify({cert:n,challenge:a,sig:s}))}catch{return!1}},LU=async(e,t)=>{try{let r=(await P()).enrolledCert,o=await Ue();if(!r||!o)return;await ln(e,r,o,{timeoutMs:dS,health:{events:t},telemetryOnly:!0})}catch{}},pS=async(e,t)=>{if(e.length!==0)try{let n=await nt(),r=n&&await uS(n.origin,zt(n),e,t);if(n&&await LU(n.origin,e),r)return;await PU(e)}catch{}},cm=async(e,t,n={readTarget:()=>nt("profile"),post:uS})=>{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 Co=["hook_registration","mcp_registration","hook_binary","beacon_target"];var hS=128,mS=300*1e3,DU=["repaired","repair_failed","flapping","pending"],NU=["settings_not_writable","apply_unconfirmed","apply_threw"],yS=["rebroke_same_day","repeat_days"],gS=new Set(se.map(e=>e.id)),ko=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),wS=e=>vi(e,Co),Rd=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},xr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,Ai=e=>{if(!(!Array.isArray(e)||!e.every(wS)))return Zn(e)},$U=e=>{if(!ko(e))return;let t=Ai(e.checks);if(!(!xr(e.since)||!vi(e.reason,yS)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},MU=e=>{if(!ko(e))return;let t={};Rd(e.day)&&(t.day=e.day),xr(e.attempts)&&(t.attempts=e.attempts);let n=Ai(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=Ai(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=Ai(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=Ai(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Rd(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),xr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),ko(e.lastRepaired)){let i={};for(let c of Co){let l=e.lastRepaired[c];xr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=$U(e.flapping);return s&&(t.flapping=s),t},FU=e=>{if(!ko(e)||!Rd(e.day)||!xr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!gS.has(e.tool)||!wS(e.checkId)||!vi(e.status,DU)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!vi(e.errorClass,NU))return;t=e.errorClass}else if(e.status==="flapping"){if(!vi(e.errorClass,yS))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,...xr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},fS=e=>{if(!ko(e))return{};let t={};if(ko(e.adapters)){let n={};for(let r of gS){let o=MU(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(FU).filter(n=>n!==void 0).slice(-hS)),xr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),ko(e.report)&&Rd(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...xr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},UU=e=>new Date(e).toISOString().slice(0,10),BU=(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)],Od=(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}:{}}},Si=(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(-hS),nextSequence:r}},WU=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),HU=async e=>await Oe(async()=>e,void 0,be)??null,KU=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=Od(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)},bS=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:BU(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}},GU=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=Od(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=bS(u,h,n,r);c[l]={...g.adapter,awaiting:w.length>0?w:void 0},i=Si(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)},jU=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Od(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:Si({...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:Si({...i,adapters:c},o,p.map(g=>({tool:e,checkId:g,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:p}}},void 0),VU=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Od(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:Zn([...l.awaiting??[],...t])},{next:Si({...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=bS(l,d,o,a);c[e]=f.adapter;let p=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:Si({...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)},YU=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>=mS));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??cm)(o.map(WU),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)},ZU=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 Co){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??Lc)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??hr)(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},JU=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<mS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await ZU(e,t,n,c,o,s);await(s.report??cm)(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)},kS=async(e,t,n)=>{let r=n.now??Date.now,o=UU(r()),a=e.managedTools??[],s={...n,readState:async()=>fS(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(fS(l)),c)};try{let i=await(s.findIntegrations??Jh)(a);await KU(i,o,s);let c=await(s.listPending??pr)().catch(()=>[]),l=new Set(c.map(g=>g.adapter));await GU(i,l,o,r(),s);let d=await(s.resolveTarget??HU)(e),u=d?await(s.findDrifted??Er)(a,d.toolOrigin):[],f=new Set(u.map(g=>g.id)),p=new Map(i.map(g=>[g.adapter.id,g]));for(let g of u)p.has(g.id)||p.set(g.id,{adapter:g,checks:{}});let h=!1,m=(s.runtimeDurable??ce)();if(d)for(let{adapter:g,checks:y}of p.values()){let b=m?Co.filter(T=>y[T]==="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(Co.map(T=>[T,"unreadable"]))}let v=b.filter(T=>A[T]==="missing"),E=f.has(g.id);if(E&&g.pointsAt&&(E=!await g.pointsAt(d.toolOrigin).catch(()=>!0)),v.length===0&&!E)continue;let I=await jU(g.id,v,E,l.has(g.id),o,r(),s);if(!I)continue;let[C]=await(s.repair??mt)([g],d.target);if(!C)continue;h=!0;let x;C.status==="configured"&&g.integrationStatus&&(x=await g.integrationStatus().catch(()=>{})),await VU(g.id,I.checks,C,x,o,r(),s)}await YU(o,r(),t,s),i=await(s.findIntegrations??Jh)(a);let w=await(s.listPending??pr)().catch(()=>[]);return await JU(e,i,w,o,r(),t,s),h}catch{return!1}};var rB=14,oB=.35,aB=900*1e3,AS=360*60*1e3,sB=.2,iB=1800*1e3,vS=3600*1e3,cB=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),lB=300*1e3,dB=30*1e3,uB=900*1e3,pB=(e=0)=>Math.min(uB,dB*2**Math.max(0,e)),SS=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}},fB=720*60*1e3,ES=1440*60*1e3,hB=300*1e3,mB=.25,yB=.5,IS=3600*1e3,gB=720*60*60*1e3,wB=360*60*1e3,bB=1440*60*1e3,kB=4,_d=e=>qU("sha256").update(e).digest("hex").slice(0,32),LS=async(e,t={})=>{if(!e)return!1;let r=(await(t.readState??Kt)().catch(()=>({}))).ownKeys;return!r?.certSig||!r.fingerprints?.length||(await(t.loadProfile??P)().catch(()=>{}))?.enrolledCert?.sig!==r.certSig?!1:r.fingerprints.includes(_d(e))},lm=(e,t,n)=>({certSig:t,fingerprints:[n,...e?.certSig===t?e.fingerprints.filter(r=>r!==n):[]].slice(0,kB)}),CB=()=>TS(QU(),".anyray"),um=()=>TS(CB(),"refresh-state.json"),pm=e=>process.env?.[e],DS=()=>pm("ANYRAY_REFRESH_DISABLE")==="true",fm=()=>{let e=pm("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:rB)*bB},Ii=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},NS=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),AB=10080*60*1e3,Td=(e,t,n=Date.now())=>{let r=[],o=Ii(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)<=AB},xi=e=>{let t=fm(),n=e?Ii(e):void 0;if(!n)return t;let r=Math.max(aB,Math.round(n*oB));return Math.min(t,r)},vB=e=>{let t=pm("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(AS,Math.max(iB,Math.round(e*sB))):AS},Kt=async()=>{try{let e=await eB(um(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Pd=async e=>{try{let t=um(),n=`${t}.${process.pid}.tmp`;await PS(n,JSON.stringify(e),{mode:384}),await fe(n,t),await tB(t,384).catch(()=>{})}catch{}},SB=3e4,EB=()=>`${um()}.lock`,xS=async e=>{try{return await PS(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},dt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??Kt,a=n.writeState??Pd,s=EB(),i=!1;try{if(i=await xS(s),!i){if(await nB(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<SB)return t;await CS(s).catch(()=>{}),i=await xS(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await CS(s).catch(()=>{})}},Ei=async(e,t={})=>{await dt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},xa=async(e={},t={})=>{let n=t.now??Date.now,r=e.expiresAt?Date.parse(e.expiresAt):NaN,o=e.keyTtlMs??(Number.isFinite(r)&&r-n()>0?r-n():void 0),a=await(t.loadProfile??P)().catch(()=>{}),s=a?.enrolledCert?.sig,i=a?.clientKey?_d(a.clientKey):void 0;await dt(({lastError:c,...l})=>({next:{...l,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??l.keyTtlMs,...s&&i?{ownKeys:lm(l.ownKeys,s,i)}:{}},result:void 0}),void 0,t).catch(()=>{})},Ao=async(e={})=>{let t=e.now??Date.now;await dt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},IB=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(gB,Math.max(IS,Math.round(o*yB))):IS},dm=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,hm=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??re,a=n.loadProfile??P,s=n.loadDevKey??Ue,i=n.renew??eS,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(Qv(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()>IB(e))return{outcome:"not-due",profile:e};if(!await dt(w=>r()-(w.lastCertRenewAt??0)<wB?{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 dm(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}},RS=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*mB):ES,r=Math.min(ES,n);return Math.min(r,hB*2**Math.max(0,e-1))},xB=()=>{let{command:e,args:t}=fn(rr);return{exe:e,args:t}},Rr=async(e={})=>{if(DS())return;let t=e.now??Date.now,n=e.readState??Kt,r=e.writeState??Pd,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=xB();zU(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await dt(s=>t()-(s.lastSpawnAt??0)<vB(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},RB=ki,OB=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 Er(r,o.toolOrigin),s=n?Mv(a):a;return s.length===0?!1:(await mt(s,o.target),!0)}catch{return!1}},_B=async(e,t,n,r,o,a)=>{try{let s=new Set(e.managedTools??[]),i=se.filter(p=>s.has(p.id));if(i.length===0)return!1;let c=await r().catch(()=>{}),l=ye({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:c,user:e.name,team:e.team}),d=e.fallbackPort,u=tt(e)&&Number.isInteger(d)&&d>0&&d<=65535&&await o(d)!==null,f=await a(u?En(l,d):l,u?`http://${pt}:${d}`:l.origin,i);return f.matched>0&&f.complete}catch{return!1}},TB=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??Kt,a=t.writeState??Pd;return kS(e,we,{now:r,deadWatcherObserved:n,readHookLane:()=>Ld({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>dt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},Ld=async(e={})=>{let n=await(e.readState??Kt)().catch(()=>({}));return vn(n.hookLane)},$S=async(e,t={})=>{try{let n=t.now??Date.now,r=await Ld(t);if(!rm(r,e,n()))return;await dt(o=>{let a=vn(o.hookLane);return rm(a,e,n())?{next:{...o,hookLane:rS(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},MS=async(e,t={})=>{try{let n=t.now??Date.now,r=await Ld(t);if(!om(r,n()))return;await dt(o=>{let a=vn(o.hookLane);return om(a,n())?{next:{...o,hookLane:oS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},PB=async(e={})=>{try{let t=e.now??Date.now;if((await Ld(e)).watchSince!==void 0)return;await dt(n=>{let r=vn(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:aS(r,t())},result:void 0}},void 0,e)}catch{}},OS=async(e,t={})=>{try{let n=t.now??Date.now;await dt(r=>{let o=vn(r.hookLane),a=sS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},FS=async(e={})=>{try{if((await(e.readState??Kt)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>dt(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??_g)())return await r()?"stamped":"skipped";let o=await(e.load??P)(),s=await(e.findTools??wo)(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??mt)(s,i.target),"repathed")}catch{return"skipped"}},US=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??Kt)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>dt(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??P)(),i=await(e.findTools??wo)(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??mt)(i,c.target)).some(d=>d.status==="failed")?(await dt(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"}},LB=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await kd(e.gateway,e.clientKey),n=await Cd(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},_S=async(e,t,n,r)=>{let a=await(t.reconcilePolicy??LB)(e).catch(()=>!1),s=a?await n().catch(()=>e):e,c=await(t.repairDrift??(l=>OB(l,r,t.runAmbientSelfcheck===!0)))(s).catch(()=>!1);return a||c},Qe=async(e={})=>{if(DS())return"disabled";let t=e.now??Date.now,n=e.loadProfile??P,r=e.saveProfile??re,o=e.loadDevKey??Ue,a=e.readState??Kt,s=e.writeState??Pd,i=e.remint??ln,c=e.heartbeat??vd,l=e.detectSeat??Nt,d=e.rewriteTools??RB,u=e.rewriteHookLaneTools??tm,f=e.probeHookLane??Ia,p=e.classifyBeacon??Cc,h=e.probe??be,m=e.installProxy??Dt,w=e.pickProxyPort??Ic,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 OS("none",{now:t,readState:a,writeState:s});return}let x=C;if(C==="repaired"){let T=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));x=T.verdict==="live"?"repaired":T.verdict==="dark"?"repair_failed":"unverified"}await OS(x,{now:t,readState:a,writeState:s})},I=async()=>{if(!e.runAmbientSelfcheck||b||!y)return!1;b=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(T=>TB(T,{now:t,readState:a,writeState:s},A)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(A=await pr().then(O=>O.some(L=>!hr(L.watcherPid))).catch(()=>!1),await PB({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??db)();let C=await n();if(y=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let x=C.gateway,T=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(T)||T<=t())return"cert-expired";let U=await o();if(!U)return"not-enrolled";let Z=await hm(C,U,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=Z.profile;let Y=Z.outcome==="renewed",W=C.enrolledCert;if(!W)return"not-enrolled";let z=Date.parse(C.clientKeyExpiresAt??""),me=Number.isFinite(z)?z-t():0,Pe=await a(),ne=!C.clientKey||me<=xi(C),He=C.credentialProtocol!=="stable-heartbeat-v1"&&t()-(Pe.lastSuccessAt??0)>=fB;if(!g&&iS(vn(Pe.hookLane),t())&&await p().catch(()=>"unreadable")!=="foreign"&&(g=!0,v=!0),C.credentialProtocol==="stable-heartbeat-v1"&&C.clientKey&&(g||ne)){let O=await dt(L=>{let H=t()-(L.lastAttemptAt??0);return H<vS?{result:"throttled"}:L.failureCount&&H<RS(L.failureCount,L.keyTtlMs)?{result:"backoff"}:{next:{...L,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(O!=="ok")return O;try{let L=await c(x,C.clientKey,W,U),H=await n().catch(()=>C);return H.clientKey!==C.clientKey||H.enrolledCert?.sig!==W.sig?"failed":(await r({...H,clientKeyExpiresAt:L.expiresAt}),await Ei(({lastError:pe,...q})=>({...q,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Ii(C)??q.keyTtlMs}),{now:t,readState:a,writeState:s}),v&&await E(await _B(C,x,C.clientKey,l,h,u)?"repaired":"repair_failed"),"heartbeat-refreshed")}catch(L){let H=L;if(L instanceof Ir&&L.status===404)try{let q=await i(x,W,U),Ve=await l().catch(()=>{}),Me=ye({origin:x,clientKey:q.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Ve,user:C.name,team:C.team}),Q=C.fallbackPort,Fe=Number.isInteger(Q)&&Q>0&&Q<=65535?Q:await w();if(!(await m({port:Fe,remoteOrigin:x})).ok||await h(Fe)===null)throw new Error("key-refresh proxy recovery failed");let V=await n().catch(()=>C);if(!await dm(V,W.sig,U,o))throw new Error("enrollment changed during proxy recovery");if(await r({...V,clientKey:q.key,clientKeyExpiresAt:q.expiresAt??V.clientKeyExpiresAt,credentialProtocol:"rotating-proxy-v1",directMigration:"pending",keyRefreshEnabled:!0,fallbackPort:Fe}),await d(En(Me,Fe),Me.origin)===!1)throw new Error("proxy recovery adapter rewrite incomplete");let Ee=q.expiresAt?Date.parse(q.expiresAt):NaN,wt=Ii(C)??(Number.isFinite(Ee)&&Ee-t()>0?Ee-t():void 0);return await Ei(({lastError:qn,...Ot})=>({...Ot,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:wt??Ot.keyTtlMs,ownKeys:lm(Ot.ownKeys,W.sig,_d(q.key))}),{now:t,readState:a,writeState:s}),await E("repaired"),"proxy-restored"}catch(q){H=q}let pe=SS(H);return await Ei(q=>({...q,lastAttemptAt:t(),failureCount:(q.failureCount??0)+1,lastError:{name:H instanceof Error?H.name:"Error",...pe!==void 0?{code:pe}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),H instanceof Ir?"cert-rejected":"failed"}}if(!g&&C.clientKey&&!ne&&!He){let O=await _S(C,e,n,h),L=await I();return O||L?"repaired":Y?"cert-renewed":"not-due"}let Le=await dt(O=>{let L=t()-(O.lastAttemptAt??0);if(g)return L<pB(O.failureCount)?{result:"throttled"}:{next:{...O,lastAttemptAt:t()},result:"ok"};let H=O.lastError?.code!==void 0&&cB.has(O.lastError.code)?lB:vS;return L<H?{result:"throttled"}:O.failureCount&&L<RS(O.failureCount,O.keyTtlMs)?{result:"backoff"}:{next:{...O,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(Le!=="ok")return Le;try{let O=await i(x,W,U),L=await l().catch(()=>{}),H=ye({origin:x,clientKey:O.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:L,user:C.name,team:C.team}),pe=H,q=H.origin;if(tt(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&&(pe=En(H,C.fallbackPort),q=`http://${pt}:${C.fallbackPort}`)}let Ve=await d(pe,q);if(C.directMigration==="pending"&&pe.viaLocalProxy===!0){let Ee=await d(pe,H.origin);Ve=Ve!==!1&&Ee!==!1}if(Ve===!1)throw new Error("one or more configured tools rejected the refreshed key");let Me=await n().catch(()=>C),Q=null,Fe;Me.enrolledCert&&await dm(Me,W.sig,U,o)&&(Fe=_d(O.key),Q={...Me,clientKey:O.key,clientKeyExpiresAt:O.expiresAt??Me.clientKeyExpiresAt},await r(Q));let De=O.expiresAt?Date.parse(O.expiresAt):NaN,V=Ii(C)??(Number.isFinite(De)&&De-t()>0?De-t():void 0);return await Ei(({lastError:Ee,...wt})=>({...wt,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:V??wt.keyTtlMs,...Fe?{ownKeys:lm(wt.ownKeys,W.sig,Fe)}:{}}),{now:t,readState:a,writeState:s}),Q&&await _S(Q,e,n,h),await E(Q?"repaired":"repair_failed"),await I(),"refreshed"}catch(O){let L=SS(O);return await Ei(H=>({...H,lastAttemptAt:t(),failureCount:(H.failureCount??0)+1,lastError:{name:O instanceof Error?O.name:"Error",...L!==void 0?{code:L}:{}}}),{now:t,readState:a,writeState:s}),await E("repair_failed"),O instanceof It?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await I()}catch{}}};import{readFile as BB}from"node:fs/promises";import{isAbsolute as WB,posix as GS,win32 as gm}from"node:path";var mm=1e4,DB=900*1e3,WS="tnt_",NB=/^\/sso\/([^/]+)\/?$/,$B=/^\/i\/([^/]+)\/?$/,MB=e=>{let t=e.match(NB);if(t)return t[1];let n=e.match($B);return n?.[1].startsWith(WS)?n[1]:void 0},xt=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=MB(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(WS))return{cpOrigin:Yn(),tenantId:t}},vo=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Gt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},ym=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)}},FB=e=>new Promise(t=>setTimeout(t,e)),Dd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??Ad)(),a;try{a=await ym(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},mm,n)}catch(h){throw new vo("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${yt(h)}`)}if(a.status!==200){let h=a.status===404,m=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new vo(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 vo("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??DB,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}`),UB(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},UB=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Nd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??FB,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 ym(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},mm,o)}catch(c){throw new Gt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${yt(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 Gt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Gt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Gt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var BS="sdc_",HS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(BS))return{cpOrigin:Yn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!em(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(BS)))return{cpOrigin:n.origin,claim:r}},KS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??Ad)(),o;try{o=await ym(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},mm,t)}catch(s){throw new Gt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${yt(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 Gt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Gt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Gt("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};var Ri=(e=process.platform,t=process.env)=>e==="darwin"?GS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?gm.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):GS.join("/etc","anyray","bootstrap.json"),HB=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),jS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(WB(e)||gm.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),KB=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}},jt=async(e=Ri())=>{try{let t=await BB(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!HB(n)||n.v!==1||typeof n.sso!="string")return;let r=xt(n.sso);if(!r)return;let o=KB(n.gateway)?n.gateway:void 0,a=jS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},VS=(e,t,n)=>{let r=xt(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!jS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&gm.isAbsolute(n)&&/^[A-Za-z]:\\/.test(n)&&!/^[A-Za-z]:\\Program Files( \(x86\))?\\/i.test(n))throw new Error("--bin on Windows must live under Program Files (admin-only writable)");return`${JSON.stringify({v:1,sso:`${r.cpOrigin}/sso/${r.tenantId}`,...t?{gateway:t}:{},...n?{bin:n}:{}},null,2)}
|
|
296
|
+
`};import{execFile as hW}from"node:child_process";import{chmod as GB,readFile as jB,rm as YS,writeFile as VB}from"node:fs/promises";import{join as YB}from"node:path";var wm=()=>YB(ee(),"sso-gate.json"),ZB=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))},Or=async()=>{try{let e=JSON.parse(await jB(wm(),"utf-8"));return ZB(e)?e:null}catch{return null}},JB=0,$d=async e=>{await bt();let t=wm(),n=`${t}.${process.pid}.${JB++}.tmp`;try{await VB(n,`${JSON.stringify(e)}
|
|
297
|
+
`,{mode:384}),await GB(n,384),await fe(n,t)}catch(r){throw await YS(n,{force:!0}).catch(()=>{}),r}},ZS=async()=>{await YS(wm(),{force:!0}).catch(()=>{})},JS=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 qB}from"node:child_process";import{homedir as QB}from"node:os";import{join as eW}from"node:path";import{spawn as XB}from"node:child_process";import{platform as zB}from"node:os";var Ra=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=zB(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=XB(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var tW=3e4,nW=5*6e4,rW=30*6e4,oW=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},aW=()=>eW(QB(),".claude","settings.json"),sW=async e=>{try{let n=(await M(aW())).env;if(!n)return!1;let r=pn(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}},iW=async e=>{await sr.apply(e,{dryRun:!1})},cW=()=>{let{command:e,args:t}=fn("__anyray-sso-poll");return{exe:e,args:t}},lW=()=>{let{exe:e,args:t}=cW(),n=qB(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))}}},dW=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},XS=(e,t,n,r)=>ye({origin:e,clientKey:r,subscription:!0,user:t.name??t.enrolledCert?.payload.user,team:n??t.team??t.enrolledCert?.payload.team}),Oa=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},zS=e=>`Anyray: one-time sign-in required to use AI tools on this device.
|
|
298
298
|
1. Open ${e.verificationUriComplete}
|
|
299
299
|
2. Confirm code ${e.userCode}
|
|
300
300
|
Your prompt was not sent \u2014 complete sign-in, then resubmit it.
|
|
301
|
-
`,
|
|
301
|
+
`,bm=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
|
|
302
302
|
`:e==="gateway-unreachable"?`Anyray: can't reach the gateway \u2014 check your network/VPN, then resubmit your prompt.
|
|
303
303
|
`:`Anyray: can't reach ${t} \u2014 check your network/VPN, then resubmit your prompt.
|
|
304
|
-
`,
|
|
305
|
-
`))}let
|
|
306
|
-
`,{mode:384}),await
|
|
307
|
-
${t.stderr??""}`}},
|
|
308
|
-
${j(e)}`),F=e=>console.log(
|
|
304
|
+
`,uW=e=>Math.min(nW,tW*2**Math.max(0,e-1)),pW=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?rW:uW(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Jn=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??P,o=t.saveProfile??re,a=t.loadDevKey??Ue,s=t.readGateState??Or,i=t.writeGateState??$d,c=t.isProcessAlive??JS,l=t.startGrant??Dd,d=t.verify??ln,u=t.routingIntact??sW,f=t.applyClaudeCode??iW,p=t.maybeSpawnRefresh??Rr,h=t.recordMint??xa,m=t.reserveMint??Ao,w=t.spawnPoller??lW,g=t.openBrowser??Ra;try{let y=xt(e.sso);if(!y)return{exitCode:0};let b=await r(),A=await s(),v=b.enrolledCert?await a():void 0,E=dW(b),I=!!(b.enrolledCert&&v)&&Number.isFinite(E)&&E>n(),C=e.gateway??b.gateway;if(I&&b.enrolledCert&&v&&C){let Y=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(Y)&&Y>n()&&b.clientKey){let me=XS(C,b,e.team,b.clientKey);return await u(me)?(Y-n()<=fm()&&await p(),{exitCode:0}):(await f(me),Oa(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
|
|
305
|
+
`))}let z;await m();try{z=await d(C,b.enrolledCert,v,{timeoutMs:1e4})}catch(me){if(!(me instanceof It))return Oa(e,bm("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(XS(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 Oa(e,zS(A))}if(A){let Y=pW(A,n());if(Y)return Oa(e,bm(Y,y.cpOrigin))}let x;try{x=await l({cpOrigin:y.cpOrigin,tenantId:y.tenantId,gatewayUrl:e.gateway,now:n})}catch(Y){let W=Y instanceof vo?Y.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:A?.lastFailure===W?(A.failureCount??0)+1:1,lastFailure:W}),Oa(e,bm(W,y.cpOrigin))}let T={v:1,status:"pending",userCode:x.userCode,verificationUriComplete:x.verificationUriComplete,grantExpiresAt:x.grantExpiresAt,startedAt:x.startedAt,lastAttemptAt:n(),failureCount:0};await i(T);let U=w(),Z={...T,pollerPid:U.pid};if(await i(Z),U.handoff({deviceCode:x.deviceCode,privateKeyPem:x.privateKeyPem,publicKeyPem:x.publicKeyPem,cpOrigin:x.cpOrigin,tenantId:x.tenantId,intervalMs:x.intervalMs,grantExpiresAt:x.grantExpiresAt,startedAt:x.startedAt,gatewayUrl:x.gatewayUrl,gatewayOverride:e.gateway,team:e.team}),e.sessionStart)try{g(x.verificationUriComplete)}catch{}return Oa(e,zS(Z))}catch{return{exitCode:0}}},fW=async()=>{try{for await(let e of process.stdin);}catch{}},qS=async e=>{await fW();try{let t=await Jn(oW(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var mW=6e4,yW=10*6e4,Xn=(e,t)=>{let n=e[t];return typeof n=="string"?n:Array.isArray(n)?n[0]:void 0},gW=e=>{if(Xn(e,"x-anyray-api-key")?.trim())return!0;let t=Xn(e,"authorization")?.trim()??"";return/^bearer\s+\S+/i.test(t)?!0:(Xn(e,"x-api-key")?.trim()??"").startsWith("ark_")},eE=e=>{if(Xn(e,"x-anyray-api-key")?.trim())return!0;let t=Xn(e,"authorization")?.trim()??"";return/^bearer\s+ark_\S+/i.test(t)?!0:(Xn(e,"x-api-key")?.trim()??"").startsWith("ark_")},tE=e=>{let t=Xn(e,"x-anyray-api-key")?.trim();if(t?.startsWith("ark_"))return{key:t,slot:"x-anyray-api-key"};let r=(Xn(e,"authorization")?.trim()??"").match(/^bearer\s+(ark_\S+)/i);if(r)return{key:r[1],slot:"authorization"};let o=Xn(e,"x-api-key")?.trim()??"";return o.startsWith("ark_")?{key:o,slot:"x-api-key"}:void 0},wW=e=>e.split("?")[0].includes("/v1/"),QS=e=>e.replace(/[^\x20-\x7e]/g,"").replace(/["'`\\$]/g,"").slice(0,300),bW=(e,t,n=process.platform,r=hW)=>{let o=QS(e),a=QS(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{}},nE=(e={})=>{let t=e.readBootstrap??jt,n=e.ssoGate??Jn,r=e.readState??Or,o=e.notify??bW,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<yW||(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(!wW(u)||gW(f)||l||a()-s<mW)return;s=a(),l=!0,d().catch(()=>{}).finally(()=>{l=!1})}catch{}}}};import{watch as kW}from"node:fs";import{basename as CW,dirname as AW}from"node:path";var vW=2e3,SW=6e4,_a=e=>e instanceof Error?e.name:"UnknownError",EW=(e,t,n)=>{let r=kW(e,{persistent:!1},(o,a)=>{t(a==null?null:a.toString())});return r.on("error",n),r},IW=async(e,t)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await Oe(async()=>e,void 0,t);if(!r)return!1;let o=await Er(n,r.toolOrigin);return o.length===0?!1:(await mt(o,r.target),!0)}catch{return!1}},rE=(e={})=>{let t=e.loadProfile??P,n=e.adapters??se,r=e.probe??be,o=e.repairDrift??(C=>IW(C,r)),a=e.resolveProfileFile??Do,s=e.watchDir??EW,i=e.debounceMs??vW,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 x=m.get(C);if(x){m.delete(C);try{x.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=>x=>{if(!u)try{let T=m.get(C);if(!T||x!==null&&!T.files.has(x))return;g()}catch(T){d(_a(T))}},b=C=>x=>{d(_a(x)),w(C),g()},A=async C=>{let x=[],T=new Set(C.managedTools??[]);for(let Y of n)if(!(!T.has(Y.id)||!Y.watchPaths))try{x.push(...await Y.watchPaths())}catch(W){d(_a(W))}let U=await a().catch(()=>{});U&&x.push(U);let Z=new Map;for(let Y of x){let W=AW(Y),z=Z.get(W)??new Set;z.add(CW(Y)),Z.set(W,z)}return Z},v=async C=>{let x=await A(C);if(!u){for(let T of[...m.keys()])x.has(T)||w(T);for(let[T,U]of x){let Z=m.get(T);if(Z){Z.files=U;continue}try{m.set(T,{handle:s(T,y(T),b(T)),files:U})}catch(Y){d(_a(Y))}}}},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(_a(C))}};return{ready:t().then(C=>v(C)).catch(C=>d(_a(C))),stop:()=>{u=!0,p!==void 0&&(clearTimeout(p),p=void 0);for(let C of[...m.keys()])w(C)}}};import{randomBytes as xW}from"node:crypto";import{chmod as RW,readFile as OW,rm as sE,writeFile as _W}from"node:fs/promises";import{join as TW}from"node:path";var PW=/^[A-Za-z0-9_-]{43}$/,LW=3600*1e3,oE=3900,DW=1e4,km=()=>TW(ee(),"device-token.json"),NW=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&PW.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},iE=async()=>{try{let e=JSON.parse(await OW(km(),"utf-8"));return NW(e)?e:null}catch{return null}},$W=0,MW=async e=>{await bt();let t=km(),n=`${t}.${process.pid}.${$W++}.tmp`;try{await _W(n,`${JSON.stringify(e)}
|
|
306
|
+
`,{mode:384}),await RW(n,384),await fe(n,t)}catch(r){throw await sE(n,{force:!0}).catch(()=>{}),r}},Md=async()=>{await sE(km(),{force:!0}).catch(()=>{})},FW=()=>xW(32).toString("base64url"),UW=e=>e instanceof Error?e.name:"UnknownError",BW=(e,t)=>{let n=setInterval(e,t);return n.unref(),{stop:()=>clearInterval(n)}},aE=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??P)(),o=r.gateway?.replace(/\/+$/,""),a=r.clientKey;if(!o||!a)return!1;let s=FW(),i=new AbortController,c=setTimeout(()=>i.abort(),DW),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:oE}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await MW({v:1,token:s,expiresAt:t()+oE*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${UW(r)}`),!1}},cE=(e={})=>{aE(e);let n=(e.scheduleRotation??BW)(()=>{aE(e)},LW);return{stop:()=>n.stop()}};var HW=1800*1e3,lE=50,KW=15e3,GW=1e3,fE=ps*1e3-1e4,dE=15*6e4,jW=75e3,VW=8e4,YW=async(e,t,n={})=>{let r=n.budgetMs??ps*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 Am(o)}},Fd=e=>{let t=e instanceof Error?e.name:"unknown",n=e?.code;return typeof n=="string"?`${t} ${n}`:t},ZW=(e,t={})=>{let n=t.exit??(f=>process.exit(f)),r=t.exitCode??0,o=t.hardCapMs??fE,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()},hE=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]),JW=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]),XW=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),zW=45*1e3,qW=600*1e3,QW=new Set(["host","connection","keep-alive","proxy-connection","content-length","transfer-encoding","upgrade"]),e1=new Set(["content-encoding","content-length","transfer-encoding","connection","keep-alive"]),t1=new Set(["missing_key","key_expired"]),n1=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"&&t1.has(r)}catch{return!1}},r1=e=>{let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(QW.has(n.toLowerCase())||(t[n.toLowerCase()]=Array.isArray(r)?r.join(", "):r));return t},o1=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))}),a1=(e,t)=>e?hE.has(e)?!0:JW.has(e)&&XW.has(t.toUpperCase()):!1,s1=new Set(["127.0.0.1","localhost","[::1]","::1"]),i1=e=>{if(e[Qu]===void 0||e.origin!==void 0)return!1;let t=(e.host??"").replace(/:\d+$/,"");return s1.has(t)},c1=(e,t)=>{let n=(t??"").split("?")[0];return e==="GET"&&n==="/__anyray/health"||e==="POST"&&n==="/__anyray/shutdown"},l1=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}}}},Am=e=>new Promise(t=>setTimeout(t,e)),uE=async(e,t,n,r,o,a=KW)=>{let s=Date.now()+a,i=lE,c=!1;for(;;){let l=await l1(e,t,n,r);if("res"in l||!o())return l;let d=l.failure.code;if(d!==void 0&&hE.has(d)){if(Date.now()+i>s)return l;await Am(i),i=Math.min(i*2,GW)}else if(!c&&a1(d,t))c=!0,await Am(lE);else return l;if(!o())return l}},Cm=async(e,t)=>{let n={};if(t.headers.forEach((s,i)=>{e1.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()},pE=(e,t,n)=>{e.headersSent||e.destroyed||(e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify({error:{type:"anyray_proxy",message:n}})))},d1=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(!i1(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 o1(a),d=r1(a.headers),u=tE(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&&!eE(a.headers)){h=!0;try{p=await e.resolveClientKey(),p&&f(p)}catch{}}let m=await uE(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("failure"in m){pE(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(n1(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 uE(`${t}${i}`,c,d,l,()=>!s.destroyed,e.unsentRetryBudgetMs);if("res"in E){E.res.status===401&&w(),await Cm(s,E.res);return}}}w(),await Cm(s,new Response(b,{status:m.res.status,headers:m.res.headers}));return}w(),await Cm(s,m.res)},o=WW.createServer((a,s)=>{s.on("error",()=>{}),c1(a.method,a.url)||(n++,s.once("close",()=>{n--})),r(a,s).catch(i=>{console.error(`anyray refresh proxy: request error ${Fd(i)}`),s.headersSent?s.end():pE(s,502,"anyray proxy internal error")})});return o.keepAliveTimeout=jW,o.headersTimeout=VW,o.on("error",a=>{a.code!=="EADDRINUSE"&&console.error(`anyray refresh proxy: server error ${Fd(a)}`)}),{server:o,inFlight:()=>n}},mE=5e3,u1=2e3,p1=(e={})=>{let t=e.now??Date.now,n=e.loadProfile??P,r=e.refresh??(()=>Qe()),o=e.remintBudgetMs??mE,a,s=-1/0,i=3e4;return Object.assign(async()=>{let l=a===void 0?u1: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<=xi(d)&&Promise.resolve().then(r).catch(()=>{})}return a=d.clientKey,s=t(),a},{invalidate:()=>{a=void 0,s=-1/0}})},yE=async()=>{let e=await P(),t=e.fallbackPort,n=e.gateway?.replace(/\/+$/,"");if(!t||!n){let p=await jt().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=nE(),o=p1(),a=d1({port:t,remoteOrigin:n,onGatewayUnauthorized:(p,h)=>r.onGatewayUnauthorized(p,h),resolveClientKey:o,recoverInjectedKey:async()=>(o.invalidate(),await Promise.race([Qe({force:!0}).catch(()=>{}),new Promise(p=>setTimeout(p,mE).unref?.())]),o()),isOwnClientKey:p=>LS(p),onShutdown:p=>f(0,{drain:p.drain})});Qe().catch(()=>{});let s=setInterval(()=>{Qe().catch(()=>{})},HW);s.unref();let i=rE(),c=cE(),l=Date.now();a.server.on("request",()=>{l=Date.now()});let d=setInterval(()=>{Date.now()-l>qW||fetch(`${n}/`,{method:"HEAD"}).catch(()=>{})},zW);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"?dE:fE;yw(Date.now()+m),ZW(a.server,{exitCode:p,inFlight:a.inFlight,ceilingMs:h.drain==="idle"?dE:void 0,exit:w=>{rp(),process.exit(w)}})};return process.once("SIGTERM",()=>f()),process.once("SIGINT",()=>f()),process.on("uncaughtException",p=>{console.error(`anyray refresh proxy: uncaught exception ${Fd(p)}`),f(1)}),process.on("unhandledRejection",p=>{console.error(`anyray refresh proxy: unhandled rejection ${p instanceof Error?Fd(p):typeof p}`),f(1)}),rp(),await uw(ls()).catch(()=>{}),await YW(a.server,t),console.error(`anyray refresh proxy listening on 127.0.0.1:${t} \u2192 ${n}`),await new Promise(()=>{}),0};import{platform as f1}from"node:os";import{stat as h1}from"node:fs/promises";import{spawnSync as m1}from"node:child_process";var gE="/Applications/Anyray Connect Tray.app",y1=new Set(["V53XMA78UF"]),g1="ai.anyray.connect-tray",w1=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,b1=e=>{let t=m1("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
|
|
307
|
+
${t.stderr??""}`}},k1=async e=>{try{return(await h1(e)).isDirectory()}catch{return!1}},C1=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},vm=async(e,t={})=>{if((t.os??f1())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??k1)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??b1;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?C1(a.output):void 0;return s?y1.has(s)?w1(a.output)!==g1?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},So=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await vm(n,t)).ok?"healthy":"gone"},Sm=async(e={})=>{try{let t=e.load??P,n=await t(),r=await So(n,e);if(r!=="gone")return r;let o=e.installScheduler??dr,a=e.installDaemon??Dt;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??re)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var A1={"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."},v1=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},S1=async(e,t)=>{let n=t.stderr??console.error,r=v1(e,"--app-path")??gE,o=await vm(r,t);if(!o.ok)return n(A1[o.reason]),1;let s=await(t.load??P)();await(t.save??re)({...s,persistenceOwner:"tray",trayAppPath:r});let c=t.uninstallScheduler??ur,l=t.uninstallDaemon??qt;return await c().catch(()=>{}),await l(s.fallbackPort).catch(()=>{}),0},E1=async e=>{let t=e.load??P,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??dr,o=e.installDaemon??Dt;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??re)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},wE=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await S1(e,t):e.includes("--release-tray")?await E1(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 bE,platform as kE}from"node:os";import{join as Ta}from"node:path";import{access as I1}from"node:fs/promises";var Em=(e=kE(),t=bE())=>{let n=a=>[Ta(t,"Library","LaunchAgents",`${a}.plist`)],r=Ta(t,".config","systemd","user"),o=a=>[Ta(t,".anyray","logs",a)];return e==="darwin"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:us,paths:n(us),dataPaths:o("connect-daemon.log")},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:ws,paths:n(ws),dataPaths:o("connect-refresh.log")}]:e==="linux"?[{kind:"daemon",title:"key-refresh daemon",supervisorName:`${lr}.service`,paths:[Ta(r,`${lr}.service`)]},{kind:"scheduler",title:"key-refresh scheduler",supervisorName:`${Vr}.timer`,paths:[Ta(r,`${Vr}.timer`),Ta(r,`${Vr}.service`)]}]:e==="win32"?[{kind:"scheduler",title:"key-refresh scheduler",supervisorName:_c,paths:[]}]:[]},CE=async e=>{try{return await I1(e),!0}catch{return!1}},Oi=async(e,t={})=>{let n=t.exists??CE;for(let r of Em(t.os,t.home))if(r.kind===e){for(let o of r.paths)if(await n(o))return!0}return!1},AE=async e=>{let t={suspected:!1,missingPaths:[],kinds:[]};if(!e.binaryDurable)return t;let n=e.exists??CE,r=Em(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},x1=[us,`${lr}.service`,ws,`${Vr}.timer`,`${Vr}.service`,_c],vE=(e,t=kE(),n=bE(),r=ir())=>{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 Em(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:",...x1.map(a=>` - ${a}`)),o};var Im=5e3,SE=3e4,R1=1440*60*1e3,O1=e=>new Promise(t=>setTimeout(t,e)),_1=async(e=P,t=Nt)=>(await Oe(e,t))?.target,T1=e=>Ht(e)?.quitGated,EE=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??T1,o=t.readPending??tl,a=t.clearPending??Fp,s=t.targetFromProfile??_1,i=t.sleep??O1,c=t.now??Date.now,l=t.maxWaitMs??R1;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),f=c(),p=Im;for(;;){let h=await o(n);if(!h||c()-f>l)return 0;if(d.isRunning()){await i(p),p=Math.min(SE,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=Im;continue}if((await u(h.op,m,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(p),p=Math.min(SE,p*2);continue}if(await a(n,h)!=="superseded")return 0;await i(p),p=Im}}catch{return 0}};import{writeFileSync as N1}from"node:fs";import{chmod as xm,stat as $1}from"node:fs/promises";import{platform as Om}from"node:os";import{dirname as OE,isAbsolute as M1}from"node:path";var Pa=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,Ud=Pa(process.stdout,process.env),IE=Pa(process.stderr,process.env),La=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,j=e=>La("1",e,Ud),S=e=>La("2",e,Ud),P1=e=>La("32",e,Ud),L1=e=>La("33",e,IE),D1=e=>La("31",e,IE),et=e=>La("36",e,Ud),k=e=>console.log(e),K=e=>console.log(`
|
|
308
|
+
${j(e)}`),F=e=>console.log(S(e)),$=e=>console.log(`${P1("\u2713")} ${e}`),D=e=>console.error(`${L1("!")} ${e}`),_=e=>console.error(`${D1("\u2717")} ${e}`);var Rm=`${j("anyray-connect managed")} \u2014 fleet-wide Claude Code routing via managed-settings.json
|
|
309
309
|
|
|
310
310
|
Emit or install the OS \`managed-settings.json\` that points a managed fleet's
|
|
311
311
|
Claude Code at the Anyray gateway. It reads at a HIGHER precedence than a user's
|
|
@@ -393,13 +393,13 @@ ${j("Examples")}
|
|
|
393
393
|
anyray-connect managed --print --tool jetbrains --bin /usr/local/bin/anyray-connect --npx /usr/local/bin/npx > acp.json
|
|
394
394
|
|
|
395
395
|
# Shell/SDK fleet snippet (base URLs only; keys stay per-user):
|
|
396
|
-
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,
|
|
397
|
-
`)},
|
|
398
|
-
`),
|
|
399
|
-
`),Ce(
|
|
400
|
-
`),Ce(
|
|
401
|
-
`+
|
|
402
|
-
`+
|
|
396
|
+
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,xE=["claude-code","jetbrains","shell","bootstrap","proxy"],F1=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(!xE.includes(a))throw new Error(`unknown --tool ${a} (expected ${xE.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&&!xt(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};function Bd(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:[xn(os(t.binaryPath,[Ze]),{matcher:"*"})],UserPromptSubmit:[xn(os(t.binaryPath,o),{timeout:30}),xn(os(t.binaryPath,[nr]))],SessionStart:[xn(os(t.binaryPath,[...o,"--session-start"]),{async:!0})]}}}let{env:r}=pn(e,{includeAuthToken:!1,includeClientKey:!1});return n.scrubDirectMode?{env:{...Object.fromEntries(Rn.map(o=>[o.name,""])),...r}}:{env:r}}var U1=(e,t)=>{let n="env"in t||"hooks"in t?t:{env:t},r={...e};e.env&&typeof e.env=="object"&&(r.env={...e.env}),e.hooks&&typeof e.hooks=="object"&&(r.hooks=Object.fromEntries(Object.entries(e.hooks).map(([a,s])=>[a,Array.isArray(s)?[...s]:s])));let o=r.env??{};for(let a of Wr)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,Ku(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},B1=e=>{let t=e.env,n=Ku(e);if(t){for(let r of Wr)r in t&&(delete t[r],n=!0);for(let{name:r}of Rn)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return n},_E=async e=>{let t=async n=>{try{return(await $1(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(OE(e))!==void 0}},TE=async(e,t)=>(t.dirExisted||await xm(OE(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await xm(e,420),{mode:420,keptRestricted:!1}):(await xm(e,t.mode),{mode:t.mode,keptRestricted:!0})),PE=(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.")))},LE=()=>process.getuid?.()===0,Ce=e=>{process.stderr.write(`${e}
|
|
397
|
+
`)},Eo=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}N1(e.out,t,"utf8"),Ce(S(`# Wrote ${e.out}`))},_m=e=>ye({origin:e.gateway??"http://localhost:8787",subscription:!!e.sso,user:e.user,team:e.team,intent:e.intent??"",intentLabel:e.intentLabel??"",session:e.session??""}),Wd=e=>M1(e)||/^[A-Za-z]:[\\/]/.test(e),DE=e=>{if(!e.sso)return;let t=xt(e.sso);if(!t)throw new Error("invalid --sso link");let n=e.bin??Re();if(!e.bin&&!ce())throw new Error("--bin is required because the running binary path is temporary; use a fleet-stable path such as /usr/local/bin/anyray-connect");if(!Wd(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}},NE=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)"}`],Tm=(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{}},W1=(e,t)=>({agent_servers:{[jn]:{command:e,args:[ad,"claude",t,"jetbrains"],env:{}},[Vn]:{command:e,args:[ad,"codex",t,"jetbrains"],env:{}}}}),RE=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(`
|
|
398
|
+
`),H1=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(!Wd(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(!cd(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return Eo(e,`${JSON.stringify(W1(e.bin,e.npx),null,2)}
|
|
399
|
+
`),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},K1=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&&!Wd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return Eo(e,VS(e.sso,e.gateway,e.bin)),Ce(S(`# Fleet bootstrap for ${Ri("linux")}`)),Ce(S(`# macOS: ${Ri("darwin")}`)),Ce(S(`# Windows: ${Ri("win32",{ProgramData:"C:\\ProgramData"})}`)),Ce(S("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},G1=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=ye({origin:`http://127.0.0.1:${ke}`});return Eo(e,RE(n)),Ce(S(`# Loopback shell snippet \u2014 pair with \`managed --tool proxy\` (daemon on :${ke}) and \`--tool bootstrap\`.`)),0}let t=_m(e);return Eo(e,RE(t)),Ce(S("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),Tm(t,Ce),0},j1=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(!Wd(e.bin))throw new Error("--bin must be an absolute fleet-stable path");let t=e.servicePlatform??(Om()==="darwin"?"launchd":"systemd"),n={command:e.bin,args:[qu]};return t==="launchd"?(Eo(e,hs(n)),Ce(S("# launchd agent \u2014 deploy to /Library/LaunchAgents/ai.anyray.connect.fallback.plist (loads for every user at login)."))):(Eo(e,ms(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},V1=e=>{let t=_m(e),n=DE(e),r=n?Bd(t,n):Bd(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(Eo(e,`${JSON.stringify(r,null,2)}
|
|
400
|
+
`),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 NE(t))Ce(S(`# ${o}`));Tm(t,Ce)}return 0},Y1=async e=>{let t=Om();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(!LE())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=_m(e),r=DE(e);r||Tm(n,u=>D(u.replace(/^!\s*/,"")));let o=Lt(t),a=await M(o),s=r?Bd(n,r):Bd(n,void 0,{scrubDirectMode:e.scrubDirectMode}),i=e.scrubDirectMode?Rn.filter(({name:u})=>{let f=a.env?.[u];return typeof f=="string"&&f.trim()!==""}):[],c=U1(a,s),l=await _E(o);await J(o,c);let d=await TE(o,l);$(`Wrote ${o}`),PE(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 NE(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},Z1=async()=>{let e=Om();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(!LE())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 M(t);if(!B1(n))return k(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await _E(t);await J(t,n);let o=await TE(t,r);return $(`Removed Anyray-owned keys from ${t} (other keys left intact).`),PE(t,o),0},$E=async e=>{let t;try{t=F1(e)}catch(n){return _(n instanceof Error?n.message:"invalid managed arguments"),k(`
|
|
401
|
+
`+Rm),1}if(t.help||e.length===0&&!t.mode)return k(Rm),0;if(!t.mode)return _("Specify a mode: --print, --write, or --revert."),k(`
|
|
402
|
+
`+Rm),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"?H1(t):n==="bootstrap"?K1(t):n==="proxy"?j1(t):G1(t):t.mode==="print"?V1(t):t.mode==="write"?await Y1(t):await Z1()}catch(n){return _(n instanceof Error?n.message:"managed settings failed"),1}};var J1=`anyray-connect print-key [--json | --passthrough-headers]
|
|
403
403
|
|
|
404
404
|
Print the current short-lived Anyray client key for a consuming app.
|
|
405
405
|
|
|
@@ -411,10 +411,10 @@ Options:
|
|
|
411
411
|
"x-anyray-provider":"anthropic","x-anyray-metadata":"..."}).
|
|
412
412
|
Carries the client key, never the seat OAuth token.
|
|
413
413
|
--help Show this help.
|
|
414
|
-
`,
|
|
415
|
-
`);let s=o.passthroughHeaders?
|
|
414
|
+
`,X1=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}},z1=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=xi(e):!0},ME=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},FE=(e,t)=>{if(!Ie(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},Pm=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,q1=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${Pm(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 \`${Pm(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 \`${Pm(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""}},Lm=async(e={})=>{let t=e.loadProfile??P,n=e.refreshIfDue??Qe,r=e.now??Date.now,o=await t();if(ME(o),!o.enrolledCert){if(!FE(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||z1(o,r)){let i=q1(await n(),o);if(i){if(!FE(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(ME(s),!Ie(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},UE=e=>de({user:e.name,team:e.team}),Q1=({profile:e,token:t})=>{let n={},r=UE(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Dm=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=UE(e);return r&&(n["x-anyray-metadata"]=r),n},eH=e=>JSON.stringify(Dm(e)),BE=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=X1(e);if(o.help)return n.write(J1),0;let a=await Lm(t);a.warning&&r.write(`${a.warning}
|
|
415
|
+
`);let s=o.passthroughHeaders?eH(a):o.json?Q1(a):a.token;return n.write(`${s}
|
|
416
416
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
417
|
-
`),1}};var
|
|
417
|
+
`),1}};var WE=`anyray-connect models [<model-id>] [--json]
|
|
418
418
|
|
|
419
419
|
List the Copilot models your seat can run on the Anyray lane, or switch the
|
|
420
420
|
Copilot CLI's startup model. The CLI's own /models cannot list models on a
|
|
@@ -426,8 +426,8 @@ Options:
|
|
|
426
426
|
--json Emit {"origin","current","models":[{"id","wire",...caps}]} instead
|
|
427
427
|
of the table (listing only).
|
|
428
428
|
--help Show this help.
|
|
429
|
-
`,
|
|
430
|
-
`),0;k(j(`Copilot models your seat serves (via ${o.origin})`));for(let h of l){let m=h.id===p?"*":" ",w=
|
|
429
|
+
`,tH=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},nH=e=>{let t=se.find(n=>n.id===no);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},rH=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(" / ")},oH=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${js(t)}/${Nn(n)==="responses"?"responses":"chat/completions"}`,HE=async(e=[],t={})=>{let n=tH(e);if(n.help)return process.stdout.write(WE),0;if(n.error)return _(n.error),process.stdout.write(WE),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??gl)({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??ta)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=kf(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:Nn(h.id),...h.maxPromptTokens?{maxPromptTokens:h.maxPromptTokens}:{},...h.maxOutputTokens?{maxOutputTokens:h.maxOutputTokens}:{}}))})}
|
|
430
|
+
`),0;k(j(`Copilot models your seat serves (via ${o.origin})`));for(let h of l){let m=h.id===p?"*":" ",w=rH(h);k(` ${m} ${h.id.padEnd(24)}${w?S(w):""}`)}return F("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),F("The CLI's own /models cannot list models on a custom provider \u2014 this list is the picker."),0}let d=l.find(p=>p.id===n.modelId);if(!d)return _(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??yl)(oH(o,i,d.id),{...bf(),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."):$(`'${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??nH)(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 $(`Copilot CLI startup model \u2192 ${d.id}`),F("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};var aH=`anyray-connect copilot-login
|
|
431
431
|
|
|
432
432
|
Sign Anyray in to GitHub Copilot (device flow) so the Copilot CLI seat lane
|
|
433
433
|
can run your plan's current models. Opens no browser for you: it prints a
|
|
@@ -435,16 +435,16 @@ code to type at github.com/login/device.
|
|
|
435
435
|
|
|
436
436
|
Options:
|
|
437
437
|
--help Show this help.
|
|
438
|
-
`,
|
|
439
|
-
`),0)};import{join as
|
|
438
|
+
`,KE=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(aH),0;k(j("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??Dk)();if(!n)return _("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;k(` 1. Open ${et(n.verificationUri)}`),k(` 2. Enter the code: ${j(n.userCode)}`),F(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??Nk)(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??$k)(r.token,o);$(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??pf)(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??ta)(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."):$(`${l.length} models available (e.g. ${l[0].id}).`),F("Now run: anyray-connect --tools copilot-cli"),0};var GE=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??P)()}catch{o={}}let a=o.gateway?.replace(/\/+$/,"");if(!a||!o.clientKey)return n.write("Not enrolled on this machine \u2014 run `npx anyray-connect` first.\n"),1;let s=await(e.readState??iE)();return!s||s.expiresAt<=r()?(n.write("No live device token yet \u2014 start the daemon: run `anyray-connect`.\n"),1):(t.write(`${a}/device?dt=${s.token}
|
|
439
|
+
`),0)};import{join as eI,dirname as yH}from"node:path";import{mkdir as gH,readFile as Bm,rm as tI,writeFile as nI}from"node:fs/promises";import{fstatSync as lH,openSync as dH,statSync as uH}from"node:fs";import{createInterface as pH}from"node:readline/promises";import{ReadStream as fH}from"node:tty";import{execFileSync as jE}from"node:child_process";import sH from"node:os";var Nm=e=>{try{return jE("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},iH=e=>{try{return jE("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},cH=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"]),$m=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:cH.has(t):!0},VE=()=>{try{return sH.userInfo().username||void 0}catch{return}},YE=()=>Nm("user.name")??Nm("user.email")??VE()??"unknown",ZE=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Nm),global:e.globalGitConfig??(t||iH)}},Io=e=>{try{return e()?.trim()||void 0}catch{return}},Mm=(e={})=>{let t=ZE(e),n=Io(e.osUsername??VE),r=Io(()=>t.global("user.email"))??Io(()=>t.local("user.email"));return r||(Io(()=>t.global("user.name"))??Io(()=>t.local("user.name"))??n??"unknown")},JE=(e={})=>{let t=Mm(e);if($m(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=ZE(e);return!!(Io(()=>n.global("user.email"))??Io(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var Vt=()=>!!process.stdin.isTTY,hH=()=>{try{let e=lH(0);return e.isCharacterDevice()&&e.rdev===uH("/dev/tty").rdev}catch{return!1}},Fm=()=>{if(hH()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new fH(dH(`/dev/fd/${e}`,"r"));return{stream:n,close:()=>n.destroy()}}catch{}}return{stream:process.stdin,close:()=>{}}},gt=class extends Error{constructor(){super("prompt cancelled"),this.name="PromptCancelledError"}},XE=async(e,t)=>{let n=t.input??Fm(),r=t.output??process.stdout,o=pH({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 gt))}),o.question(e).then(d=>l(()=>a(d)),d=>l(()=>s(c?d:new gt)))})}finally{o.close(),n.close()}},Da=async(e,t={})=>{let n=(await XE(`${e} ${S("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},Na=async(e,t,n={})=>{let r=t?` ${S(`[${t}]`)}`:"";return(await XE(`${e}${r}: `,n)).trim()||t},zE=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return F(`Your name: ${t} ${S("(cached \u2014 pass --user to change)")}`),t;let r=YE();return n||!Vt()?(F(`Your name: ${r} ${S("(auto-detected \u2014 pass --user to change)")}`),r):Na("? Your name",r)},qE=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return F(`Team: ${t} ${S("(cached \u2014 pass --team to change)")}`),t;if(!(n||!Vt()))return Na("? Team (optional)")},_r=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return dn(e??n)},QE=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,$a="claude-desktop",_i=e=>e!=="cursor",Ti=(e,t,n)=>_i(e)?n:t,Hd=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await vr(e.runReg??Gn))return n("managed-policy")}catch{return n("policy-unreadable")}let s=Wt({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=on(r);return await co(o,r)?n("managed-policy"):(await ka({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")}},Kd=e=>e.id!==$a||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",mH={"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"},Gd=(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=mH[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 Um=["claude-code","codex"],wH="anyray-connect print-key",Wm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bH=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:Xa,authMode:"placeholder",metadata:{}}),Hm=e=>eI(e,".claude","settings.json"),kH=async(e,t,n)=>{let r=Hm(e),o=await M(r),{env:a}=pn(t,{includeAuthToken:!1,includeClientKey:!1}),s=Wm(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Kr(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=wH,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]}},rI=async(e=process.cwd())=>{let t=[],n=Hm(e);try{if(await R(n)){let o=await M(n),a=Wm(o.env)?o.env:{};(Wr.some(s=>s in a)||Kr(o))&&t.push(n)}}catch{}let r=Km(e);try{if(await R(r)){let o=await Bm(r,"utf-8");Cp(o)&&t.push(r)}}catch{}return t},CH=async(e,t)=>{let n=Hm(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await M(n),o=!1;if(Wm(r.env)){let s={...r.env};for(let i of Wr)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Kr(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 tI(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]}},Km=e=>eI(e,".codex","config.toml"),AH=async(e,t,n)=>{let r=Km(e),o=await Bm(r,"utf-8").catch(()=>""),a=Hc(o,vs(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await gH(yH(r),{recursive:!0}),await nI(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]}},vH=async(e,t)=>{let n=Km(e);if(!await R(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await Bm(n,"utf-8"),o=Kc(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await tI(n,{force:!0}):await nI(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},oI=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...Um],r=n.filter(s=>!Um.includes(s));if(r.length>0)return _(`--project supports ${Um.join(", ")} \u2014 not: ${r.join(", ")}. Other tools keep per-machine state (run anyray-connect without --project there).`),1;let o;if(!e.revert){let s=await P(),i=e.gateway??s.gateway;if(!i)return _("--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=bH(Ye(i))}if(k(j(e.revert?"Anyray connect \u2014 remove project config":"Anyray connect \u2014 project config")),K("Project"),k(` Directory: ${t}`),o&&k(` Gateway: ${o.origin}`),k(` Tools: ${n.join(", ")}`),e.revert||(D(`
|
|
440
440
|
A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),F(" Each machine still needs `anyray-connect` on PATH and a one-time enrollment (--sso/--enroll); the files carry no credential and no identity.")),!e.yes&&!e.dryRun){if(!Vt())return _(`
|
|
441
441
|
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;let s=e.revert?"remove Anyray project config for":"write committable project config for";if(!await Da(`
|
|
442
442
|
${s} ${n.length} tool(s)?`))return F("Aborted. Nothing changed."),0}e.dryRun&&F(`
|
|
443
|
-
Dry run \u2014 no files will be written.`);let a=[];for(let s of n){K(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await
|
|
444
|
-
`),1;try{let o=await
|
|
443
|
+
Dry run \u2014 no files will be written.`);let a=[];for(let s of n){K(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await kH(t,o,e.dryRun):await AH(t,o,e.dryRun):s==="claude-code"?await CH(t,e.dryRun):await vH(t,e.dryRun);for(let c of i.messages)k(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(K("Next"),e.revert)$(" Project config removed. Commit the change to propagate it.");else{$(" Commit these files to route every checkout of this repo:");for(let s of a)k(` ${s}`);k(S(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as SH}from"node:child_process";var EH="/usr/bin/security",IH=["find-generic-password","-s","Claude Code-credentials","-w"],xH=1e4,RH=64*1024,OH=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,aI="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",_H=(e,t,n)=>new Promise((r,o)=>{SH(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),sI=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),TH=e=>{let t=JSON.parse(e);if(!sI(t)||!sI(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!OH.test(n))throw new Error("unexpected keychain access token");return n},iI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${aI}
|
|
444
|
+
`),1;try{let o=await Lm(t),a=Dm(o),s=await(t.execSecurity??_H)(EH,[...IH],{encoding:"utf8",timeout:xH,maxBuffer:RH,shell:!1}),i=TH(s.stdout);return o.warning&&r.write(`${o.warning}
|
|
445
445
|
`),n.write(`${JSON.stringify({token:i,headers:a})}
|
|
446
|
-
`),0}catch{return r.write(`${
|
|
447
|
-
`),1}};import{mkdir as
|
|
446
|
+
`),0}catch{return r.write(`${aI}
|
|
447
|
+
`),1}};import{mkdir as aK,writeFile as sK}from"node:fs/promises";import{dirname as iK}from"node:path";import{Buffer as cK}from"node:buffer";import{constants as cI}from"node:fs";import{access as PH,chmod as LH,mkdir as DH,open as NH,readFile as $H,realpath as MH,rm as FH,stat as uI,writeFile as UH}from"node:fs/promises";import{randomUUID as BH}from"node:crypto";import{platform as pI}from"node:os";import{dirname as WH,join as HH,posix as KH,win32 as fI}from"node:path";var jd="/usr/local/bin/anyray-credential-helper",Vd="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Gm="Managed by anyray-connect desktop helper; do not edit.",GH=`anyray-connect desktop helper <--write|--print> --bin <absolute> [options]
|
|
448
448
|
|
|
449
449
|
Create the credential helper required by Claude Desktop and Codex fleet
|
|
450
450
|
artifacts. The helper stores no key. It invokes a durable anyray-connect binary
|
|
@@ -474,13 +474,13 @@ Examples:
|
|
|
474
474
|
|
|
475
475
|
anyray-connect desktop helper --print --platform posix \\
|
|
476
476
|
--bin /usr/local/bin/anyray-connect > anyray-credential-helper
|
|
477
|
-
`,
|
|
478
|
-
`);let r=
|
|
479
|
-
`)},Yd=(e,t)=>{if(!
|
|
480
|
-
`),0;if(s!==
|
|
477
|
+
`,lI=(e=pI())=>e==="win32"?"windows":"posix",jH=e=>e==="windows"?Vd:jd,dI=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},VH=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":dI(t,"write");break;case"--print":dI(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},YH=e=>/[\0\r\n]/.test(e),ZH=e=>/^[A-Za-z]:[\\/]/.test(e)&&fI.isAbsolute(e),Pi=(e,t)=>!YH(e)&&(t==="windows"?ZH(e):KH.isAbsolute(e)),jm=e=>e.replace(/\\/g,"/").toLowerCase(),hI=(e,t)=>{if(!Pi(e,t))return!1;let n=jm(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)))},Vm=(e,t)=>t==="windows"?fI.normalize(e):e,JH=e=>`'${e.replace(/'/g,`'"'"'`)}'`,XH=(e,t)=>{if(!hI(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Vm(t,e);if(e==="windows")return["@echo off",`REM ${Gm}`,'if "%~1"=="" goto json','if not "%~2"=="" exit /b 64','if "%~1"=="--token" goto token',"exit /b 64",":json",`"${n}" print-key --json`,"exit /b %ERRORLEVEL%",":token",`"${n}" print-key`,"exit /b %ERRORLEVEL%",""].join(`\r
|
|
478
|
+
`);let r=JH(n);return["#!/bin/sh",`# ${Gm}`,'if [ "$#" -eq 0 ]; then',` exec ${r} print-key --json`,"fi",'if [ "$#" -eq 1 ] && [ "$1" = "--token" ]; then',` exec ${r} print-key`,"fi","exit 64",""].join(`
|
|
479
|
+
`)},Yd=(e,t)=>{if(!Pi(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=Vm(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"]}},zH=async e=>{try{return await $H(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},qH=async(e,t)=>{try{let n=await MH(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!hI(r,t))throw new Error;if(!(await uI(n)).isFile())throw new Error;await PH(n,t==="posix"?cI.X_OK:cI.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},QH=e=>e.slice(0,300).includes(Gm),eK=async(e,t,n)=>{let r=await zH(e);if(r!==void 0&&r!==t&&!QH(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 uI(e)).mode&511)===493)return"unchanged"}catch{}}let o=WH(e);try{await DH(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=HH(o,`.anyray-credential-helper.${process.pid}.${BH()}.tmp`),s=!1;try{await UH(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await LH(a,493);let i=await NH(a,"r");try{await za(i)}finally{await i.close()}await fe(a,e),s=!0}catch{throw new Error(`could not install credential helper at ${e}`)}finally{s||await FH(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},mI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=VH(e);if(o.help)return n.write(GH),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??pI)(),s=o.targetPlatform??lI(a),i=Vm(o.helperPath??jH(s),s);if(!Pi(i,s))throw new Error(`--path must be an absolute ${s} path`);if(s==="windows"&&Yd("windows",i),jm(i)===jm(o.binaryPath))throw new Error("--path must differ from --bin (the helper cannot invoke itself)");let c=XH(s,o.binaryPath);if(o.mode==="print")return n.write(c),r.write(`Deploy this wrapper at ${i} after deploying the binary at ${o.binaryPath}.
|
|
480
|
+
`),0;if(s!==lI(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await qH(o.binaryPath,s);let l=await eK(i,c,s);return r.write(l==="unchanged"?`Credential helper already current at ${i}.
|
|
481
481
|
`:`${l==="installed"?"Installed":"Updated"} credential helper at ${i}.
|
|
482
482
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
483
|
-
`),1}};var
|
|
483
|
+
`),1}};var tK=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),nK=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,rK=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.")},oK=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Zd=(e,t)=>{let n;try{n=new URL(e)}catch{throw new Error(`${t} must be a valid HTTPS URL.`)}if(n.protocol!=="https:"||n.username!==""||n.password!==""||n.hash!==""||rK(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Ma=(e,t,n)=>{if(!(e===void 0&&!n)){if(typeof e!="string"||e.trim()==="")throw new Error(`--bootstrap-oidc ${t} must be a non-empty string.`);return e.trim()}},yI=e=>{if(!oK(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!tK.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Ma(e.clientId,"clientId",!0),r=Ma(e.scopes,"scopes",!0),o=Ma(e.issuer,"issuer",!1),a=Ma(e.authorizationUrl,"authorizationUrl",!1),s=Ma(e.tokenUrl,"tokenUrl",!1),i=Ma(e.additionalRedirectReferrerHosts,"additionalRedirectReferrerHosts",!1);if(!o&&!(a&&s))throw new Error("--bootstrap-oidc requires issuer, or both authorizationUrl and tokenUrl.");let c=e.redirectPort;if(c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<1||c>65535))throw new Error("--bootstrap-oidc redirectPort must be an integer from 1 to 65535.");return{clientId:n,scopes:r,...o?{issuer:Zd(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:Zd(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:Zd(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},gI=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return yI(t)},Ym=e=>{let t=Zd(e.url,"--bootstrap-url"),n=e.oidc?yI(e.oidc):void 0,r;if(e.deploymentOrganizationUuid!==void 0&&(r=e.deploymentOrganizationUuid.trim(),!nK.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}:{}}},Zm=e=>ia(Ym(e));var lK=`anyray-connect desktop [disconnect] [options]
|
|
484
484
|
|
|
485
485
|
The minimum Claude Desktop workflow:
|
|
486
486
|
anyray-connect desktop Connect this machine
|
|
@@ -522,8 +522,8 @@ Options:
|
|
|
522
522
|
|
|
523
523
|
Older flag-based Claude artifacts and Codex fleet output remain accepted for
|
|
524
524
|
compatibility, but are not part of the recommended Claude Desktop workflow.
|
|
525
|
-
`,
|
|
526
|
-
<string>${
|
|
525
|
+
`,dK=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",uK=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),pK=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[dK(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...uK(o)]},fK=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),Jm=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>fK.has(r))||t.includes("--apply")&&t.includes("--revert")||n==="disconnect"&&t.includes("--apply")))return n==="disconnect"&&(t=["--revert",...t.slice(1)]),t=t.filter(r=>r!=="--apply"),[...t,"--tools","claude-desktop"]},zn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),wI=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),hK=(e,t)=>` <key>${zn(e)}</key>
|
|
526
|
+
<string>${zn(t)}</string>`,Xm=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>hK(i,c)).join(`
|
|
527
527
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
528
528
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
529
529
|
<plist version="1.0">
|
|
@@ -532,15 +532,15 @@ compatibility, but are not part of the recommended Claude Desktop workflow.
|
|
|
532
532
|
<array>
|
|
533
533
|
<dict>
|
|
534
534
|
<key>PayloadType</key>
|
|
535
|
-
<string>${
|
|
535
|
+
<string>${zn(e)}</string>
|
|
536
536
|
<key>PayloadVersion</key>
|
|
537
537
|
<integer>1</integer>
|
|
538
538
|
<key>PayloadIdentifier</key>
|
|
539
|
-
<string>${
|
|
539
|
+
<string>${zn(t)}.payload</string>
|
|
540
540
|
<key>PayloadUUID</key>
|
|
541
|
-
<string>${
|
|
541
|
+
<string>${zn(o)}</string>
|
|
542
542
|
<key>PayloadDisplayName</key>
|
|
543
|
-
<string>${
|
|
543
|
+
<string>${zn(n)}</string>
|
|
544
544
|
${s}
|
|
545
545
|
</dict>
|
|
546
546
|
</array>
|
|
@@ -549,27 +549,27 @@ ${s}
|
|
|
549
549
|
<key>PayloadVersion</key>
|
|
550
550
|
<integer>1</integer>
|
|
551
551
|
<key>PayloadIdentifier</key>
|
|
552
|
-
<string>${
|
|
552
|
+
<string>${zn(t)}</string>
|
|
553
553
|
<key>PayloadUUID</key>
|
|
554
|
-
<string>${
|
|
554
|
+
<string>${zn(r)}</string>
|
|
555
555
|
<key>PayloadDisplayName</key>
|
|
556
|
-
<string>${
|
|
556
|
+
<string>${zn(n)}</string>
|
|
557
557
|
</dict>
|
|
558
558
|
</plist>
|
|
559
|
-
`},
|
|
560
|
-
`,
|
|
561
|
-
`,
|
|
562
|
-
`),
|
|
559
|
+
`},mK=(e,t)=>Xm("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",ia(io(e,t))),yK=(e,t)=>`${JSON.stringify(io(e,t),null,2)}
|
|
560
|
+
`,gK=e=>Xm("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",Zm(e)),wK=e=>`${JSON.stringify(Ym(e),null,2)}
|
|
561
|
+
`,kI=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries(e).map(([n,r])=>`"${wI(n)}"="${wI(r)}"`),""].join(`
|
|
562
|
+
`),bK=(e,t)=>{let n=jl(e,t);return kI(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},kK=e=>kI(Zm(e)),CK=(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=Yd(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${vs(e,o).join(`
|
|
563
563
|
`)}
|
|
564
|
-
`},
|
|
564
|
+
`},AK=e=>Xm("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:cK.from(e,"utf-8").toString("base64")}),vK=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},SK=e=>{if(!e.gateway?.trim())throw new Error("--gateway is required for static fleet artifacts; local profile and environment values are intentionally ignored.");let t=dn(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:Xa,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},bI=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??aK,o=n.writeFile??sK;await r(iK(t),{recursive:!0}),await o(t,e)},EK=(e,t,n,r,o)=>{o.write(`This artifact requires the credential helper at ${n}; the artifact does not install or update it. Deploy a stable anyray-connect binary through your software-distribution system first, then install/package the helper with:
|
|
565
565
|
`),o.write(r==="windows"?` anyray-connect desktop helper --write --platform windows --bin "C:\\Program Files\\Anyray\\anyray-connect.exe" --path "${n}"
|
|
566
566
|
`:` sudo anyray-connect desktop helper --write --platform posix --bin /usr/local/bin/anyray-connect --path '${n.replace(/'/g,`'"'"'`)}'
|
|
567
567
|
`),e==="codex"?o.write(`Non-MDM Codex fleets can place this TOML at /etc/codex/managed_config.toml on Unix or %ProgramData%\\OpenAI\\Codex\\managed_config.toml on Windows.
|
|
568
568
|
`):t==="json"&&o.write(`Deploy this file to /etc/claude-desktop/managed-settings.json.
|
|
569
|
-
`)},
|
|
569
|
+
`)},IK=e=>{e.write(`This artifact is a stable MDM trust anchor; it contains no inference credential. Claude Desktop authenticates the user and fetches the effective configuration from the bootstrap service at launch.
|
|
570
570
|
`),e.write(`Update the bootstrap response instead of redeploying MDM. Claude polls every 30 minutes, then applies changed values on the next Claude Desktop launch; no managed action is required for each policy update.
|
|
571
571
|
`),e.write(`Each bootstrap response replaces the allowed managed configuration; omitted keys are unset.
|
|
572
|
-
`)},
|
|
572
|
+
`)},xK=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??po)({account:e.account,allAccounts:e.allAccounts});if(!o.ok)return r.write(`Cannot migrate: ${o.reason}.
|
|
573
573
|
${o.remedy}
|
|
574
574
|
`),1;let a=o.lanes.reduce((c,l)=>c+l.migrated,0),s=o.portableAssets.reduce((c,l)=>c+l.migrated,0),i={code:"Claude Code sessions",cowork:"Cowork tasks"};for(let c of o.lanes){let l=[c.alreadyPresent>0?`${c.alreadyPresent} already there`:"",c.skippedNoTranscript>0?`${c.skippedNoTranscript} skipped, transcript no longer on disk`:"",c.failed>0?`${c.failed} failed`:""].filter(Boolean);n.write(` ${i[c.lane]}: ${c.migrated} migrated`+(l.length>0?` (${l.join("; ")})`:"")+`
|
|
575
575
|
`)}for(let c of o.portableAssets){let l=c.migrated+c.alreadyPresent,d=c.conflicts+c.invalid+c.failed;if(l+d===0)continue;let u=c.kind==="skill"?"User-created skills":c.kind==="plugin"?"User-installed plugins":"Local MCP servers";n.write(` ${u}: ${c.migrated} migrated`+(c.alreadyPresent>0?` (${c.alreadyPresent} already there)`:"")+(d>0?` (${d} preserved or skipped)`:"")+`
|
|
@@ -580,10 +580,10 @@ Reopen Claude Desktop \u2014 migrated ${c} available in the Anyray profile.
|
|
|
580
580
|
Your previous profile is untouched, so \`desktop disconnect\` still works.
|
|
581
581
|
`)}else n.write(`
|
|
582
582
|
Nothing new to migrate \u2014 no local sessions or portable local data needed copying.
|
|
583
|
-
`);return n.write(" claude.ai chats live on your account, not this machine: bring those\n over with `anyray-connect history restore <export.zip>`.\n"),0},
|
|
584
|
-
`),0}if(!a.helperPath?.trim())throw new Error(`--helper-path is required for fleet artifacts. Deploy it first with \`anyray-connect desktop helper --write\`; use ${jd} on macOS/Linux or ${Vd} 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(!
|
|
583
|
+
`);return n.write(" claude.ai chats live on your account, not this machine: bring those\n over with `anyray-connect history restore <export.zip>`.\n"),0},CI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=pK(e);if(o[0]==="helper")return mI(o.slice(1),t);let a=vK(o);if(a.help)return n.write(lK),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 xK(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:gI(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},f=a.artifact==="reg"?kK(u):a.artifact==="json"?wK(u):gK(u);return await bI(f,a.path,t),IK(r),a.path&&n.write(`Wrote ${a.path}
|
|
584
|
+
`),0}if(!a.helperPath?.trim())throw new Error(`--helper-path is required for fleet artifacts. Deploy it first with \`anyray-connect desktop helper --write\`; use ${jd} on macOS/Linux or ${Vd} 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(!Pi(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"&&Yd("windows",i);let l=SK(a),d;if(a.target==="claude")d=a.artifact==="reg"?bK(l,i):a.artifact==="json"?yK(l,i):mK(l,i);else{let u=CK(l,i);d=a.artifact==="mobileconfig"?AK(u):u}return await bI(d,a.path,t),EK(a.target,a.artifact,i,c,r),a.path&&n.write(`Wrote ${a.path}
|
|
585
585
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
586
|
-
`),1}};var
|
|
586
|
+
`),1}};var RK=`anyray-connect retrieve <handle> [--source auto|claude|profile]
|
|
587
587
|
|
|
588
588
|
Print the original content Anyray externalized behind a "\xB7 retrieve ctx_\u2026"
|
|
589
589
|
marker. The content is written to stdout byte-for-byte (no trailing newline
|
|
@@ -593,7 +593,7 @@ Options:
|
|
|
593
593
|
--source <s> Which client config resolves the gateway: auto (default),
|
|
594
594
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
595
595
|
--help Show this help.
|
|
596
|
-
`,
|
|
596
|
+
`,OK=`anyray-connect recall <query> [--k N] [--source auto|claude|profile]
|
|
597
597
|
|
|
598
598
|
Semantic search over your externalized tool outputs. Prints one match per line
|
|
599
599
|
to stdout as: handle<TAB>score<TAB>preview. Fetch a full original with
|
|
@@ -604,36 +604,36 @@ Options:
|
|
|
604
604
|
--source <s> Which client config resolves the gateway: auto (default),
|
|
605
605
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
606
606
|
--help Show this help.
|
|
607
|
-
`,
|
|
607
|
+
`,AI=(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},_K=e=>e.replace(/[\t\r\n]+/g," ").trim(),vI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=AI(e,!1);if(o.help)return n.write(RK),0;let a=o.positional?.trim();if(!a)return r.write(`A handle is required: anyray-connect retrieve ctx_\u2026 (see --help)
|
|
608
608
|
`),1;let s=await(t.readTarget??nt)(o.source),i=await(t.retrieve??Ea)(s,a,{probe:!0});return i.ok?(n.write(i.content),0):(r.write(`${i.message}
|
|
609
609
|
`),1)}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
610
|
-
`),1}},
|
|
610
|
+
`),1}},SI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=AI(e,!0);if(o.help)return n.write(OK),0;let a=o.positional?.trim();if(!a)return r.write(`A query is required: anyray-connect recall "what to find" (see --help)
|
|
611
611
|
`),1;let s=await(t.readTarget??nt)(o.source),i=await(t.recall??xd)(s,a,o.k,{probe:!0});if(!i.ok)return r.write(`${i.message}
|
|
612
612
|
`),1;if(i.matches.length===0)return r.write(`No matching externalized outputs found.
|
|
613
|
-
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${
|
|
613
|
+
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${_K(c.preview)}
|
|
614
614
|
`)}return r.write(`Fetch a full original: anyray-connect retrieve <handle>
|
|
615
615
|
`),0}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
616
|
-
`),1}};import{promises as
|
|
616
|
+
`),1}};import{promises as nG}from"node:fs";var Sn=e=>typeof e=="string"?e:"",TK=e=>{let t=Sn(e.text).trim();if(t)return t;let n=e.content;if(!Array.isArray(n))return"";let r=[];for(let o of n){if(!o||typeof o!="object")continue;let a=Sn(o.text).trim();a&&r.push(a)}return r.join(`
|
|
617
617
|
|
|
618
|
-
`).trim()},
|
|
618
|
+
`).trim()},PK=e=>{let t=Sn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},LK=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=TK(r);if(!o)continue;let a=Sn(r.created_at).trim();t.push({role:PK(r),text:o,...a?{createdAt:a}:{}})}return t},Jd=e=>{let t;try{t=JSON.parse(e)}catch{return{ok:!1,conversations:[],skipped:0,message:"the file is not valid JSON"}}let n=Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.conversations)?t.conversations:null;if(!n)return{ok:!1,conversations:[],skipped:0,message:"expected a list of conversations \u2014 is this the conversations.json from a Claude data export?"};let r=[],o=0;for(let a of n){if(!a||typeof a!="object"){o+=1;continue}let s=a,i=LK(s.chat_messages??s.messages);if(i.length===0){o+=1;continue}let c=(Sn(s.uuid)||Sn(s.id)).trim(),l=(Sn(s.name)||Sn(s.title)).trim()||"Untitled conversation",d=Sn(s.created_at).trim(),u=Sn(s.updated_at).trim();r.push({uuid:c,title:l,...d?{createdAt:d}:{},...u?{updatedAt:u}:{},messages:i})}return{ok:!0,conversations:r,skipped:o}};import{createHash as XK}from"node:crypto";import{promises as Di}from"node:fs";import{homedir as TI}from"node:os";import{join as qd}from"node:path";import{promises as EI}from"node:fs";import zm from"node:path";var DK=4e4,NK=16*1024*1024,Li=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),Xd=async(e,t={})=>{let n=(e??"").trim();if(!n)return Li("","path is required");let r=t.cwd??process.cwd(),o=zm.resolve(r,n),a=zm.relative(r,o);if(a.startsWith("..")||zm.isAbsolute(a))return Li(n,"path is outside the workspace");let s=t.maxBytes??DK,i;try{let w=await EI.stat(o);if(!w.isFile())return Li(n,"not a regular file");let g=t.maxFileBytes??NK;if(w.size>g)return Li(n,`file too large to read (${w.size} bytes; limit ${g})`);i=await EI.readFile(o,"utf8")}catch(w){return Li(n,w instanceof Error?w.message:"read failed")}let c=i.split(`
|
|
619
619
|
`),l=Math.max(1,t.startLine??1),d=Math.min(c.length,t.endLine??c.length),u=l<=d?c.slice(l-1,d):[],f=u.join(`
|
|
620
620
|
`),p=l<=d?d:l,h=!1,m=!1;if(Buffer.byteLength(f,"utf8")>s){let w=0,g=0;for(let y of u){let b=Buffer.byteLength(y,"utf8")+(g===0?0:1);if(w+b>s)break;w+=b,g+=1}g===0?(f=Buffer.from(u[0]??"","utf8").subarray(0,s).toString("utf8").replace(/\uFFFD$/,""),p=l,h=!0):(f=u.slice(0,g).join(`
|
|
621
|
-
`),p=l+g-1),m=!0}return{ok:!0,content:f,path:n,lines:c.length,truncated:m,span:{startLine:l,endLine:p,...h?{partialLine:!0}:{}}}},
|
|
621
|
+
`),p=l+g-1),m=!0}return{ok:!0,content:f,path:n,lines:c.length,truncated:m,span:{startLine:l,endLine:p,...h?{partialLine:!0}:{}}}},qm=e=>{if(!e.ok)return`Read failed: ${e.message??"unknown error"}`;if(!e.truncated)return`${e.path}:
|
|
622
622
|
${e.content}`;let t=e.span?`lines ${e.span.startLine}-${e.span.endLine}`:"a prefix",n=e.span&&!e.span.partialLine&&e.span.endLine<e.lines?` Continue with anyray_read(path="${e.path}", startLine=${e.span.endLine+1}).`:"";return`${e.path} (truncated \u2014 showing ${t} of ${e.lines}).${n}
|
|
623
|
-
${e.content}`};import{spawn as
|
|
624
|
-
`)){if(r.length>=n)break;if(!o)continue;let a=o.indexOf(":");if(a<=0)continue;let s=o.indexOf(":",a+1);if(s<0)continue;let i=o.slice(0,a).replace(/^\.\//,""),c=Number(o.slice(a+1,s));if(!Number.isInteger(c)||c<=0)continue;let l=o.slice(s+1);r.push({file:i,line:c,text:
|
|
625
|
-
`);for(let
|
|
623
|
+
${e.content}`};import{spawn as $K}from"node:child_process";import{promises as Qm}from"node:fs";import ey from"node:path";var ty=400,MK=240,FK=4e3,UK=4e3,BK=512*1024,WK=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),xI=(e,t)=>e.length>t?e.slice(0,t):e,HK=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"]),KK=8,GK=2e3,jK=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],VK=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")},RI=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!HK.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=KK))break}return n},OI=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},YK=(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)},II=(e,t,n)=>{let r=[];for(let o of e.split(`
|
|
624
|
+
`)){if(r.length>=n)break;if(!o)continue;let a=o.indexOf(":");if(a<=0)continue;let s=o.indexOf(":",a+1);if(s<0)continue;let i=o.slice(0,a).replace(/^\.\//,""),c=Number(o.slice(a+1,s));if(!Number.isInteger(c)||c<=0)continue;let l=o.slice(s+1);r.push({file:i,line:c,text:xI(l,t)})}return r},ZK=(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 jK)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=$K("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=II(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=II(d,o,r+1),w=m.length>r;f({ok:!0,matches:w?m.slice(0,r):m,truncated:w,engine:"ripgrep"})})}),JK=async(e,t,n,r,o,a,s)=>{let i=OI(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 Qm.readdir(m,{withFileTypes:!0})}catch{return}for(let g of w){if(u.length>=r||Date.now()>a){p=!0;return}let y=ey.join(m,g.name);if(g.isDirectory()){if(WK.has(g.name))continue;await h(y)}else if(g.isFile()){if(f>=UK){p=!0;return}if(d.length&&!d.some(v=>g.name.endsWith(v))||VK(ey.relative(t,y)))continue;f+=1;let b;try{if((await Qm.stat(y)).size>BK)continue;b=await Qm.readFile(y,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let A=b.split(`
|
|
625
|
+
`);for(let v=0;v<A.length;v+=1){let E=c(A[v]);if(l.some(I=>E.includes(I))&&(u.push({file:ey.relative(t,y),line:v+1,text:xI(A[v],o)}),u.length>=r)){p=!0;return}}}}};return await h(t),{ok:!0,matches:u,truncated:p,engine:"walk"}},zd=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??ty,s=t.maxColumns??MK,i=t.timeoutMs??FK,c=Date.now()+i,l=RI(n),d=l.length>1,u=Math.min(a*4,GK),f=(g,y)=>JK(n,r,o,g,s,c,y),p=async g=>{let y=await g(u,l);if(!y.ok)return y;let b=YK(y.matches,l,OI(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)=>ZK(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))},_I=(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=RI(e).length>1?" Searched the phrase and each word separately. Try one identifier on its own (a function, type, or error string), or narrow with globs.":" Try a shorter or differently-cased fragment, or narrow with globs.";return`No matches for "${e}".${d}`}let r=t.matched==="tokens"&&t.tokens?.length?`No line contains "${e}"; showing lines matching its terms (${t.tokens.join(", ")}), most complete first.
|
|
626
626
|
`:"";if(n==="paths"){let d=new Map;for(let f of t.matches)d.set(f.file,(d.get(f.file)??0)+1);let u=[...d].map(([f,p])=>`${f} (${p} match${p===1?"":"es"})`);return[`${r}${d.size}${t.truncated?"+":""} file${d.size===1?"":"s"} match "${e}":`,...u].join(`
|
|
627
627
|
`)}let o=`${r}${t.matches.length}${t.truncated?"+":""} matches for "${e}":`,a=t.matches.map(d=>n==="lines"?`${d.file}:${d.line}`:`${d.file}:${d.line}: ${d.text}`),s=d=>`\u2026 ${d} more match${d===1?"":"es"} not shown (output limit). Narrow with globs or a more specific query, or set resultShape:"paths" to see every file.`,i=s(a.length).length+1,c=o.length,l=0;for(let d of a){if(c+1+d.length+i>4e4)break;c+=1+d.length,l+=1}return l>=a.length?[o,...a].join(`
|
|
628
628
|
`):[o,...a.slice(0,Math.max(1,l)),s(a.length-Math.max(1,l))].join(`
|
|
629
|
-
`)};var
|
|
629
|
+
`)};var PI=448,zK=384,qK=4e4,Pr=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=qd(TI(),".anyray");try{if((await Di.stat(t)).isDirectory())return qd(t,"history")}catch{}return qd(TI(),".anyray-history")},QK=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:eG(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},eG=e=>{let t=XK("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)},tG=e=>{let t=[`# ${e.title}`,"",e.createdAt?`- Created: ${e.createdAt}`:"",e.updatedAt?`- Updated: ${e.updatedAt}`:"",e.uuid?`- Claude conversation id: ${e.uuid}`:"",""].filter((r,o,a)=>!(r===""&&a[o-1]==="")),n=e.messages.map(r=>{let o=r.role==="user"?"User":"Claude",a=r.createdAt?` (${r.createdAt})`:"";return`## ${o}${a}
|
|
630
630
|
|
|
631
631
|
${r.text}
|
|
632
632
|
`});return[...t,...n].join(`
|
|
633
633
|
`).replace(/\n{3,}/g,`
|
|
634
634
|
|
|
635
635
|
`)+`
|
|
636
|
-
`},Qd=async e=>{let t=await
|
|
636
|
+
`},Qd=async e=>{let t=await Pr();await Di.mkdir(t,{recursive:!0,mode:PI});try{await Di.chmod(t,PI)}catch{}let n=0,r=0;for(let o of e)try{await Di.writeFile(qd(t,QK(o)),tG(o),{mode:zK}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Fa=async()=>{try{let e=await Pr();return(await Di.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},LI=async e=>{let t=await Pr();return zd(e,{cwd:t,globs:["*.md"]})},DI=async e=>{let t=await Pr();return Xd(e,{cwd:t,maxBytes:qK})};var NI=`anyray-connect history <command>
|
|
637
637
|
|
|
638
638
|
Make past Claude conversations searchable from any Anyray-connected client.
|
|
639
639
|
|
|
@@ -654,7 +654,7 @@ Which one you want:
|
|
|
654
654
|
conversation into the chat when you ask for it. Recall, not a list.
|
|
655
655
|
|
|
656
656
|
Running both is fine, and gets you both.
|
|
657
|
-
`,
|
|
657
|
+
`,rG=async e=>{try{return{raw:await nG.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"})`}}},oG=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 rG(t);if("error"in n)return _(n.error),1;let r=Jd(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 Qd(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 $(`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},aG=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 Yl(t);return n.ok?($(`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)},sG=async()=>{let e=await Pr(),t=await Fa();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):($(`${t} conversation${t===1?"":"s"} in ${e}`),0)},$I=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(NI),0):t==="import"?oG(e.slice(1)):t==="restore"?aG(e.slice(1)):t==="status"?sG():(_(`Unknown history command: ${t}`),console.log(NI),1)};import{promises as iG}from"node:fs";var cG=`anyray-connect migrate [options]
|
|
658
658
|
|
|
659
659
|
Bring what Claude Desktop was showing you onto Anyray. Quit Claude Desktop first.
|
|
660
660
|
|
|
@@ -683,50 +683,50 @@ Getting the export (you do this, not Anyray \u2014 it needs your Claude login):
|
|
|
683
683
|
Open claude.ai -> Settings -> Privacy -> Export data. Anthropic emails a link.
|
|
684
684
|
Pass the .zip to --export, and the conversations.json inside it to
|
|
685
685
|
--conversations. Both are safe to re-run; they skip what is already there.
|
|
686
|
-
`,
|
|
687
|
-
`).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${
|
|
686
|
+
`,lG=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},MI={code:"Claude Code sessions",cowork:"Cowork tasks"},dG=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`${MI[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},uG=async(e,t)=>{k(j("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??po)({account:e.account,allAccounts:e.allAccounts,command:"anyray-connect migrate"});if(!n.ok){_(` ${n.reason}`);for(let s of n.remedy.split(`
|
|
687
|
+
`).filter(Boolean))k(` ${s}`);return!1}for(let s of n.lanes)k(` ${dG(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(` ${MI[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),k(` ${Th(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},pG=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 Yl(e.exportZip);if(!n.ok){_(` ${n.reason}`),k(` ${n.remedy}`);return}$(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),k(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);$(` 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.`))}},fG=async e=>{if(k(""),k(j("3. Searchable from every Anyray client")),!e.conversations){let o=await Fa();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 iG.readFile(e.conversations,"utf8")}catch{_(` could not read ${e.conversations}`);return}let n=Jd(t);if(!n.ok){_(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await Qd(n.conversations);$(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),k(S(` Ask any Anyray-connected client about a past chat. ${await Pr()}`))},hG=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`."))},FI=async(e,t={})=>{let n;try{n=lG(e)}catch(o){return _(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(cG),0;k(j("Migrating Claude Desktop onto Anyray")),k(S("Claude Desktop must be fully quit.")),k("");let r=await uG(n,t);return await pG(n,!r),await fG(n),r?(hG(n),0):(k(""),D("Fix the item above and re-run to finish the migration."),1)};var mG=3e3,eu=async(e,t={})=>{let n=t.timeoutMs??mG,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`:yt(s).trim()||"connection failed"}}finally{clearTimeout(a)}};var yG="enl_",gG="enp_",UI=e=>e.startsWith(yG)||e.startsWith(gG),wG=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],ny=e=>wG.find(t=>e.startsWith(t.prefix)),BI=/^\/enroll\/([^/]+)\/?$/,WI=/^\/i\/([^/]+)\/?$/,HI=e=>{let t=e.match(BI);if(t)return ny(t[1])?void 0:t[1];let n=e.match(WI);return n&&UI(n[1])?n[1]:void 0},bG=1e4,tu=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=HI(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!ny(t))return{cpOrigin:Yn(),token:t}},KI=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(BI)??o.pathname.match(WI);if(!a)return;n=a[1]}catch{}let r=ny(n);return r?{flag:r.flag,what:r.what}:void 0},$i=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:HI(n.pathname)!==void 0}catch{return UI(t)}},Ni=e=>typeof e=="string"&&e.trim()?e.trim():void 0,GI=async(e,t={})=>{let n=t.timeoutMs??bG,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.`:yt(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"&&Ni(u.url)!==void 0),d=Ni(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:Ni(l?.deploymentId),org:Ni(i.org),email:Ni(i.email),seatMode:i.seatMode===!0}};var jI=()=>Fm(),VI=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??jI)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},kG=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},YI=async(e,t={})=>{let n=(t.openInput??jI)(),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=Pa(o,t.env??process.env),l=(h,m)=>c?`\x1B[${h}m${m}\x1B[0m`:m,d=()=>{let h=[l("1",e.title)];for(let m=0;m<e.items.length;m++){let w=e.items[m],g=m===s?l("36","\u276F"):" ",y=e.single?a[m]?"(\u25CF)":"(\u25CB)":a[m]?"[x]":"[ ]",b=w.hint?` ${l("2",w.hint)}`:"";h.push(`${g} ${y} ${w.label}${b}`)}h.push(l("2",e.single?"\u2191/\u2193 move \xB7 space choose \xB7 enter accept \xB7 q cancel":"\u2191/\u2193 move \xB7 space toggle \xB7 a toggle all \xB7 enter accept \xB7 q cancel")),i>0&&o.write(`\x1B[${i}A`),o.write(h.map(m=>`\r\x1B[2K${m}`).join(`
|
|
688
688
|
`)),o.write(`
|
|
689
689
|
`),i=h.length},u=()=>{i!==0&&(o.write(`\x1B[${i}A`),o.write(Array.from({length:i},()=>`\r\x1B[2K
|
|
690
|
-
`).join("")),o.write(`\x1B[${i}A`))},f=!!r.isRaw,p=!1;try{return p=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((h,m)=>{let w=()=>{r.off("data",
|
|
691
|
-
`)&&g({kind:"ok",values:[]});continue}if(I==="\x1B[A"||I==="k")s=(s-1+e.items.length)%e.items.length,d();else if(I==="\x1B[B"||I==="j")s=(s+1)%e.items.length,d();else if(I===" "){if(e.single){let C=!a[s];a.fill(!1),a[s]=C}else a[s]=!a[s];d()}else if(I==="a"&&!e.single){let C=e.items.map((
|
|
692
|
-
`){g({kind:"ok",values:e.items.filter((C,x)=>a[x]).map(C=>C.value)});return}}}catch(I){y(I)}};r.on("data",
|
|
693
|
-
`),t();let a=0,s=()=>{r.write(`\r${
|
|
694
|
-
`)){let[r,o]=n.trim().split(/\s+/);if(!r||!o)continue;if((o.startsWith("*")?o.slice(1):o)===t&&/^[0-9a-f]{64}$/i.test(r))return r.toLowerCase()}},jI=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&&Ba(e.current,e.minVersion)<0&&Ba(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},_G=e=>Ba(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}:{...jI(e),downgradeBlocked:!1},Ha=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",PG=(e=process.execPath)=>{let t=Uu(e);return t?Pr(t):Pr(Pr(e))},TG=async(e=ft())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=ut(PG(e.execPath),"bin",Ha());try{if(await ru(t)!==await ru(e.execPath))return}catch{return}return t},ay=async(e=ft(),t=ee())=>{let n=await TG(e);if(n)return{kind:"managed",root:Pr(Pr(n)),link:n,entryPath:Qn(e)};let r=Qn(e);return Hu(r,t)?{kind:"durable",root:t,entryPath:r}:Mu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},au=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),t);try{return await fetch(e,{...n,signal:r.signal})}finally{clearTimeout(o)}},sy=async(e=ou)=>{let t=await au(`${WI}/latest`,e,{redirect:"manual"});return OG(t.headers.get("location"))},LG=async e=>{try{let t=await au(`${e}/connect-update.json`,ou);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}},Fi=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},iy=async(e,t,n)=>{let r=await au(e,IG);if(!r.ok||!r.body)throw new Fi(r.status);let o=CG("sha256"),a=0;if(await vG(AG.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>EG)throw new Error("asset exceeds size cap");o.update(c),yield c}},mG(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},DG=e=>Qm(e)===Ha()?Qm(Pr(e)):Qm(e),NG=async e=>{let t=await ry(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Rt(ut(e,n),{force:!0}).catch(()=>{})},VI=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Rt(r,{force:!0}).catch(()=>{});let o=!1;try{await nu(e,r),o=!0}catch{}try{await ty(t,e),await kG(ns(e),DG(t))}catch(a){throw o&&await nu(r,e).catch(()=>{}),a}await Rt(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Rt(n,{force:!0}),await bG(t,n),await nu(n,e)},$G=async(e,t={})=>{let n=ut(e.root,"bin"),r=ut(e.root,"versions"),o=ut(n,Ha());await Ua(n,{recursive:!0,mode:448}),await Ua(r,{recursive:!0,mode:448});let a=ut(r,e.version),i=(await ny(a).catch(()=>{}))?.isFile()?a:ut(a,Ha());if(!(await ny(i).catch(()=>{}))?.isFile()){let l=await(t.fetchResponse??au)(`${e.tagUrl}/SHA256SUMS`,ou),d=l.ok?oy(await l.text(),e.asset):void 0;if(!d)throw new Error("no published checksum");await Ua(Pr(i),{recursive:!0,mode:448}),await NG(Pr(i));let u=`${i}.part-${process.pid}`;try{await(t.download??iy)(`${e.tagUrl}/${e.asset}`,u,d),await gG(u,493),await nu(u,i)}catch(f){throw await Rt(u,{force:!0}).catch(()=>{}),f}}return await(t.activate??VI)(o,i),{link:o,target:i,versionsDir:r}},MG=async e=>{let t=yG(e,["--version"],{stdio:"ignore",timeout:ou});return!t.error&&t.status===0},FG=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??go)(n);if(r.length>0){let o=await(t.resolveTarget??Oe)(async()=>e);if(!o||!(await(t.repair??mt)(r,o.target)).every(yo))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??lr)()).ok||e.keyRefreshEnabled&&(!e.gateway||!e.fallbackPort||!(await(t.installDaemon??Dt)({port:e.fallbackPort,remoteOrigin:e.gateway})).ok))},UG=async e=>{let t=await e.install();if(!await(e.smoke??MG)(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},BG=async(e,t)=>{let n=await ry(e).catch(()=>[]);for(let r of n)t.includes(r)||await Rt(ut(e,r),{force:!0,recursive:!0}).catch(()=>{})},HG=async e=>{let t=await ry(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Rt(ut(e,n),{force:!0}).catch(()=>{})},WG=async(e,t)=>{let n=async()=>{await Rt(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await Ua(e,{recursive:!1}),n}catch{}let r=await wG(e).catch(()=>{});if(!(!r||t-r.mtimeMs<RG)){await n();try{return await Ua(e,{recursive:!1}),n}catch{return}}},ey=e=>ut(e,"update-state.json"),KG=async e=>{let t=await M(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},GG=1e3,jG=16*6e4,VG=e=>e.inFlight===0,YG=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??jG);for(;;){let i=await r(e).catch(()=>null);if(i!==null&&i.version===t&&VG(i))return!0;if(a()>=s)return!1;await o(GG)}},Ui=async(e={})=>{let t=e.now??Date.now,n=we;if(kt(ht(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??ft(),o=e.root??ee(),a;try{let s=await ay(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=GI(e.platform??process.platform,e.arch??process.arch);if(!c)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??sy)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let l=a;if(!i&&l===n)return{outcome:"current",current:n,latest:l};if(i&&Ba(l,n)<0)return{outcome:"migration-deferred",current:n,latest:l};let d=e.force===!0,u=await KG(ey(o));if(!d&&u.failedVersion===l&&u.failedAt!==void 0&&t()-u.failedAt<xG)return{outcome:"failed",current:n,latest:l};let f=`${WI}/download/${KI}${l}`,p=await(e.load??T)().catch(()=>({})),h=p.autoUpdate!==!1,m=h||d?void 0:await(e.minimumVersion??LG)(f),w={current:n,latest:l,autoUpdate:h,forced:d,minVersion:m},g=i?_G(w):{...jI(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 bt():await Ua(o,{recursive:!0,mode:448});let y=await WG(ut(o,"update.lock"),t());if(!y)return{outcome:i?"migration-available":"available",current:n,latest:l};let b,A;try{await HG(ut(o,"bin"));let I=await ru(ut(o,"versions")).catch(()=>{}),C=await ru(ut(o,"bin",Ha())).catch(()=>{}),x=C&&pc(C,I)?C:void 0,P=ut(o,"bin",Ha());i&&process.platform==="win32"&&(await ny(P).catch(()=>{}))?.isFile()&&(A=`${P}.rollback-${process.pid}`,await ty(P,A));let U=()=>(e.installBinary??$G)({root:o,version:l,asset:c,tagUrl:f});i?b=await UG({install:U,smoke:e.smoke,rollback:async({link:Z,target:Y})=>{A?(await ty(A,Z),await Rt(ns(Z),{force:!0}).catch(()=>{})):x&&x!==Y?await VI(Z,x):(await Rt(Z,{force:!0}),await Rt(ns(Z),{force:!0}).catch(()=>{}))},repoint:async Z=>e.repoint?e.repoint(p,Z):FG(p),prune:async()=>{await(e.pruneDurable??(Z=>fc(Z)))(r)}}):b=await U(),await BG(b.versionsDir,[l,n]),await Rt(ey(o),{force:!0}).catch(()=>{})}finally{A&&await Rt(A,{force:!0}).catch(()=>{}),await y()}let S=e.bounceDaemon??tp,E=p.persistenceOwner==="tray";if(!i&&(p.refreshSchedulerEnabled||p.keyRefreshEnabled)){let I=p.fallbackPort??ke,C=E?!0:await lw().catch(()=>!0),x=await S(p.fallbackPort,{drain:"idle"}).catch(()=>!1);!C&&p.gateway&&((x?await(e.waitForDaemon??YG)(I,l):!0)?await Dt({port:I,remoteOrigin:p.gateway}).catch(()=>{}):await(e.writeUnitFile??uw)().catch(()=>!1))}return{outcome:i?"migrated":"updated",current:n,latest:l,managedPath:b.link,mandatory:g.mandatory}}catch{return a&&await X(ey(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},YI=async(e={})=>{let t=e.context??ft(),n=await ay(t,e.root??ee()),r=$o(e.root??ee());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:we,managedPath:n.link??r}:Ui({...e,context:t,allowNpmMigration:!0})},Io=async(e={})=>{let t=e.context??ft(),n=e.root??ee(),r=await ay(t,n),o=r.kind==="npm"||r.kind==="durable"?$o(n):void 0,a=await(e.load??T)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!GI(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=kt(ht(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 ZG=async(e,t)=>{if(!e.gateway||!e.clientKey)return;let n=await t().catch(()=>{});return ye({origin:e.gateway,clientKey:e.clientKey,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:n,user:e.name,team:e.team})},ZI=(e,t)=>e.keyRefreshEnabled===t.keyRefreshEnabled&&e.fallbackPort===t.fallbackPort,XG=(e,t)=>async n=>{let r=await e(),{next:o,result:a}=n(r);return o&&await t(o),a},cy=async(e={})=>{let t=e.load??T,n=e.save??re,r=e.mutate??(e.load||e.save?XG(t,n):bg),o=e.loadDevKey??Ue,a=e.heartbeat??vd,s=e.detectSeat??Nt,i=e.rewriteTools??ki,c=e.uninstallProxy??zt;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 Sr&&y.status===404?"unsupported":"pending"}let p=await r(y=>{if(y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||!ZI(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 ZG(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://${pt}:${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"||!ZI(y,p)?{result:!1}:{next:{...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"complete",keyRefreshEnabled:!1,fallbackPort:void 0},result:!0})?((m||l.fallbackPort!==void 0)&&await c(w).catch(()=>{}),"migrated"):"pending"}catch{return"pending"}};var JG=12e3,qG="anyray-wiring-probe-not-a-real-token",zG={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},dy={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},xo=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},JI=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},uy=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},XI=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."],QG=e=>e.includes("no provider key configured for"),py=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},fy=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>"]}),Bi=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."]}),ej=(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?py(t)?fy(e):uy(t)?Bi(e):JI(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${xo(t)}`,remedy:["The org provider rejected the request \u2014 check the gateway\u2019s provider","key/config (e.g. the model is enabled for that account)."]}:QG(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${xo(t)}`,remedy:["Your enrollment key is fine \u2014 the gateway has NO server-side provider","key configured (org-key mode), so it refused to forward the request.","Fix: add a provider key in the console \u2192 Providers.",...n.includes("opencode")?XI([" \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}): ${xo(t)}`,remedy:n.includes("opencode")?["Your enrollment key is fine \u2014 the gateway forwarded the request and the","upstream model provider refused the credential it was given: this","gateway has no WORKING provider key for it (either none is configured,","or the configured one is wrong or revoked).",...XI([" \u2022 open the console \u2192 Providers and add a key for that provider, or"," replace the one already listed (fixes it for everyone), or"])]:["Your enrollment key is fine \u2014 the gateway forwarded the request and the","upstream model provider refused it.","Open the console \u2192 Providers: if no key is listed for that provider,","add one; if a key IS listed, it is wrong, revoked, or not entitled to","the model \u2014 replace it.","Either way this is gateway config, not your enrollment. Alternatively,","sign in with your own provider subscription instead of the org key.","If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]}:{kind:"unknown",detail:`gateway responded HTTP ${e}: ${xo(t)}`,remedy:[]},tj=(e,t)=>{if(uy(t))return Bi(e);if(py(t))return fy(e);if(JI(t))return{kind:"routed-elsewhere",detail:"gateway sent the request to the org provider, not your subscription.",remedy:["Pass-through isn\u2019t being honored for this gateway \u2014 your seat token would","not be used. Check the gateway is current (subscription pass-through support)."]};let n=t.toLowerCase();return e===401||n.includes("authentication_error")||n.includes("invalid bearer")||n.includes('"provider":"anthropic"')?{kind:"ok",detail:"gateway passes your sign-in through to Anthropic \u2014 your Claude seat will be used.",remedy:[]}:e>=200&&e<300?{kind:"ok",detail:"gateway pass-through reached the provider \u2014 your seat will be used.",remedy:[]}:{kind:"unknown",detail:`seat-wiring probe got HTTP ${e}: ${xo(t)}`,remedy:[]}},nj=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),rj=(e,t)=>{if(uy(t))return Bi(e);if(py(t))return fy(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")||nj(n));return e>=200&&e<300||r?{kind:"ok",detail:e>=200&&e<300?"gateway served a completion through the configured BYO upstream.":`gateway authenticated and reached the configured BYO upstream, which rejected this probe's fixed model (HTTP ${e}).`,remedy:[]}:{kind:"unknown",detail:`BYO-upstream probe got HTTP ${e}: ${xo(t)}`,remedy:[`The probe asks for a fixed model (${dy.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."]}},ly=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)}},oj=async(e,t)=>{if(!e.clientKey)return Bi(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?Bi(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${xo(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},aj=(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."]}},Hi=async(e,t={})=>{let n=t.timeoutMs??JG,r=de(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await oj(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 ly(`${e.anthropicBaseUrl}/v1/messages`,l,dy,n);return rj(d,u)}if(J(e,"anthropic")){let l={Authorization:`Bearer ${qG}`,"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 ly(`${e.anthropicBaseUrl}/v1/messages`,l,dy,n);return tj(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await ly(`${e.openaiBaseUrl}/chat/completions`,s,zG,n);return ej(i,c,t.tools??[])}catch(o){return aj(n,o)}};var qI=async e=>{let t=await T(),n;try{n=Rr(e.gateway,t)}catch(s){return k(j("Anyray connect \u2014 status")),F(`Gateway: ${s.message}`),0}k(j("Anyray connect \u2014 status")),K("Gateway"),k(` Origin: ${et(n)}`),t.gateway?F(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?F(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||F(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),K("Identity"),k(` Name: ${t.name??v("(not set)")}`),k(` Team: ${t.team??v("(not set)")}`);let r=ht();r&&(K("Environment"),k(` Remote dev context: ${ir(r)}`),kt(r)&&F(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),F(" VS Code tools configure the remote server variant backing this window.")),t.credentialProtocol==="stable-heartbeat-v1"&&(K("Credential renewal"),t.directMigration==="pending"?(k(" Stable-key heartbeat active; direct-routing migration is still completing."),F(" The local proxy remains available until every managed tool moves.")):($(" Direct gateway routing with a proof-backed stable-key heartbeat."),F(" Renewal extends the same key; tool configuration is not rewritten.")));let o=!!(tt(t)&&t.fallbackPort),a=o?`http://${pt}:${t.fallbackPort}`:n;o&&(K("Local key-refresh proxy"),await be(t.fallbackPort)?$(` Running on 127.0.0.1:${t.fallbackPort} \u2192 ${n} `+v("(auto-refreshes your key so long sessions never 401)")):(L(` Enabled on 127.0.0.1:${t.fallbackPort} but NOT responding \u2014 your tools cannot reach any gateway until it's back.`),k(v(" Re-run `anyray-connect`, or check the service logs.")))),K("Tools");for(let s of se){if(!(await s.detect()).installed){F(` ${s.title}: not installed`);continue}if(!s.pointsAt){F(` ${s.title}: installed ${v("(status not introspectable)")}`);continue}let c=await s.pointsAt(Pi(s.id,n,a));if(c){if(s.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){$(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),k(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}$(` ${s.title}: pointed at Anyray${o&&_i(s.id)?v(" (via key-refresh proxy)"):""}`)}else{let l=null,d=null;if(s.id===$a&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,f=await Wd();l=Kd({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=Gd(l,d);L(` ${s.title}: ${u.headline}`);for(let f of u.detail)k(v(` ${f}`))}else F(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as uj}from"node:fs";import{isAbsolute as pj}from"node:path";import{access as sj}from"node:fs/promises";import{constants as ij}from"node:fs";import{platform as cj}from"node:os";var lj=async e=>{try{return await sj(e,ij.F_OK),!0}catch{return!1}},dj=e=>e==="darwin"?["/Library/LaunchDaemons/com.fleetdm.orbit.plist","/opt/orbit/bin/orbit"]:e==="linux"?["/etc/systemd/system/orbit.service","/usr/lib/systemd/system/orbit.service","/opt/orbit/bin/orbit"]:e==="win32"?["C:\\Program Files\\Orbit\\bin\\orbit\\orbit.exe"]:[],Ro=async(e={})=>{let t=e.os??cj(),n=e.exists??lj;for(let r of dj(t))if(await n(r))return!0;return!1};var Yt="connect",hy=e=>e.replace(/-/g,"_"),zI=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:Yt,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:Yt,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:Yt,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.fallbackProxy.enabled&&t.push({tool:Yt,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:Yt,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:Yt,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:Yt,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=hy(e.retrieval.kind);t.push({tool:Yt,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":hy(e.verify.kind);t.push({tool:Yt,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:Yt,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:hy(e.hookLane.reason)}:{}})}t.push({tool:Yt,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)i.installed&&(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp&&t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing"}),a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"}));return t.push({tool:Yt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function fj(){return we}var hj="ctx_doctor-probe-synthetic",mj=(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: ${gy(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 yj(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function gj(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function gy(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 QI=e=>Kd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),my=e=>e.pointedAt===!1&&e.tombstoned!==!0&&QI(e)!=="unverifiable",ex=e=>e.registered&&e.command&&pj(e.command)?uj(e.command):null,yy=e=>(my(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),wj=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,bj=async(e,t)=>{if(e.length===0)return!1;for(let n of e){let r=t.find(a=>a.id===n);if(!r?.inferenceAuthLanes)return!1;let o=await r.inferenceAuthLanes().catch(()=>["unknown"]);if(o.length===0||o.some(a=>a!=="subscription"&&a!=="native"))return!1}return!0},tx=async e=>{for(let t of e)if(t.integrationStatus)try{if(!(await t.detect()).installed)continue;if((await t.integrationStatus()).hook_registration==="owned")return!0}catch{}return!1},kj=(e,t)=>{let n=c=>typeof c=="object"&&c!==null&&!Array.isArray(c),r=c=>typeof c=="number"&&Number.isSafeInteger(c)&&c>=0&&Number.isFinite(new Date(c).getTime()),o=new Set(t.map(c=>c.id)),a=new Set(ko),s=[],i=n(e.selfcheck?.adapters)?e.selfcheck.adapters:{};for(let[c,l]of Object.entries(i)){if(!o.has(c)||!n(l))continue;let d=n(l.lastRepaired)?l.lastRepaired:{},u=Object.entries(d).filter(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},Cj=async(e,t,n,r,o,a,s=n,i=Hi,c=!0,l=vo,d=Io,u=Kt,f=Ia)=>{let p=c?await eu(e):null,h=!!(tt(t)&&t.fallbackPort),m=h?await be(t.fallbackPort):null,w=h?`http://${pt}:${t.fallbackPort}`:e,g=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,y=V=>V&&Lm(V)?"machine_default":null,b=t.enrolledCert?.payload,A=b?.expiresAt??t.enrolledCertExpiry??null,E=(await a())?.sso??null,I=gj({ssoLink:E,enrolledViaToken:!!t.enrolledTokenHash}),C=Ct(),x=await Bw(C),P=x?[]:jw(ye({origin:w})),U=[];for(let V of r){let Ee=await V.detect(),wt=null;if(Ee.installed&&V.mcpStatus)try{let _o=await V.mcpStatus();wt={..._o,commandOk:ex(_o)}}catch{}let qn=Ee.installed&&V.id===$a?await o():void 0,Ot=Ee.installed&&V.pointsAt?await V.pointsAt(Pi(V.id,e,w)):null,Dr=await wj(Ot,V,t.managedTools??[]),Qi=Ot===!1&&Dr===null,ec=Dr===!1&&V.routingPendingReload?await V.routingPendingReload().catch(()=>!1):!1,Va=Ee.installed?V.runtimeDiagnostics?await V.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:V.routingOverrides?await V.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Ya,claudeCodeHookPolicy:tc}=Va,Za=t.fleetToolPolicy,Xa=Za?.enabled.includes(V.id)?Za.tiers?.[V.id]??va:void 0;U.push({id:V.id,title:V.title,installed:Ee.installed,...Ee.detail?{detail:Ee.detail}:{},pointedAt:Dr,...Qi?{routingHeld:!0}:{},...ec?{routingPendingReload:!0}:{},...Ya.length?{routingOverrides:Ya}:{},...tc===void 0?{}:{claudeCodeHookPolicy:tc},mcp:wt,...Xa?{policyTier:Xa}:{},...t.revertedTools?.includes(V.id)?{tombstoned:!0}:{},...V.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...qn===void 0?{}:{inferenceIntrospectable:qn.authoritative,...qn.authoritative?{}:{inferenceUnverifiableReason:qn.reason}}})}let Z=s?await(async()=>{let{kind:V,detail:Ee,remedy:wt}=await i(ye({origin:e,clientKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey,subscription:t.authMode==="subscription",placeholder:t.authMode==="placeholder",byoUpstream:t.byoUpstream,...t.authMode==="auto"?{seat:{anthropic:!1,openai:!1,copilot:!1}}:{},user:t.name,team:t.team}),{tools:t.managedTools??[]});return{kind:V,detail:Ee,remedy:wt}})():null,Y=Z?.kind==="provider-rejected"&&await bj(t.managedTools??[],r),H=Z?{...Z,...Y?{notApplicableSubscription:!0}:{}}:null,q=n?mj(await Ea({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:de({user:t.name,team:t.team})},hj,{probe:!0}),{mode:I,ssoLink:E}):null,me=await u().catch(()=>({})),Te=Cn(me.hookLane),ne=s?await tx(r):!1,We=ne?await(async()=>{let V=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...om(V,{hookRegistered:ne,neverInvoked:nm(Te,Date.now())}),lastInvokedAt:Ed(Te)}})():null,Le=(await ur()).map(V=>({adapter:V.adapter,op:V.op,requestedAt:V.requestedAt,watcherAlive:fr(V.watcherPid)})),O=Le.find(V=>V.adapter==="cursor"),D=O?{op:O.op,requestedAt:O.requestedAt,watcherAlive:O.watcherAlive}:null,W=!!t.refreshSchedulerEnabled,pe=await Lc(),z=await d(),Ve=t.persistenceOwner==="tray",Me=Ve?await l(t)==="healthy":null,Q=await wE({daemonEnabled:h&&!Ve,daemonHealthy:h?!!m:null,schedulerEnabled:W&&!Ve,schedulerInstalled:pe,binaryDurable:!Ge(sr())}),Fe=await Lu(),De=0;p&&!p.reachable&&(De+=1),h&&!m&&(De+=1),Ve?W&&!Me&&(De+=1):W&&!pe&&(De+=1);for(let V of U)De+=yy(V);return H&&H.kind!=="ok"&&!H.notApplicableSubscription&&(De+=1),q&&q.kind!=="ok"&&(De+=1),We?.verdict==="dark"&&(De+=1),P.length>0&&(De+=1),De+=Le.filter(V=>!V.watcherAlive).length,Fe.length>0&&(De+=1),{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:fj(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:ht(),selfUpdate:{managed:z.managed,available:z.available,autoUpdate:z.autoUpdate,state:z.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:W,installed:pe,owner:Ve?"tray":"os",...Ve?{trayHealthy:!!Me}:{}},serviceRemoval:Q,retiredFallbackState:Fe,fleetdPresent:await Ro(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:g,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:y(t.name)},enrollment:{enrolled:!!b,deploymentId:b?.deploymentId??null,issuedAt:b?.issuedAt??null,expiresAt:A,expired:A?Date.parse(A)<Date.now():null,orgMode:I,ssoLink:E},shell:{profilePath:C,blockPresent:x,staleExports:P},tools:U,...t.fleetToolPolicy?{fleetPlan:wd(t,t.fleetToolPolicy,!1)}:{},cursorQueue:D,pendingOps:Le,ambientRepairs:kj(me,r),verify:H,retrieval:q,hookLane:We,problems:De}},Aj=e=>{if(e.serviceRemoval.suspected){K("Endpoint security"),L(" Anyray installed these background services, but their files are gone from disk \u2014"),L(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),L(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)k(v(` missing: ${t}`));k(v(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),k(v(" tools straight at the gateway (your key then needs a periodic re-run).")),k(v(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),k(v(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},vj=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(v(` ${t}`));k(v(" Fix: `anyray-connect doctor --repair` deletes it (a normal `anyray-connect` run does too)."))}},Sj=e=>{switch(k(j("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(K("Environment"),k(` Remote dev context: ${ir(e.connect.remoteContext)}`),kt(e.connect.remoteContext)&&k(v(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."))),K("CLI updates"),e.connect.selfUpdate.state){case"managed":$(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||L(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":L(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),k(v(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":L(" Self-update is unavailable on this platform because no standalone binary is published."),k(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":k(v(" This copy is externally managed; update it with the method that installed it."));break;case"container":k(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(K("Gateway"),e.gateway.reachable===null?k(v(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?$(` Reachable: ${e.gateway.origin} ${v(`(${e.gateway.detail})`)}`):(_(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),k(v(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.fallbackProxy.enabled&&(K("Local key-refresh proxy"),e.fallbackProxy.healthy?$(` Running on 127.0.0.1:${e.fallbackProxy.port} \u2192 ${e.gateway.origin} `+v("(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(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to point tools straight at the gateway.")))),e.refreshScheduler.enabled&&(K("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?$(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh and supervises the daemon."):(_(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),k(v(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?$(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(_(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||k(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),Aj(e),vj(e),K("Personal key"),yj(e)){case"env":$(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":$(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":L(" Enrolled, but no personal key is cached locally right now."),k(v(" Fix: re-run `anyray-connect` to re-mint it from your enrollment \u2014 no need to re-enroll. Claude Code and Codex are still attributed to you by name."));break;default:L(" Enrollment required \u2014 no personal gateway key is available."),k(v(` Fix: ${gy(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?L(` Enrollment cert expired ${v(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):$(` Enrollment cert valid until ${e.enrollment.expiresAt} ${v(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(K("Shell"),_(" This terminal still exports Anyray, but the config is gone."),k(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),k(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),k(v(" Anything you start from this terminal keeps reaching the gateway with")),k(v(" no credential, and fails with 401.")),k(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),k(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),k(v(" reuses the environment it captured at launch, so a new terminal")),k(v(" (or Reload Window) keeps serving the old one.")));let 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"),_(` ${bc(c)}.`),k(v(` ${kc(c)}`))}K("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])_(` ${c.title}: ${l.problem}.`),k(v(` ${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(v(" Fix: re-run `anyray-connect` to re-register the current binary."))):$(` ${c.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(L(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),k(v(" 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(v(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){k(v(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){$(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),k(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}$(` ${c.title}: pointed at ${e.gateway.origin}${e.fallbackProxy.enabled&&_i(c.id)?v(" (via key-refresh proxy)"):""}`),o(c),c.id==="claude-code"&&k(v(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===$a&&k(v(` ${EC}`)),c.id==="codex"&&k(v(" Note: Codex app, CLI, and IDE extension share config.toml; Codex cloud/web tasks cannot route through a local gateway.")),a(c)}else{o(c);let l=QI(c);if(l==="not-routed"||l==="unverifiable"){let d=Gd(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});L(` ${c.title}: ${d.headline}`);for(let u of d.detail)k(v(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(L(` ${c.title}: reverted locally against admin policy (out of compliance)`),k(v(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?L(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):k(v(` ${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(v(" 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(v(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(L(" No tools are pointed at this gateway yet."),k(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){K("Queued operations");for(let c of e.pendingOps){let l=Wt(c.adapter)?.title??c.adapter;c.watcherAlive?L(` ${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(v(` 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=Wt(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?L(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=>Wt(d)?.title??d).join(", ");i.freshIds.length>0&&k(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&L(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(K("Auth probe"),e.verify.notApplicableSubscription)$(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")$(` ${e.verify.detail}`);else{_(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)k(v(` ${c}`))}if(e.retrieval)if(K("Retrieval loop"),e.retrieval.kind==="ok")$(` ${e.retrieval.detail}`);else{_(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)k(v(` ${c}`))}if(e.hookLane){if(K("Hook lane"),e.hookLane.verdict==="live")$(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(v(` ${c}`))}else{L(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(v(` ${c}`))}e.hookLane.lastInvokedAt!==null&&k(v(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}K("Summary"),e.problems===0?(e.verify?$(" No problems found."):$(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),k(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):_(` ${e.problems} problem(s) found \u2014 see fixes above.`)},Ej=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}),Ij=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!Qh(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??Ia,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??Qe)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=Cn((await(t.readRefreshState??Kt)().catch(()=>({}))).hookLane),l=om(i,{hookRegistered:await tx(t.adapters??se).catch(()=>!1),neverInvoked:nm(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:Ed(c)},note:d}},xj=async(e,t,n={})=>{let r=n.adapters??se,o=n.resolveTarget??Oe,a=n.applyTools??mt,s=await Ij(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&&(my(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 ${gy(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),!yo(y))continue;let b=e.tools.find(P=>P.id===y.id);if(!b)continue;let A=r.find(P=>P.id===y.id),S=b.mcp;if(A?.mcpStatus)try{let P=await A.mcpStatus();S={...P,commandOk:ex(P)}}catch{}let E=my(b)?!0:b.pointedAt;if(A?.pointsAt&&b.pointedAt!==null)try{E=await A.pointsAt(Pi(A.id,e.gateway.origin,e.toolOrigin))}catch{}let I=b.routingOverrides,C=b.claudeCodeHookPolicy;if(A?.runtimeDiagnostics)try{let P=await A.runtimeDiagnostics();I=P.routingOverrides.length?P.routingOverrides:void 0,C=P.claudeCodeHookPolicy}catch{}else if(A?.routingOverrides)try{let P=await A.routingOverrides();I=P.length?P:void 0}catch{}let x={...b,pointedAt:E,mcp:S,...I?{routingOverrides:I}:{},...C===void 0?{}:{claudeCodeHookPolicy:C}};I||delete x.routingOverrides,C===void 0&&delete x.claudeCodeHookPolicy,w.set(y.id,x),g+=yy(b)-yy(x)}return{entries:f,remainingProblems:Math.max(0,e.problems-g-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:p}},Rj=e=>{K("Repair"),e.entries.length===0&&$(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?$(` ${t.title}: re-applied`):t.status==="queued"?$(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?k(v(` ${t.title}: ${t.status}`)):_(` ${t.title}: ${t.status}`);for(let t of e.notes)k(v(` ${t}`))},nx=async(e,t={})=>{let n=await T();if(e.securityReview){k(j("Anyray connect \u2014 security review"));for(let c of bE(n.fallbackPort??ke))k(c?` ${c}`:"");return 0}let r;try{r=Rr(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(v(" 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 Cj(r,n,!!e.verify&&!e.quick,t.adapters??se,t.inferenceIntrospection??Wd,t.fleetBootstrap??jt,o,t.verifyAuth??Hi,!e.quick,t.checkTray??vo,t.updateStatus??Io,t.readRefreshState??Kt,t.probeHookLane??Ia);e.repair&&a.retiredFallbackState.length>0&&(await lc(),a.retiredFallbackState=await Lu(),a.retiredFallbackState.length===0&&(a.problems-=1));let s=e.repair?await xj(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(Ej(i),null,2)):(Sj(i),s&&Rj(s));try{e.quick||await(t.reportHealth??cS)(zI(i),i.connect.version)}catch{}return i.problems===0?0:1};var Oj=()=>{let e=[];for(let t of se){let n=t.skillsDir?.();n&&e.push(n)}return e},rx=async e=>{let t=await T();k(j("Anyray connect \u2014 sync"));let n;try{n=Rr(e.gateway,t)}catch(s){return _(s.message),1}F(`Gateway: ${n}`);let r=XE(t.clientKey,"anyray-placeholder"),o;try{o=await kd(n,r)}catch(s){return _(`Team policy sync failed: ${bd(s)}`),1}let a=Oj();if(a.length===0)_j();else if(o.skills.length===0)F("No team skills published yet \u2014 nothing to sync.");else{let s=await Kv(o,a,t.syncedSkills??{});K("Skills");for(let i of s.results)i.written?$(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):F(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await re({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){F(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}K("Summary"),k(` ${et(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Cd(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(k(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&F(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){F(`Fleet policy reconcile skipped: ${bd(s)}`)}return 0},_j=()=>{F("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as D2}from"node:zlib";import{promisify as N2}from"node:util";var Tr={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},wy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),ox=e=>`
|
|
690
|
+
`).join("")),o.write(`\x1B[${i}A`))},f=!!r.isRaw,p=!1;try{return p=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((h,m)=>{let w=()=>{r.off("data",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 I of kG(E)){if(I===""||I==="\x1B"||I==="q"){g({kind:"cancelled"});return}if(e.items.length===0){(I==="\r"||I===`
|
|
691
|
+
`)&&g({kind:"ok",values:[]});continue}if(I==="\x1B[A"||I==="k")s=(s-1+e.items.length)%e.items.length,d();else if(I==="\x1B[B"||I==="j")s=(s+1)%e.items.length,d();else if(I===" "){if(e.single){let C=!a[s];a.fill(!1),a[s]=C}else a[s]=!a[s];d()}else if(I==="a"&&!e.single){let C=e.items.map((T,U)=>({item:T,index:U})).filter(({item:T})=>T.requiresExplicitChoice!==!0),x=!C.every(({index:T})=>a[T]);for(let{index:T}of C)a[T]=x;d()}else if(I==="\r"||I===`
|
|
692
|
+
`){g({kind:"ok",values:e.items.filter((C,x)=>a[x]).map(C=>C.value)});return}}}catch(I){y(I)}};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 ZI=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],CG=80,Mi=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&Pa(r,n.env??process.env)))return r.write(`${e}
|
|
693
|
+
`),t();let a=0,s=()=>{r.write(`\r${ZI[a++%ZI.length]} ${e}`)};s();let i=setInterval(s,CG);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as AG}from"node:fs";import{spawnSync as vG}from"node:child_process";import{chmod as SG,copyFile as ay,lstat as sy,mkdir as Ua,readdir as iy,realpath as ru,rename as nu,rm as Rt,stat as EG,symlink as IG,writeFile as xG}from"node:fs/promises";import{createHash as RG}from"node:crypto";import{basename as ry,dirname as Lr,join as ut}from"node:path";import{Readable as OG}from"node:stream";import{pipeline as _G}from"node:stream/promises";var JI="https://github.com/anyrayHQ/install/releases",XI="connect-v",TG=new RegExp(`/releases/tag/${XI}([0-9][0-9A-Za-z.-]*)$`),PG=300*1024*1024,ou=1e4,LG=5*6e4,DG=360*6e4,NG=30*6e4,Ba=(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)},zI=(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"}},$G=e=>{if(e)return TG.exec(e.trim())?.[1]},cy=(e,t)=>{for(let n of e.split(`
|
|
694
|
+
`)){let[r,o]=n.trim().split(/\s+/);if(!r||!o)continue;if((o.startsWith("*")?o.slice(1):o)===t&&/^[0-9a-f]{64}$/i.test(r))return r.toLowerCase()}},qI=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&&Ba(e.current,e.minVersion)<0&&Ba(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},MG=e=>Ba(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}:{...qI(e),downgradeBlocked:!1},Wa=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",FG=(e=process.execPath)=>{let t=Uu(e);return t?Lr(t):Lr(Lr(e))},UG=async(e=ft())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=ut(FG(e.execPath),"bin",Wa());try{if(await ru(t)!==await ru(e.execPath))return}catch{return}return t},ly=async(e=ft(),t=ee())=>{let n=await UG(e);if(n)return{kind:"managed",root:Lr(Lr(n)),link:n,entryPath:er(e)};let r=er(e);return Wu(r,t)?{kind:"durable",root:t,entryPath:r}:Mu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},au=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),t);try{return await fetch(e,{...n,signal:r.signal})}finally{clearTimeout(o)}},dy=async(e=ou)=>{let t=await au(`${JI}/latest`,e,{redirect:"manual"});return $G(t.headers.get("location"))},BG=async e=>{try{let t=await au(`${e}/connect-update.json`,ou);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}},Fi=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},uy=async(e,t,n)=>{let r=await au(e,LG);if(!r.ok||!r.body)throw new Fi(r.status);let o=RG("sha256"),a=0;if(await _G(OG.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>PG)throw new Error("asset exceeds size cap");o.update(c),yield c}},AG(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},WG=e=>ry(e)===Wa()?ry(Lr(e)):ry(e),HG=async e=>{let t=await iy(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Rt(ut(e,n),{force:!0}).catch(()=>{})},QI=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Rt(r,{force:!0}).catch(()=>{});let o=!1;try{await nu(e,r),o=!0}catch{}try{await ay(t,e),await xG(ns(e),WG(t))}catch(a){throw o&&await nu(r,e).catch(()=>{}),a}await Rt(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Rt(n,{force:!0}),await IG(t,n),await nu(n,e)},KG=async(e,t={})=>{let n=ut(e.root,"bin"),r=ut(e.root,"versions"),o=ut(n,Wa());await Ua(n,{recursive:!0,mode:448}),await Ua(r,{recursive:!0,mode:448});let a=ut(r,e.version),i=(await sy(a).catch(()=>{}))?.isFile()?a:ut(a,Wa());if(!(await sy(i).catch(()=>{}))?.isFile()){let l=await(t.fetchResponse??au)(`${e.tagUrl}/SHA256SUMS`,ou),d=l.ok?cy(await l.text(),e.asset):void 0;if(!d)throw new Error("no published checksum");await Ua(Lr(i),{recursive:!0,mode:448}),await HG(Lr(i));let u=`${i}.part-${process.pid}`;try{await(t.download??uy)(`${e.tagUrl}/${e.asset}`,u,d),await SG(u,493),await nu(u,i)}catch(f){throw await Rt(u,{force:!0}).catch(()=>{}),f}}return await(t.activate??QI)(o,i),{link:o,target:i,versionsDir:r}},GG=async e=>{let t=vG(e,["--version"],{stdio:"ignore",timeout:ou});return!t.error&&t.status===0},jG=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??wo)(n);if(r.length>0){let o=await(t.resolveTarget??Oe)(async()=>e);if(!o||!(await(t.repair??mt)(r,o.target)).every(go))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??dr)()).ok||e.keyRefreshEnabled&&(!e.gateway||!e.fallbackPort||!(await(t.installDaemon??Dt)({port:e.fallbackPort,remoteOrigin:e.gateway})).ok))},VG=async e=>{let t=await e.install();if(!await(e.smoke??GG)(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},YG=async(e,t)=>{let n=await iy(e).catch(()=>[]);for(let r of n)t.includes(r)||await Rt(ut(e,r),{force:!0,recursive:!0}).catch(()=>{})},ZG=async e=>{let t=await iy(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Rt(ut(e,n),{force:!0}).catch(()=>{})},JG=async(e,t)=>{let n=async()=>{await Rt(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await Ua(e,{recursive:!1}),n}catch{}let r=await EG(e).catch(()=>{});if(!(!r||t-r.mtimeMs<NG)){await n();try{return await Ua(e,{recursive:!1}),n}catch{return}}},oy=e=>ut(e,"update-state.json"),XG=async e=>{let t=await M(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},zG=1e3,qG=16*6e4,QG=e=>e.inFlight===0,ej=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??qG);for(;;){let i=await r(e).catch(()=>null);if(i!==null&&i.version===t&&QG(i))return!0;if(a()>=s)return!1;await o(zG)}},Ui=async(e={})=>{let t=e.now??Date.now,n=we;if(kt(ht(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??ft(),o=e.root??ee(),a;try{let s=await ly(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=zI(e.platform??process.platform,e.arch??process.arch);if(!c)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??dy)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let l=a;if(!i&&l===n)return{outcome:"current",current:n,latest:l};if(i&&Ba(l,n)<0)return{outcome:"migration-deferred",current:n,latest:l};let d=e.force===!0,u=await XG(oy(o));if(!d&&u.failedVersion===l&&u.failedAt!==void 0&&t()-u.failedAt<DG)return{outcome:"failed",current:n,latest:l};let f=`${JI}/download/${XI}${l}`,p=await(e.load??P)().catch(()=>({})),h=p.autoUpdate!==!1,m=h||d?void 0:await(e.minimumVersion??BG)(f),w={current:n,latest:l,autoUpdate:h,forced:d,minVersion:m},g=i?MG(w):{...qI(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 bt():await Ua(o,{recursive:!0,mode:448});let y=await JG(ut(o,"update.lock"),t());if(!y)return{outcome:i?"migration-available":"available",current:n,latest:l};let b,A;try{await ZG(ut(o,"bin"));let I=await ru(ut(o,"versions")).catch(()=>{}),C=await ru(ut(o,"bin",Wa())).catch(()=>{}),x=C&&pc(C,I)?C:void 0,T=ut(o,"bin",Wa());i&&process.platform==="win32"&&(await sy(T).catch(()=>{}))?.isFile()&&(A=`${T}.rollback-${process.pid}`,await ay(T,A));let U=()=>(e.installBinary??KG)({root:o,version:l,asset:c,tagUrl:f});i?b=await VG({install:U,smoke:e.smoke,rollback:async({link:Z,target:Y})=>{A?(await ay(A,Z),await Rt(ns(Z),{force:!0}).catch(()=>{})):x&&x!==Y?await QI(Z,x):(await Rt(Z,{force:!0}),await Rt(ns(Z),{force:!0}).catch(()=>{}))},repoint:async Z=>e.repoint?e.repoint(p,Z):jG(p),prune:async()=>{await(e.pruneDurable??(Z=>fc(Z)))(r)}}):b=await U(),await YG(b.versionsDir,[l,n]),await Rt(oy(o),{force:!0}).catch(()=>{})}finally{A&&await Rt(A,{force:!0}).catch(()=>{}),await y()}let v=e.bounceDaemon??tp,E=p.persistenceOwner==="tray";if(!i&&(p.refreshSchedulerEnabled||p.keyRefreshEnabled)){let I=p.fallbackPort??ke,C=E?!0:await fw().catch(()=>!0),x=await v(p.fallbackPort,{drain:"idle"}).catch(()=>!1);!C&&p.gateway&&((x?await(e.waitForDaemon??ej)(I,l):!0)?await Dt({port:I,remoteOrigin:p.gateway}).catch(()=>{}):await(e.writeUnitFile??mw)().catch(()=>!1))}return{outcome:i?"migrated":"updated",current:n,latest:l,managedPath:b.link,mandatory:g.mandatory}}catch{return a&&await J(oy(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},ex=async(e={})=>{let t=e.context??ft(),n=await ly(t,e.root??ee()),r=Mo(e.root??ee());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:we,managedPath:n.link??r}:Ui({...e,context:t,allowNpmMigration:!0})},xo=async(e={})=>{let t=e.context??ft(),n=e.root??ee(),r=await ly(t,n),o=r.kind==="npm"||r.kind==="durable"?Mo(n):void 0,a=await(e.load??P)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!zI(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=kt(ht(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 tj=async(e,t)=>{if(!e.gateway||!e.clientKey)return;let n=await t().catch(()=>{});return ye({origin:e.gateway,clientKey:e.clientKey,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:n,user:e.name,team:e.team})},tx=(e,t)=>e.keyRefreshEnabled===t.keyRefreshEnabled&&e.fallbackPort===t.fallbackPort,nj=(e,t)=>async n=>{let r=await e(),{next:o,result:a}=n(r);return o&&await t(o),a},py=async(e={})=>{let t=e.load??P,n=e.save??re,r=e.mutate??(e.load||e.save?nj(t,n):vg),o=e.loadDevKey??Ue,a=e.heartbeat??vd,s=e.detectSeat??Nt,i=e.rewriteTools??ki,c=e.uninstallProxy??qt;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 Ir&&y.status===404?"unsupported":"pending"}let p=await r(y=>{if(y.clientKey!==l.clientKey||y.enrolledCert?.sig!==d||!tx(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 tj(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://${pt}:${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"||!tx(y,p)?{result:!1}:{next:{...y,clientKeyExpiresAt:f.expiresAt,credentialProtocol:"stable-heartbeat-v1",directMigration:"complete",keyRefreshEnabled:!1,fallbackPort:void 0},result:!0})?((m||l.fallbackPort!==void 0)&&await c(w).catch(()=>{}),"migrated"):"pending"}catch{return"pending"}};var rj=12e3,oj="anyray-wiring-probe-not-a-real-token",aj={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},hy={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},Ro=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},rx=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},my=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},nx=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."],sj=e=>e.includes("no provider key configured for"),yy=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},gy=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>"]}),Bi=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."]}),ij=(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?yy(t)?gy(e):my(t)?Bi(e):rx(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${Ro(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)."]}:sj(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${Ro(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")?nx([" \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}): ${Ro(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).",...nx([" \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}: ${Ro(t)}`,remedy:[]},cj=(e,t)=>{if(my(t))return Bi(e);if(yy(t))return gy(e);if(rx(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}: ${Ro(t)}`,remedy:[]}},lj=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),dj=(e,t)=>{if(my(t))return Bi(e);if(yy(t))return gy(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")||lj(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}: ${Ro(t)}`,remedy:[`The probe asks for a fixed model (${hy.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."]}},fy=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)}},uj=async(e,t)=>{if(!e.clientKey)return Bi(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?Bi(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${Ro(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},pj=(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."]}},Wi=async(e,t={})=>{let n=t.timeoutMs??rj,r=de(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await uj(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 fy(`${e.anthropicBaseUrl}/v1/messages`,l,hy,n);return dj(d,u)}if(X(e,"anthropic")){let l={Authorization:`Bearer ${oj}`,"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 fy(`${e.anthropicBaseUrl}/v1/messages`,l,hy,n);return cj(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await fy(`${e.openaiBaseUrl}/chat/completions`,s,aj,n);return ij(i,c,t.tools??[])}catch(o){return pj(n,o)}};var ox=async e=>{let t=await P(),n;try{n=_r(e.gateway,t)}catch(s){return k(j("Anyray connect \u2014 status")),F(`Gateway: ${s.message}`),0}k(j("Anyray connect \u2014 status")),K("Gateway"),k(` Origin: ${et(n)}`),t.gateway?F(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?F(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||F(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),K("Identity"),k(` Name: ${t.name??S("(not set)")}`),k(` Team: ${t.team??S("(not set)")}`);let r=ht();r&&(K("Environment"),k(` Remote dev context: ${cr(r)}`),kt(r)&&F(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),F(" VS Code tools configure the remote server variant backing this window.")),t.credentialProtocol==="stable-heartbeat-v1"&&(K("Credential renewal"),t.directMigration==="pending"?(k(" Stable-key heartbeat active; direct-routing migration is still completing."),F(" The local proxy remains available until every managed tool moves.")):($(" Direct gateway routing with a proof-backed stable-key heartbeat."),F(" Renewal extends the same key; tool configuration is not rewritten.")));let o=!!(tt(t)&&t.fallbackPort),a=o?`http://${pt}:${t.fallbackPort}`:n;o&&(K("Local key-refresh proxy"),await be(t.fallbackPort)?$(` 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 se){if(!(await s.detect()).installed){F(` ${s.title}: not installed`);continue}if(!s.pointsAt){F(` ${s.title}: installed ${S("(status not introspectable)")}`);continue}let c=await s.pointsAt(Ti(s.id,n,a));if(c){if(s.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){$(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),k(S(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}$(` ${s.title}: pointed at Anyray${o&&_i(s.id)?S(" (via key-refresh proxy)"):""}`)}else{let l=null,d=null;if(s.id===$a&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,f=await Hd();l=Kd({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=Gd(l,d);D(` ${s.title}: ${u.headline}`);for(let f of u.detail)k(S(` ${f}`))}else F(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as wj}from"node:fs";import{isAbsolute as bj}from"node:path";import{access as fj}from"node:fs/promises";import{constants as hj}from"node:fs";import{platform as mj}from"node:os";var yj=async e=>{try{return await fj(e,hj.F_OK),!0}catch{return!1}},gj=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"]:[],Oo=async(e={})=>{let t=e.os??mj(),n=e.exists??yj;for(let r of gj(t))if(await n(r))return!0;return!1};var Yt="connect",wy=e=>e.replace(/-/g,"_"),ax=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:Yt,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:Yt,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:Yt,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.fallbackProxy.enabled&&t.push({tool:Yt,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:Yt,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:Yt,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:Yt,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=wy(e.retrieval.kind);t.push({tool:Yt,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":wy(e.verify.kind);t.push({tool:Yt,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:Yt,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:wy(e.hookLane.reason)}:{}})}t.push({tool:Yt,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)i.installed&&(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp&&t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing"}),a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"}));return t.push({tool:Yt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function kj(){return we}var Cj="ctx_doctor-probe-synthetic",Aj=(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: ${Cy(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 vj(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function Sj(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function Cy(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 sx=e=>Kd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),by=e=>e.pointedAt===!1&&e.tombstoned!==!0&&sx(e)!=="unverifiable",ix=e=>e.registered&&e.command&&bj(e.command)?wj(e.command):null,ky=e=>(by(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),Ej=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,Ij=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},cx=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},xj=(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(Co),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},Rj=async(e,t,n,r,o,a,s=n,i=Wi,c=!0,l=So,d=xo,u=Kt,f=Ia)=>{let p=c?await eu(e):null,h=!!(tt(t)&&t.fallbackPort),m=h?await be(t.fallbackPort):null,w=h?`http://${pt}:${t.fallbackPort}`:e,g=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,y=V=>V&&$m(V)?"machine_default":null,b=t.enrolledCert?.payload,A=b?.expiresAt??t.enrolledCertExpiry??null,E=(await a())?.sso??null,I=Sj({ssoLink:E,enrolledViaToken:!!t.enrolledTokenHash}),C=Ct(),x=await Gw(C),T=x?[]:Jw(ye({origin:w})),U=[];for(let V of r){let Ee=await V.detect(),wt=null;if(Ee.installed&&V.mcpStatus)try{let To=await V.mcpStatus();wt={...To,commandOk:ix(To)}}catch{}let qn=Ee.installed&&V.id===$a?await o():void 0,Ot=Ee.installed&&V.pointsAt?await V.pointsAt(Ti(V.id,e,w)):null,$r=await Ej(Ot,V,t.managedTools??[]),Qi=Ot===!1&&$r===null,ec=$r===!1&&V.routingPendingReload?await V.routingPendingReload().catch(()=>!1):!1,Va=Ee.installed?V.runtimeDiagnostics?await V.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:V.routingOverrides?await V.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Ya,claudeCodeHookPolicy:tc}=Va,Za=t.fleetToolPolicy,Ja=Za?.enabled.includes(V.id)?Za.tiers?.[V.id]??va:void 0;U.push({id:V.id,title:V.title,installed:Ee.installed,...Ee.detail?{detail:Ee.detail}:{},pointedAt:$r,...Qi?{routingHeld:!0}:{},...ec?{routingPendingReload:!0}:{},...Ya.length?{routingOverrides:Ya}:{},...tc===void 0?{}:{claudeCodeHookPolicy:tc},mcp:wt,...Ja?{policyTier:Ja}:{},...t.revertedTools?.includes(V.id)?{tombstoned:!0}:{},...V.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...qn===void 0?{}:{inferenceIntrospectable:qn.authoritative,...qn.authoritative?{}:{inferenceUnverifiableReason:qn.reason}}})}let Z=s?await(async()=>{let{kind:V,detail:Ee,remedy:wt}=await i(ye({origin:e,clientKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey,subscription:t.authMode==="subscription",placeholder:t.authMode==="placeholder",byoUpstream:t.byoUpstream,...t.authMode==="auto"?{seat:{anthropic:!1,openai:!1,copilot:!1}}:{},user:t.name,team:t.team}),{tools:t.managedTools??[]});return{kind:V,detail:Ee,remedy:wt}})():null,Y=Z?.kind==="provider-rejected"&&await Ij(t.managedTools??[],r),W=Z?{...Z,...Y?{notApplicableSubscription:!0}:{}}:null,z=n?Aj(await Ea({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:de({user:t.name,team:t.team})},Cj,{probe:!0}),{mode:I,ssoLink:E}):null,me=await u().catch(()=>({})),Pe=vn(me.hookLane),ne=s?await cx(r):!1,He=ne?await(async()=>{let V=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...im(V,{hookRegistered:ne,neverInvoked:am(Pe,Date.now())}),lastInvokedAt:Ed(Pe)}})():null,Le=(await pr()).map(V=>({adapter:V.adapter,op:V.op,requestedAt:V.requestedAt,watcherAlive:hr(V.watcherPid)})),O=Le.find(V=>V.adapter==="cursor"),L=O?{op:O.op,requestedAt:O.requestedAt,watcherAlive:O.watcherAlive}:null,H=!!t.refreshSchedulerEnabled,pe=await Lc(),q=await d(),Ve=t.persistenceOwner==="tray",Me=Ve?await l(t)==="healthy":null,Q=await AE({daemonEnabled:h&&!Ve,daemonHealthy:h?!!m:null,schedulerEnabled:H&&!Ve,schedulerInstalled:pe,binaryDurable:!Ge(ir())}),Fe=await Lu(),De=0;p&&!p.reachable&&(De+=1),h&&!m&&(De+=1),Ve?H&&!Me&&(De+=1):H&&!pe&&(De+=1);for(let V of U)De+=ky(V);return W&&W.kind!=="ok"&&!W.notApplicableSubscription&&(De+=1),z&&z.kind!=="ok"&&(De+=1),He?.verdict==="dark"&&(De+=1),T.length>0&&(De+=1),De+=Le.filter(V=>!V.watcherAlive).length,Fe.length>0&&(De+=1),{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:kj(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:ht(),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:pe,owner:Ve?"tray":"os",...Ve?{trayHealthy:!!Me}:{}},serviceRemoval:Q,retiredFallbackState:Fe,fleetdPresent:await Oo(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:g,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:y(t.name)},enrollment:{enrolled:!!b,deploymentId:b?.deploymentId??null,issuedAt:b?.issuedAt??null,expiresAt:A,expired:A?Date.parse(A)<Date.now():null,orgMode:I,ssoLink:E},shell:{profilePath:C,blockPresent:x,staleExports:T},tools:U,...t.fleetToolPolicy?{fleetPlan:wd(t,t.fleetToolPolicy,!1)}:{},cursorQueue:L,pendingOps:Le,ambientRepairs:xj(me,r),verify:W,retrieval:z,hookLane:He,problems:De}},Oj=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."))}},_j=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)."))}},Tj=e=>{switch(k(j("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(K("Environment"),k(` Remote dev context: ${cr(e.connect.remoteContext)}`),kt(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":$(" 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?$(` 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?$(` 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?$(" 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?$(" 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.")))),Oj(e),_j(e),K("Personal key"),vj(e)){case"env":$(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":$(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":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: ${Cy(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.`):$(` 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"),_(` ${bc(c)}.`),k(S(` ${kc(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."))):$(` ${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){$(` ${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}$(` ${c.title}: pointed at ${e.gateway.origin}${e.fallbackProxy.enabled&&_i(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===$a&&k(S(` ${OC}`)),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=sx(c);if(l==="not-routed"||l==="unverifiable"){let d=Gd(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=Ht(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=Ht(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:p,at:h})=>`${c(p)} ${new Date(h).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let f=` ${d}: ${u.join("; ")}`;l.flapping?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=>Ht(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)$(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")$(` ${e.verify.detail}`);else{_(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)k(S(` ${c}`))}if(e.retrieval)if(K("Retrieval loop"),e.retrieval.kind==="ok")$(` ${e.retrieval.detail}`);else{_(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)k(S(` ${c}`))}if(e.hookLane){if(K("Hook lane"),e.hookLane.verdict==="live")$(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)k(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()}`))}K("Summary"),e.problems===0?(e.verify?$(" No problems found."):$(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),k(S(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):_(` ${e.problems} problem(s) found \u2014 see fixes above.`)},Pj=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}),Lj=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!nm(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??Ia,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??Qe)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=vn((await(t.readRefreshState??Kt)().catch(()=>({}))).hookLane),l=im(i,{hookRegistered:await cx(t.adapters??se).catch(()=>!1),neverInvoked:am(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:Ed(c)},note:d}},Dj=async(e,t,n={})=>{let r=n.adapters??se,o=n.resolveTarget??Oe,a=n.applyTools??mt,s=await Lj(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&&(by(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 ${Cy(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),!go(y))continue;let b=e.tools.find(T=>T.id===y.id);if(!b)continue;let A=r.find(T=>T.id===y.id),v=b.mcp;if(A?.mcpStatus)try{let T=await A.mcpStatus();v={...T,commandOk:ix(T)}}catch{}let E=by(b)?!0:b.pointedAt;if(A?.pointsAt&&b.pointedAt!==null)try{E=await A.pointsAt(Ti(A.id,e.gateway.origin,e.toolOrigin))}catch{}let I=b.routingOverrides,C=b.claudeCodeHookPolicy;if(A?.runtimeDiagnostics)try{let T=await A.runtimeDiagnostics();I=T.routingOverrides.length?T.routingOverrides:void 0,C=T.claudeCodeHookPolicy}catch{}else if(A?.routingOverrides)try{let T=await A.routingOverrides();I=T.length?T:void 0}catch{}let x={...b,pointedAt:E,mcp:v,...I?{routingOverrides:I}:{},...C===void 0?{}:{claudeCodeHookPolicy:C}};I||delete x.routingOverrides,C===void 0&&delete x.claudeCodeHookPolicy,w.set(y.id,x),g+=ky(b)-ky(x)}return{entries:f,remainingProblems:Math.max(0,e.problems-g-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:p}},Nj=e=>{K("Repair"),e.entries.length===0&&$(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?$(` ${t.title}: re-applied`):t.status==="queued"?$(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?k(S(` ${t.title}: ${t.status}`)):_(` ${t.title}: ${t.status}`);for(let t of e.notes)k(S(` ${t}`))},lx=async(e,t={})=>{let n=await P();if(e.securityReview){k(j("Anyray connect \u2014 security review"));for(let c of vE(n.fallbackPort??ke))k(c?` ${c}`:"");return 0}let r;try{r=_r(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 Rj(r,n,!!e.verify&&!e.quick,t.adapters??se,t.inferenceIntrospection??Hd,t.fleetBootstrap??jt,o,t.verifyAuth??Wi,!e.quick,t.checkTray??So,t.updateStatus??xo,t.readRefreshState??Kt,t.probeHookLane??Ia);e.repair&&a.retiredFallbackState.length>0&&(await lc(),a.retiredFallbackState=await Lu(),a.retiredFallbackState.length===0&&(a.problems-=1));let s=e.repair?await Dj(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(Pj(i),null,2)):(Tj(i),s&&Nj(s));try{e.quick||await(t.reportHealth??pS)(ax(i),i.connect.version)}catch{}return i.problems===0?0:1};var $j=()=>{let e=[];for(let t of se){let n=t.skillsDir?.();n&&e.push(n)}return e},dx=async e=>{let t=await P();k(j("Anyray connect \u2014 sync"));let n;try{n=_r(e.gateway,t)}catch(s){return _(s.message),1}F(`Gateway: ${n}`);let r=QE(t.clientKey,"anyray-placeholder"),o;try{o=await kd(n,r)}catch(s){return _(`Team policy sync failed: ${bd(s)}`),1}let a=$j();if(a.length===0)Mj();else if(o.skills.length===0)F("No team skills published yet \u2014 nothing to sync.");else{let s=await Yv(o,a,t.syncedSkills??{});K("Skills");for(let i of s.results)i.written?$(` ${i.name} ${S(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):F(` ${i.name} ${S(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await re({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){F(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}K("Summary"),k(` ${et(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Cd(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(k(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&F(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){F(`Fleet policy reconcile skipped: ${bd(s)}`)}return 0},Mj=()=>{F("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as WV}from"node:zlib";import{promisify as HV}from"node:util";var Dr={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},Ay=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),ux=e=>`
|
|
695
695
|
|
|
696
696
|
\u2026[anyray-hook trimmed ${e} chars (~${Math.round(e/3.3)} tokens) \u2014 elided locally, cache-safe]\u2026
|
|
697
697
|
|
|
698
|
-
`,su=(e,t={})=>{if(typeof e!="string")return
|
|
698
|
+
`,su=(e,t={})=>{if(typeof e!="string")return Ay(String(e??""));let n=Math.max(1,t.maxChars??Dr.maxChars);if(e.length<=n)return Ay(e);let r=e.length,o=Math.max(0,t.headChars??Dr.headChars),a=Math.max(0,t.tailChars??Dr.tailChars),s=Math.max(0,t.middleWindows??Dr.middleWindows),i=100*(s+2),c=Math.max(1,n-1-i);o+a>c&&(a=Math.min(a,c),o=Math.max(0,c-a));let l=o,d=r-a,u=[];o>0&&u.push([0,o]);let f=c-o-a;if(s>0&&f>0&&d>l){let 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),I=e.lastIndexOf(`
|
|
699
699
|
`,E);I>=l&&(E=I+1);let C=e.indexOf(`
|
|
700
|
-
`,
|
|
700
|
+
`,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+=ux(g-m)),h+=e.slice(g,y),m=y;if(r>m&&(h+=ux(r-m)),h.length>=r)return Ay(e);let w=r-h.length;return{text:h,trimmed:!0,originalChars:r,trimmedChars:h.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},Fj=["stdout","content","output","text","result"],px=e=>{if(typeof e=="string")return{body:e,rebuild:o=>o};if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(Array.isArray(t.content)){let o=t.content,a=[];for(let[i,c]of o.entries())c&&typeof c=="object"&&!Array.isArray(c)&&typeof c.text=="string"&&a.push({index:i,part:c,text:c.text});let s=Object.prototype.hasOwnProperty.call(t,"structuredContent")&&t.structuredContent!==void 0;if(a.length===1&&!s){let i=a[0];return{body:i.text,rebuild:c=>({...t,content:o.map((l,d)=>d===i.index?{...i.part,text:c}:l)})}}if(a.length>0||s){let i=a.map(({text:d},u)=>`--- MCP text part ${u+1} ---
|
|
701
701
|
${d}`);s&&i.push(`--- MCP structuredContent ---
|
|
702
702
|
${JSON.stringify(t.structuredContent)}`);let c=a[0],l=new Set(a.map(({index:d})=>d));return{body:i.join(`
|
|
703
703
|
|
|
704
|
-
`),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((f,p)=>l.has(p)?p!==c?.index?[]:[{...c.part,text:d}]:[f]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n=
|
|
705
|
-
`),s=0,i=0;for(let c of a)c.trim()&&(s++,
|
|
706
|
-
${e.slice(-
|
|
707
|
-
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},
|
|
708
|
-
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},
|
|
709
|
-
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},
|
|
710
|
-
`).filter(s=>s.trim()!==""),r=
|
|
704
|
+
`),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((f,p)=>l.has(p)?p!==c?.index?[]:[{...c.part,text:d}]:[f]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n=Fj.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 Uj=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},Hi={minChars:8e3,minDataLineRatio:.6,minDataLines:20},iu=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??Hi.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??Hi.minDataLineRatio,o=t.minDataLines??Hi.minDataLines,a=e.split(`
|
|
705
|
+
`),s=0,i=0;for(let c of a)c.trim()&&(s++,Uj(c)&&i++);return s===0||i<o?!1:i/s>=r};var Ki=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,cu={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"},mx=new Set(["npm","pnpm","yarn","bun"]),lu=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},Bj=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=lu(r[0]);if(o in cu)return cu[o];if((o==="npx"||o==="bunx")&&r[1]){let a=lu(r[1]);if(a in cu)return cu[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||mx.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},Sy=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=Bj(t);if(n)return n}return null},Wj={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},Hj=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,Kj=(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},yx=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=lu(r[0]);if(mx.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&Hj.test(i)}let a=r[1]?lu(r[1]):void 0;if(Kj(o,a,r))return!1;let s=Wj[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},Gj=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==="]"},jj=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},Vj=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=jj(t);return r>0&&t[r+1]===":"},Yj=80,Zj=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/Yj),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,Vj(e[o])&&r++;return n>0&&r/n>.3},Jj=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,Xj=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();(Jj.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},zj=[/\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],vy=8192,qj=e=>{let t=e.length>2*vy?`${e.slice(0,vy)}
|
|
706
|
+
${e.slice(-vy)}`:e;return zj.some(n=>n.test(t))},Qj=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),eV=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),tV=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},nV=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),fx=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(eV(i)){t.push(Ki(i));continue}let c=tV(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(Ki(c)),o=12;continue}Qj(i)||nV(i)||o>0&&(t.push(Ki(s)),o--)}if(t.length===0)return null;let a=r>0?` (+${r} more)`:"";return{text:t.join(`
|
|
707
|
+
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},rV=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,gx=e=>{let t=rV.exec(e);return t&&/[/.]/.test(t[1])?t:null},oV=/^([^\s:]+)-(\d+)-/,aV=e=>{if(e==="--")return!0;let t=oV.exec(e);return t!=null&&/[/.]/.test(t[1])},sV=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>gx(r)!=null).length;return n>=3&&n/t.length>=.7},hx=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=gx(c);if(!l){if(aV(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(Ki(` ${u.line}: ${u.content.trim()}`)),s++;l.length>d&&a.push(` \u2026+${l.length-d} more in this file`)}return i&&a.push("",`\u2026+${o-s} more matches elided`),{text:a.join(`
|
|
708
|
+
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},iV=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(),cV=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=iV(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=Ki(a.trim());return s>1?`[\xD7${s}] ${i}`:i}).join(`
|
|
709
|
+
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},wx=(e,t)=>{if(typeof t!="string"||t.length===0||Gj(t))return null;let n=t.split(`
|
|
710
|
+
`).filter(s=>s.trim()!==""),r=Sy(e),o=qj(t),a=null;return r==="test-run"&&o?a=fx(n):r==="grep"&&(a=hx(n,.5)),a||(o?a=fx(n):sV(n)?a=hx(n,.7):!Xj(n)&&!Zj(n)&&(a=cV(n))),!a||a.text.length>=t.length?null:a},Ey=(e,t)=>t?`
|
|
711
711
|
|
|
712
712
|
\u2026[anyray-hook digest \u2014 ${e}; full output: ${t}]\u2026`:`
|
|
713
713
|
|
|
714
|
-
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,
|
|
714
|
+
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,bx=e=>`
|
|
715
715
|
|
|
716
|
-
\u2026[anyray-hook \u2014 full output: ${e}]\u2026`;import{createHash as
|
|
717
|
-
`):"",
|
|
718
|
-
`).slice(0,
|
|
719
|
-
`);i=l>=0?i.slice(l+1):""}let c
|
|
720
|
-
`));return
|
|
721
|
-
`:"",
|
|
722
|
-
${
|
|
723
|
-
`}catch{return}},
|
|
716
|
+
\u2026[anyray-hook \u2014 full output: ${e}]\u2026`;import{createHash as lV}from"node:crypto";import{homedir as dV}from"node:os";import{join as _o}from"node:path";import{chmod as uV,mkdir as pV,readdir as vx,stat as ji,unlink as Gi,utimes as fV,writeFile as xy}from"node:fs/promises";var du={ttlMs:720*60*60*1e3,maxAgeMs:2160*60*60*1e3,maxTotalBytes:128*1024*1024,maxFiles:2e4,sweepIntervalMs:3600*1e3,writeGraceMs:30*1e3},Sx=".swept",hV=".sweeping",kx=64,Cx=448,Ry=384,mV=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",Ex=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,Ix=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=ee();try{if((await ji(t)).isDirectory())return _o(t,"hook-tee")}catch{}return _o(dV(),".anyray-hook-tee")},yV=async(e,t={})=>{let n=t.limits??du;try{let r=Date.now(),o=(await vx(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=kx)await Promise.all(o.slice(c,c+kx).map(async l=>{let d=_o(e,l);try{let u=await ji(d);if(!u.isFile())return;let f=r-u.mtimeMs>n.ttlMs||r-Ex(u)>n.maxAgeMs;if(d!==t.protect&&f){await Gi(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 Gi(c.path).catch(()=>{})}}catch{}},xx=async e=>{try{return Date.now()-(await ji(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},Ax=async e=>{try{return await xy(e,"",{mode:Ry,flag:"wx"}),!0}catch{return!1}},gV=async(e,t)=>{let n=du,r=_o(e,hV),o=_o(e,Sx);if(!await Ax(r)){let a=0;try{a=Date.now()-(await ji(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await Gi(r).catch(()=>{}),!await Ax(r)))return!1}try{return await xx(o)<n.sweepIntervalMs?!1:(await xy(o,"",{mode:Ry}).catch(()=>{}),await yV(e,{protect:t}),!0)}finally{await Gi(r).catch(()=>{})}},Iy=async(e,t)=>await xx(_o(e,Sx))<du.sweepIntervalMs?!1:gV(e,t),wV=async()=>{try{let e=await Ix();if(!(await vx(e)).some(t=>t.endsWith(".txt")))return;await Iy(e)}catch{}},Rx=async e=>{if(mV())return await wV(),null;try{let t=await Ix();await pV(t,{recursive:!0,mode:Cx}),await uV(t,Cx).catch(()=>{});let n=`${lV("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=_o(t,n),o=Date.now();try{let a=await ji(r);if(a.isFile()){if(o-Ex(a)<=du.maxAgeMs){let s=new Date(o);return await fV(r,s,s).catch(()=>{}),await Iy(t,r),r}await Gi(r).catch(()=>{})}}catch{}return await xy(r,e,{mode:Ry}),await Iy(t,r),r}catch{return null}};import{createHash as bV}from"node:crypto";import{homedir as Ox}from"node:os";import{join as Oy}from"node:path";import{readFile as kV,writeFile as CV,chmod as AV,stat as vV,unlink as SV}from"node:fs/promises";var EV=200,IV=1440*60*1e3,xV=4e6,_x=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",Tx=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},RV=()=>Tx("ANYRAY_HOOK_CACHE_MAX_ENTRIES",EV),Px=()=>Tx("ANYRAY_HOOK_CACHE_TTL_MS",IV),Lx=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=Oy(Ox(),".anyray");try{if((await vV(t)).isDirectory())return Oy(t,"hook-cache.json")}catch{}return Oy(Ox(),".anyray-hook-cache.json")},Dx=(e,t,n)=>bV("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),Nx=async e=>{try{let t=JSON.parse(await kV(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},$x=async e=>{if(_x())return null;try{let n=(await Nx(await Lx())).entries[e];return!n||Date.now()-n.at>Px()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},OV=e=>{let t=Date.now(),n=Px(),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=RV();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>xV&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},Mx=async(e,t)=>{if(_x())return;let n;try{let r=await Lx(),o=await Nx(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=OV(o.entries),n=`${r}.${process.pid}.tmp`,await CV(n,JSON.stringify(o),{mode:384}),await AV(n,384),await fe(n,r)}catch{if(n)try{await SV(n)}catch{}}};import{open as _V,stat as TV}from"node:fs/promises";var Fx=600,PV=3,LV=256e3,DV=e=>typeof e=="string"?e:Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
717
|
+
`):"",NV=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),$V=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},MV=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=DV(o.message?.content).trim();if(!(!a||NV(a))&&(t.unshift(a),n+=a.length,t.length>=PV||n>=Fx))break}return t.join(`
|
|
718
|
+
`).slice(0,Fx)};var FV=e=>/(^|[\\/])subagents[\\/]/i.test(e),UV=e=>/\.jsonl$/i.test(e),BV=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),Ux=async e=>{let t={intent:"",kind:"unknown"};if(!e||!UV(e))return t;let n;try{let{size:r}=await TV(e),o=Math.max(0,r-LV),a=r-o;if(a<=0)return t;n=await _V(e,"r");let s=new Uint8Array(a);await n.read(s,0,a,o);let i=new TextDecoder().decode(s);if(o>0){let l=i.indexOf(`
|
|
719
|
+
`);i=l>=0?i.slice(l+1):""}let c=$V(i.split(`
|
|
720
|
+
`));return BV(c)?{intent:MV(c),kind:FV(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var KV=3e3,GV=1500,jV=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:KV},VV={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},YV=new Set(["claude","opencode"]),ZV=(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:VV[t]})},JV={cacheGet:async()=>null,cachePut:async()=>{}},XV=(e,t={cacheGet:$x,cachePut:Mx,tee:Rx})=>e==="claude"?t:JV,zV=1e3,qV=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),uu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),QV=e=>{try{let t=JSON.parse(e);if(!uu(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 uu(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},e2=e=>{try{let t=JSON.parse(e);return uu(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},t2=e=>uu(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
|
|
721
|
+
`:"",_y=e=>Math.round(Math.max(0,e)/4),Bx=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",n2=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),r2=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),o2=["tool_output","tool_response","tool_result"],a2=e=>{for(let t of o2)if(t in e)return e[t]},s2=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},i2=120,c2=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??zV))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=Ey(r.stat,null).length+i2;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=Ey(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}}},l2=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(n2.has(o)||r2(o))return n;let a=px(a2(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(Wx(o)&&l.retrievalContext!=="available")return n;let d=await c2(t,s2(o,r.tool_input),i),u=d?.body??i,f=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!iu(i,{minChars:GV})))return n;let p=i.length-u.length-f.length,h=async(E,I,C=E.length+f.length)=>{let x=d?.teePath??null;if(!x&&t.tee)try{x=await t.tee(i)}catch{x=null}let T=x?E.replaceAll("; not retrievable in this context]","]"):E,U=x&&!f?bx(x):"",Z=T+f+U,Y=U.length,W=Z;if(t.finalizeOutput)try{let ne=t.finalizeOutput(Z);ne.length<=Z.length&&(W=ne)}catch{W=Z}let z=Z.length-W.length,me=_y(Math.max(0,p-Y))+I+_y(z);me>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,C+Y-z),estTokensSaved:me,...d&&{digest:d.decision}});let Pe=a.rebuild(W);return{stdout:qV(Pe),replacement:Pe}},m=async()=>d?h(u,0):n;if(d&&u.length<=t.sizeGate)return h(u,0);let w=l.intent?`${l.intent}
|
|
722
|
+
${Bx(r.tool_input)}`:Bx(r.tool_input),g=Dx(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=m2(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:_y(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()},Vi=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},d2=()=>{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")}},u2=HV(WV),p2=async e=>{try{let t=await u2(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},Wx=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),f2=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},h2=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),m2=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),y2=2048,g2=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,y2),n=Sd(t);if(!n)return;await MS({at:Date.now(),status:e.status,code:n})}catch{}},w2=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),jV());try{let c=await p2(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...Wx(t)||f2(t)&&a==="available"?{reversible:!0}:{},...h2(t)?{semanticRerank:!0}:{},output:r})),l=zt(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 g2(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)}},Hx=async(e="claude")=>{let t=await Vi();if(e!=="cursor"&&e2(t))return 0;let n=e==="cursor"?QV(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await Ty(n,e);if(e==="cursor"){let a=t2(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},Ty=async(e,t="claude",n)=>{await Rr(),await $S(t);let r=d2(),o=await nt(),a=o&&{...o,metadata:ZV(o.metadata,t)},s=XV(t);return l2(e,{optimize:(i,c,l,d,u)=>w2(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await Ux(i);return{intent:c.intent,retrievalContext:c.kind==="main"?"available":c.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:i=>su(i,r),beacon:(i,c)=>Ac(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??Dr.maxChars,digestCommand:wx,tee:s.tee,mediumBand:YV.has(t),finalizeOutput:n})};var Kx=async()=>0;var b2=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},k2=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??jt)();if(!r)return;let o=await(t.ssoGate??Jn)({sso:r.sso,gateway:r.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(o.exitCode!==2||!o.stderr)return;let a=o.stderr.trim().replace(/Your prompt was not sent — complete sign-in, then resubmit it\.?/,"This request will fail until sign-in completes \u2014 then just continue chatting.");return`${JSON.stringify({continue:!0,user_message:a})}
|
|
723
|
+
`}catch{return}},C2=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},A2=()=>{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")}},v2=(e,t)=>{let n=t.minChars??Hi.minChars,r={maxChars:Math.min(Dr.maxChars,n)},o=su(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},Gx=async()=>{let e=await C2(),t=await k2(e);t&&process.stdout.write(t);let n=A2(),r=await nt();return await b2(e,{isPaste:o=>iu(o,n),measure:o=>v2(o,n),beacon:o=>Ac(r,"prompt",o)}),0};import{spawn as S2}from"node:child_process";var jx=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),E2=/[|&;<>`$()\n]/,Vx=e=>{if(E2.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},I2=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!jx(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!jx(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(Gu)||!t.isRecognized(o)||Vx(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},x2=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?Vx(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
|
|
724
724
|
`),1;let o;try{o=await t.exec(r)}catch{return t.writeErr(`anyray: failed to run wrapped command
|
|
725
|
-
`),1}if(o.alreadyWritten)return o.code;let a=o.output;try{a=await t.trim(n,o.output)}catch{a=o.output}return t.write(a),o.code},CV=16*1024*1024,AV=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=gV(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>CV){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)}}),vV=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await xy(n,"cursor");return typeof r=="string"?r:t},Bx=e=>{let t=e[0]==="--b64"?e[1]:void 0;return kV(t,{exec:AV,trim:vV,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},Hx=async()=>{let e=await Vi();if(process.platform==="win32")return 0;let t=bV(e,{isRecognized:n=>ky(n)!==null||lx(n),wrap:n=>Tt(Gu,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as SV}from"node:crypto";import{homedir as Wx}from"node:os";import{extname as EV,isAbsolute as IV,join as Ry,resolve as Yi,sep as Kx}from"node:path";import{chmod as xV,readFile as RV,stat as Zx,unlink as OV,writeFile as _V}from"node:fs/promises";var _y=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),PV=16*1024,Gx=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],TV=["pattern","query","regex","search"],LV=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"]),DV=720*60*1e3,NV=512,Oy=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},$V=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],jx=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(Kx)?n:n+Kx)),MV=(e,t,n)=>IV(e)?[Yi(e)]:[...new Set([Yi(t,e),...n.map(r=>Yi(r,e))])],Vx=(e,t,n)=>SV("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),Yx=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),FV=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!_y(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!_y(o))return"";let a=$V(n.workspace_roots).map(d=>Yi(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=Oy(o,TV);if(!d)return"";let u=Oy(o,Gx);return u&&!jx(Yi(s,u),a)||!await t.remember(Vx(i,"Grep",d))?"":Yx(`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=Oy(o,Gx);if(!c||LV.has(EV(c).toLowerCase()))return"";let l=await t.resolveFile(MV(c,s,a));return!l||l.bytes<PV||!jx(l.path,a)||!await t.remember(Vx(i,"Read",l.path))?"":Yx(`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.`)},UV=async e=>{for(let t of e)try{let n=await Zx(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},BV=async()=>{let e=Ry(Wx(),".anyray");try{if((await Zx(e)).isDirectory())return Ry(e,"cursor-redirects.json")}catch{}return Ry(Wx(),".anyray-cursor-redirects.json")},HV=async e=>{let t;try{let n=await BV(),r=Date.now(),o={};try{let s=JSON.parse(await RV(n,"utf-8"));if(s?.v===1&&_y(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=DV&&(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,NV);return t=`${n}.${process.pid}.tmp`,await _V(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await xV(t,384),await fe(t,n),!0}catch{if(t)try{await OV(t)}catch{}return!1}},Xx=async()=>{let e=await Vi(),t="";try{t=await FV(e,{resolveFile:UV,remember:HV})}catch{t=""}return t&&process.stdout.write(t),0};var Zi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},Py=e=>typeof e=="string"&&e.trim()?e.trim():void 0,WV=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Zi(n,"deviceCode"),o=Zi(n,"privateKeyPem"),a=Zi(n,"publicKeyPem"),s=Zi(n,"cpOrigin"),i=Zi(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=Py(n.gatewayUrl),f=Py(n.gatewayOverride),p=Py(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}},KV=e=>new Promise(t=>setTimeout(t,e)),GV=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})},jV=async(e,t={})=>{let n=t.poll??Nd,r=t.verify??cn,o=t.loadProfile??T,a=t.saveProfile??re,s=t.saveDevKey??ic,i=t.readGateState??xr,c=t.writeGateState??$d,l=t.clearGateState??GS,d=t.sleep??KV,u=t.now??Date.now,f=t.recordMint??xa,p=t.reserveMint??Co,h=t.applyClaudeCode??(async I=>{await ar.apply(I,{dryRun:!1})}),m=I=>GV(I,{readGateState:i,writeGateState:c,now:u}),w={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:e.deviceCode,userCode:"",verificationUriComplete:"",intervalMs:e.intervalMs,grantExpiresAt:e.grantExpiresAt,startedAt:e.startedAt,privateKeyPem:e.privateKeyPem,publicKeyPem:e.publicKeyPem,gatewayUrl:e.gatewayUrl},g;try{g=await n(w,{gatewayUrl:e.gatewayOverride})}catch(I){let C=I instanceof Gt?I.kind:"cp-unreachable";return await m(C),C}let y=e.gatewayOverride??g.gatewayUrl,b=await o(),A={...b,gateway:y??b.gateway,name:g.cert.payload.user||b.name,team:e.team??g.cert.payload.team??b.team,enrolledCert:g.cert,enrolledCertExpiry:g.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(g.privateKeyPem),await a(A)}catch{return"failed"}if(!y)return await m("gateway-unreachable"),"gateway-unreachable";let S;await p();for(let I=0;I<3;I++)try{S=await r(y,g.cert,g.privateKeyPem,{timeoutMs:1e4});break}catch(C){if(C instanceof It||I===2)break;await d(1e3)}if(!S)return await m("gateway-unreachable"),"gateway-unreachable";let E={...A,gateway:y,name:S.user,team:e.team??S.team??A.team,clientKey:S.key,clientKeyExpiresAt:S.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:S.expiresAt});let I=ye({origin:y,clientKey:S.key,subscription:!0,user:E.name,team:E.team});return await h(I),await l(),"enrolled"}catch{return await m("gateway-unreachable"),"failed"}},VV=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},Jx=async()=>{let e=WV(await VV());if(e)try{await jV(e)}catch{}return 0};var YV=1e4,Ty=/^[\w.:-]{1,64}$/,Zt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},Ly=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,qx=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),YV);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 Zt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},ZV=e=>{let t=Ly(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}},XV=e=>{let t=Ly(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&Ty.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&Ty.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},JV=e=>{let t=Ly(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ie(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!Ty.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}}},qV=e=>new Promise(t=>setTimeout(t,e)),zV=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Zt("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 Na("Choose a team",r),a=o?Number.parseInt(o,10):NaN,s=Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:o;if(!s||!e.includes(s))throw new Zt("invalid-team","Choose one of the teams shown above.");return s},QV=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??qV,a=t.loadProfile??T,s=t.saveProfile??re,i=t.clearDevKey??es,c=t.chooseTeam??zV,l=t.apply??(async g=>{await ar.apply(g,{dryRun:!1})}),d=t.log??F,u=await a(),f=Rr(e.gateway,u),p=await qx(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),h=ZV(p.body);if(p.status!==200||!h)throw new Zt("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??Ra)(h.browser_url);let m=r()+h.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<m;){let g=await qx(`${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 Zt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(g.status===410)throw new Zt("expired","SSO login expired before it completed. Run anyray-connect login again.");let y=XV(g.body);if(g.status===200&&y){if(w&&!y.teams.includes(w))throw new Zt("invalid-team",`Team ${w} is not available for this account.`);w=await c(y.teams,y.default_team,e.interactive??Vt());continue}let b=JV(g.body);if(g.status!==200||!b)throw new Zt("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(ye({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Zt("expired","SSO login expired before it completed. Run anyray-connect login again.")},eY=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
725
|
+
`),1}if(o.alreadyWritten)return o.code;let a=o.output;try{a=await t.trim(n,o.output)}catch{a=o.output}return t.write(a),o.code},R2=16*1024*1024,O2=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=S2(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>R2){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)}}),_2=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await Ty(n,"cursor");return typeof r=="string"?r:t},Yx=e=>{let t=e[0]==="--b64"?e[1]:void 0;return x2(t,{exec:O2,trim:_2,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},Zx=async()=>{let e=await Vi();if(process.platform==="win32")return 0;let t=I2(e,{isRecognized:n=>Sy(n)!==null||yx(n),wrap:n=>Pt(Gu,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as T2}from"node:crypto";import{homedir as Jx}from"node:os";import{extname as P2,isAbsolute as L2,join as Py,resolve as Yi,sep as Xx}from"node:path";import{chmod as D2,readFile as N2,stat as t0,unlink as $2,writeFile as M2}from"node:fs/promises";var Dy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),F2=16*1024,zx=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],U2=["pattern","query","regex","search"],B2=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"]),W2=720*60*1e3,H2=512,Ly=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},K2=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],qx=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(Xx)?n:n+Xx)),G2=(e,t,n)=>L2(e)?[Yi(e)]:[...new Set([Yi(t,e),...n.map(r=>Yi(r,e))])],Qx=(e,t,n)=>T2("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),e0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),j2=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!Dy(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!Dy(o))return"";let a=K2(n.workspace_roots).map(d=>Yi(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=Ly(o,U2);if(!d)return"";let u=Ly(o,zx);return u&&!qx(Yi(s,u),a)||!await t.remember(Qx(i,"Grep",d))?"":e0(`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=Ly(o,zx);if(!c||B2.has(P2(c).toLowerCase()))return"";let l=await t.resolveFile(G2(c,s,a));return!l||l.bytes<F2||!qx(l.path,a)||!await t.remember(Qx(i,"Read",l.path))?"":e0(`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.`)},V2=async e=>{for(let t of e)try{let n=await t0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},Y2=async()=>{let e=Py(Jx(),".anyray");try{if((await t0(e)).isDirectory())return Py(e,"cursor-redirects.json")}catch{}return Py(Jx(),".anyray-cursor-redirects.json")},Z2=async e=>{let t;try{let n=await Y2(),r=Date.now(),o={};try{let s=JSON.parse(await N2(n,"utf-8"));if(s?.v===1&&Dy(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=W2&&(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,H2);return t=`${n}.${process.pid}.tmp`,await M2(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await D2(t,384),await fe(t,n),!0}catch{if(t)try{await $2(t)}catch{}return!1}},n0=async()=>{let e=await Vi(),t="";try{t=await j2(e,{resolveFile:V2,remember:Z2})}catch{t=""}return t&&process.stdout.write(t),0};var Zi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},Ny=e=>typeof e=="string"&&e.trim()?e.trim():void 0,J2=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Zi(n,"deviceCode"),o=Zi(n,"privateKeyPem"),a=Zi(n,"publicKeyPem"),s=Zi(n,"cpOrigin"),i=Zi(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=Ny(n.gatewayUrl),f=Ny(n.gatewayOverride),p=Ny(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}},X2=e=>new Promise(t=>setTimeout(t,e)),z2=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})},q2=async(e,t={})=>{let n=t.poll??Nd,r=t.verify??ln,o=t.loadProfile??P,a=t.saveProfile??re,s=t.saveDevKey??ic,i=t.readGateState??Or,c=t.writeGateState??$d,l=t.clearGateState??ZS,d=t.sleep??X2,u=t.now??Date.now,f=t.recordMint??xa,p=t.reserveMint??Ao,h=t.applyClaudeCode??(async I=>{await sr.apply(I,{dryRun:!1})}),m=I=>z2(I,{readGateState:i,writeGateState:c,now:u}),w={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:e.deviceCode,userCode:"",verificationUriComplete:"",intervalMs:e.intervalMs,grantExpiresAt:e.grantExpiresAt,startedAt:e.startedAt,privateKeyPem:e.privateKeyPem,publicKeyPem:e.publicKeyPem,gatewayUrl:e.gatewayUrl},g;try{g=await n(w,{gatewayUrl:e.gatewayOverride})}catch(I){let C=I instanceof Gt?I.kind:"cp-unreachable";return await m(C),C}let y=e.gatewayOverride??g.gatewayUrl,b=await o(),A={...b,gateway:y??b.gateway,name:g.cert.payload.user||b.name,team:e.team??g.cert.payload.team??b.team,enrolledCert:g.cert,enrolledCertExpiry:g.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(g.privateKeyPem),await a(A)}catch{return"failed"}if(!y)return await m("gateway-unreachable"),"gateway-unreachable";let v;await p();for(let I=0;I<3;I++)try{v=await r(y,g.cert,g.privateKeyPem,{timeoutMs:1e4});break}catch(C){if(C instanceof It||I===2)break;await d(1e3)}if(!v)return await m("gateway-unreachable"),"gateway-unreachable";let E={...A,gateway:y,name:v.user,team:e.team??v.team??A.team,clientKey:v.key,clientKeyExpiresAt:v.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:v.expiresAt});let I=ye({origin:y,clientKey:v.key,subscription:!0,user:E.name,team:E.team});return await h(I),await l(),"enrolled"}catch{return await m("gateway-unreachable"),"failed"}},Q2=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},r0=async()=>{let e=J2(await Q2());if(e)try{await q2(e)}catch{}return 0};var eY=1e4,$y=/^[\w.:-]{1,64}$/,Zt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},My=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,o0=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),eY);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 Zt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},tY=e=>{let t=My(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}},nY=e=>{let t=My(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&$y.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&$y.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},rY=e=>{let t=My(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ie(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!$y.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}}},oY=e=>new Promise(t=>setTimeout(t,e)),aY=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Zt("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 Na("Choose a team",r),a=o?Number.parseInt(o,10):NaN,s=Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:o;if(!s||!e.includes(s))throw new Zt("invalid-team","Choose one of the teams shown above.");return s},sY=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??oY,a=t.loadProfile??P,s=t.saveProfile??re,i=t.clearDevKey??es,c=t.chooseTeam??aY,l=t.apply??(async g=>{await sr.apply(g,{dryRun:!1})}),d=t.log??F,u=await a(),f=_r(e.gateway,u),p=await o0(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),h=tY(p.body);if(p.status!==200||!h)throw new Zt("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??Ra)(h.browser_url);let m=r()+h.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<m;){let g=await o0(`${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 Zt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(g.status===410)throw new Zt("expired","SSO login expired before it completed. Run anyray-connect login again.");let y=nY(g.body);if(g.status===200&&y){if(w&&!y.teams.includes(w))throw new Zt("invalid-team",`Team ${w} is not available for this account.`);w=await c(y.teams,y.default_team,e.interactive??Vt());continue}let b=rY(g.body);if(g.status!==200||!b)throw new Zt("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(ye({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Zt("expired","SSO login expired before it completed. Run anyray-connect login again.")},iY=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
726
726
|
|
|
727
727
|
Start browser SSO, choose a team, mint a personal gateway key, and configure
|
|
728
728
|
the subscription-backed Connect lane. In a non-interactive shell, --team may be
|
|
729
|
-
omitted only when the identity authority supplies a default or sole team.`,
|
|
729
|
+
omitted only when the identity authority supplies a default or sole team.`,a0=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(iY),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 sY({gateway:n,team:r},t);return $(`Signed in as ${o.user} for team ${o.team}. Your personal key was saved and configured.`),0}catch(o){if(o instanceof gt)throw o;return _(o instanceof Zt?o.message:"SSO login failed."),1}};var s0=`anyray-connect update [--check] [--auto on|off] [--json]
|
|
730
730
|
|
|
731
731
|
Keep this machine's anyray-connect binary on the published release. Runs
|
|
732
732
|
automatically about every 30 minutes; this command forces it now.
|
|
@@ -737,32 +737,32 @@ Options:
|
|
|
737
737
|
Off still accepts a release the Anyray team marks mandatory.
|
|
738
738
|
--json Emit the result as JSON.
|
|
739
739
|
--help Show this help.
|
|
740
|
-
`,
|
|
741
|
-
`),0}let n=await Ui({checkOnly:t.check,force:!t.check,allowNpmMigration:!0});if(t.json){let o=await
|
|
742
|
-
`),n.outcome==="failed"?1:0}let r=
|
|
740
|
+
`,cY=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},lY=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}.`}},i0=async e=>{let t;try{t=cY(e)}catch(o){return _(o.message),process.stderr.write(s0),1}if(t.help)return process.stdout.write(s0),0;if(t.auto!==void 0){let o=await P();if(o.autoUpdate!==!1!==t.auto&&await re({...o,autoUpdate:t.auto}),t.json||($(`Automatic updates ${t.auto?"enabled":"disabled"}.`),t.auto||k("A release the Anyray team marks mandatory still installs \u2014 that lever is for security fixes.")),!t.auto)return t.json&&process.stdout.write(`${JSON.stringify({autoUpdate:!1},null,2)}
|
|
741
|
+
`),0}let n=await Ui({checkOnly:t.check,force:!t.check,allowNpmMigration:!0});if(t.json){let o=await xo();return process.stdout.write(`${JSON.stringify({...n,autoUpdate:o.autoUpdate,path:o.path,selfUpdateAvailable:o.available,selfUpdateState:o.state},null,2)}
|
|
742
|
+
`),n.outcome==="failed"?1:0}let r=lY(n);switch(n.outcome){case"updated":case"migrated":$(r);break;case"current":$(r);break;case"available":case"migration-available":k(r),t.check&&k(`Run ${j("anyray-connect update")} to install it.`);break;case"migration-deferred":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 dY=3e3,c0=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>dy(dY)),o=e.updateStatus??xo;t(`anyray-connect ${we}
|
|
743
743
|
`);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&Ba(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}
|
|
744
744
|
${i}
|
|
745
|
-
`)}else s?.state==="will-migrate"?n("This npm runtime will migrate to the managed standalone binary on the next persistent setup change.\nRun `anyray-connect update` to migrate now.\n"):s?.state==="container"?n("Self-update and the npm-to-managed-binary migration are off in this container.\nUpdates arrive when the container is rebuilt, not via `anyray-connect update`.\n"):s?.state==="platform-unsupported"&&n("Self-update is unavailable on this platform; use `npx anyray-connect@latest` to stay current.\n");return 0};var
|
|
746
|
-
`),0};var
|
|
747
|
-
`)},
|
|
748
|
-
If the user expected one, their export may predate it, or no export has been imported yet (\`anyray-connect history import <conversations.json>\`).`;let n=new Map;for(let a of t.matches){let s=n.get(a.file)??[];s.push(a),n.set(a.file,s)}let r=[...n.entries()].slice(0,
|
|
745
|
+
`)}else s?.state==="will-migrate"?n("This npm runtime will migrate to the managed standalone binary on the next persistent setup change.\nRun `anyray-connect update` to migrate now.\n"):s?.state==="container"?n("Self-update and the npm-to-managed-binary migration are off in this container.\nUpdates arrive when the container is rebuilt, not via `anyray-connect update`.\n"):s?.state==="platform-unsupported"&&n("Self-update is unavailable on this platform; use `npx anyray-connect@latest` to stay current.\n");return 0};var uY=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},pY=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),fY=async(e={})=>{try{let t=await(e.readBootstrap??jt)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??Qe)().catch(()=>{});let n=await(e.loadProfile??P)();if(Ie(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??Jn)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??P)(),Ie(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??Or)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!uY(a)||!pY(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"}}},l0=async(e={})=>{let t=await fY(e);return process.stdout.write(`${JSON.stringify(t)}
|
|
746
|
+
`),0};var hY="2025-06-18",mY={name:"anyray",version:"1"},d0={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}},yY=20,u0={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=ty,gY=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)},wY=e=>e==="paths"||e==="lines"||e==="full"?e:"full",p0={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}},f0={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}},bY=8,kY=3,h0={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}},CY=e=>{if(e.length===0)return"No matching stashed outputs found.";let t=e.map((n,r)=>`${r+1}. ${n.handle} (score ${n.score.toFixed(2)})`+(typeof n.startLine=="number"&&typeof n.endLine=="number"?` (lines ${n.startLine}-${n.endLine})`:"")+(n.preview?` \u2014 ${n.preview}`:""));return[`Found ${e.length} matching stashed output${e.length===1?"":"s"} (ranked by relevance):`,...t,"Call anyray_retrieve with a handle above \u2014 pass its lines (startLine/endLine) to fetch just the matching part, or no extra params for the full original."].join(`
|
|
747
|
+
`)},AY=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
|
|
748
|
+
If the user expected one, their export may predate it, or no export has been imported yet (\`anyray-connect history import <conversations.json>\`).`;let n=new Map;for(let a of t.matches){let s=n.get(a.file)??[];s.push(a),n.set(a.file,s)}let r=[...n.entries()].slice(0,bY).map(([a,s])=>{let i=s.slice(0,kY).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
|
|
749
749
|
`)});return[t.matched==="tokens"&&t.tokens?.length?`No imported conversation contains "${e}"; ${n.size} mention${n.size===1?"s":""} some of its terms (${t.tokens.join(", ")}):`:`${n.size} imported conversation${n.size===1?"":"s"} mention "${e}":`,...r,'Call anyray_history({open: "<filename>"}) to read one in full.'].join(`
|
|
750
|
-
`)},
|
|
750
|
+
`)},Te=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),Fy=(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?`
|
|
751
751
|
|
|
752
752
|
[anyray: error output cut to fit the tool-result limit \u2014 ${n.length} chars total.]`:`
|
|
753
753
|
|
|
754
754
|
[anyray: output cut to fit the tool-result limit \u2014 ${n.length} chars total. Re-run narrowed (globs, a line range, or grep) to see the rest.]`,o=n.slice(0,4e4-r.length),a=o.lastIndexOf(`
|
|
755
|
-
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},
|
|
756
|
-
${p.content}`))}return
|
|
757
|
-
`)}catch{}},l=async f=>{let p=f.trim();if(!p)return;let h;try{h=JSON.parse(p)}catch{console.error("anyray mcp: dropping unparseable frame");return}let m;try{m=await
|
|
758
|
-
`))>=0;){let h=u.slice(0,p);u=u.slice(p+1),await l(h)}}u.trim()&&await l(u)}catch(f){console.error("anyray mcp: stdin error",f instanceof Error?f.message:f)}finally{clearInterval(d)}return 0};import{spawn as
|
|
755
|
+
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},vY=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 Te(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:hY,capabilities:{tools:{}},serverInfo:mY});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return Te(n??null,{});case"tools/list":{let a=[d0,u0];t.advertiseContextTools!==!1&&a.push(p0,f0);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(h0),Te(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===d0.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return Te(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 Te(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 Te(n??null,Ae("grep must be non-empty",!0));if(s.grep.length>256)return Te(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 Te(n??null,Ae(p.kind==="slice-unsupported"?h:p.message,!0));if(f&&(p.partial===void 0||typeof p.totalLines!="number"))return Te(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 ${yY} 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 Te(n??null,Ae(`${m}
|
|
756
|
+
${p.content}`))}return Te(n??null,Ae(p.content))}if(a.name===u0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Te(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 Te(n??null,l.ok?Ae(CY(l.matches)):Ae(l.message,!0))}if(a.name===p0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Te(n??null,Ae("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(f=>typeof f=="string"):void 0,l=gY(s.maxResults),d=wY(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 Te(n??null,u.ok?Ae(_I(i,u,d)):Ae(u.message??"search failed",!0))}if(a.name===h0.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 Te(n??null,d.ok?Ae(qm(d)):Ae(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return Te(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 Te(n??null,l.ok?Ae(AY(c,l)):Ae(l.message??"history search failed",!0))}if(a.name===f0.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return Te(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 Te(n??null,l.ok?Ae(qm(l)):Ae(l.message??"read failed",!0))}return Fy(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:Fy(n??null,-32601,`method not found: ${o}`)}},SY=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),Id);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:zt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},EY=(e,t=!0)=>({retrieve:async(n,r)=>Ea(await e(),n,r),recall:async(n,r)=>xd(await e(),n,r),search:(n,r,o)=>zd(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>Xd(n,r),historySearch:n=>LI(n),historyOpen:n=>DI(n),historyAvailable:async()=>await Fa()>0,advertiseContextTools:t,heartbeat:()=>{e().then(SY).catch(()=>{})}}),y0=async(e="auto",t={})=>{let n=EY(()=>nt(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,Rr().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=f=>{try{o.write(JSON.stringify(f)+`
|
|
757
|
+
`)}catch{}},l=async f=>{let p=f.trim();if(!p)return;let h;try{h=JSON.parse(p)}catch{console.error("anyray mcp: dropping unparseable frame");return}let m;try{m=await vY(h,n)}catch(w){console.error("anyray mcp: dispatch error",w instanceof Error?w.message:w),m=h?.id===void 0?null:Fy(h.id,-32603,"internal error")}m&&c(m),i()};i();let d=setInterval(i,30*6e4);d.unref?.();let u="";try{for await(let f of r){u+=f.toString("utf-8");let p;for(;(p=u.indexOf(`
|
|
758
|
+
`))>=0;){let h=u.slice(0,p);u=u.slice(p+1),await l(h)}}u.trim()&&await l(u)}catch(f){console.error("anyray mcp: stdin error",f instanceof Error?f.message:f)}finally{clearInterval(d)}return 0};import{spawn as IY}from"node:child_process";var xY=e=>e==="jetbrains"||e==="windsurf"?e:void 0,RY=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(`
|
|
759
759
|
`);h!==-1?c(s.slice(0,h)):s.length>65536&&c(void 0)},u=()=>c(void 0),f=()=>c(s.length>0?s:void 0);t.on("data",d),t.once("error",u),t.once("end",f)});if(o===void 0)return!1;try{let s=JSON.parse(o)?.id;return typeof s!="number"&&typeof s!="string"?!1:(n.write(`${JSON.stringify({jsonrpc:"2.0",id:s,error:{code:-32e3,message:e}})}
|
|
760
|
-
`),!0)}catch{return!1}},
|
|
760
|
+
`),!0)}catch{return!1}},OY={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},_Y=(e,t,n)=>{let r=new Set(OY[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}},g0=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
|
|
761
761
|
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!cd(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
|
|
762
|
-
`),1;await(n.refreshIfDue??Qe)().catch(()=>{});let s=await(n.loadProfile??
|
|
763
|
-
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??Nt)():void 0,d=ye({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=
|
|
764
|
-
`),1;w=n.comSpec??a.ComSpec??"cmd.exe",g=["/d","/s","/c",`"${h.command}" ${h.args.join(" ")}`]}return await new Promise(y=>{let b=
|
|
765
|
-
`),y(1)}),A.once("exit",(
|
|
762
|
+
`),1;await(n.refreshIfDue??Qe)().catch(()=>{});let s=await(n.loadProfile??P)(),i=await(n.readBootstrap??jt)().catch(()=>{});if(i){let y=await(n.ssoGate??Jn)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(y.exitCode===2&&y.stderr)return await RY(y.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(y.stderr),1;s=await(n.loadProfile??P)()}if(!s.gateway)return r.write(`Anyray ACP agent is not configured; run anyray-connect first.
|
|
763
|
+
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??Nt)():void 0,d=ye({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=xY(n.clientTool);u&&(d.metadata.tool=u);let f=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",p=(n.hookBinaryIsDurable??ce)(),h=Ev(d,t,{mcpServer:p?je("profile"):void 0})[f],m=n.spawn??IY,w=h.command,g=h.args;if(o==="win32"){if(!h.args.every(y=>y==="--yes"||/^@agentclientprotocol\/(claude-agent-acp|codex-acp)@[0-9]+(?:\.[0-9]+){2}$/.test(y)))return r.write(`Anyray ACP adapter arguments are invalid.
|
|
764
|
+
`),1;w=n.comSpec??a.ComSpec??"cmd.exe",g=["/d","/s","/c",`"${h.command}" ${h.args.join(" ")}`]}return await new Promise(y=>{let b=_Y(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.
|
|
765
|
+
`),y(1)}),A.once("exit",(v,E)=>{y(typeof v=="number"?v:E?1:0)})})};import{createReadStream as TY}from"node:fs";import{spawnSync as O0}from"node:child_process";import{createHash as PY}from"node:crypto";import{access as _0,chmod as Wy,copyFile as LY,lstat as DY,mkdir as NY,mkdtemp as T0,readFile as yu,rename as $Y,rm as Nr,stat as MY,writeFile as FY}from"node:fs/promises";import{constants as P0}from"node:fs";import{platform as Ga,tmpdir as UY}from"node:os";import{dirname as BY,isAbsolute as WY,join as fu}from"node:path";import{z as $e}from"zod";var HY="fleetd-installer-v4.89.2",w0=`https://github.com/anyrayHQ/install/releases/download/${HY}`,KY=1e4,GY=1e4,b0=31,jY=1500,L0=20*1024,Uy=20,VY="0.25",YY="/var/tmp",Ka="/Library/LaunchDaemons/com.fleetdm.orbit.plist",hu="/etc/default/orbit",Xi="/opt/orbit/anyray-enroll-secret.txt",D0="/opt/orbit/secret-orbit-node-key.txt",ZY="/opt/orbit/bin/orbit/orbit",zi="C:\\Program Files\\Orbit",JY=`${zi}\\bin\\orbit`,N0=`${zi}\\secret-orbit-node-key.txt`,Ji=`${zi}\\secret.txt`,XY=`${zi}\\fleet_url.txt`,$0=`${zi}\\anyray-managed.txt`,mu="Fleet osquery",Hy="C:\\Windows\\System32\\sc.exe",zY="C:\\Windows\\System32\\whoami.exe",pu="C:\\Windows\\System32\\icacls.exe",qY="C:\\Windows\\System32\\msiexec.exe",Ky="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",k0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],QY=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],eZ=`anyray-connect endpoint install
|
|
766
766
|
|
|
767
767
|
Install Fleet's signed endpoint agent and enroll this machine in Anyray.
|
|
768
768
|
|
|
@@ -770,11 +770,11 @@ Supported on macOS, Linux and Windows.
|
|
|
770
770
|
|
|
771
771
|
The command uses the current seat's stored gateway key. Administrator access is
|
|
772
772
|
required: on macOS and Linux Connect asks through sudo once when /dev/tty is
|
|
773
|
-
available; on Windows, run it from a shell started as Administrator.`,
|
|
774
|
-
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",
|
|
775
|
-
`&&r--;let o=n.end;for(;o<e.length&&/\s/.test(e[o]);)o++;if(e.startsWith("<string>",o)){let a=e.indexOf("</string>",o);return a<0?null:{start:r,end:a+9}}if(e.startsWith("<true",o)||e.startsWith("<false",o)){let a=e.indexOf("/>",o);return a<0?null:{start:r,end:a+2}}return null},
|
|
773
|
+
available; on Windows, run it from a shell started as Administrator.`,Vy=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),M0=(e,t=Ga())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),F0=(e,t=Ga(),n=!1)=>(Vy(e)||n)&&t!=="win32",ie=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},tZ=$e.object({kind:$e.enum(["pkg","deb","rpm","msi"]),path:$e.string().min(1).refine(WY),sha256:$e.string().regex(/^[0-9a-f]{64}$/)}).strict(),nZ=$e.object({action:$e.literal("restart"),os:$e.enum(["darwin","linux","win32"])}).strict(),rZ=$e.object({action:$e.literal("configure"),os:$e.enum(["darwin","linux","win32"]),fleetUrl:$e.string().min(1).max(2048),enrollSecret:$e.string().min(1).max(4096),package:tZ.optional()}).strict(),oZ=$e.discriminatedUnion("action",[nZ,rZ]),qi=(e,t)=>{let n=O0(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},Yy=async e=>{try{return await _0(e,P0.F_OK),!0}catch{return!1}},aZ=async e=>{try{let t=await MY(e);return t.isFile()&&t.size>0}catch{return!1}},Zy=(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}},By=(e,t)=>Zy(e,t)!==null,C0=e=>e==="win32"?Ji:Xi,sZ=e=>e==="win32"?N0:D0,iZ=e=>By(e,"ORBIT_FLEET_URL")&&By(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${Xi}</string>`)&&!By(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),cZ=e=>{let t=(n,r)=>e.split(`
|
|
774
|
+
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",Xi)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},Gy=(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()},U0=e=>{let t=e(Hy,["qc",mu,"8192"]);return t.status===0?t.stdout:""},jy=e=>{let t=e(Ky,QY(mu)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},lZ=async e=>{try{return e==="win32"?Gy(e,U0(qi)):Gy(e,await yu(e==="darwin"?Ka:hu,"utf8"))}catch{return}},dZ=async e=>{try{if(e==="win32")return await Yy($0)&&Gy(e,U0(qi))!==void 0;let n=await yu(e==="darwin"?Ka:hu,"utf8");return e==="darwin"?iZ(n):cZ(n)}catch{return!1}},B0=async(e,t={})=>{let n=t.exists??Yy,r=t.command??qi,o,a="absent";if(e==="win32")a=jy(r),o=await n(JY)&&a!=="absent";else{let l=e==="darwin"?await n(Ka):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(ZY)&&l}let s=await(t.configured??dZ)(e),i=await(t.hasNodeKey??(()=>aZ(sZ(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}},uZ=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),W0=(e,t)=>{let n=Zy(e,t);if(!n)return null;let r=n.start;for(;r>0&&(e[r-1]===" "||e[r-1]===" ");)r--;r>0&&e[r-1]===`
|
|
775
|
+
`&&r--;let o=n.end;for(;o<e.length&&/\s/.test(e[o]);)o++;if(e.startsWith("<string>",o)){let a=e.indexOf("</string>",o);return a<0?null:{start:r,end:a+9}}if(e.startsWith("<true",o)||e.startsWith("<false",o)){let a=e.indexOf("/>",o);return a<0?null:{start:r,end:a+2}}return null},pZ=(e,t)=>{let n=W0(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},A0=(e,t,n)=>{let r=`
|
|
776
776
|
<key>${t}</key>
|
|
777
|
-
<string>${
|
|
777
|
+
<string>${uZ(n)}</string>`,o=W0(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=Zy(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new ie("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)},fZ=(e,t,n=Xi)=>{let r=pZ(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=A0(r,"ORBIT_FLEET_URL",t),A0(r,"ORBIT_ENROLL_SECRET_PATH",n)},hZ=(e,t,n=Xi)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
|
|
778
778
|
`).filter(a=>{let s=a.indexOf("=");return s<0?!0:!r.has(a.slice(0,s).trim())}).filter((a,s,i)=>a.trim()!==""||i[s-1]?.trim()!=="").join(`
|
|
779
779
|
`).trimEnd()}
|
|
780
780
|
|
|
@@ -784,13 +784,13 @@ available; on Windows, run it from a shell started as Administrator.`,Wy=e=>!!(e
|
|
|
784
784
|
# file, never in this world-readable one.
|
|
785
785
|
ORBIT_FLEET_URL=${t}
|
|
786
786
|
ORBIT_ENROLL_SECRET_PATH=${n}
|
|
787
|
-
`},
|
|
788
|
-
`,384);e.os!=="win32"&&await
|
|
789
|
-
`,384),e.os==="win32"&&
|
|
790
|
-
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??
|
|
791
|
-
sudo anyray-connect endpoint install`),"deferred"}
|
|
792
|
-
`;if(Buffer.byteLength(t)>
|
|
793
|
-
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Ga()==="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
|
|
787
|
+
`},H0=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}},mZ=$e.object({code:$e.string().min(1).optional(),message:$e.string().min(1).optional()}).passthrough(),v0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},yZ=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=mZ.safeParse(t);if(!r.success)return n;let o=v0(r.data.message??""),a=v0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},S0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??GY),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 ie("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new ie("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new ie(yZ(a.status,c))}let s;try{s=await a.json()}catch{throw new ie("The gateway returned malformed endpoint enrollment data.")}let i=$e.object({fleetUrl:$e.string().min(1).max(2048),enrollSecret:$e.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!H0(i.data.fleetUrl))throw new ie("The gateway returned invalid endpoint enrollment data.");return i.data},gZ=async(e={})=>{let t=e.exists??Yy;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 ie("Linux endpoint installation requires either dpkg or rpm.")},wZ=async e=>e==="darwin"?"pkg":e==="win32"?"msi":gZ(),Jy=e=>`fleetd.${e}`,bZ=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",kZ=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),KY);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},CZ=async(e,t={})=>{let n=Jy(e),r=t.fetchResponse??fetch,o;try{o=await kZ(`${w0}/SHA256SUMS`,r)}catch{throw new ie("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new ie(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=cy(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await T0(fu(UY(),"anyray-endpoint-")),i=fu(s,n);try{await Wy(s,448),await(t.download??uy)(`${w0}/${n}`,i,a)}catch(c){if(await Nr(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Fi&&c.status===404)return;throw new ie("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>Nr(s,{recursive:!0,force:!0})}},AZ=async(e,t,n)=>{await NY(BY(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Nr(r,{force:!0});try{await FY(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await $Y(r,e)}catch(o){throw await Nr(r,{force:!0}).catch(()=>{}),o}},E0=async e=>{let t=PY("sha256");for await(let n of TY(e))t.update(n);return t.digest("hex")},vZ=async(e,t={})=>{let n=await DY(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new ie("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await E0(e.path)!==e.sha256)throw new ie("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await T0(fu(YY,"anyray-endpoint-root-")),o=fu(r,Jy(e.kind));try{if(await Wy(r,448),await LY(e.path,o),await Wy(o,384),await E0(o)!==e.sha256)throw new ie("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>Nr(r,{recursive:!0,force:!0})}}catch(a){throw await Nr(r,{recursive:!0,force:!0}).catch(()=>{}),a}},Ha=(e,t)=>{if(e.status!==0)throw new ie(t)},I0="com.fleetdm.fleetd.config",SZ="com.fleetdm.fleetd.enroll.secret",EZ=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",D0],IZ=[XY,N0],xZ=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(I0))throw new ie(`This machine already receives its endpoint configuration from an MDM profile (${I0}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},x0=async(e,t,n)=>{let r=n.removeFile??(o=>Nr(o,{force:!0}));for(let o of e==="win32"?IZ:EZ)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",SZ,"/Library/Keychains/System.keychain"])},RZ=e=>{e(pu,[Ji,"/inheritance:r"]),e(pu,[Ji,"/grant:r","*S-1-5-18:(F)"]),e(pu,[Ji,"/grant:r","*S-1-5-32-544:(F)"]),e(pu,[Ji,"/remove:g","*S-1-5-32-545"])},OZ=(e,t,n)=>{if(e.kind==="pkg"){Ha(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){Ha(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){Ha(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}Ha(t(qY,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},_Z=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<Uy;r++){if(n=t("/bin/launchctl",["bootstrap","system",Ka]),n.status===0)return;t("/bin/sleep",[VY])}throw new ie(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(Hy,["stop",mu]);for(let n=0;n<Uy;n++){let r=jy(t);if(r==="Stopped"||r==="absent")break;t(Ky,k0)}for(let n=0;n<Uy;n++){if(t(Hy,["start",mu]).status===0||jy(t)==="Running")return;t(Ky,k0)}throw new ie("Orbit was configured, but the Windows service could not be started.")}Ha(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),Ha(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},TZ=e=>new Promise(t=>setTimeout(t,e)),K0=async(e,t={})=>{let n=t.command??qi,r=t.readText??(c=>yu(c,"utf8")),o=t.writeText??AZ,a=t.removeSecret??(()=>Nr(C0(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&xZ(n),e.package&&!bZ(e.os,e.package.kind))throw new ie("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new ie("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await x0(e.os,n,t),e.package){let d=await(t.preparePackage??vZ)(e.package);i=d.cleanup,OZ(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Ka);await o(Ka,fZ(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(hu);await o(hu,hZ(d,e.fleetUrl),420)}else await o($0,`anyray
|
|
788
|
+
`,384);e.os!=="win32"&&await x0(e.os,n,t),await o(C0(e.os),`${e.enrollSecret}
|
|
789
|
+
`,384),e.os==="win32"&&RZ(n),s=e.os!=="win32"}_Z(e.os,n);let c=t.checkIn??(async d=>{let u=await B0(d);return u.running&&u.checkedIn}),l=t.wait??TZ;for(let d=0;d<(t.attempts??b0);d++){if(await c(e.os))return;d+1<(t.attempts??b0)&&await l(jY)}throw new ie("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(()=>{})}},PZ=async()=>{try{return await _0("/dev/tty",P0.R_OK),!0}catch{return!1}},LZ=12288,DZ=e=>{let t=e(zY,["/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>=LZ},NZ=async(e,t={})=>{if((t.os??Ga())==="win32")return(t.elevated??(()=>DZ(t.command??qi)))()?(await e(),"direct"):((t.print??k)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
|
|
790
|
+
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??PZ)()){if(await(t.reexec??(async()=>1))()!==0)throw new ie("Administrator access did not complete; the endpoint agent was not enrolled.");return"sudo"}return(t.print??k)(`Administrator access is required. Run:
|
|
791
|
+
sudo anyray-connect endpoint install`),"deferred"},$Z=async e=>{let t=`${JSON.stringify(e)}
|
|
792
|
+
`;if(Buffer.byteLength(t)>L0)throw new ie("The privileged endpoint plan is unexpectedly large.");let n=un(["__anyray-endpoint-install"]);return O0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},MZ=async(e,t={})=>(t.withRoot??NZ)(()=>(t.apply??K0)(e),{...t.root,reexec:()=>(t.sudo??$Z)(e)}),R0=async()=>{if((process.getuid?.()??-1)!==0||!process.env.SUDO_USER)return P();let e=process.env.SUDO_USER;if(!/^[A-Za-z0-9._-]{1,64}$/.test(e))return P();let t;try{let s=(await yu("/etc/passwd","utf8")).split(`
|
|
793
|
+
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Ga()==="darwin"?`/Users/${e}`:`/home/${e}`;let n=process.env.HOME,r=process.env.USERPROFILE;process.env.HOME=t,process.env.USERPROFILE=t;try{return await P()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},G0=async(e={},t={})=>{let n=t.os??Ga();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new ie("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??B0)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??R0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??lZ)(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??S0)(l,d);if(u===f.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};F("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new ie("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??R0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new ie("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??S0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>wZ(r)))();if(i=await(t.stagePackage??CZ)(f),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${Jy(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??MZ)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},Xy=e=>e instanceof ie?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",j0=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return k(eZ),0;if(e.length!==1||e[0]!=="install")return _("Usage: anyray-connect endpoint install"),1;try{let t=await G0();return t.message&&(t.outcome==="installed"?$(t.message):F(t.message)),0}catch(t){return _(Xy(t)),1}},FZ=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>L0)throw new ie("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new ie("The privileged endpoint plan is malformed.")}let r=oZ.safeParse(n);if(!r.success||r.data.os!==Ga()||r.data.action==="configure"&&!H0(r.data.fleetUrl))throw new ie("The privileged endpoint plan is invalid.");return r.data},V0=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 K0(await FZ()),0}catch(t){return _(Xy(t)),1}},Y0=async(e,t=G0)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?$(n.message):F(n.message)),n.outcome}catch(n){F(`Endpoint agent: ${Xy(n)} Tool routing remains configured.`);return}};import{execSync as zy}from"node:child_process";import{hostname as UZ}from"node:os";var BZ=e=>{try{if(e==="darwin"){let t=zy("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=zy('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 zy("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},gu=(e={platform:process.platform,read:()=>BZ(process.platform),hostname:UZ})=>e.read().trim()||e.hostname().trim();var WZ=(e,t=Date.now())=>e.credentialProtocol==="stable-heartbeat-v1"||!Td(e,void 0,t),Z0=async(e,t={})=>{if(!await(t.fleetdPresent??Oo)())return{retired:!1,reason:"no-fleetd",messages:[]};if(!WZ(e,t.now??Date.now()))return{retired:!1,reason:"seat-could-lapse",messages:[]};let r=[],o=await(t.uninstallScheduler??ur)();r.push(...o.messages);let a=await(t.uninstallProxy??qt)();return r.push(...a.messages),{retired:!0,messages:r}};var J0=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();return t?t.toLowerCase():(e.platform??process.platform)==="darwin"?(e.readMacUuid??(()=>gu()))().trim().toLowerCase():""};var X0=["reapply_config","remint","revert","revert_tool"],HZ=/^[a-z0-9][a-z0-9-]{0,31}$/;var KZ=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"||!X0.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&HZ.test(t.tool):t.tool===void 0},qy=e=>e?.name??"error",z0=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":X0.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!KZ(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",qy(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",qy(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:",qy(i))}return a.kind};var GZ=1e4,ja=e=>e?.name??"Error",Qy=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(GZ)})}catch(o){console.error(`anyray seat offboard report: ${ja(o)}`)}},jZ=e=>e==="reverted"||e==="queued",q0=async(e={})=>{let t=e.loadProfile??P,n=e.clearDeviceTokenState??Md,r=e.reportSeatOffboarded??Qy,o=e.clearEnrollment??cc,a=e.recordManagedTools??Qn,s=e.markSeatOffboarded??dc,i=e.adapterById??Ht,c=e.uninstallProxy??qt,l=e.uninstallScheduler??ur,d=e.unitsPresent??Oi,u=e.saveProfile??re,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: ${ja(E)}`)}let w=[],g=[],y=[];for(let E of p){let I=i(E);if(!I){y.push(E);continue}try{let C=await I.revert({dryRun:!1,fullRevert:!0});w.push({id:E,status:C.status}),jZ(C.status)?g.push(E):y.push(E)}catch(C){console.error(`anyray offboard: reverting ${E}: ${ja(C)}`),y.push(E)}}let b=!0;try{await a(w,!0,!0)}catch(E){b=!1,console.error(`anyray offboard: recording managed tools: ${ja(E)}`)}let A=y.length===0&&b,v=!1;if(A)try{await s(),v=!0}catch(E){console.error(`anyray offboard: stamping offboard: ${ja(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: ${ja(E)}`)}return{reverted:g,unresolved:y,enrollmentCleared:h,credentialHeld:m,recordPersisted:b,offboardMarked:v,ok:y.length===0&&!m&&b&&v}};var Q0=e=>e?.name??"Error",eR=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??P,r=t.recordManagedTools??Qn,o=t.adapterById??Ht,a=t.isLocked??wi,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}: ${Q0(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${Q0(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{platform as rR}from"node:os";var oR=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
794
794
|
|
|
795
795
|
${j("Usage")}
|
|
796
796
|
npx anyray-connect [options]
|
|
@@ -827,7 +827,7 @@ ${j("What it does")}
|
|
|
827
827
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
828
828
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
829
829
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
830
|
-
per-skill versions ${
|
|
830
|
+
per-skill versions ${S("sync")} last wrote \u2014 for zero-question re-runs.`,aR=`${j("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
831
831
|
|
|
832
832
|
${j("Usage")}
|
|
833
833
|
npx anyray-connect <gateway-url> [options]
|
|
@@ -1023,22 +1023,22 @@ ${j("What it does")}
|
|
|
1023
1023
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
1024
1024
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
1025
1025
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
1026
|
-
per-skill versions ${
|
|
1027
|
-
${e.length===1?`${e[0]} is open and won't pick this up until it restarts. Quit it now?`:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]} are open and won't pick this up until they restart. Quit them now?`}`,
|
|
1028
|
-
${o} ${n} tool target(s)?`;return await(r.confirm??Da)(a)?"proceed":"declined"},fX=async e=>{if(e[0]==="__anyray-hook"){let n=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return Nx(n)}if(e[0]==="__anyray-codex-hook")return $x();if(e[0]==="__anyray-prompt-hook")return Mx();if(e[0]==="__anyray-shell-pretool")return Hx();if(e[0]==="__anyray-shell-run")return Bx(e.slice(1));if(e[0]==="__anyray-read-pretool")return Xx();if(e[0]==="__anyray-sso-gate")return ZS(e.slice(1));if(e[0]==="__anyray-sso-poll")return Jx();if(e[0]==="__anyray-vscode-gate")return n0();if(e[0]==="__anyray-spawn-refresh")return await Ir(),0;if(e[0]==="__anyray-mcp-server"){let n=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return l0(n)}if(e[0]==="__anyray-acp-agent")return d0(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return U0(e.slice(1));if(e[0]==="__anyray-refresh"){await cy(),await Qe({runAmbientSelfcheck:!0}),await Cm(),await aX(),await DS(),await NS();let n=await T().catch(()=>{});if(n){process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged&&(n.anyrayFleetManaged=!0,await re(n).catch(()=>{}));let r=n.anyrayFleetManaged===!0&&await Ro().catch(()=>!1);if(await H0(n,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey){let o=n.gateway,a=n.clientKey,s=W0(),i=n.enrolledCert;if(s&&i){let l=await Ue().catch(()=>{});l&&await Vv(o,a,i,l,s).catch(()=>{})}await G0(o,a,{execute:async(l,d)=>l==="remint"||l==="reapply_config"?await Qe({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?Y0(d):(await j0()).ok?"ok":"failed"}).catch(()=>{})}}return await Ui(),0}if(e[0]==="__anyray-fallback-proxy")return pE();if(e[0]==="__anyray-persistence")return hE(e.slice(1));if(e[0]==="__anyray-quit-watch")return CE(e.slice(1));if(e[0]===ti)return rI(e.slice(1));if(e[0]==="--version"||e[0]==="-V")return t0();try{let n=await Rg(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(uX(e)){let n=dX(await YI());n?.level==="warn"?L(n.message):n&&console.error(n.message)}if(e[0]==="managed")return TE(e.slice(1));if(e[0]==="endpoint")return F0(e.slice(1));if(e[0]==="print-key")return $E(e.slice(1));if(e[0]==="models")return FE(e.slice(1));if(e[0]==="copilot-login")return UE(e.slice(1));if(e[0]==="desktop"){let n=e.slice(1),r=Vm(n);return r?Jy(r,!1):gI(n)}if(e[0]==="retrieve")return bI(e.slice(1));if(e[0]==="recall")return kI(e.slice(1));if(e[0]==="history")return TI(e.slice(1));if(e[0]==="migrate")return DI(e.slice(1));if(e[0]==="login")return zx(e.slice(1));if(e[0]==="update")return e0(e.slice(1));let t=e[0];if(t&&cX.has(t)){let n=e.slice(1),r;try{r=Q0(n)}catch(o){return _(o.message),k("\nRun `npx anyray-connect --help` for usage."),1}return r.help?(k(r.helpAll?z0:q0),0):t==="status"?qI({gateway:r.gateway}):t==="doctor"?nx({gateway:r.gateway,json:r.json,verify:r.verify,noVerify:r.noVerify,quick:r.quick,repair:r.repair,securityReview:r.securityReview}):t==="sync"?rx({gateway:r.gateway}):t==="device-url"?BE():Jy(n,!0)}return Jy(e,!1)},eR=async e=>{try{return await fX(e)}catch(t){if(t instanceof gt)return console.error(v("Cancelled.")),130;throw t}},hX=async(e,t,n={})=>{let r=n.isInteractive??Vt,o;try{o=Q0(e)}catch(O){return _(O.message),k("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return k(o.helpAll?z0:q0),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):eI({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 D=o.upstreamKey.trim();if(!D)return _("--upstream-key must not be empty."),1;a={url:Ye(o.upstream),key:D}}let s=await T();if(!o.revert&&!o.dryRun&&o.noKeyRefresh!==!0){let O=await cy();(O==="migrated"||O==="already-direct")&&(s=await T())}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream),o.retiredFallbackFlag&&L("--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&&Vt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??QZ)(o,s),c=!0);let l;try{l=HZ(o.tools)}catch(O){return _(O.message),1}k(j(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&$i(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=tu(o.enroll);if(O)try{let D=await Mi("Resolving enrollment link\u2026",()=>MI(O)),W=!o.gateway;W&&(o.gateway=D.gatewayUrl),d=D.deploymentId,u=D.email,f=!0,W&&F(`Enrollment link${D.org?` for ${D.org}`:""}: gateway ${D.gatewayUrl}`),D.seatMode&&!o.subscription&&(o.subscription=!0,F("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(D){let W=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(W)F(`Could not resolve the gateway from the enrollment link \u2014 using ${W}.`);else return _(D instanceof Error?D.message:String(D)),1}}let p,h;if(o.claim&&!o.revert)if(o.dryRun)F("dry run: not enrolled (skipped redeeming the enrollment link).");else{let O=FS(o.claim);if(!O)return _("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let D=await Mi("Connecting this machine\u2026",()=>US({cpOrigin:O.cpOrigin,claim:O.claim,gatewayUrl:o.gateway}));p={cert:D.cert,privateKeyPem:D.privateKeyPem},D.deploymentId&&(d=D.deploymentId),!o.gateway&&D.gatewayUrl&&(o.gateway=D.gatewayUrl),h=D.ssoLink}catch(D){return _(D instanceof Error?D.message:String(D)),1}}if(o.sso&&!p&&!o.revert)if(o.dryRun)F("dry run: not enrolled via SSO (skipped minting a personal key).");else{let O=xt(o.sso);if(!O)return _($i(o.sso)?"that is an enrollment link, not an SSO link \u2014 re-run with --enroll instead of --sso.":"invalid --sso value: expected a https://\u2026/sso/<tenantId> link or a tnt_ id."),1;try{let D=await Dd({cpOrigin:O.cpOrigin,tenantId:O.tenantId,gatewayUrl:o.gateway,log:pe=>F(pe),open:r()?Ra:void 0}),W=await Mi("Waiting for SSO sign-in\u2026",()=>Nd(D,{gatewayUrl:o.gateway}));p={cert:W.cert,privateKeyPem:W.privateKeyPem},W.deploymentId&&(d=W.deploymentId),!o.gateway&&W.gatewayUrl&&(o.gateway=W.gatewayUrl)}catch(D){return _(D instanceof Error?D.message:String(D)),1}}let m=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;m&&(o.gateway=m);let w;try{w=ln(o.gateway)}catch(O){return _(O.message),1}let g,y;m&&!o.revert&&F(`Gateway: ${w} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&Qy(w)&&L(`${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||KZ(s),S,E,I,C,x,P,U=s.credentialProtocol==="stable-heartbeat-v1",Z=async O=>{await Co();let D=jv(O.token),W=Yv(s.enrolledCert,s.enrolledCertExpiry,O.deploymentId,Date.now(),D,s.enrolledTokenHash,O.expectedUser),pe=W?await Ue():void 0,z=W&&pe&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:pe,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,Ve=Fe=>Zv({cpOrigin:O.cpOrigin,token:O.token,gatewayOrigin:w,email:O.email,team:O.team,machineId:O.machineId,deploymentId:O.deploymentId,reuse:Fe?z:void 0}),Me=!!z,Q=await(async()=>{try{return await Ve(Me)}catch(Fe){if(z&&Fe instanceof It)return F("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),Me=!1,await Ve(!1);throw Fe}})();A=Q.clientKey,o.user=wu(o.user,Q.user),o.team=wu(o.team,Q.team),S=Q.cert,E=Q.cert.payload.expiresAt,P=Q.expiresAt,U=Q.capabilities?.includes(bi)===!0,x=void 0,Me||(I=Q.privateKeyPem),Me||(C=D),$(`Enrolled${Q.user?` as ${Q.user}`:""}${Me?" (reused your saved cert)":""} \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)};if(o.enroll&&!o.revert)if(o.dryRun)F("dry run: not enrolled (skipped minting a personal key).");else{let O=tu(o.enroll);if(!O)return _(xt(o.enroll)?"that is an SSO link, not an enrollment link \u2014 re-run with --sso instead of --enroll.":"invalid --enroll value: expected a https://\u2026/enroll/<token> link or a bare token."),1;try{let D=o.machine?gu():void 0,W=u??BZ(o.user);if(!o.machine&&!o.user&&!u){let z=jE();z.distinct||(L(` Enrolling as "${z.identity}" \u2014 this may not be unique to you.`),L(z.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"),L(z.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."),L(" Re-run with `--user you@company.com` (or set `git config --global"),L(" user.email`) so your usage is attributed to you."))}let pe=o.machine?`machine:${D}`:f?W:void 0;await Z({cpOrigin:O.cpOrigin,token:O.token,email:W,team:o.team,machineId:D,deploymentId:d,expectedUser:pe})}catch(D){return _(D instanceof Error?D.message:String(D)),D instanceof It&&F("The gateway rejected this enrollment. Ask your admin to confirm the gateway is connected and entitled, and that your link targets the right gateway \u2014 the exact reason is in the gateway logs."),1}}if(p){await Co();try{let O=await cn(w,p.cert,p.privateKeyPem);A=O.key,o.user=wu(o.user,O.user),o.team=wu(o.team,O.team),S=p.cert,E=p.cert.payload.expiresAt,I=p.privateKeyPem,P=O.expiresAt,U=O.capabilities?.includes(bi)===!0;let D=o.sso?xt(o.sso):void 0;x=D?`${D.cpOrigin}/sso/${D.tenantId}`:h,$(`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 It&&F("The gateway rejected your SSO sign-in. Ask your admin to confirm the gateway is connected and entitled \u2014 the exact reason is in the gateway logs."),1}}if(!o.revert){let O=o.yes;g=await YE(o.user,s.name,O),y=await ZE(o.team,s.team,O)}let Y;!o.revert&&!o.subscription&&!o.placeholder&&(Y=await Nt(),K("Detecting your sign-ins"),k(` Claude (Anthropic): ${a?et("BYO upstream key (passthrough)"):Y.anthropic?et("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),k(` Codex (ChatGPT): ${Y.openai?et("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),!Y.anthropic&&!Y.openai&&!Y.copilot&&Wr()&&(L(" No subscription sign-ins found on this host. Sign-ins do not cross the"),L(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),L(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),L(" and re-run, or everything below routes on the org key instead.")));let H=ye({origin:w,placeholderKey:o.key,clientKey:A,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:Y,user:g,team:y,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),q=o.revert===!0&&(o.tools?.length??0)===0,me={dryRun:o.dryRun,fullRevert:q};if(!o.revert&&H.clientKey&&!Ie(H.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&&!H.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?(L(` ${O}`),F(" Dry run only \u2014 no placeholder configuration will be written."),await Z0(l,"after-enrollment"),F(`
|
|
1029
|
-
Dry run complete \u2014 no files were written.`),0):(_(` ${O}`),1)}o.revert||
|
|
1030
|
-
Dry run \u2014 no files will be written.`);let
|
|
1031
|
-
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(
|
|
1032
|
-
Gateway ${
|
|
1026
|
+
per-skill versions ${S("sync")} last wrote \u2014 for zero-question re-runs.`,YZ=e=>{let t=e?.trim();return t||Mm()},wu=(e,t)=>t||e,sR=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},ZZ=e=>!e||e.length===0?se:e.map(t=>{let n=Ht(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${se.map(r=>r.id).join(", ")}`);return n}),JZ=(e,t)=>{if(K("Gateway target"),k(` Origin: ${et(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 (${$t(e.clientKey)}) ${S("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=X(e,"anthropic")?et("your subscription"):"org key",r=X(e,"openai")?et("your subscription"):"org key";k(` Auth: auto ${S("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&k(` Client key: personal gateway key (${$t(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 (${$t(e.clientKey)}) ${S("rides x-anyray-api-key")}`)):e.clientKey?k(` Auth: personal gateway key (${$t(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: ${et("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: ${et("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: ${et("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)")}`)},tR=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}`:""}`):F(` ${n.title} ${S(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},XZ=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!Ie(n))return;let r=e.clientKeyExpiresAt?.trim();if(!r)return n;let o=Date.parse(r);return Number.isFinite(o)&&o>t?n:void 0},zZ={loadDevKey:Ue,saveDevKey:ic,clearDevKey:es,saveProfile:re},qZ=async(e,t,n,r=zZ,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}},QZ=async(e,t,n,r,o)=>{n.dryRun||await lc();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"?$(` ${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"?F(" left on its own plan (no change)"):F(` ${p.status}`)}catch(p){l.push({id:u.id,status:"failed"}),_(` failed: ${p instanceof Error?p.message:String(p)}`)}}if(d.length>0&&F(`Skipped ${d.length} not installed (${d.join(", ")})`),!n.dryRun){let u=await fc().catch(()=>[]);u.length&&F(` Removed ${u.length} unused Anyray runtime copies.`)}return{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l}},eJ=(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},tJ=async(e,t,n=rR())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!wb(i,n)||!gb(i,n))continue;let c=mb(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:yb(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},nJ=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,rJ=e=>`
|
|
1027
|
+
${e.length===1?`${e[0]} is open and won't pick this up until it restarts. Quit it now?`:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]} are open and won't pick this up until they restart. Quit them now?`}`,oJ=async(e,t={})=>{let n=t.requestQuit??(a=>kb(a)),r=t.waitFor??(a=>Cb(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),$(` Closed ${a.title}.`);continue}D(` ${a.title} is still open \u2014 leaving it alone.`),F(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},aJ=(e,t={})=>{let n=t.relaunch??(o=>Ab(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),$(` Reopened ${o.title}.`)):D(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},bu=e=>e.changesBilling!==!0,sJ=async(e,t,n={})=>{let r=n.hasEnrollment??Pu,o=n.canMultiSelect??VI,a=n.multiSelect??YI,s=n.prompt??Na,i=n.registry??se;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 gt;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 gt;for(let l=0;l<3;l++)if(c==="enroll"){let d=await s("? Enrollment link or token");if(d&&$i(d)&&tu(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&&xt(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&&$i(d)){e.enroll=d,k("That looks like an enrollment link \u2014 using passwordless enrollment.");break}try{if(!d)throw new Error("missing gateway");e.gateway=dn(d);break}catch{D("That is not a valid http(s) gateway URL. Try again.")}}if(!e.enroll&&!e.sso&&!e.gateway)throw new gt}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=>bu(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:bu(h)?void 0:"moves inference spend from your subscription to the org API bill",selected:bu(h),requiresExplicitChoice:!bu(h)}))});if(p.kind==="cancelled")throw new gt;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 gt}l.length>0&&F(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},iJ=async(e,t)=>{K("Verifying the connection");let n=await Mi("Checking the gateway\u2026",()=>Wi(e,{tools:t}));n.kind==="ok"?$(` ${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}`))},cJ=5e3,lJ=500,nR=3,dJ=600*1e3,uJ=async()=>{try{let e=await VZ(await Do());return Date.now()-e.mtimeMs}catch{return Number.POSITIVE_INFINITY}},pJ=async(e={})=>{try{let t=await(e.load??P)();if(t.keyRefreshEnabled!==!0){if((e.draining??op)()||!await(e.unitExists??pw)()||await(e.profileAgeMs??uJ)()<dJ)return;await(e.uninstall??qt)(t.fallbackPort??ke);return}if(!t.gateway||t.persistenceOwner==="tray"&&await(e.checkTray??So)(t)==="healthy")return;let n=t.fallbackPort??ke,r=e.probe??be,o=e.probeGapMs??lJ;for(let s=0;s<nR;s++){if(await r(n,s===0?void 0:cJ)!==null)return;s<nR-1&&o>0&&await new Promise(c=>setTimeout(c,o))}if((e.draining??op)())return;let a=await(e.install??Dt)({port:n,remoteOrigin:new URL(t.gateway).origin});if(!a.ok)for(let s of a.messages)console.error(s)}catch{}},fJ=async(e,t,n={})=>{let r=n.install??Dt,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?($(` Running on 127.0.0.1:${t} \u2192 ${e.origin} \u2014 your key refreshes automatically, no restart needed.`),En(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.":kt(ht())?" 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)},hJ=async(e,t={})=>{if(e.dryRun)return;let n=t.install??dr,r=t.uninstall??ur;if(e.want&&e.trayManaged){e.announcePrimary&&(K("Automatic key refresh"),$(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."));return}if(e.want){let o=await n();if(e.announcePrimary){K("Automatic key refresh");for(let a of o.messages)k(` ${a}`);o.ok&&$(" Your gateway key now re-mints every ~30 min \u2014 no tool will 401 on a stale key mid-session.")}o.ok||await re({...await P(),refreshSchedulerEnabled:!1});return}if(!e.scopedRevert&&e.wasEnabled){K("Automatic key refresh");let o=await r();for(let a of o.messages)k(` ${a}`);await re({...await P(),refreshSchedulerEnabled:!1}),$(" Removed the automatic key-refresh schedule.")}},mJ=new Set(["login","wizard","status","doctor","sync","device-url"]),yJ=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint"]),gJ=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."}},wJ=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=Jm(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]||!yJ.has(e[0])},eg=async(e,t)=>{try{return await CJ(e,t)}catch(n){if(n instanceof gt)return console.error(S("Cancelled \u2014 nothing was written.")),130;throw n}},bJ=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??Vt)())return"non-interactive";let o=e.revert?"remove Anyray config from":"configure",a=t?"Apply this configuration?":`
|
|
1028
|
+
${o} ${n} tool target(s)?`;return await(r.confirm??Da)(a)?"proceed":"declined"},kJ=async e=>{if(e[0]==="__anyray-hook"){let n=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return Hx(n)}if(e[0]==="__anyray-codex-hook")return Kx();if(e[0]==="__anyray-prompt-hook")return Gx();if(e[0]==="__anyray-shell-pretool")return Zx();if(e[0]==="__anyray-shell-run")return Yx(e.slice(1));if(e[0]==="__anyray-read-pretool")return n0();if(e[0]==="__anyray-sso-gate")return qS(e.slice(1));if(e[0]==="__anyray-sso-poll")return r0();if(e[0]==="__anyray-vscode-gate")return l0();if(e[0]==="__anyray-spawn-refresh")return await Rr(),0;if(e[0]==="__anyray-mcp-server"){let n=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return y0(n)}if(e[0]==="__anyray-acp-agent")return g0(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return V0(e.slice(1));if(e[0]==="__anyray-refresh"){await py(),await Qe({runAmbientSelfcheck:!0}),await Sm(),await pJ(),await FS(),await US();let n=await P().catch(()=>{});if(n){process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged&&(n.anyrayFleetManaged=!0,await re(n).catch(()=>{}));let r=n.anyrayFleetManaged===!0&&await Oo().catch(()=>!1);if(await Z0(n,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey){let o=n.gateway,a=n.clientKey,s=J0(),i=n.enrolledCert;if(s&&i){let l=await Ue().catch(()=>{});l&&await Xv(o,a,i,l,s).catch(()=>{})}await z0(o,a,{execute:async(l,d)=>l==="remint"||l==="reapply_config"?await Qe({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?eR(d):(await q0()).ok?"ok":"failed"}).catch(()=>{})}}return await Ui(),0}if(e[0]==="__anyray-fallback-proxy")return yE();if(e[0]==="__anyray-persistence")return wE(e.slice(1));if(e[0]==="__anyray-quit-watch")return EE(e.slice(1));if(e[0]===ti)return iI(e.slice(1));if(e[0]==="--version"||e[0]==="-V")return c0();try{let n=await Pg(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(wJ(e)){let n=gJ(await ex());n?.level==="warn"?D(n.message):n&&console.error(n.message)}if(e[0]==="managed")return $E(e.slice(1));if(e[0]==="endpoint")return j0(e.slice(1));if(e[0]==="print-key")return BE(e.slice(1));if(e[0]==="models")return HE(e.slice(1));if(e[0]==="copilot-login")return KE(e.slice(1));if(e[0]==="desktop"){let n=e.slice(1),r=Jm(n);return r?eg(r,!1):CI(n)}if(e[0]==="retrieve")return vI(e.slice(1));if(e[0]==="recall")return SI(e.slice(1));if(e[0]==="history")return $I(e.slice(1));if(e[0]==="migrate")return FI(e.slice(1));if(e[0]==="login")return a0(e.slice(1));if(e[0]==="update")return i0(e.slice(1));let t=e[0];if(t&&mJ.has(t)){let n=e.slice(1),r;try{r=sR(n)}catch(o){return _(o.message),k("\nRun `npx anyray-connect --help` for usage."),1}return r.help?(k(r.helpAll?aR:oR),0):t==="status"?ox({gateway:r.gateway}):t==="doctor"?lx({gateway:r.gateway,json:r.json,verify:r.verify,noVerify:r.noVerify,quick:r.quick,repair:r.repair,securityReview:r.securityReview}):t==="sync"?dx({gateway:r.gateway}):t==="device-url"?GE():eg(n,!0)}return eg(e,!1)},iR=async e=>{try{return await kJ(e)}catch(t){if(t instanceof gt)return console.error(S("Cancelled.")),130;throw t}},CJ=async(e,t,n={})=>{let r=n.isInteractive??Vt,o;try{o=sR(e)}catch(O){return _(O.message),k("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return k(o.helpAll?aR:oR),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):oI({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 L=o.upstreamKey.trim();if(!L)return _("--upstream-key must not be empty."),1;a={url:Ye(o.upstream),key:L}}let s=await P();if(!o.revert&&!o.dryRun&&o.noKeyRefresh!==!0){let O=await py();(O==="migrated"||O==="already-direct")&&(s=await P())}!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&&Vt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??sJ)(o,s),c=!0);let l;try{l=ZZ(o.tools)}catch(O){return _(O.message),1}k(j(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&$i(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=tu(o.enroll);if(O)try{let L=await Mi("Resolving enrollment link\u2026",()=>GI(O)),H=!o.gateway;H&&(o.gateway=L.gatewayUrl),d=L.deploymentId,u=L.email,f=!0,H&&F(`Enrollment link${L.org?` for ${L.org}`:""}: gateway ${L.gatewayUrl}`),L.seatMode&&!o.subscription&&(o.subscription=!0,F("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(L){let H=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(H)F(`Could not resolve the gateway from the enrollment link \u2014 using ${H}.`);else return _(L instanceof Error?L.message:String(L)),1}}let p,h;if(o.claim&&!o.revert)if(o.dryRun)F("dry run: not enrolled (skipped redeeming the enrollment link).");else{let O=HS(o.claim);if(!O)return _("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let L=await Mi("Connecting this machine\u2026",()=>KS({cpOrigin:O.cpOrigin,claim:O.claim,gatewayUrl:o.gateway}));p={cert:L.cert,privateKeyPem:L.privateKeyPem},L.deploymentId&&(d=L.deploymentId),!o.gateway&&L.gatewayUrl&&(o.gateway=L.gatewayUrl),h=L.ssoLink}catch(L){return _(L instanceof Error?L.message:String(L)),1}}if(o.sso&&!p&&!o.revert)if(o.dryRun)F("dry run: not enrolled via SSO (skipped minting a personal key).");else{let O=xt(o.sso);if(!O)return _($i(o.sso)?"that is an enrollment link, not an SSO link \u2014 re-run with --enroll instead of --sso.":"invalid --sso value: expected a https://\u2026/sso/<tenantId> link or a tnt_ id."),1;try{let L=await Dd({cpOrigin:O.cpOrigin,tenantId:O.tenantId,gatewayUrl:o.gateway,log:pe=>F(pe),open:r()?Ra:void 0}),H=await Mi("Waiting for SSO sign-in\u2026",()=>Nd(L,{gatewayUrl:o.gateway}));p={cert:H.cert,privateKeyPem:H.privateKeyPem},H.deploymentId&&(d=H.deploymentId),!o.gateway&&H.gatewayUrl&&(o.gateway=H.gatewayUrl)}catch(L){return _(L instanceof Error?L.message:String(L)),1}}let m=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;m&&(o.gateway=m);let w;try{w=dn(o.gateway)}catch(O){return _(O.message),1}let g,y;m&&!o.revert&&F(`Gateway: ${w} ${S("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&rg(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||XZ(s),v,E,I,C,x,T,U=s.credentialProtocol==="stable-heartbeat-v1",Z=async O=>{await Ao();let L=Jv(O.token),H=zv(s.enrolledCert,s.enrolledCertExpiry,O.deploymentId,Date.now(),L,s.enrolledTokenHash,O.expectedUser),pe=H?await Ue():void 0,q=H&&pe&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:pe,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,Ve=Fe=>qv({cpOrigin:O.cpOrigin,token:O.token,gatewayOrigin:w,email:O.email,team:O.team,machineId:O.machineId,deploymentId:O.deploymentId,reuse:Fe?q:void 0}),Me=!!q,Q=await(async()=>{try{return await Ve(Me)}catch(Fe){if(q&&Fe instanceof It)return F("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),Me=!1,await Ve(!1);throw Fe}})();A=Q.clientKey,o.user=wu(o.user,Q.user),o.team=wu(o.team,Q.team),v=Q.cert,E=Q.cert.payload.expiresAt,T=Q.expiresAt,U=Q.capabilities?.includes(bi)===!0,x=void 0,Me||(I=Q.privateKeyPem),Me||(C=L),$(`Enrolled${Q.user?` as ${Q.user}`:""}${Me?" (reused your saved cert)":""} \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)};if(o.enroll&&!o.revert)if(o.dryRun)F("dry run: not enrolled (skipped minting a personal key).");else{let O=tu(o.enroll);if(!O){let L=KI(o.enroll);return _(L?`that is ${L.what}, not an enrollment link \u2014 re-run with ${L.flag} instead of --enroll.`:xt(o.enroll)?"that is an SSO link, not an enrollment link \u2014 re-run with --sso instead of --enroll.":"invalid --enroll value: expected a https://\u2026/enroll/<token> link or a bare token."),1}try{let L=o.machine?gu():void 0,H=u??YZ(o.user);if(!o.machine&&!o.user&&!u){let q=JE();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 pe=o.machine?`machine:${L}`:f?H:void 0;await Z({cpOrigin:O.cpOrigin,token:O.token,email:H,team:o.team,machineId:L,deploymentId:d,expectedUser:pe})}catch(L){return _(L instanceof Error?L.message:String(L)),L instanceof It&&F("The gateway rejected this enrollment. Ask your admin to confirm the gateway is connected and entitled, and that your link targets the right gateway \u2014 the exact reason is in the gateway logs."),1}}if(p){await Ao();try{let O=await ln(w,p.cert,p.privateKeyPem);A=O.key,o.user=wu(o.user,O.user),o.team=wu(o.team,O.team),v=p.cert,E=p.cert.payload.expiresAt,I=p.privateKeyPem,T=O.expiresAt,U=O.capabilities?.includes(bi)===!0;let L=o.sso?xt(o.sso):void 0;x=L?`${L.cpOrigin}/sso/${L.tenantId}`:h,$(`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 It&&F("The gateway rejected your SSO sign-in. Ask your admin to confirm the gateway is connected and entitled \u2014 the exact reason is in the gateway logs."),1}}if(!o.revert){let O=o.yes;g=await zE(o.user,s.name,O),y=await qE(o.team,s.team,O)}let Y;!o.revert&&!o.subscription&&!o.placeholder&&(Y=await Nt(),K("Detecting your sign-ins"),k(` Claude (Anthropic): ${a?et("BYO upstream key (passthrough)"):Y.anthropic?et("signed in \u2192 your subscription"):S("not signed in \u2192 org key")}`),k(` Codex (ChatGPT): ${Y.openai?et("signed in \u2192 your subscription"):S("not signed in \u2192 org key")}`),!Y.anthropic&&!Y.openai&&!Y.copilot&&Gr()&&(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=ye({origin:w,placeholderKey:o.key,clientKey:A,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:Y,user:g,team:y,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),z=o.revert===!0&&(o.tools?.length??0)===0,me={dryRun:o.dryRun,fullRevert:z};if(!o.revert&&W.clientKey&&!Ie(W.clientKey))return _("Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key."),1;if(!o.revert&&!W.clientKey){K("Enrollment required");let O="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(D(` ${O}`),F(" Dry run only \u2014 no placeholder configuration will be written."),await tR(l,"after-enrollment"),F(`
|
|
1029
|
+
Dry run complete \u2014 no files were written.`),0):(_(` ${O}`),1)}o.revert||JZ(W,l),c&&!o.revert&&await tR(l,"plan"),o.dryRun&&F(`
|
|
1030
|
+
Dry run \u2014 no files will be written.`);let Pe=await bJ(o,c,l.length,{isInteractive:r,confirm:n.confirm});if(Pe==="non-interactive")return _(`
|
|
1031
|
+
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(Pe==="declined")return F(c?"Nothing was written. Re-run `npx anyray-connect wizard` when you're ready.":"Aborted. Nothing changed."),0;if(!o.dryRun&&!o.revert&&!o.force){let O=await eu(W.origin);if(!O.reachable)return _(`
|
|
1032
|
+
Gateway ${W.origin} is not reachable (${O.detail}).`),k(S(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
|
|
1033
1033
|
that would break them until you re-run with --revert.`)),k(`
|
|
1034
|
-
Start the gateway and try again, or pass --force to configure anyway.`),1;$(`Gateway reachable (${O.detail}).`)}let ne=o.revert?[]:await
|
|
1035
|
-
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),k("Run --revert with no --tools to remove it."));let Qi=l;if(o.revert&&!
|
|
1036
|
-
Remove them from the repo (then commit):`),k(
|
|
1037
|
-
Fix this terminal:`),k(
|
|
1038
|
-
Every other open terminal needs the same \u2014 or just open a new one.`),k(" VS Code injects a copy it captured when IT launched, so its"),k(" terminals stay stale even if you open a new one: quit the app"),k(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if($(`Done (${ec} file(s) written).`),Va.length>0){let
|
|
1039
|
-
Skipped the connection smoke test (--skip-verify).`):await
|
|
1040
|
-
Re-test by hand any time:`),
|
|
1041
|
-
-H "x-anyray-api-key: $(anyray-connect print-key)"`)),k(
|
|
1034
|
+
Start the gateway and try again, or pass --force to configure anyway.`),1;$(`Gateway reachable (${O.detail}).`)}let ne=o.revert?[]:await tJ(l,W.origin),He=[],Le=()=>{He.length!==0&&(K("Reopening"),aJ(He),He=[])};if(ne.length>0){let O=ne.map(H=>H.title),L=O.length===1?"it":"them";if(K("Open apps"),nJ(o,Vt()))o.quitApps===!0||await Da(rJ(O))?He=await oJ(ne):F(` Leaving ${L} open \u2014 restart when convenient.`);else{let H=o.noQuitApps===!0?"":" (or pass --quit-apps)";F(o.dryRun?` Would offer to quit ${O.join(", ")} \u2014 dry run, nothing was closed.`:` ${O.join(", ")} ${O.length===1?"is":"are"} open; restart ${L} to pick this up${H}.`)}}try{if(!o.dryRun)try{await bt()}catch{return _("Could not prepare the owner-only Anyray state directory."),1}let O=l.some(ge=>ge.id==="claude-code")&&X(W,"anthropic")||l.some(ge=>ge.id==="codex")&&X(W,"openai"),L=Td(s,T),H=s.anyrayFleetManaged===!0&&await Oo().catch(()=>!1),pe=F0(o,rR(),H),q=!o.revert&&o.noKeyRefresh!==!0&&O&&L&&!U&&!pe,Me=!o.revert&&(o.tools?.length??0)>0&&o.noKeyRefresh!==!0&&!!s.keyRefreshEnabled,Q=!!(b&&W.clientKey===b&&!v),Fe=!Q&&!!(v??s.enrolledCert),De=l.some(ge=>NS.has(ge.id)),V=!o.revert&&o.noKeyRefresh!==!0&&Fe&&(L||!De),Ee=o.dryRun?await So(s):await Sm(),wt=Ee==="healthy";Ee==="healed"&&(delete s.persistenceOwner,delete s.trayAppPath);let qn=W,Ot=q||Me,$r=Ot?s.fallbackPort:void 0;if(q&&!o.dryRun&&($r=s.fallbackPort??await Ic()),!o.revert&&!o.dryRun){let ge={...s,gateway:W.origin,name:g,team:y,clientKey:W.clientKey??s.clientKey,enrolledCert:Q?void 0:v??s.enrolledCert,enrolledCertExpiry:Q?void 0:E??s.enrolledCertExpiry,enrolledTokenHash:Q?void 0:C??s.enrolledTokenHash,ssoLink:Q?void 0:p?x:v?void 0:s.ssoLink,clientKeyExpiresAt:Q?void 0:T??(W.clientKey===s.clientKey?.trim()?s.clientKeyExpiresAt:void 0),authMode:W.authMode,byoUpstream:W.byoUpstream,credentialProtocol:Q?void 0:Ot?"rotating-proxy-v1":U?"stable-heartbeat-v1":s.credentialProtocol,directMigration:Q?void 0:Ot?"pending":U?"complete":s.directMigration,keyRefreshEnabled:Ot,refreshSchedulerEnabled:V,fallbackPort:$r};try{await qZ(s,ge,I,void 0,Q)}catch{return _("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}T&&!Q&&await xa({expiresAt:T})}if(q&&!o.dryRun&&(qn=await fJ(W,$r,{trayManaged:wt})),z)if(o.dryRun)await Pu()&&(K("Enrollment"),k(" would remove the stored gateway credential"));else{await Qy(s),await Md().catch(()=>{});try{await cc()&&(K("Enrollment"),$(" Removed the stored gateway credential."),F(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(ge){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(`
|
|
1035
|
+
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),k("Run --revert with no --tools to remove it."));let Qi=l;if(o.revert&&!z){let ge=l.filter(_t=>wi(s,_t.id));if(ge.length>0){K("Fleet policy");for(let _t of ge)D(` ${_t.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);Qi=l.filter(_t=>!wi(s,_t.id))}}let{changes:ec,manual:Va,manualAdminOnly:Ya,manualAdminOnlyIds:tc,results:Za}=await QZ(Qi,qn,me,o.revert,new Set(o.tools??[])),Ja;if(Vy(o)){K("Endpoint agent");try{Ja=await(n.installEndpointAfterEnrollment??Y0)({gateway:w,clientKey:W.clientKey})}catch{F("Endpoint agent setup did not complete. Tool routing remains configured.")}}let To=pe&&M0(Ja),tg=V&&!To;if(pe&&!To&&V&&!o.dryRun&&F(" The machine is not under endpoint policy, so automatic key refresh stays on this seat."),To&&!o.dryRun&&await re({...await P(),refreshSchedulerEnabled:!1}).catch(()=>{}),o.dryRun||(await Qn(Za,o.revert,z).catch(()=>{}),z&&await dc().catch(()=>{})),!Ot&&!o.dryRun&&(tt(s)||s.fallbackPort||await Oi("daemon"))){K("Local loopback proxy");let ge=await qt(s.fallbackPort);for(let _t of ge.messages)k(` ${_t}`);await re({...await P(),keyRefreshEnabled:!1,fallbackPort:void 0}),$(" Removed the local loopback proxy.")}if(await hJ({want:tg,announcePrimary:!q,scopedRevert:!!o.revert&&!z,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!tg&&await Oi("scheduler"),trayManaged:wt}),!o.revert&&!o.dryRun&&!Q){let ge=I??await Ue();ge&&await hm(await P(),ge).catch(()=>{})}if(Le(),K("Summary"),o.dryRun)F("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){$(`Reverted (${ec} file(s) touched).`),F("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let ge=await rI();ge.length>0&&(K("This repo carries its own Anyray routing"),D(` Committed here: ${ge.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(`
|
|
1036
|
+
Remove them from the repo (then commit):`),k(S(" anyray-connect --project --revert")));let _t=[W,...s.fallbackPort?[En(W,s.fallbackPort)]:[]],nc=Tp(_t);nc.length>0&&(K("This terminal still points at the gateway"),D(` Still exported here: ${nc.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(`
|
|
1037
|
+
Fix this terminal:`),k(S(` unset ${nc.join(" ")}`)),k(`
|
|
1038
|
+
Every other open terminal needs the same \u2014 or just open a new one.`),k(" VS Code injects a copy it captured when IT launched, so its"),k(" terminals stay stale even if you open a new one: quit the app"),k(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if($(`Done (${ec} file(s) written).`),Va.length>0){let Tt=Ya.length===Va.length;K(Tt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let ng of eJ(Va,Ya,tc.includes("claude-desktop")?process.platform:void 0))D(ng);Vt()&&!o.yes&&!Tt&&(await Da("Have you applied the manual settings shown above?")?$("Acknowledged."):D("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}o.skipVerify?F(`
|
|
1039
|
+
Skipped the connection smoke test (--skip-verify).`):await iJ(W,l.map(Tt=>Tt.id)),K("What's next");let ge=new Set(Za.filter(Tt=>Tt.status==="configured").map(Tt=>Tt.id)),_t=l.filter(Tt=>ge.has(Tt.id)).map(Tt=>Tt.title);if(k(_t.length>0?` Connected: ${_t.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(`
|
|
1040
|
+
Re-test by hand any time:`),W.authMode!=="placeholder"&&l.length===1&&l[0]?.id==="cursor"?(k(S(` curl -sS ${W.origin}/connect/savings \\
|
|
1041
|
+
-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 \\
|
|
1042
1042
|
-H "Content-Type: application/json" \\
|
|
1043
|
-
-H "Authorization: Bearer ${
|
|
1044
|
-
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),k(
|
|
1043
|
+
-H "Authorization: Bearer ${W.clientKey?`<your personal key (${$t(W.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
|
|
1044
|
+
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),k(S(" Revert: npx anyray-connect --revert"))}return 0}finally{Le()}};iR(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});
|