anyray-connect 0.11.167 → 0.11.169
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 +233 -234
- package/package.json +1 -2
- package/native/macos/Package.swift +0 -34
- package/native/macos/Sources/AnyrayDeviceProofCLI/main.swift +0 -77
- package/native/macos/Sources/AnyrayDeviceProofCore/base64URL.swift +0 -34
- package/native/macos/Sources/AnyrayDeviceProofCore/deviceProofClaims.swift +0 -58
- package/native/macos/Sources/AnyrayDeviceProofCore/deviceProofError.swift +0 -58
- package/native/macos/Sources/AnyrayDeviceProofCore/managedPreferences.swift +0 -129
- package/native/macos/Sources/AnyrayDeviceProofCore/p256PublicKey.swift +0 -31
- package/native/macos/Sources/AnyrayDeviceProofCore/proofOutput.swift +0 -77
- package/native/macos/Sources/AnyrayDeviceProofCore/proofRequest.swift +0 -58
- package/native/macos/Sources/AnyrayDeviceProofCore/signingChallenge.swift +0 -150
- package/native/macos/Sources/AnyrayDeviceProofMacOS/managedPreferencesReader.swift +0 -122
- package/native/macos/Sources/AnyrayDeviceProofMacOS/securityBootstrapSigner.swift +0 -94
- package/native/macos/Sources/AnyrayDeviceProofMacOS/securityDeviceIdentity.swift +0 -209
- package/native/macos/Tests/AnyrayDeviceProofCoreTests/deviceProofCoreTests.swift +0 -440
- package/native/macos/Tests/AnyrayDeviceProofMacOSTests/managedPreferencesReaderTests.swift +0 -166
- package/native/macos/Tests/AnyrayDeviceProofMacOSTests/securityDeviceIdentityTests.swift +0 -96
package/dist/index.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`;if(a||n.tombstoneAbsent!==!1)try{await
|
|
4
|
-
`),await
|
|
5
|
-
`,{mode:384})}catch(s){throw await Io(t,{recursive:!0,force:!0}).catch(()=>{}),s}return async()=>{try{JSON.parse(await Za(n,"utf-8")).nonce===o&&await Io(t,{recursive:!0,force:!0})}catch{}}}catch(s){if(s.code!=="EEXIST")throw s}if(!(await
|
|
6
|
-
`,{mode:384}),await Pu(r,384);try{await
|
|
7
|
-
`)},tn=(e,t={})=>{let n=e.byoUpstream,r=!n&&ee(e,"anthropic"),o=
|
|
8
|
-
`)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},rw=async()=>{try{let e=await D();return e.gateway?{origin:new URL(e.gateway).origin,metadata:pe({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},nt=async(e="auto")=>e==="profile"?rw():e==="claude"?nw():await nw()??await rw(),lc=async(e={})=>{let t=e.readTarget??nt,n=e.loadProfile??D,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a;try{a=new URL(r.gateway).origin}catch{return"unreadable"}return a===o.origin?"owned":"foreign"},Gt=e=>{let t={"content-type":"application/json"};return e.metadata&&(t["x-anyray-metadata"]=e.metadata),e.apiKey&&(t["x-anyray-api-key"]=e.apiKey),t},dc=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),GO);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Gt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var Xn=()=>fc(pc(),".claude","settings.json"),uc=()=>fc(pc(),".claude.json"),VO=ac,zn="anyray",KO=()=>({type:"stdio",...Ue("claude"),alwaysLoad:!0}),$r=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),jO=e=>{if("mcpServers"in e&&!$r(e.mcpServers))return"conflict";let t=$r(e.mcpServers)?{...e.mcpServers}:{},n=t[zn];return n!==void 0&&!Ut(n,"claude")?"conflict":(t[zn]=KO(),e.mcpServers=t,"installed")},ow=e=>{let t=e.mcpServers;return!t||!(zn in t)||!Ut(t[zn],"claude")?!1:(delete t[zn],Object.keys(t).length===0&&delete e.mcpServers,!0)},ZO=e=>{nc(e,"PostToolUse",Je,kn(xt(Je),{matcher:"*"})),nc(e,"UserPromptSubmit",Zn,kn(xt(Zn)))},YO=e=>{nc(e,"SessionStart",Yn,kn(xt(Yn),{async:!0}))},iw=e=>To(e,"SessionStart",Yn),aw=e=>{let t=To(e,"PostToolUse",Je),n=To(e,"UserPromptSubmit",Zn),r=iw(e);return t||n||r},JO="print-key",XO=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Re()),Mr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===JO&&XO(t)},zO=async(e,t)=>{let n=(await _r(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of VO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},qO=e=>typeof e.apiKeyHelper=="string"&&!Mr(e),cw=async e=>{let t=await Xu(),n=async()=>t,[r,o,a]=await Promise.all([Zg({userSettings:e,readManaged:n}),Qg({userSettings:e,readManaged:n}).catch(()=>[]),qg({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},sw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await cw(e),o=Ju(t),a=tw(n);return{routingOverrides:[...t.map(i=>({problem:Yu(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:ew(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},qn={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=fc(pc(),".claude"),t=await x(e);return{installed:t,detail:t?Xn():"no ~/.claude directory"}},async apply(e,t){let n=Xn(),r=await B(n),o=Ug(r),a=await Gg(e.origin,e.clientKey,o),s=Vg(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=tn(e,{contextWindowTokens:s.envTokens}),{directOverrides:p,hookPolicy:f}=await cw(r),h=p.filter(R=>!R.repairable),m=p.filter(R=>R.repairable),w=[...h.map(R=>`WARNING: ${Yu(R)}.`),...h.length?[Ju(h)]:[],...f.state==="fine"?[]:[`WARNING: ${ic(f)}.`,cc(f)],...m.map(R=>Yg(R)),`${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 y=r.env??{};r.env={...y,...i};let g=r.env;for(let{name:R}of vn)m.some(P=>P.name===R)?g[R]="":g[R]===""&&(process.env[R]??"").trim()===""&&delete g[R];if(u||delete g.ANTHROPIC_CUSTOM_HEADERS,c&&(y.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete g.ANTHROPIC_AUTH_TOKEN),l)for(let R of Hg)delete g[R];let b=!!e.clientKey,k=ce(),C=qO(r);!c&&!l&&b&&k&&!C?(r.apiKeyHelper=Wg(),g.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).")):Mr(r)&&delete r.apiKeyHelper,C&&!c&&!l&&b&&k&&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&&k?(YO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):iw(r),ce()?(ZO(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.")):(aw(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 Y(n,r);let E=[n],I=uc();try{let R=await B(I),P=!1;ce()?jO(R)==="conflict"?w.push(`MCP name conflict in ${I}: mcpServers.${zn} 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=ow(R),P&&(await Y(I,R),E.push(I))}catch(R){w.push(`Could not register the Anyray MCP server in ${I} (${R instanceof Error?R.message:String(R)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:E}},skillsDir(){return fc(pc(),".claude","skills")},async pointsAt(e){let t=Xn();if(!await x(t))return!1;try{let o=(await B(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await B(Xn()).catch(()=>({}));return sw(e)},async routingOverrides(){let e=await B(Xn()).catch(()=>({}));return(await sw(e)).routingOverrides},async mcpStatus(){let e=uc();if(!await x(e))return{registered:!1,command:null};try{let r=(await B(e)).mcpServers?.[zn];return!r||!Ut(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 x(n))e="missing";else try{let s=await B(n);if(s.hooks===void 0)e="missing";else if(!$r(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>jn(c,Je))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>jn(c,Je)&&$r(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>$r(l)&&rc(l.command,Je))))}}catch{e="unreadable"}let r,o=!0,a=uc();if(!await x(a))r="missing";else try{let s=await B(a);if(s.mcpServers===void 0)r="missing";else if(!$r(s.mcpServers))r="unreadable";else{let i=s.mcpServers[zn];r=i===void 0?"missing":Ut(i,"claude")?"owned":"foreign",r==="owned"&&(o=oc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Lr()?"owned":"missing",beacon_target:await lc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await B(Xn()),t=$r(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 x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await B(t),r=n.env,o=aw(n),a=Mr(n);a&&delete n.apiKeyHelper;let s=r?await zO(t,r):[],i=Kg(typeof n.model=="string"?n.model:void 0,(await _r(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await Y(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=uc();try{let d=await B(l);ow(d)&&(await Y(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await re(t),{status:"reverted",messages:c,changedFiles:[t]}}};var Qn=e=>{let{command:t,args:n}=en([e]);return{command:t,args:n}},er=()=>Dr();import{homedir as qu,platform as dw}from"node:os";import{join as hc}from"node:path";import{mkdir as eT,rm as uw,writeFile as tT,link as nT,copyFile as rT,readFile as CX}from"node:fs/promises";import{spawnSync as oT}from"node:child_process";import{homedir as lw,userInfo as QO}from"node:os";var ns=()=>{try{return lw()!==QO().homedir}catch{return!1}},zu=e=>[`Skipped ${e} \u2014 HOME (${lw()}) 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 Qu="ai.anyray.connect.app",rs="Anyray",pw=(e=qu())=>hc(e,"Applications",`${rs}.app`),fw="anyray-connect",aT=e=>`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
var PR="http://localhost:8787",Ka="anyray-placeholder",Ee=e=>{let t=e?.trim();return!!(t&&/^ark_[A-Za-z0-9_-]{20,512}$/.test(t))},Ht=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},ku=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,DR=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),ag=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!DR.has(n)}catch{return!1}},Qt=e=>{let t=Ht(e||process.env.ANYRAY_GATEWAY_URL||PR),n;try{n=new URL(t)}catch{throw new Error(`invalid gateway URL: "${t}" (expected e.g. http://localhost:8787)`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`invalid gateway URL: "${t}" \u2014 must start with http:// or https://`);return t},xe=(e={})=>{let t=Qt(e.origin),n=e.placeholderKey?.trim()||Ka,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 wc,platform as np}from"node:os";import{join as Wr}from"node:path";import{mkdir as ep,readFile as oT,rename as aT,writeFile as mc,rm as Fr}from"node:fs/promises";import{spawnSync as sT}from"node:child_process";import{homedir as uc}from"node:os";import{join as pc}from"node:path";import{access as BR,chmod as FR,mkdir as vu,open as Ru,readFile as pg,rm as Ut,stat as ig,utimes as WR}from"node:fs/promises";import{createHash as HR,randomUUID as fg}from"node:crypto";import{dirname as Ou,join as UR}from"node:path";import{isDeepStrictEqual as vo}from"node:util";import{randomUUID as LR}from"node:crypto";import{lstat as NR,rename as Ki,rm as $R}from"node:fs/promises";import{platform as sg}from"node:os";var MR=e=>e?.code==="ENOENT",Tr=async(e,t=sg())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},he=async(e,t,n=sg())=>{if(n!=="win32"){await Ki(e,t);return}let r=`${t}.anyray-old-${process.pid}-${LR()}`,o=!1;try{let a=await NR(t);if(!a.isFile()&&!a.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await Ki(t,r),o=!0}catch(a){if(!MR(a))throw a}try{await Ki(e,t)}catch(a){if(o)try{await Ki(r,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${r}`)}throw a}o&&await $R(r,{force:!0})};var ja=e=>`${e}.anyray-bak`,mg=async e=>{let t;try{t=await Ru(Ou(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},cg=async(e,t)=>{let n,r;try{n=await Ru(e,"wx",384),await n.writeFile(t,"utf-8"),await Tr(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Ut(e,{force:!0}).catch(()=>{}),r;await mg(e)},GR=async e=>{let t;try{t=await Ru(e,"r"),await Tr(t)}finally{await t?.close().catch(()=>{})}await mg(e)},x=async e=>{try{return await BR(e),!0}catch{return!1}},B=async e=>{if(!await x(e))return{};let t=await pg(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},Y=async(e,t,n={})=>{await vu(Ou(e),{recursive:!0,mode:448});let r=ja(e);if(n.backup!==!1&&!await x(r)){let a=await x(e),s=a?await pg(e,"utf-8"):`{}
|
|
3
|
+
`;if(a||n.tombstoneAbsent!==!1)try{await cg(r,s)}catch(i){if(i.code!=="EEXIST")throw i}}let o=`${e}.anyray-tmp-${process.pid}-${fg()}`;try{await cg(o,`${JSON.stringify(t,null,2)}
|
|
4
|
+
`),await he(o,e),await FR(e,384),await GR(e)}finally{await Ut(o,{force:!0}).catch(()=>{})}},hg=1,lg=3e4,VR=5e3,KR=/^[a-f0-9]{64}$/,yg=e=>`${e}.pending`,jR=e=>`${e}.lock`,Su=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=>Su(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Su(t[n])}`).join(",")}}`},Iu=(e,t)=>({exists:e,sha256:HR("sha256").update(Su(t)).digest("hex")}),Eu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),dg=e=>Eu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&KR.test(e.sha256),ZR=e=>Eu(e)&&e.transactionVersion===hg&&dg(e.before)&&dg(e.after)&&Eu(e.journal),xu=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,So=async(e,t)=>{try{return await B(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},YR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},gg=async e=>{let t=jR(e),n=UR(t,"owner.json");await vu(Ou(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=fg();try{await vu(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await So(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 ig(n)).mtimeMs;i=!YR(c.pid)||l>lg}catch{try{i=Date.now()-(await ig(t)).mtimeMs>lg}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Ut(t,{recursive:!0,force:!0});continue}try{await Y(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Ut(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await So(n,"ownership journal")).nonce!==o)return;let i=new Date;await WR(n,i,i)}catch{}})()},VR);return a.unref(),async()=>{clearInterval(a);try{(await So(n,"ownership journal")).nonce===o&&await Ut(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},wg=async e=>{let t=await x(e),n={};if(t)try{n=await B(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:Iu(t,n)}},bg=async(e,t)=>{let n=yg(t);if(!await x(n))return;let r=await So(n,"prepared ownership transaction");if(!ZR(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await wg(e),a=await x(t),s=await x(ja(e)),i=xu(o.fingerprint,r.before),c=xu(o.fingerprint,r.after),l=r.journal.fileExisted;if(c&&(a||l===!1||s)&&(!i||a||s)){await Y(t,r.journal,{backup:!1}),await Ut(n,{force:!0});return}if(i){await Ut(n,{force:!0}),a||await re(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},ji=async(e,t,n)=>{let r=await gg(t);try{return await bg(e,t),await n()}finally{await r()}},ug=async(e,t,n,r)=>{if(!await x(e)){if(n)throw new Error("journaled JSON rollback found a missing prior file");return}let a=await So(e,"ownership journal");if(!(n&&vo(a,t))){if(!vo(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await Y(e,t,{backup:!1}):await Ut(e,{force:!0})}},Zi=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await gg(a);try{await bg(n,a);let l=await wg(n),d=Iu(i,r),u=await x(a),p=u?await So(a,"ownership journal"):void 0,f=p&&typeof p.fileExisted=="boolean"?{...s,fileExisted:p.fileExisted}:s;if(!xu(l.fingerprint,d)){if(vo(l.value,o)&&p&&vo(p,f))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&vo(l.value,o)&&p&&vo(p,f))return;let m=await x(ja(n));if(p?.fileExisted===!0&&!m)throw new Error("ownership backup is missing; configuration was left unchanged");if(m&&!p)throw new Error("an unjournaled ownership backup already exists; configuration was left unchanged");let h=yg(a),w={transactionVersion:hg,before:l.fingerprint,after:Iu(!0,o),journal:f};await Y(h,w,{backup:!1});try{await Y(n,o,p?{backup:!1}:{tombstoneAbsent:!1}),await(t.writeJournal??Y)(a,f,{backup:!1}),await Ut(h,{force:!0})}catch(y){try{await ug(n,l.value,l.exists,o)}catch(g){throw new AggregateError([y,g],"ownership journal publication failed and config rollback was incomplete")}try{await ug(a,p??{},u,f),await Ut(h,{force:!0}),!m&&!p&&await re(n)}catch(g){throw new AggregateError([y,g],"ownership journal publication failed after config rollback")}throw y}}finally{await c()}},_r=async e=>{try{return await B(ja(e))}catch{return{}}},re=async e=>{await Ut(ja(e),{force:!0}).catch(()=>{})};import{access as bO}from"node:fs/promises";import{spawnSync as oO}from"node:child_process";import{readFileSync as aO,realpathSync as Xa,statSync as Rg}from"node:fs";import{access as sO,cp as Og,mkdir as Eg,readdir as iO,readFile as Bu,realpath as cO,rename as lO,rm as $u,writeFile as dO}from"node:fs/promises";import{tmpdir as uO}from"node:os";import{basename as Eo,dirname as He,join as Re,resolve as pO}from"node:path";import{writeFile as Yi,readFile as Za,chmod as Pu,stat as Du,mkdir as kg,rm as Io}from"node:fs/promises";import{AsyncLocalStorage as JR}from"node:async_hooks";import{randomUUID as XR}from"node:crypto";import{homedir as vg}from"node:os";import{join as Pr}from"node:path";var Q=()=>Pr(vg(),".anyray"),Sg=async()=>{let e=Q();try{if((await Du(e)).isDirectory())return Pr(e,"connect.json")}catch{}return e},Lu=()=>Pr(Q(),"dev-key.pem"),tt=async()=>{let e=Q(),t;try{if(!(await Du(e)).isDirectory())t=await Za(e,"utf-8").catch(()=>{}),await Io(e,{force:!0});else return}catch{}if(await kg(e,{recursive:!0,mode:448}),t!==void 0){let n=Pr(e,"connect.json");await Yi(n,t,{mode:384}),await Pu(n,384)}},Ji=async e=>{await tt();let t=Lu();await Yi(t,e,{mode:384}),await Pu(t,384)},$e=async()=>{try{let e=await Za(Lu(),"utf-8");return e.trim()?e:void 0}catch{return}},Ya=async()=>{await Io(Lu(),{force:!0}).catch(()=>{})},D=async()=>{try{let e=await Za(await Sg(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:t}catch{return{}}},zR=0,qR=3e4,QR=5e3,eO=25,tO=()=>Pr(vg(),".anyray-connect-profile.lock"),Tu=new JR,nO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},rO=async e=>{try{let t=JSON.parse(await Za(Pr(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!nO(t.pid)}catch{}return Date.now()-(await Du(e)).mtimeMs>qR},Ig=async(e=QR)=>{let t=tO(),n=Pr(t,"owner.json"),r=Date.now()+e;for(;;){let o=XR();try{await kg(t,{mode:448});try{await Yi(n,`${JSON.stringify({pid:process.pid,nonce:o})}
|
|
5
|
+
`,{mode:384})}catch(s){throw await Io(t,{recursive:!0,force:!0}).catch(()=>{}),s}return async()=>{try{JSON.parse(await Za(n,"utf-8")).nonce===o&&await Io(t,{recursive:!0,force:!0})}catch{}}}catch(s){if(s.code!=="EEXIST")throw s}if(!(await rO(t).catch(()=>!1)&&await Io(t,{recursive:!0,force:!0}).then(()=>!0).catch(()=>!1))){if(Date.now()>=r)throw new Error("connect profile is busy; retry the command");await new Promise(s=>setTimeout(s,eO))}}},Ja=async(e,t={})=>{if(Tu.getStore()===!0)return e();let n=await Ig(t.waitMs);try{return await Tu.run(!0,e)}finally{await n()}},Ag=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Sg(),r=`${n}.${process.pid}.${zR++}.tmp`;await Yi(r,`${JSON.stringify(t,null,2)}
|
|
6
|
+
`,{mode:384}),await Pu(r,384);try{await he(r,n)}catch(o){throw await Io(r,{force:!0}).catch(()=>{}),o}},oe=async e=>{if(Tu.getStore()===!0){await Ag(e);return}let t=await Ig();try{await Ag(e)}finally{await t()}};var _u=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],Cg="ssoLink",Nu=async()=>{let e=await D();return _u.some(t=>e[t]!==void 0)?!0:await $e()!==void 0},Xi=async()=>{let e=await D(),t=_u.some(a=>e[a]!==void 0),n=e[Cg]!==void 0,r=e.byoUpstream!==void 0,o=await $e()!==void 0;if(t||n||r||e.managedEnrollmentDisabled!==!0){let a={...e};for(let s of _u)delete a[s];delete a[Cg],delete a.byoUpstream,a.managedEnrollmentDisabled=!0,delete a.anyrayFleetManaged,await oe(a)}if(await Ya(),await $e())throw new Error(`could not remove the dev key from ${Q()}`);return t||n||r||o},Vn=async(e,t,n=!1)=>{let r=await D(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=r.offboardedAt;for(let m of e){let h=m.status==="configured"||m.status==="queued";!t&&h&&(o.add(m.id),a.delete(m.id),s=void 0),t&&(m.status==="reverted"||m.status==="queued")&&(o.delete(m.id),a.add(m.id))}n&&o.clear();let i=[...o].sort(),c=[...r.managedTools??[]].sort(),l=[...a].sort(),d=[...r.revertedTools??[]].sort();if(i.length===c.length&&i.every((m,h)=>m===c[h])&&r.revertedTools!=null&&l.length===d.length&&l.every((m,h)=>m===d[h])&&s===r.offboardedAt)return;let{offboardedAt:p,...f}=r;await oe({...f,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},zi=async(e=new Date().toISOString())=>{await oe({...await D(),offboardedAt:e})};var xo=e=>pO(e).replace(/\\/g,"/").toLowerCase(),Mu=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",za=e=>`${e}.source`,Tg=e=>/(^|\/)_npx(\/|$)/.test(xo(e)),Fu=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(xo(e)),Wu=e=>{let t=xo(e),n=[uO(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(xo);return Tg(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},ft=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),qa=e=>/[\\/](node|node\.exe)$/i.test(e),Kn=(e=ft())=>qa(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,xg=e=>{try{let t=Rg(e);return t.isFile()?t.size:void 0}catch{return}},Hu=e=>{let t=He(e);if(Eo(t)==="versions")return t;let n=He(t);return Eo(n)==="versions"?n:void 0},Qi=(e,t)=>t!==void 0&&(He(e)===t||He(He(e))===t),fO=e=>{let t=Hu(e);if(!t)return;let n=Re(He(t),"bin",Mu());try{let r=Xa(n);return r===Xa(e)||Qi(r,Xa(t))?n:void 0}catch{return}},Ro=(e=Q(),t=process.platform)=>{let n=Re(e,"bin",Mu(t));try{let r=Xa(n),o=Xa(Re(e,"versions"));if(Qi(r,o))return n;if(t==="win32"){let a=aO(za(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=xg(Re(o,a,Mu(t)))??xg(Re(o,a));if(s!==void 0&&s===Rg(n).size)return n}}catch{return}},Dr=(e=ft())=>{let t=Kn(e),n=Fu(t)||Gu(t)?Ro():void 0;return fO(e.execPath)??n??t},_g=(e=ft())=>Dr(e)!==Kn(e),en=(e,t=ft())=>{let n=Dr(t);return qa(t.execPath)&&t.scriptPath!==void 0&&n===Kn(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},Pg=(e=ft())=>{let t=Dr(e);return!qa(e.execPath)&&!Wu(t)?He(t):Re(Q(),"bin")},qi=async e=>{try{return await sO(e),!0}catch{return!1}},mO=async e=>{let t=await cO(e),n=He(t),r=He(n),o=Re(r,"package.json"),a=await Bu(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 qi(Re(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},hO=async(e,t)=>{let n=t;for(;;){let r=Re(n,"node_modules",e);if(await qi(Re(r,"package.json")))return r;let o=He(n);if(o===n)return;n=o}},yO=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await Bu(Re(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await hO(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await Og(i,Re(t,s),{recursive:!0}),r.push(i)}}},gO=async(e=ft())=>{let t=Ro();if(t)return{command:t,args:[],entryPath:t};if(!qa(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await mO(e.scriptPath);await tt();let r=Re(Q(),"bin",`connect-runtime-${n.version}`),o=Re(r,"dist","index.js");if(!await qi(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await $u(a,{recursive:!0,force:!0}),await Eg(a,{recursive:!0,mode:448});try{await Og(n.dist,Re(a,"dist"),{recursive:!0}),await dO(Re(a,"package.json"),await Bu(n.packageJson),{mode:384}),await yO(n.root,Re(a,"node_modules")),await Eg(He(r),{recursive:!0,mode:448});try{await lO(a,r)}catch(s){if(!await qi(o))throw s}}finally{await $u(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Uu=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,wO=e=>{let t=Eo(He(He(e)));return Uu.test(t)?t:void 0},Gu=(e,t=Q())=>{let n=He(He(e));return xo(He(n))===xo(Re(t,"bin"))&&Uu.test(Eo(n))&&Eo(He(e))==="dist"&&Eo(e)==="index.js"},ec=async(e=ft())=>{let t=Re(Q(),"bin"),n=wO(Kn(e)),r=[];for(let o of await iO(t).catch(()=>[])){if(!Uu.test(o)||o===n)continue;let a=Re(t,o);await $u(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},Dg=async(e,t=ft())=>{let n=Kn(t);if(!qa(t.execPath)||!Tg(n)||Ro())return;let r=await gO(t),o=oO(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var Vu=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,Qa=(e,t)=>[e,...t].map(Vu).join(" "),kn=(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}:{}}]}),jn=(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))},tc=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!jn(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},Oo=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!jn(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=>!jn(s,"__anyray-"));a.length!==o.length&&(n=!0,a.length?t[r]=a:delete t[r])}return n&&Object.keys(t).length===0&&delete e.hooks,n};var Xe="__anyray-hook",Lg="__anyray-codex-hook",Zn="__anyray-prompt-hook",Ng="__anyray-shell-pretool",ju="__anyray-shell-run",$g="__anyray-read-pretool",Yn="__anyray-refresh",es=(e,t=[])=>{let{command:n,args:r}=en([e,...t]);return{command:n,args:r}},Rt=(e,t=[])=>{let n=es(e,t);return[n.command,...n.args].map(Vu).join(" ")},nc=(e,t,n=[])=>typeof e=="string"&&e.trim()===Rt(t,n),Mg=()=>Rt("print-key"),Oe=()=>Dr(),Ue=Wu,ce=()=>!Ue(Oe()),Lr=async()=>{if(!ce())return!1;try{return await bO(Oe()),!0}catch{return!1}},Jn="__anyray-mcp-server",Ge=e=>es(Jn,[e]),AO=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),rc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=Ge(t);return n.command===r.command&&AO(n.args,r.args)},Gt=(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)===Jn&&r.at(-1)===t};var ee=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,ue=e=>{let t=Object.entries(e).filter(([,n])=>n);if(t.length!==0)return JSON.stringify(Object.fromEntries(t))};var Nr=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Bg=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],oc=[...Nr,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],CO=(e,t,n,r)=>{let o=[];return(t||r)&&(o.push("x-anyray-provider: anthropic"),o.push("x-anyray-auth-mode: passthrough"),r&&o.push(`x-anyray-custom-host: ${r}`),n&&o.push(`x-anyray-api-key: ${n}`)),e&&o.push(`x-anyray-metadata: ${e}`),o.join(`
|
|
7
|
+
`)},tn=(e,t={})=>{let n=e.byoUpstream,r=!n&&ee(e,"anthropic"),o=ue({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1,s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=CO(o,r,a?e.clientKey:void 0,n?.url);return{env:{ANTHROPIC_BASE_URL:e.anthropicBaseUrl,...c?{ANTHROPIC_CUSTOM_HEADERS:c}:{},...n&&s?{ANTHROPIC_AUTH_TOKEN:n.key}:{},...r||n||!s?{}:{ANTHROPIC_AUTH_TOKEN:e.clientKey??e.placeholderKey},...n?{}:{ENABLE_TOOL_SEARCH:"true"},...n?{}:{_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL:"1"},...i!==void 0?{CLAUDE_CODE_MAX_CONTEXT_TOKENS:String(i)}:{}},subscription:r,byoUpstream:!!n,meta:o,headers:c}};import{z as Zu}from"zod";var kO=5e3,vO=1e3,SO=1e8,IO=Zu.object({modelContext:Zu.object({contextTokens:Zu.number().int().min(vO).max(SO)}).optional()}),Fg=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},Wg=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??kO,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=IO.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var EO=1e6,ts="[1m]",xO=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},Hg=(e,t)=>!e||t===void 0?{}:xO(e)?{envTokens:t}:t<EO?{}:e.toLowerCase().endsWith(ts)?{}:{model:`${e}${ts}`},Ug=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(ts))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(ts))return e.slice(0,-ts.length)};import{platform as RO}from"node:os";var Ot=(e=RO())=>{switch(e){case"darwin":return"/Library/Application Support/ClaudeCode/managed-settings.json";case"win32":return"C:\\Program Files\\ClaudeCode\\managed-settings.json";default:return"/etc/claude-code/managed-settings.json"}};var vn=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],ac=e=>typeof e=="string"&&e.trim()!=="",OO=(e,t)=>typeof e[t]=="string"&&!ac(e[t]),Gg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},TO=()=>B(Ot()).catch(()=>({})),Vg=async(e={})=>{let t=e.env??process.env,n=Gg(e.userSettings??{}),r=Gg(await(e.readManaged??TO)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of vn)ac(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Ot()})`,repairable:!1}):ac(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!OO(n,a)&&ac(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},Yu=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`,Ju=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.",Kg=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 _O=vn.map(e=>e.name),PO=oc.filter(e=>!_O.includes(e)),jg=e=>typeof e=="string"&&e.trim()!=="",Zg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},DO=(e,t,n)=>{if(typeof e!="string"||typeof t!="string")return!1;let r=o=>n?o.trim().replace(/\/+$/,""):o.trim();return r(e)===r(t)},LO=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},Xu=()=>B(Ot()).catch(()=>({})),Yg=Xu,NO=e=>{let t=e.hooks;if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=t.PostToolUse;return Array.isArray(n)&&n.some(r=>jn(r,Xe))},Jg=async(e={})=>{let t=await(e.readManaged??Yg)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!NO(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},sc=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Ot()}) \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 (${Ot()}), 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",ic=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.",Xg=async(e={})=>{let t=Zg(e.userSettings??{}),n=Zg(await(e.readManaged??Yg)().catch(()=>({}))),r=[];for(let o of PO){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?LO(n[o]):void 0;r.push({name:o,source:`managed settings (${Ot()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},zg=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`,qg=e=>"Fix: the managed settings file is IT-owned \u2014 ask your admin to "+(e.some(t=>t.routing)?"point it at the Anyray gateway (`anyray-connect managed --print` emits the block to deploy) or drop the key so per-user setup governs":"drop the key so per-user setup governs")+", then restart Claude Code.";import{homedir as $O}from"node:os";import{join as MO}from"node:path";import{readFile as BO}from"node:fs/promises";var FO=400,Qg=async()=>{try{let e=MO($O(),".claude","settings.json"),n=JSON.parse(await BO(e,"utf-8"))?.env,r=n?.ANTHROPIC_BASE_URL;if(!r)return null;let o=new URL(r).origin,a=n?.ANTHROPIC_CUSTOM_HEADERS??"",s=l=>{for(let d of a.split(`
|
|
8
|
+
`)){let u=d.indexOf(":");if(u>0&&d.slice(0,u).trim().toLowerCase()===l)return d.slice(u+1).trim()}},i=s("x-anyray-api-key"),c=n?.ANTHROPIC_AUTH_TOKEN;return{origin:o,metadata:s("x-anyray-metadata"),apiKey:i||(c?.startsWith("ark_")?c:void 0)}}catch{return null}},ew=async()=>{try{let e=await D();return e.gateway?{origin:new URL(e.gateway).origin,metadata:ue({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},nt=async(e="auto")=>e==="profile"?ew():e==="claude"?Qg():await Qg()??await ew(),cc=async(e={})=>{let t=e.readTarget??nt,n=e.loadProfile??D,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a;try{a=new URL(r.gateway).origin}catch{return"unreadable"}return a===o.origin?"owned":"foreign"},Vt=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},lc=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),FO);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Vt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var Xn=()=>pc(uc(),".claude","settings.json"),dc=()=>pc(uc(),".claude.json"),WO=oc,zn="anyray",HO=()=>({type:"stdio",...Ge("claude"),alwaysLoad:!0}),$r=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),UO=e=>{if("mcpServers"in e&&!$r(e.mcpServers))return"conflict";let t=$r(e.mcpServers)?{...e.mcpServers}:{},n=t[zn];return n!==void 0&&!Gt(n,"claude")?"conflict":(t[zn]=HO(),e.mcpServers=t,"installed")},tw=e=>{let t=e.mcpServers;return!t||!(zn in t)||!Gt(t[zn],"claude")?!1:(delete t[zn],Object.keys(t).length===0&&delete e.mcpServers,!0)},GO=e=>{tc(e,"PostToolUse",Xe,kn(Rt(Xe),{matcher:"*"})),tc(e,"UserPromptSubmit",Zn,kn(Rt(Zn)))},VO=e=>{tc(e,"SessionStart",Yn,kn(Rt(Yn),{async:!0}))},ow=e=>Oo(e,"SessionStart",Yn),nw=e=>{let t=Oo(e,"PostToolUse",Xe),n=Oo(e,"UserPromptSubmit",Zn),r=ow(e);return t||n||r},KO="print-key",jO=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Oe()),Mr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===KO&&jO(t)},ZO=async(e,t)=>{let n=(await _r(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of WO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},YO=e=>typeof e.apiKeyHelper=="string"&&!Mr(e),aw=async e=>{let t=await Xu(),n=async()=>t,[r,o,a]=await Promise.all([Vg({userSettings:e,readManaged:n}),Xg({userSettings:e,readManaged:n}).catch(()=>[]),Jg({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},rw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await aw(e),o=Ju(t),a=qg(n);return{routingOverrides:[...t.map(i=>({problem:Yu(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:zg(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},qn={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=pc(uc(),".claude"),t=await x(e);return{installed:t,detail:t?Xn():"no ~/.claude directory"}},async apply(e,t){let n=Xn(),r=await B(n),o=Fg(r),a=await Wg(e.origin,e.clientKey,o),s=Hg(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=tn(e,{contextWindowTokens:s.envTokens}),{directOverrides:p,hookPolicy:f}=await aw(r),m=p.filter(R=>!R.repairable),h=p.filter(R=>R.repairable),w=[...m.map(R=>`WARNING: ${Yu(R)}.`),...m.length?[Ju(m)]:[],...f.state==="fine"?[]:[`WARNING: ${sc(f)}.`,ic(f)],...h.map(R=>Kg(R)),`${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 y=r.env??{};r.env={...y,...i};let g=r.env;for(let{name:R}of vn)h.some(P=>P.name===R)?g[R]="":g[R]===""&&(process.env[R]??"").trim()===""&&delete g[R];if(u||delete g.ANTHROPIC_CUSTOM_HEADERS,c&&(y.ANTHROPIC_AUTH_TOKEN&&w.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete g.ANTHROPIC_AUTH_TOKEN),l)for(let R of Bg)delete g[R];let b=!!e.clientKey,k=ce(),C=YO(r);!c&&!l&&b&&k&&!C?(r.apiKeyHelper=Mg(),g.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).")):Mr(r)&&delete r.apiKeyHelper,C&&!c&&!l&&b&&k&&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&&k?(VO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):ow(r),ce()?(GO(r),w.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(nw(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await Y(n,r);let I=[n],E=dc();try{let R=await B(E),P=!1;ce()?UO(R)==="conflict"?w.push(`MCP name conflict in ${E}: mcpServers.${zn} 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=tw(R),P&&(await Y(E,R),I.push(E))}catch(R){w.push(`Could not register the Anyray MCP server in ${E} (${R instanceof Error?R.message:String(R)}); retrieval via anyray_retrieve is unavailable until this is fixed.`)}return{status:"configured",messages:w,changedFiles:I}},skillsDir(){return pc(uc(),".claude","skills")},async pointsAt(e){let t=Xn();if(!await x(t))return!1;try{let o=(await B(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await B(Xn()).catch(()=>({}));return rw(e)},async routingOverrides(){let e=await B(Xn()).catch(()=>({}));return(await rw(e)).routingOverrides},async mcpStatus(){let e=dc();if(!await x(e))return{registered:!1,command:null};try{let r=(await B(e)).mcpServers?.[zn];return!r||!Gt(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 x(n))e="missing";else try{let s=await B(n);if(s.hooks===void 0)e="missing";else if(!$r(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>jn(c,Xe))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>jn(c,Xe)&&$r(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>$r(l)&&nc(l.command,Xe))))}}catch{e="unreadable"}let r,o=!0,a=dc();if(!await x(a))r="missing";else try{let s=await B(a);if(s.mcpServers===void 0)r="missing";else if(!$r(s.mcpServers))r="unreadable";else{let i=s.mcpServers[zn];r=i===void 0?"missing":Gt(i,"claude")?"owned":"foreign",r==="owned"&&(o=rc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Lr()?"owned":"missing",beacon_target:await cc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await B(Xn()),t=$r(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 x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await B(t),r=n.env,o=nw(n),a=Mr(n);a&&delete n.apiKeyHelper;let s=r?await ZO(t,r):[],i=Ug(typeof n.model=="string"?n.model:void 0,(await _r(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await Y(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=dc();try{let d=await B(l);tw(d)&&(await Y(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await re(t),{status:"reverted",messages:c,changedFiles:[t]}}};var Qn=e=>{let{command:t,args:n}=en([e]);return{command:t,args:n}},er=()=>Dr();import{homedir as qu,platform as iw}from"node:os";import{join as fc}from"node:path";import{mkdir as XO,rm as cw,writeFile as zO,link as qO,copyFile as QO,readFile as J5}from"node:fs/promises";import{spawnSync as eT}from"node:child_process";import{homedir as sw,userInfo as JO}from"node:os";var ns=()=>{try{return sw()!==JO().homedir}catch{return!1}},zu=e=>[`Skipped ${e} \u2014 HOME (${sw()}) 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 Qu="ai.anyray.connect.app",rs="Anyray",lw=(e=qu())=>fc(e,"Applications",`${rs}.app`),dw="anyray-connect",tT=e=>`<?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
12
|
<key>CFBundleIdentifier</key><string>${Qu}</string>
|
|
13
13
|
<key>CFBundleName</key><string>${rs}</string>
|
|
14
14
|
<key>CFBundleDisplayName</key><string>${rs}</string>
|
|
15
|
-
<key>CFBundleExecutable</key><string>${
|
|
15
|
+
<key>CFBundleExecutable</key><string>${dw}</string>
|
|
16
16
|
<key>CFBundlePackageType</key><string>APPL</string>
|
|
17
17
|
<key>CFBundleShortVersionString</key><string>${e}</string>
|
|
18
18
|
<key>CFBundleVersion</key><string>${e}</string>
|
|
@@ -22,104 +22,104 @@ var $R="http://localhost:8787",Ka="anyray-placeholder",Ee=e=>{let t=e?.trim();re
|
|
|
22
22
|
<key>NSHumanReadableCopyright</key><string>Othentic Labs LTD</string>
|
|
23
23
|
</dict>
|
|
24
24
|
</plist>
|
|
25
|
-
`,
|
|
25
|
+
`,nT="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",rT=e=>{try{eT(nT,["-f",e],{stdio:"ignore",timeout:1e4})}catch{}},uw=async(e={})=>{if((e.os??iw())!=="darwin")return{ok:!0,messages:[]};let n=e.home??qu(),r=e.binaryPath??er();if(Ue(r))return{ok:!1,messages:[`Skipped the Login Items identity app \u2014 anyray-connect is running from a temporary path (${r}).`]};if(ns())return{ok:!1,messages:["Skipped the Login Items identity app \u2014 HOME is redirected away from the real account."]};let o=lw(n),a=fc(o,"Contents","MacOS"),s=fc(a,dw),i=e.version??"0.0.0";try{await cw(o,{recursive:!0,force:!0}),await XO(a,{recursive:!0}),await zO(fc(o,"Contents","Info.plist"),tT(i),"utf8");try{await qO(r,s)}catch{await QO(r,s)}return(e.register??rT)(o),{ok:!0,messages:[`Registered ${rs} as the Login Items identity.`]}}catch(c){return{ok:!1,messages:[`Could not write the Login Items identity app (${c?.name??"Error"}). Background items will show the signing certificate name instead.`]}}},pw=async(e={})=>{if((e.os??iw())!=="darwin")return{ok:!0,messages:[]};if(ns())return{ok:!0,messages:[]};let n=lw(e.home??qu());try{return await cw(n,{recursive:!0,force:!0}),{ok:!0,messages:[`Removed ${rs}.app.`]}}catch(r){return{ok:!1,messages:[`Could not remove the Login Items identity app (${r?.name??"Error"}).`]}}};var Ae="0.11.169";var nn=(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,Br=(e=process.env)=>nn(e)!==null,Sn=e=>e==="codespaces"||e==="devcontainer",To=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var fw=()=>Wr(wc(),".anyray","logs"),tp=()=>Wr(fw(),"connect-refresh.log"),gc=1800,bc="ai.anyray.connect.refresh",ss="anyray-refresh",rp="\\AnyrayConnectKeyRefresh",Ac=bc,is=ss,as=rp,iT=String(gc/60),op=(e,t)=>{let n=sT(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},ap=()=>Wr(wc(),"Library","LaunchAgents",`${Ac}.plist`),sp=()=>Wr(wc(),".config","systemd","user"),mw=()=>Wr(sp(),`${is}.service`),yc=()=>Wr(sp(),`${is}.timer`),hc=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Cc=()=>Qn(Yn),cT=(e=Cc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${hc(o)}</string>`).join(`
|
|
26
26
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
27
27
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
28
28
|
<plist version="1.0">
|
|
29
29
|
<dict>
|
|
30
|
-
<key>Label</key><string>${
|
|
30
|
+
<key>Label</key><string>${Ac}</string>
|
|
31
31
|
<key>AssociatedBundleIdentifiers</key>
|
|
32
32
|
<array>
|
|
33
|
-
<string>${
|
|
33
|
+
<string>${hc(Qu)}</string>
|
|
34
34
|
</array>
|
|
35
35
|
<key>ProgramArguments</key>
|
|
36
36
|
<array>
|
|
37
37
|
${r}
|
|
38
38
|
</array>
|
|
39
|
-
<key>StartInterval</key><integer>${
|
|
39
|
+
<key>StartInterval</key><integer>${gc}</integer>
|
|
40
40
|
<key>RunAtLoad</key><true/>
|
|
41
41
|
<key>ProcessType</key><string>Background</string>
|
|
42
42
|
<key>LowPriorityIO</key><true/>
|
|
43
|
-
<key>StandardOutPath</key><string>${
|
|
44
|
-
<key>StandardErrorPath</key><string>${
|
|
43
|
+
<key>StandardOutPath</key><string>${hc(tp())}</string>
|
|
44
|
+
<key>StandardErrorPath</key><string>${hc(tp())}</string>
|
|
45
45
|
</dict>
|
|
46
46
|
</plist>
|
|
47
|
-
`},
|
|
47
|
+
`},lT=(e=Cc())=>{let{command:t,args:n}=e;return`[Unit]
|
|
48
48
|
Description=Anyray connect gateway key refresh
|
|
49
49
|
After=network-online.target
|
|
50
50
|
|
|
51
51
|
[Service]
|
|
52
52
|
Type=oneshot
|
|
53
53
|
ExecStart=${[t,...n].map(o=>/\s/.test(o)?JSON.stringify(o):o).join(" ")}
|
|
54
|
-
`},
|
|
55
|
-
Description=Anyray connect gateway key refresh (every ${
|
|
54
|
+
`},dT=()=>`[Unit]
|
|
55
|
+
Description=Anyray connect gateway key refresh (every ${gc/60}m)
|
|
56
56
|
|
|
57
57
|
[Timer]
|
|
58
58
|
OnBootSec=5min
|
|
59
|
-
OnUnitActiveSec=${
|
|
59
|
+
OnUnitActiveSec=${gc/60}min
|
|
60
60
|
Persistent=true
|
|
61
61
|
|
|
62
62
|
[Install]
|
|
63
63
|
WantedBy=timers.target
|
|
64
|
-
`,
|
|
65
|
-
${t.stderr??""}`}},
|
|
66
|
-
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},
|
|
67
|
-
`),o=
|
|
68
|
-
`),s=
|
|
69
|
-
`),
|
|
64
|
+
`,uT=(e=Cc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),os=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&&ns(),pT=async(e,t)=>await oT(ap(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Ac]).ok,tr=async(e={})=>{let t=e.os??np(),n=e.invocation??Cc(),r=e.run??op,o=e.binaryPath??er();if(Ue(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:zu("auto-refresh scheduling")};let a=nn(e.env??(e.run?{}:process.env));if(Sn(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${To(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=ap(),i=cT(n);if(await pT(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await ep(fw(),{recursive:!0,mode:448}),await ep(Wr(wc(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=await uw({os:t,binaryPath:o,version:Ae}),d=`${s}.new-${process.pid}`;await Fr(d,{force:!0}).catch(()=>{}),await mc(d,i),r("launchctl",["bootout",`gui/${c}`,s]),await Fr(s,{force:!0}).catch(()=>{});try{await aT(d,s)}catch{await mc(s,i),await Fr(d,{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}).`,...l.ok?[]:l.messages]}:{ok:!1,messages:[`Wrote ${s} but launchd would not load the agent.`,...os(n)]}}if(t==="linux")return await ep(sp(),{recursive:!0}),await mc(mw(),lT(n)),await mc(yc(),dT()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${is}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${yc()}).`]}:{ok:!1,messages:[`Wrote ${yc()} but \`systemctl --user enable --now\` failed.`,...os(n)]};if(t==="win32"){let s=uT(n);return r("schtasks",["/Create","/TN",as,"/TR",s,"/SC","MINUTE","/MO",iT,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",as]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${as}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...os(n)]}}return{ok:!1,messages:os(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...os(n)]}}},nr=async(e={})=>{await Fr(tp(),{force:!0}).catch(()=>{});let t=e.os??np(),n=e.run??op,r=[];if(hw(e))return{ok:!0,messages:zu("scheduler teardown")};try{if(t==="darwin"){let o=ap(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Fr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.");let s=await pw();s.ok||r.push(...s.messages)}else t==="linux"?(n("systemctl",["--user","disable","--now",`${is}.timer`]),await Fr(yc(),{force:!0}),await Fr(mw(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",as,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},_o=async(e=np(),t=op)=>e==="win32"?t("schtasks",["/Query","/TN",as]).ok:e==="darwin"?t("launchctl",["list",Ac]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${is}.timer`]).ok:!1;import{platform as fT}from"node:os";import{stat as mT}from"node:fs/promises";import{spawnSync as hT}from"node:child_process";var yw="/Applications/Anyray Connect Tray.app",yT=new Set(["V53XMA78UF"]),gT="ai.anyray.connect-tray",wT=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,bT=e=>{let t=hT("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
|
|
65
|
+
${t.stderr??""}`}},AT=async e=>{try{return(await mT(e)).isDirectory()}catch{return!1}},CT=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},ip=async(e,t={})=>{if((t.os??fT())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??AT)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??bT;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?CT(a.output):void 0;return s?yT.has(s)?wT(a.output)!==gT?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},Po=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await ip(n,t)).ok?"healthy":"gone"},cp=async(e={})=>{try{let t=e.load??D,n=await t(),r=await Po(n,e);if(r!=="gone")return r;let o=e.installScheduler??tr;return n.refreshSchedulerEnabled&&await o().catch(()=>{}),await(e.save??oe)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var kT={"not-macos":"persistence swap: macOS only \u2014 the LaunchAgent stays in place on this OS.","bad-path":"persistence swap: --app-path must point at a .app bundle.",missing:"persistence swap: tray app bundle not found \u2014 nothing changed.",unsigned:"persistence swap: tray app failed codesign verification \u2014 refusing to adopt (RFC 0010 invariant 5).","no-team-identifier":"persistence swap: tray app has no Developer ID TeamIdentifier (adhoc or unsigned) \u2014 refusing to adopt (RFC 0010 invariant 5).","untrusted-team":"persistence swap: tray app is signed by a Developer ID that is not Anyray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgent stays in place.","untrusted-bundle-id":"persistence swap: that bundle is not the Anyray Connect Tray \u2014 refusing to adopt (RFC 0010 invariant 5). The LaunchAgent stays in place."},vT=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},ST=async(e,t)=>{let n=t.stderr??console.error,r=vT(e,"--app-path")??yw,o=await ip(r,t);if(!o.ok)return n(kT[o.reason]),1;let s=await(t.load??D)();return await(t.save??oe)({...s,persistenceOwner:"tray",trayAppPath:r}),await(t.uninstallScheduler??nr)().catch(()=>{}),0},IT=async e=>{let t=e.load??D,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??tr;return n.refreshSchedulerEnabled&&await r().catch(()=>{}),await(e.save??oe)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},gw=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await ST(e,t):e.includes("--release-tray")?await IT(t):(n("persistence swap: expected --adopt-tray or --release-tray."),1)}catch(r){return n(`persistence swap: failed (${r instanceof Error?r.name:"Error"}).`),1}};import{access as ET}from"node:fs/promises";import{homedir as ww,platform as lp}from"node:os";import{join as cs}from"node:path";var dp=(e=lp(),t=ww())=>{if(e==="darwin")return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:bc,paths:[cs(t,"Library","LaunchAgents",`${bc}.plist`)],dataPaths:[cs(t,".anyray","logs","connect-refresh.log")]}];if(e==="linux"){let n=cs(t,".config","systemd","user");return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:`${ss}.timer`,paths:[cs(n,`${ss}.timer`),cs(n,`${ss}.service`)]}]}return e==="win32"?[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:rp,paths:[]}]:[]},bw=async e=>{try{return await ET(e),!0}catch{return!1}},kc=async(e={})=>{let t=e.os??lp(),n=e.exists??bw;for(let r of dp(t,e.home)){if(r.paths.length===0){if(await(e.supervisorHolds??(async a=>{try{return await _o(a)}catch{return!1}}))(t))return!0;continue}for(let o of r.paths)if(await n(o))return!0}return!1},Aw=async e=>{let t={suspected:!1,missingPaths:[],kinds:[]};if(!e.binaryDurable||!e.schedulerEnabled||e.schedulerInstalled)return t;let n=e.exists??bw;for(let r of dp(e.os,e.home))for(let o of r.paths)await n(o)||(t.missingPaths.push(o),t.kinds.includes(r.kind)||t.kinds.push(r.kind));return t.suspected=t.missingPaths.length>0,t},Cw=(e=lp(),t=ww(),n=er())=>{let r=["Anyray connect can install one per-user background scheduler. It is","unprivileged, runs as the logged-in user, and renews the seat gateway key","so a long AI-coding session does not lose access.","","Executable:",` ${n}`,""];for(let o of dp(e,t)){r.push(`${o.title} \u2014 supervisor name: ${o.supervisorName}`);for(let a of o.paths)r.push(` ${a}`);o.paths.length===0&&r.push(" (no unit file \u2014 held in the Task Scheduler store)");for(let a of o.dataPaths??[])r.push(` ${a} (captured stdout/stderr \u2014 error names only)`);r.push("")}return r.push("Also spawns, detached and short-lived (same executable, hidden","subcommands \u2014 not a separate install):"," - Coding-tool MCP clients run `anyray-connect __anyray-mcp-server` as a"," stdio server, which may spawn `anyray-connect __anyray-refresh`."," - The Anyray VS Code extension may spawn"," `anyray-connect __anyray-spawn-refresh` on activation."," These triggers are throttled and serialized with the scheduler.","","Network behavior:"," - Outbound: your org's Anyray gateway and endpoint-control APIs over HTTPS.","","Why it looks like persistence to a heuristic scanner: it is a real login","item, by design, so key renewal survives reboots. Allow-list the paths above","or let Fleet provide the refresh trigger instead."),r};import{homedir as LT}from"node:os";import{join as Tc}from"node:path";import{chmod as NT,readFile as ls,rm as xw,copyFile as $T}from"node:fs/promises";var Hr="# >>> anyray connect >>>",Ic="# <<< anyray connect <<<",up="# restore: ",kw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ec=e=>{let t=new RegExp(`\\n*${kw(Hr)}[\\s\\S]*?${kw(Ic)}\\n?`,"g");return e.replace(t,"")},pp=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},vc=(e,t)=>e.split(t).length-1,vw=e=>vc(e,"[")-vc(e,"]"),xT=e=>e.replace(/^['"]|['"]$/g,""),Sc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){vc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+vw(pp(a))),t.push({kind:"other"});continue}let s=a.trim();if(s===""||s.startsWith("#")){t.push({kind:"other"});continue}if(s.startsWith("[")){t.push({kind:"table"});continue}let i=a.indexOf("="),c=i>=0?xT(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=pp(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])vc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+vw(l)))}return t},fp=e=>e.findIndex(t=>t.kind==="table"),mp=e=>e.includes(Hr),Sw=(e,t)=>{let n=`[${t}]`;return e.split(`
|
|
66
|
+
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},hp=(e,t)=>Sw(Ec(e),t),yp=e=>{let t=e.indexOf(Hr);if(t<0)return;let n=e.indexOf(Ic,t+Hr.length);if(!(n<0))return e.slice(t,n)},Iw=(e,t)=>{let n=e.indexOf(Hr);if(n<0)return!1;let r=e.indexOf(Ic,n+Hr.length);return r<0?!1:Sw(e.slice(n,r),t)},gp=(e,t)=>{let r=Ec(e).split(`
|
|
67
|
+
`),o=Sc(r),a=fp(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=pp(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}},xc=(e,t,n)=>{let r=Ew(e),a=Ec(e).split(`
|
|
68
|
+
`),s=Sc(a),i=fp(s),c=new Set(n),l=i===-1?a.length:i,d=[],u=new Map(r);for(let b=0;b<a.length;b++){let k=s[b];if(b<l&&k.kind==="key"&&c.has(k.key)){u.has(k.key)||u.set(k.key,a[b].trim());continue}d.push(a[b])}let p=Sc(d),f=fp(p),m=(f===-1?d:d.slice(0,f)).join(`
|
|
69
|
+
`),h=f===-1?"":d.slice(f).join(`
|
|
70
70
|
`),w=[...u.entries()].sort(([b],[k])=>b.localeCompare(k)).map(([,b])=>`${up}${b}`),y=[Hr,...w,...t,Ic].join(`
|
|
71
|
-
`);return[
|
|
71
|
+
`);return[m.replace(/\s*$/,""),y,h.replace(/^\s*/,"")].filter(b=>b.length>0).join(`
|
|
72
72
|
|
|
73
73
|
`).replace(/\s*$/,"")+`
|
|
74
|
-
`},
|
|
75
|
-
`)){let o=r.trim();if(!o.startsWith(up))continue;let a=o.slice(up.length).trim(),[s]=
|
|
74
|
+
`},Ew=e=>{let t=new Map,n=yp(e);if(n===void 0)return t;for(let r of n.split(`
|
|
75
|
+
`)){let o=r.trim();if(!o.startsWith(up))continue;let a=o.slice(up.length).trim(),[s]=Sc([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},Rc=e=>{if(!mp(e))return null;let t=[...Ew(e).entries()].sort(([a],[s])=>a.localeCompare(s)).map(([,a])=>a),n=Ec(e).replace(/^\s*/,"").replace(/\s*$/,""),o=[t.join(`
|
|
76
76
|
`),n].filter(a=>a.length>0).join(`
|
|
77
77
|
|
|
78
78
|
`);return o.length>0?o+`
|
|
79
|
-
`:""};import{randomUUID as
|
|
79
|
+
`:""};import{randomUUID as RT}from"node:crypto";import{chmod as OT,mkdir as TT,rm as _T,writeFile as PT}from"node:fs/promises";import{dirname as DT}from"node:path";var we=async(e,t)=>{await TT(DT(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${RT()}`;try{await PT(n,t,{flag:"wx",mode:384}),await he(n,e),await OT(e,384)}finally{await _T(n,{force:!0}).catch(()=>{})}};var MT="codex",BT="Codex app / CLI / IDE",FT="https://chatgpt.com/backend-api/codex",WT="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",HT="x-anyray-client-context-window",UT="x-anyray-client-auto-compact-limit",_c=()=>process.env.CODEX_HOME?.trim()||Tc(LT(),".codex"),Ur=()=>Tc(_c(),"config.toml"),Oc=()=>`${Ur()}.anyray-bak`,wp=()=>Tc(_c(),"hooks.json"),In=()=>Tc(_c(),"anyray.config.toml"),Rw=e=>Oo(e,"PostToolUse",Lg),Ow=(e,t=!1)=>ue({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||MT,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||BT}),rt=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,bp=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,ds=(e,t={})=>{let n=Ow(e,t.ignoreEnv),r=ee(e,"openai"),o=t.auth==="command"&&!r,a=r?"openai":t.ignoreEnv?void 0:process.env.ANYRAY_CODEX_PROVIDER?.trim(),s=t.ignoreEnv?void 0:bp(),i=e.clientKey,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${rt(FT)}`,`"x-anyray-forward-headers" = ${rt(WT)}`,...i?[`"x-anyray-api-key" = ${rt(e.clientKey)}`]:[]]:o?[]:[`"Authorization" = ${rt(`Bearer ${e.clientKey??e.placeholderKey}`)}`];return n&&c.push(`"x-anyray-metadata" = ${rt(n)}`),a&&c.push(`"x-anyray-provider" = ${rt(a)}`),t.modelContextWindow&&c.push(`"${HT}" = ${rt(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${UT}" = ${rt(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 = ${rt(s)}`]:[],"","[model_providers.anyray]",'name = "Anyray Gateway"',`base_url = ${rt(e.openaiBaseUrl)}`,'wire_api = "responses"',...r?["requires_openai_auth = true"]:[],...c.length>0?[`http_headers = { ${c.join(", ")} }`]:[],...o?["","[model_providers.anyray.auth]",`command = ${rt(t.authCommand??"")}`,...t.authArgs&&t.authArgs.length>0?[`args = [${t.authArgs.map(l=>rt(l)).join(", ")}]`]:[]]:[],...t.mcpServer?["","[mcp_servers.anyray]",`command = ${rt(t.mcpServer.command)}`,`args = [${t.mcpServer.args.map(rt).join(", ")}]`]:[]]},GT=()=>bp()?["model_provider","model"]:["model_provider"],Tw={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=_c(),t=await x(e);return{installed:t,detail:t?Ur():`no ${e} directory`}},async apply(e,t){let n=Ur(),r=wp(),o=Ow(e),a=ee(e,"openai"),s=bp(),i=ce(),c={},l=await x(r);try{l&&(c=await B(r))}catch(k){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${r} (${k instanceof Error?k.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run Connect so the retired Anyray PostToolUse entry can be removed safely.`]}}let d=Rw(c),u=await x(n),p=u?await ls(n,"utf-8"):"";if(hp(p,"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 f=hp(p,"mcp_servers.anyray"),m=gp(p,"model_context_window"),h=gp(p,"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.",h?`Context budget: follows model_auto_compact_token_limit=${h}.`:m?`Context budget: follows model_context_window=${m}.`:"Context budget: follows the request model; unknown models use the safe fallback.",`Attribution: ${o??"(none \u2014 pass --user)"}`,"Codex cloud/web tasks run on OpenAI infrastructure and cannot route through a local gateway."];if(t.dryRun)return 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 y=[];d?(await Y(r,c,{backup:!1}),await re(r),y.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 x(Oc())&&(await $T(n,Oc()),await NT(Oc(),384),w.push(`Backed up your original config to ${Oc()}.`));let g=i&&!f?Ge("profile"):void 0;w.push(f?`MCP name conflict in ${n}: mcp_servers.anyray is not owned by Anyray Connect, so it was left untouched.`:g?"Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.":`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable retrieval.`);let b=xc(p,ds(e,{mcpServer:g,modelContextWindow:m,modelAutoCompactTokenLimit:h}),GT());return await we(n,b),y.push(n),await x(In())&&(await xw(In(),{force:!0}),y.push(In()),w.push(`Removed the old opt-in profile ${In()} (the default route replaces it).`)),{status:"configured",messages:w,changedFiles:y}},async pointsAt(e){let t=Ur();if(!await x(t))return!1;try{let n=await ls(t,"utf-8"),r=`base_url = ${rt(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async mcpStatus(){let e=Ur();if(!await x(e))return{registered:!1,command:null};try{let t=await ls(e,"utf-8");if(!Iw(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 ls(Ur(),"utf-8"),t=yp(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=Ur(),n=await x(t),r=await x(In()),o=await x(wp());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=wp(),c;try{c=await B(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.`]}}Rw(c)&&(e.dryRun||(await Y(i,c,{backup:!1}),await re(i)),s.push(i),a.push(e.dryRun?`would remove the retired Anyray Codex PostToolUse hook from ${i}`:`removed the retired Anyray Codex PostToolUse hook from ${i}`))}if(n){let i=Rc(await ls(t,"utf-8"));i!==null&&(e.dryRun||await we(t,i),s.push(t),a.push(e.dryRun?`would remove the Anyray default route from ${t}`:`removed the Anyray default route from ${t}`))}return r&&(e.dryRun||await xw(In(),{force:!0}),s.push(In()),a.push(e.dryRun?`would remove the old opt-in profile ${In()}`:`removed the old opt-in profile ${In()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await re(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as JT}from"node:os";import{join as XT}from"node:path";import{readFile as Lw,rm as Cp}from"node:fs/promises";import{readFile as VT,writeFile as _w,access as KT}from"node:fs/promises";import{homedir as jT}from"node:os";import{join as Ap}from"node:path";var ZT="# >>> anyray connect >>>",YT="# <<< anyray connect <<<",us=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:ZT,end:YT},gt=()=>{let e=jT(),t=process.env.SHELL||"";return t.includes("zsh")?Ap(e,".zshrc"):t.includes("bash")?Ap(e,".bashrc"):Ap(e,".profile")},Pc=async e=>{try{return await KT(e),await VT(e,"utf-8")}catch{return""}},Pw=(e,t)=>{let{begin:n,end:r}=us(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]===`
|
|
80
80
|
`;)s-=1;let i=a+r.length;return e[i]===`
|
|
81
|
-
`&&(i+=1),e.slice(0,s)+e.slice(i)},
|
|
81
|
+
`&&(i+=1),e.slice(0,s)+e.slice(i)},Dc=async(e,t,n)=>{let r=await Pc(e),{begin:o,end:a}=us(n),s=Pw(r,n).replace(/\s*$/,""),i=[o,...t,a].join(`
|
|
82
82
|
`),c=s?`${s}
|
|
83
83
|
|
|
84
84
|
${i}
|
|
85
85
|
`:`${i}
|
|
86
|
-
`;return await
|
|
87
|
-
`).filter(c=>c.trim().length>0)}
|
|
88
|
-
`),!0):!1};var
|
|
89
|
-
`)):w&&g&&await Cp(d,{force:!0}),await
|
|
86
|
+
`;return await _w(e,c),e},Lc=async(e,t)=>{let n=await Pc(e),{begin:r,end:o}=us(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(`
|
|
87
|
+
`).filter(c=>c.trim().length>0)},Dw=async(e,t)=>(await Pc(e)).includes(us(t).begin),ps=async(e,t)=>{let n=await Pc(e);return n.includes(us(t).begin)?(await _w(e,Pw(n,t).replace(/\s*$/,"")+`
|
|
88
|
+
`),!0):!1};var Tt=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 ke=e=>`'${e.replace(/'/g,"'\\''")}'`,zT=e=>{let t=ke(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},Nw=(e,t,n,r)=>[`export OPENAI_BASE_URL=${ke(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${ke(t)}`],`export ANTHROPIC_BASE_URL=${ke(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${ke(t)}`],...e.byoUpstream?[]:["export ENABLE_TOOL_SEARCH='true'"],...e.byoUpstream?[]:["export _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL='1'"]],qT=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],QT=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],kp=()=>XT(JT(),".anyray","shell-env.sh"),Mw="# Managed by anyray-connect. Do not source this file anywhere else.",$w=e=>e.split(/\r?\n/,1)[0]===Mw,vp=e=>QT.some(t=>e.startsWith(`export ${t}=`)),Nc=(e,t=process.env)=>t.ANTHROPIC_BASE_URL===e.anthropicBaseUrl||t.OPENAI_BASE_URL===e.openaiBaseUrl?qT.filter(r=>(t[r]??"")!==""):[],Bw={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=gt();return{installed:!0,detail:await x(e)?e:`${e} (will be created)`}},async inferenceAuthLanes(){try{let e=await Lc(gt());return e?e.some(n=>vp(n)||n.includes(kp()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=gt(),r=ee(e,"openai"),o=ee(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=Nw(e,s,r,o),c=i.filter(vp),l=i.filter(b=>!vp(b)),d=kp(),u=Pg(),p=[zT(u),...l,...c.length>0?[`[ -r ${ke(d)} ] && . ${ke(d)}`]:[]],f=e.clientKey?Nw(e,Tt(e.clientKey),r,o):i,m=r&&o?"either family":r?"OpenAI":"Anthropic",h=[`${n} \u2190 managed Anyray block`,` ${u} added to PATH (so \`anyray-connect\` runs from a new shell)`,...f.map(b=>` ${b}`),...c.length>0?[`${d} \u2190 owner-only credentials (mode 0600)`]:[],`Run \`source ${n}\` or open a new terminal to apply.`,...a?[`No auth token exported for ${m} \u2014 your seat-based tool keeps`,"its own sign-in (a placeholder here would override it). Raw SDK/script","calls on a seat need your own key."]:["Note: standard SDK env vars carry no per-user header, so attribution","for these falls back to the gateway default."]],w=await x(d),y=w?await Lw(d,"utf8"):void 0,g=y===void 0||$w(y);if(c.length>0&&!g)return{status:"manual",messages:[`Refused to overwrite user-managed ${d}; move or rename that file, then run Connect again.`]};if(g||h.push(`Preserved unrelated existing ${d}.`),t.dryRun)return{status:"configured",messages:h};try{c.length>0?await we(d,[Mw,...c,""].join(`
|
|
89
|
+
`)):w&&g&&await Cp(d,{force:!0}),await Dc(n,p)}catch(b){try{y!==void 0&&g?await we(d,y):g&&await Cp(d,{force:!0})}catch{throw new Error("shell environment update failed and credential rollback could not be completed")}throw b}return{status:"configured",messages:h,changedFiles:[n,...c.length>0||w&&g?[d]:[]]}},async revert(e){let t=gt(),n=kp(),r=await x(n),o=r?$w(await Lw(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 ps(t);o&&await Cp(n,{force:!0});let s=[...a?[t]:[],...o?[n]:[]];return{status:s.length>0?"reverted":"not-found",messages:[a?`removed the Anyray block from ${t}`:`no Anyray block found in ${t}`,...o?[`removed owner-only credentials from ${n}`]:r?[`preserved user-managed ${n}`]:[]],changedFiles:s.length>0?s:void 0}}};import{spawnSync as $_}from"node:child_process";import{closeSync as M_,copyFileSync as B_,existsSync as ve,mkdirSync as F_,openSync as W_,readFileSync as yb,readSync as H_,renameSync as U_,rmSync as rn,writeFileSync as $p}from"node:fs";import{homedir as gb,platform as G_}from"node:os";import{dirname as wb,join as $o,resolve as V_}from"node:path";import{isIP as _p}from"node:net";import{homedir as e_,platform as t_}from"node:os";import{join as $c}from"node:path";var Ve=e=>{let t=e_();switch(t_()){case"darwin":return $c(t,"Library","Application Support",e);case"win32":return $c(process.env.APPDATA??$c(t,"AppData","Roaming"),e);default:return $c(t,".config",e)}};import{execFileSync as Fc}from"node:child_process";import{mkdtempSync as n_,rmSync as r_,writeFileSync as o_}from"node:fs";import{createRequire as a_}from"node:module";import{tmpdir as s_}from"node:os";import{join as Fw}from"node:path";var fs=class extends Error{},ms=e=>e instanceof fs?`: ${e.message}`:"",Ww=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new fs("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new fs(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},Hw=()=>{try{return Fc("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Ip=64*1024*1024,i_=Ip*2+64,Bc=e=>`'${e.replace(/'/g,"''")}'`,c_=(e,t)=>Fc("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:i_,stdio:["ignore","pipe","pipe"]}),l_=(e,t)=>Fc("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Ip,stdio:["pipe","pipe","pipe"]}),Uw=(e,t,n=c_)=>{let r=Bc(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
|
|
90
90
|
`)?a.slice(0,-2):a.endsWith(`
|
|
91
|
-
`)?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")},
|
|
91
|
+
`)?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")},Gw=(e,t=l_)=>{let r=t(e,`.bail on
|
|
92
92
|
.timeout 5000
|
|
93
93
|
PRAGMA wal_checkpoint(TRUNCATE);
|
|
94
|
-
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");
|
|
95
|
-
`);
|
|
96
|
-
`,{mode:384}),await
|
|
97
|
-
`),
|
|
98
|
-
`,{encoding:"utf-8",flag:"wx",mode:384})},
|
|
99
|
-
`,{encoding:"utf-8",flag:"wx",mode:384});try{j_(n,e)}catch(r){throw rn(n,{force:!0}),r}},uP=(e,t)=>{let n=Lo(e);Ib(e,{...n,lastWritten:t})},ne=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),gb=e=>ne(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Lo=e=>{let t=bb(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(ne(n)&&(Object.keys(n).length===2||Object.keys(n).length===3)&&Object.prototype.hasOwnProperty.call(n,"applicationUser")&&Object.prototype.hasOwnProperty.call(n,"openAIKey")&&(typeof n.applicationUser=="string"||n.applicationUser===null)&&(typeof n.openAIKey=="string"||n.openAIKey===null)&&(n.lastWritten===void 0||ne(n.lastWritten)&&Object.keys(n.lastWritten).length===2&&typeof n.lastWritten.applicationUser=="string"&&typeof n.lastWritten.openAIKey=="string"))return{applicationUser:n.applicationUser,openAIKey:n.openAIKey,...n.lastWritten?{lastWritten:{applicationUser:n.lastWritten.applicationUser,openAIKey:n.lastWritten.openAIKey}}:{}};if(!ne(n)||n.version!==1||!ne(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Xe],o=n.rows[at];if(!gb(r)||!gb(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}},wb=e=>{let t=Buffer.alloc(16),n=V_(e,"r");try{return K_(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{H_(n)}},pP=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return ne(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var xb=e=>{let t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".lan")||t.endsWith(".internal")||t.endsWith(".home")||!t.includes(".")&&_p(t)===0||t==="0.0.0.0")return!0;if(_p(t)===4){let[n,r,o]=t.split(".").map(Number);return n===10||n===0||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===192&&r===0&&(o===0||o===2)||n===198&&(r===18||r===19)||n===198&&r===51&&o===100||n===203&&r===0&&o===113||n>=224}if(_p(t)===6){let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(n){let r=Number.parseInt(n[1],16),o=Number.parseInt(n[2],16);return xb(`${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},Rb=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!xb(t.hostname)}catch{return!1}},fP=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${vb}`}catch{}return{...e,openaiBaseUrl:t}},No=["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."],Ob=()=>{let e=Vr();if(!ke(e))return"clear";let t=ms();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Xe)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return ne(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},hP=(e,t)=>{if(!Rb(e))return{routed:!1,problem:"gateway-not-public-https"};let n=Vr();if(!ke(n))return{routed:!1,problem:"state-db-missing"};let r=ms();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Xe),a=r.readItem(n,at)}catch{return{routed:!1,problem:"state-db-unreadable"}}if(o===void 0)return{routed:!1,problem:"settings-missing"};let s;try{s=JSON.parse(o)}catch{return{routed:!1,problem:"settings-malformed"}}if(!ne(s))return{routed:!1,problem:"settings-malformed"};let i=`${Wt(e)}/v1${vb}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Ee(a)||!Ee(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},mP=(e,t=[])=>({command:xt(e,[...t,Xc])}),Bp=(e,t,n)=>{if(!ne(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===xt(t,[...n,Xc])||r===xt(t,n)||r.endsWith(` ${Xc}`)&&r.includes(` ${t} `)},yP=(e,t)=>ne(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),Tb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Bp(a,t,n)){r=!0;continue}if(!ne(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!yP(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}},Fp=(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},_b=(e,t,n,r,o)=>ne(e.hooks)&&Fp(e.hooks,t).some(a=>ne(a)&&a.matcher===o&&Bp(a,n,r)),gP=(e,t,n,r,o)=>ne(e.hooks)&&Fp(e.hooks,t).some(a=>ne(a)&&a.matcher===o&&Bp(a,n,r)&&rc(a.command,n,[...r,Xc])),Pb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!ne(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=ne(e.hooks)?{...e.hooks}:{},{entries:s}=Tb(Fp(a,t),n,r);return s.push({...mP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},wP=(e,t,n,r=[])=>{if(!ne(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=Tb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},bP=async()=>{let e=on();if(!ce()){let t=await Lb();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 B(e);for(let n of Kr)t=Pb(t,n.event,n.flag,n.trailingArgs,n.matcher);return await Y(e,t),{changedFiles:[e],messages:[`Installed Cursor global hooks in ${e} (postToolUse trims oversized MCP tool outputs; preToolUse trims recognized Shell command output and redirects bulky built-in Read/Grep to Anyray's context tools; beforeSubmitPrompt beacons oversized pasted-data prompts). Cursor hook cache/tee persistence is disabled; gateway request logs and savings/spend rows remain metadata-only, while trace decision content follows the deployment's ANYRAY_CONTENT_MODE.`],complete:!0}}catch{return{changedFiles:[],messages:[`Could not install Cursor hooks in ${e}. Chat can still route through Anyray, but hook-based trimming/beacons are unavailable until this is fixed.`],complete:!1}}},Jc=()=>{let e=Ue("profile");return{command:e.command,args:[...e.args,Eb]}},Dp=e=>ne(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===Jc().command&&e.args.length===Jc().args.length&&e.args.every((t,n)=>t===Jc().args[n]),AP=e=>{if(!ne(e)||Object.keys(e).some(o=>o!=="command"&&o!=="args")||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(o=>typeof o=="string")||He(e.command))return!1;let t=e.args;if(t.at(-2)!==Jn||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!He(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},zc=e=>ne(e)&&Array.isArray(e.args)&&e.args.at(-1)===Eb||AP(e),CP=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,kP=async()=>{if(!ce())return Db();let e=an();try{let t=await B(e);if(t.mcpServers!==void 0&&!ne(t.mcpServers))throw new Error("mcpServers is not an object");let n=ne(t.mcpServers)?{...t.mcpServers}:{},r=n[Tt];return r!==void 0&&!zc(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Tt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Tt]=Jc(),await Y(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}}},Db=async()=>{let e=an();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await B(e);if(!ne(t.mcpServers)||!(Tt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!zc(t.mcpServers[Tt]))return{changedFiles:[],messages:[`Preserved the foreign ${Tt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Tt];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await Y(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}}},Lb=async()=>{let e=on();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await B(e),n=t;for(let r of Kr)n=wP(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await Y(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=q_(e);if(!n)return t;let r=Mo(n,bs),o=z_();try{if(ke(r)){let a=bb(r,"utf8");if(a===o)return t;if(!a.includes(Sb))return{...t,messages:[`Left ${bs} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Mp}"`]}}return G_(Cb(r),{recursive:!0}),$p(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${bs} 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 ${bs} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Nb=async()=>{let e=await bP(),t=await kP(),n=await vP();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Lp=async()=>{let e=await Lb(),t=await Db();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},$b=async()=>{if(!ce()){let e=await Lp();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 B(on());for(let r of Kr)e=Pb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await B(an());if(t.mcpServers!==void 0&&!ne(t.mcpServers))throw new Error("mcpServers is not an object");let n=ne(t.mcpServers)?t.mcpServers[Tt]:void 0;return n!==void 0&&!zc(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${an()} already contains a foreign ${Tt} 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 ${on()} and ${an()}, then re-run Connect.`],complete:!1}}},SP=async()=>{if(!ce())return!1;try{let e=await B(on());if(!ne(e.hooks)||!Kr.every(r=>_b(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await B(an()),n=ne(t.mcpServers)?t.mcpServers[Tt]:void 0;return Dp(n)}catch{return!1}},Mb=["openAIBaseUrl","useOpenAIKey"],Cs=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!ne(t))throw new Error("Cursor application-user settings are not an object");return t},EP=(e,t,n)=>{let r=Cs(e),o=Cs(t??void 0),a=n===void 0?void 0:Cs(n),s={...r},i=[];for(let c of Mb){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}},Pp=(e,t)=>{let n=Cs(e),r=Cs(t??void 0),o={...n};for(let a of Mb)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)}},jc=e=>typeof e=="string"&&e.startsWith("ark_"),Zc=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);ne(o)&&(n=o)}catch{}let r=jc(t)||n!==null&&(jc(n.useOpenAIKey)||jc(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,jc(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}},ot=(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.",...No];let n=pe(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.",...No]},Np=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!ce())return n;if(t.dryRun)return{status:"queued",messages:[`Cursor is running \u2014 would queue the ${o} and complete it automatically when Cursor quits.`]};let a;try{a=await gs("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]}},IP=async(e,t)=>{if(!Ee(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 or("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 $b();if(!n.complete)return{status:"manual",messages:n.messages};let r=ke(As())||ke($o());if(r&&Yc())return Np("native",t,{status:"manual",messages:["Cursor is running \u2014 fully quit it and re-run so Connect can restore the journaled BYOK override before enabling native subscription mode."]},["No native Claude/Opus request will be redirected: the queued operation restores Cursor\u2019s prior settings, then installs only Anyray hooks/MCP."]);if(!r){let c=Ob();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 ${ke($o())?$o():As()}, 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 ${on()}, and register the Anyray retrieval MCP server in ${an()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await ks.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 Nb(),s=[];if(!t.preservePendingOp)try{await or("cursor")}catch{s.push("Could not clear Cursor's stale queue marker.")}return{status:a.complete&&s.length===0?"configured":"manual",changedFiles:[...new Set([...o?.changedFiles??[],...a.changedFiles])],messages:[...o?.messages??[],"Kept Cursor's native Team sign-in and Claude/Opus model route; no Anyray OpenAI override or model credential was written.",...a.messages,...s,"Claude/Opus inference remains Cursor-hosted and will not produce gateway inference traces. Anyray records content-free hook savings only when a supported oversized Shell/MCP result is actually reduced.",`Make it seamless org-wide: paste this into Cursor's dashboard Team Rules and mark it Required, so every member's agent uses Anyray's tools without being asked -- "${Mp}" (connect already writes ${bs} 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."]}},ks={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>Yc(),quitTarget:J_,needsTarget:e=>e!=="revert",async complete(e,t,n){return X_(e)?e!=="revert"&&t?ks.apply(t,n):ks.revert(n):{status:"manual",messages:[`Cursor could not service a queued "${e}" operation it does not recognise; the queue entry was dropped.`]}}},async detect(){let e=kb(),t=ke(e);return{installed:t,detail:t?Vr():"Cursor user dir not found"}},async mcpStatus(){let e=an();if(!await x(e))return{registered:!1,command:null};try{let t=await B(e),n=ne(t.mcpServers)?t.mcpServers[Tt]:void 0;return Dp(n)?{registered:!0,command:CP(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=on();if(!await x(n))e="missing";else try{let s=await B(n);if(s.hooks===void 0)e="missing";else if(!ne(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(Kr.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Kr.every(c=>_b(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Kr.every(c=>gP(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=an();if(!await x(a))r="missing";else try{let s=await B(a);if(s.mcpServers===void 0)r="missing";else if(!ne(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Tt];r=i===void 0?"missing":zc(i)?"owned":"foreign",r==="owned"&&(o=Dp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Lr()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await D();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(Q_(e))return IP(e,t);let n=fP(e),r=Vr(),o=As(),a=$o();if(!Ee(e.clientKey))return{status:"manual",messages:ot(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let s={changedFiles:[],messages:[],complete:!0},i=y=>{let g=y.status==="configured"&&!s.complete;return{...y,status:g?"manual":y.status,changedFiles:[...y.changedFiles??[],...s.changedFiles],messages:[...y.messages,...s.messages,...g?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!Rb(n.openaiBaseUrl))return i({status:"manual",messages:[`Cursor routing was not changed: ${n.openaiBaseUrl} is not a public HTTPS gateway base URL. Cursor's servers make the BYOK request and cannot reach private or LAN addresses.`,"Publish the gateway behind trusted TLS, then re-run Connect.",...No]});let c=await $b();if(!c.complete)return{status:"manual",messages:c.messages};let l=ms();if(!l)return i({status:"manual",messages:ot(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!ke(r))return i({status:"manual",messages:ot(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(ke(a)){if(ke(o))return i({status:"manual",messages:ot(n,`Both a legacy Cursor Anyray backup (${a}) and a current value backup (${o}) exist \u2014 ambiguous which holds the real pre-Anyray values. Run 'anyray-connect --tools cursor --revert', then re-apply.`)});try{wb(a)?d="sqlite":(Lo(a),d="value")}catch{d=null}if(!d)return i({status:"manual",messages:ot(n,`Legacy Cursor Anyray backup at ${a} is unreadable \u2014 refusing to delete unverified recovery data. Resolve or remove it by hand, then re-apply.`)})}let p;if(ke(o))try{p=Lo(o)}catch{return i({status:"manual",messages:ot(n,`Existing Cursor backup at ${o} is invalid \u2014 refusing to write or replace recovery data.`)})}if(Yc())return i(await Np("apply",t,{status:"manual",messages:ot(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...No,...d?[`The legacy Anyray backup at ${a} will be migrated automatically when the queued apply runs.`]:[]]));if(t.dryRun)return{status:"configured",messages:[...d?[`Would migrate the legacy Anyray backup at ${a}: restore the pre-Anyray values it held and remove it, before configuring.`]:[],`Would checkpoint ${r}, ${ke(o)?`retain the original value backup at ${o}`:`create a mode-0600 value backup at ${o}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${on()}, and register the Anyray retrieval MCP server in ${an()}.`,...No]};if(d){try{l.checkpointWal(r)}catch(g){return i({status:"manual",messages:ot(n,`Couldn't checkpoint Cursor's state DB at ${r} while migrating the legacy Anyray backup at ${a}${hs(g)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(d==="sqlite")y=Zc(l.readItem(a,Xe)??null,l.readItem(a,at)??null);else{let g=Lo(a);y=Zc(g.applicationUser,g.openAIKey)}}catch{return i({status:"manual",messages:ot(n,`Couldn't read the legacy Anyray backup at ${a} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{l.mutateRows(r,[Pp(l.readItem(r,Xe),y.applicationUser),y.openAIKey===null?{key:at}:{key:at,value:y.openAIKey}])}catch{return i({status:"manual",messages:ot(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${a} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{rn(a,{force:!0}),rn(`${a}-wal`,{force:!0}),rn(`${a}-shm`,{force:!0}),u=`Migrated the legacy Anyray backup at ${a}: restored the pre-Anyray values it held and removed it.`}catch{u=`Migrated the legacy Anyray backup at ${a}: restored the pre-Anyray values it held, but couldn't remove the file \u2014 delete it by hand or the next apply will refuse as ambiguous.`}}try{l.checkpointWal(r)}catch(y){return i({status:"manual",messages:ot(n,`Couldn't checkpoint Cursor's state DB at ${r}${hs(y)} \u2014 refusing to write; set it by hand:`)})}let f;try{f=l.readItem(r,Xe)}catch{return i({status:"manual",messages:ot(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let h=pP(f,n);if(!h)return i({status:"manual",messages:ot(n,"Cursor's exact application-user settings row is malformed \u2014 refusing to replace unrelated settings; set it by hand:")});let m={applicationUser:h.value,openAIKey:e.clientKey};if(ke(o))try{uP(o,m)}catch{return i({status:"manual",messages:ot(n,`Couldn't update three-way ownership in the protected Cursor backup at ${o} \u2014 refusing to write; set it by hand:`)})}else try{dP(l,o,r,m)}catch{return i({status:"manual",messages:ot(n,`Couldn't create the protected Cursor value backup at ${o} \u2014 refusing to write; set it by hand:`)})}try{l.mutateRows(r,[{key:Xe,value:h.value},{key:at,value:e.clientKey}])}catch{let y=!0;if(p)try{Ib(o,p)}catch{y=!1}return i({status:"manual",messages:[y?`Cursor rejected the exact-row transaction. No partial row or integration write was committed; the prior recovery ownership baseline remains at ${o}. Re-run Connect to converge the route, or run --revert to clean up.`:`Cursor rejected the exact-row transaction, and the recovery ownership baseline at ${o} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}s=await Nb();let w=[];if(!t.preservePendingOp)try{await or("cursor")}catch{w.push("Cursor routing was configured, but its stale queue marker could not be cleared.")}return i({status:"configured",changedFiles:[r],messages:[...u?[u]:[],`Atomically configured Cursor's exact OpenAI settings and credential rows \u2192 base URL ${n.openaiBaseUrl} (mode-0600 value backup at ${o}).`,"Stored the API key in Cursor's credential row (not shown here).",...w,...No,"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await D().catch(()=>{}),n=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?ke(As())||ke($o())||Ob()!=="clear"?!1:SP():hP(e,n).routed},async revert(e){let t=Vr(),n=As(),r=$o(),o=ke(n),a=ke(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 ${on()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${on()} and unregister its owned retrieval MCP server.`]};if((o||a)&&Yc()){if(e.fullRevert){let h=await Lp(),m=!0;try{await or("cursor")}catch{m=!1}return{status:"manual",changedFiles:h.changedFiles,messages:[...h.messages,...m?[]:["Could not clear Cursor's stale queue marker."],`Cursor is running, so its saved settings in ${a?r:n} were left in place and nothing was queued. Quit Cursor and re-run --revert to restore them.`]}}return Np("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=ms(),i=!1,c=!1,l,d=[];if(a)try{if(wb(r))if(ke(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let h=Zc(s.readItem(r,Xe)??null,s.readItem(r,at)??null);s.mutateRows(t,[Pp(s.readItem(t,Xe),h.applicationUser),h.openAIKey===null?{key:at}:{key:at,value:h.openAIKey}]),c=!0}else i=!0,U_(r,t),rn(`${t}-wal`,{force:!0}),rn(`${t}-shm`,{force:!0});else{let h=Lo(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!ke(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let m=Zc(h.applicationUser,h.openAIKey);s.mutateRows(t,[Pp(s.readItem(t,Xe),m.applicationUser),m.openAIKey===null?{key:at}:{key:at,value:m.openAIKey}]),c=!0}}catch(h){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${hs(h)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Lo(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(!ke(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=EP(s.readItem(t,Xe),l.applicationUser,l.lastWritten?.applicationUser);d.push(...h.conflicts);let m=[h.mutation],w=s.readItem(t,at);l.lastWritten&&w===l.lastWritten.openAIKey?m.push(l.openAIKey===null?{key:at}:{key:at,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,m)}catch(h){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${hs(h)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],p=!0;try{rn(r,{force:!0}),rn(`${r}-wal`,{force:!0}),rn(`${r}-shm`,{force:!0}),rn(n,{force:!0})}catch{p=!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 or("cursor")}catch{p=!1,u.push("Could not clear Cursor's stale queue marker.")}let f=await Lp();return p=p&&f.complete,{status:p?"reverted":"manual",changedFiles:[...o||a?[t]:[],...f.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(", ")}.`]:[],...f.messages,"Restart Cursor."]}}};import{chmod as OD,mkdir as TD,readFile as kA,rm as _D,writeFile as PD}from"node:fs/promises";import{randomUUID as DD}from"node:crypto";import{dirname as LD,join as vA}from"node:path";import{constants as OP,chmod as TP,copyFile as _P,readFile as Bb}from"node:fs/promises";import{applyEdits as PP,modify as DP}from"jsonc-parser";var xP=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]!==`
|
|
100
|
-
`;)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},
|
|
101
|
-
`,r=n.trim()?
|
|
94
|
+
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");Ww(o?.slice(1).map(Number))},d_=(e,t)=>{let n=n_(Fw(s_(),"anyray-cursor-"));try{let o=[".bail on",".timeout 5000","BEGIN IMMEDIATE;",...t.map((a,s)=>{if(a.value===void 0)return`DELETE FROM ItemTable WHERE key=${Bc(a.key)};`;let i=Fw(n,`value-${s}`);return o_(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${Bc(a.key)}, CAST(readfile(${Bc(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
|
|
95
|
+
`);Fc("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Ip,stdio:["pipe","ignore","pipe"]})}finally{try{r_(n,{recursive:!0,force:!0})}catch{}}},u_={kind:"sqlite3-cli",readItem:(e,t)=>Uw(e,t),checkpointWal:e=>Gw(e),mutateRows:d_},p_=()=>{try{let t=a_(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},Sp=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},f_=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),m_=e=>({kind:"node-sqlite",readItem:(t,n)=>Sp(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:f_(o.value)}),checkpointWal:t=>Sp(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);Ww(o)}),mutateRows:(t,n)=>Sp(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}})}),Mc,hs=()=>{if(Mc!==void 0)return Mc;let e=p_();return Mc=e?m_(e):Hw()?u_:null,Mc};import{spawn as h_}from"node:child_process";import{randomUUID as Vw}from"node:crypto";import{constants as Kw}from"node:fs";import{chmod as y_,copyFile as jw,mkdir as g_,readdir as w_,readFile as b_,rename as A_,rm as ys,writeFile as C_}from"node:fs/promises";import{join as Ep}from"node:path";var xp=/^[a-z0-9][a-z0-9-]{0,31}$/,k_=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,Zw=/^[a-z0-9][a-z0-9-]{0,31}$/,v_=/^[0-9TZ:.+-]{1,40}$/,Rp=()=>Ep(Q(),"pending"),Hc=e=>{if(!xp.test(e)||k_.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return Ep(Rp(),`${e}.json`)},Yw=()=>Ep(Q(),"cursor-pending.json"),S_=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),I_=(e,t)=>{if(!S_(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!xp.test(n)||typeof e.op!="string"||!Zw.test(e.op)||typeof e.requestedAt!="string"||!v_.test(e.requestedAt)||Number.isNaN(Date.parse(e.requestedAt))))return{version:1,adapter:n,op:e.op,requestedAt:e.requestedAt,watcherPid:typeof e.watcherPid=="number"&&Number.isSafeInteger(e.watcherPid)&&e.watcherPid>0?e.watcherPid:void 0,...typeof e.generation=="string"&&e.generation?{generation:e.generation}:{}}},Op=async(e,t)=>{try{return I_(JSON.parse(await b_(e,"utf-8")),t)}catch{return}},Jw=async()=>{let e=Yw(),t=await Op(e,"cursor");if(!t)return;let n=!1;try{await Xw(),await jw(e,Hc("cursor"),Kw.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await ys(e,{force:!0})}catch{}return t},Uc=async e=>{let t=await Op(Hc(e),e);return t||(e==="cursor"?Jw():void 0)},rr=async()=>{let e;try{e=await w_(Rp())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!xp.test(r))continue;let o=await Uc(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await Jw();n&&t.push(n)}return t},Xw=async()=>{await tt();let e=Rp();await g_(e,{recursive:!0,mode:448});try{await y_(e,448)}catch{}},Wc=async e=>{await Xw();let t=Hc(e.adapter),n=`${t}.${process.pid}.tmp`;await C_(n,`${JSON.stringify(e)}
|
|
96
|
+
`,{mode:384}),await he(n,t)},E_=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,or=async(e,t)=>await Tp(e,t)==="claimed",Tp=async(e,t)=>{let n=Hc(e);if(t){let o=`${n}.${process.pid}.${Vw()}.claimed`;try{await A_(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Op(o,e);if(a&&E_(a,t))return await ys(o,{force:!0}),"claimed";let s=!1;try{await jw(o,n,Kw.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await ys(o,{force:!0})}return"superseded"}let r=!1;try{await ys(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await ys(Yw(),{force:!0})}catch{}return r?"claimed":"absent"},ar=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},x_=e=>{let{command:t,args:n}=Qn("__anyray-quit-watch");return{exe:t,args:[...n,e]}},R_=e=>{let{exe:t,args:n}=x_(e),r=h_(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},zw=R_;var qw=async()=>{let e=[],t;try{t=await rr()}catch{return e}for(let n of t)if(!ar(n.watcherPid))try{let r=zw(n.adapter);if(!r)continue;await Wc({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},gs=async(e,t)=>{if(!Zw.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await Uc(e),r=new Date().toISOString(),o=Vw();if(n&&ar(n.watcherPid))return await Wc({...n,adapter:e,op:t,requestedAt:r,generation:o}),{watcherPid:n.watcherPid,alreadyWatching:!0};await Wc({version:1,adapter:e,op:t,requestedAt:r,generation:o});let a;try{a=zw(e)}catch{a=void 0}return a&&await Wc({version:1,adapter:e,op:t,requestedAt:r,watcherPid:a,generation:o}),{watcherPid:a,alreadyWatching:!1}};import{spawn as O_,spawnSync as eb}from"node:child_process";import{existsSync as Gc}from"node:fs";import{homedir as T_,platform as sr}from"node:os";import{join as tb,win32 as Qw}from"node:path";var nb=(e,t={})=>{let n=t.env??process.env,r=t.exists??Gc,o=(t.home??T_)(),a={localAppData:n.LOCALAPPDATA??Qw.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=Qw.join(i,s.path);if(r(c))return c}},Gr=/^[A-Za-z0-9 ._-]{1,64}$/,__=/^[A-Za-z0-9.-]{1,128}$/,Vc=e=>e.darwinBundleId&&__.test(e.darwinBundleId)?e.darwinBundleId:void 0,rb=(e,t=sr())=>t==="darwin"?Vc(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",ob=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",ab=(e,t=sr(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return nb(e,r)!==void 0;let o=e.linuxProcess;return!o||!Gr.test(o)?!1:n.split(":").filter(Boolean).some(a=>Gc(tb(a,o)))},sb=(e,t=sr())=>{if(t==="darwin"&&Vc(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Gr.test(n))},ib=1e4,ws=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=tb(t,"System32",e);return Gc(n)?n:e},P_=e=>{let t=`/usr/bin/${e}`;return Gc(t)?t:e},D_=(e,t)=>{try{let n=eb(e,t,{encoding:"utf-8",timeout:ib,windowsHide:!0,...sr()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:sr()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},L_=e=>new Promise(t=>setTimeout(t,e)),cb=(e,t={})=>{let n=t.runtimePlatform??sr(),r=t.run??D_;if(n==="darwin"){let a=Vc(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||!Gr.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||!Gr.test(a)?!1:r(ws("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Gr.test(o)?!1:r(P_("pkill"),["-TERM","-o","-x",o])},lb=async(e,t=2e4,n={})=>{let r=n.sleep??L_,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},N_=(e,t,n={})=>{let r=sr();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=eb(e,t,{stdio:"ignore",timeout:ib,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=O_(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},db=(e,t={})=>{let n=t.runtimePlatform??sr(),r=t.launch??N_;if(n==="darwin"){let a=Vc(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!Gr.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=nb(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!Gr.test(o)?!1:r(o,[])};var K_={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"}]},j_=e=>e==="apply"||e==="native"||e==="revert",bb=()=>Ve("Cursor"),Vr=()=>$o(bb(),"User","globalStorage","state.vscdb"),As=()=>`${Vr()}.anyray-bak.json`,No=()=>`${Vr()}.anyray-bak`,ze="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",at="cursorAuth/openAIKey";var Ab="/seat/cursor",Mp="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.",bs=$o(".cursor","rules","anyray.mdc"),Cb="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",Z_=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",Cb,"",Mp,""].join(`
|
|
97
|
+
`),Y_=e=>{let t=V_(e);for(;;){if(ve($o(t,".git")))return t;let n=wb(t);if(n===t)return null;t=n}},J_=e=>e.authMode!=="placeholder",on=()=>$o(gb(),".cursor","hooks.json"),an=()=>$o(gb(),".cursor","mcp.json"),_t="anyray",kb="--anyray-owner=cursor-v1",X_="postToolUse",z_="beforeSubmitPrompt",ub="preToolUse",q_="^MCP:",Q_="UserPromptSubmit",eP="Shell",tP="^(Read|Grep)$",Jc="--anyray-owner=cursor-hook-v1",Kr=[{event:X_,flag:Xe,trailingArgs:["cursor"],matcher:q_},{event:z_,flag:Zn,trailingArgs:[],matcher:Q_},{event:ub,flag:Ng,trailingArgs:[],matcher:eP},{event:ub,flag:$g,trailingArgs:[],matcher:tP}];var pb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},nP=(e,t,n)=>$_(e,t,n),fb=nP,rP,oP=()=>{let e=rP??G_();if(e==="win32"){let t=fb(ws("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],pb);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=fb("pgrep",["-x",t],pb);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},aP=oP,Zc=()=>aP();var sP=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,ze)??null,openAIKey:e.readItem(n,at)??null,lastWritten:r};$p(t,`${JSON.stringify(o,null,2)}
|
|
98
|
+
`,{encoding:"utf-8",flag:"wx",mode:384})},vb=(e,t)=>{let n=`${e}.${process.pid}.tmp`;$p(n,`${JSON.stringify(t,null,2)}
|
|
99
|
+
`,{encoding:"utf-8",flag:"wx",mode:384});try{U_(n,e)}catch(r){throw rn(n,{force:!0}),r}},iP=(e,t)=>{let n=Do(e);vb(e,{...n,lastWritten:t})},ne=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),mb=e=>ne(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Do=e=>{let t=yb(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(ne(n)&&(Object.keys(n).length===2||Object.keys(n).length===3)&&Object.prototype.hasOwnProperty.call(n,"applicationUser")&&Object.prototype.hasOwnProperty.call(n,"openAIKey")&&(typeof n.applicationUser=="string"||n.applicationUser===null)&&(typeof n.openAIKey=="string"||n.openAIKey===null)&&(n.lastWritten===void 0||ne(n.lastWritten)&&Object.keys(n.lastWritten).length===2&&typeof n.lastWritten.applicationUser=="string"&&typeof n.lastWritten.openAIKey=="string"))return{applicationUser:n.applicationUser,openAIKey:n.openAIKey,...n.lastWritten?{lastWritten:{applicationUser:n.lastWritten.applicationUser,openAIKey:n.lastWritten.openAIKey}}:{}};if(!ne(n)||n.version!==1||!ne(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[ze],o=n.rows[at];if(!mb(r)||!mb(o))throw new Error("Cursor value backup is missing an exact managed row");return{applicationUser:r.exists?r.value:null,openAIKey:o.exists?o.value:null}},hb=e=>{let t=Buffer.alloc(16),n=W_(e,"r");try{return H_(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{M_(n)}},cP=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return ne(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Sb=e=>{let t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".lan")||t.endsWith(".internal")||t.endsWith(".home")||!t.includes(".")&&_p(t)===0||t==="0.0.0.0")return!0;if(_p(t)===4){let[n,r,o]=t.split(".").map(Number);return n===10||n===0||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===192&&r===0&&(o===0||o===2)||n===198&&(r===18||r===19)||n===198&&r===51&&o===100||n===203&&r===0&&o===113||n>=224}if(_p(t)===6){let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(t);if(n){let r=Number.parseInt(n[1],16),o=Number.parseInt(n[2],16);return Sb(`${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},Ib=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Sb(t.hostname)}catch{return!1}},lP=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${Ab}`}catch{}return{...e,openaiBaseUrl:t}},Lo=["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."],Eb=()=>{let e=Vr();if(!ve(e))return"clear";let t=hs();if(!t)return"unverifiable";let n;try{n=t.readItem(e,ze)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return ne(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},dP=(e,t)=>{if(!Ib(e))return{routed:!1,problem:"gateway-not-public-https"};let n=Vr();if(!ve(n))return{routed:!1,problem:"state-db-missing"};let r=hs();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,ze),a=r.readItem(n,at)}catch{return{routed:!1,problem:"state-db-unreadable"}}if(o===void 0)return{routed:!1,problem:"settings-missing"};let s;try{s=JSON.parse(o)}catch{return{routed:!1,problem:"settings-malformed"}}if(!ne(s))return{routed:!1,problem:"settings-malformed"};let i=`${Ht(e)}/v1${Ab}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Ee(a)||!Ee(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},uP=(e,t=[])=>({command:Rt(e,[...t,Jc])}),Bp=(e,t,n)=>{if(!ne(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Rt(t,[...n,Jc])||r===Rt(t,n)||r.endsWith(` ${Jc}`)&&r.includes(` ${t} `)},pP=(e,t)=>ne(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),xb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Bp(a,t,n)){r=!0;continue}if(!ne(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!pP(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}},Fp=(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},Rb=(e,t,n,r,o)=>ne(e.hooks)&&Fp(e.hooks,t).some(a=>ne(a)&&a.matcher===o&&Bp(a,n,r)),fP=(e,t,n,r,o)=>ne(e.hooks)&&Fp(e.hooks,t).some(a=>ne(a)&&a.matcher===o&&Bp(a,n,r)&&nc(a.command,n,[...r,Jc])),Ob=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!ne(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=ne(e.hooks)?{...e.hooks}:{},{entries:s}=xb(Fp(a,t),n,r);return s.push({...uP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},mP=(e,t,n,r=[])=>{if(!ne(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=xb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},hP=async()=>{let e=on();if(!ce()){let t=await _b();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable cache-safe trimming and paste-savings beacons.`],complete:t.complete}}try{let t=await B(e);for(let n of Kr)t=Ob(t,n.event,n.flag,n.trailingArgs,n.matcher);return await Y(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}}},Yc=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,kb]}},Dp=e=>ne(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===Yc().command&&e.args.length===Yc().args.length&&e.args.every((t,n)=>t===Yc().args[n]),yP=e=>{if(!ne(e)||Object.keys(e).some(o=>o!=="command"&&o!=="args")||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(o=>typeof o=="string")||Ue(e.command))return!1;let t=e.args;if(t.at(-2)!==Jn||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!Ue(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},Xc=e=>ne(e)&&Array.isArray(e.args)&&e.args.at(-1)===kb||yP(e),gP=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,wP=async()=>{if(!ce())return Tb();let e=an();try{let t=await B(e);if(t.mcpServers!==void 0&&!ne(t.mcpServers))throw new Error("mcpServers is not an object");let n=ne(t.mcpServers)?{...t.mcpServers}:{},r=n[_t];return r!==void 0&&!Xc(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${_t} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[_t]=Yc(),await Y(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}}},Tb=async()=>{let e=an();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await B(e);if(!ne(t.mcpServers)||!(_t in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!Xc(t.mcpServers[_t]))return{changedFiles:[],messages:[`Preserved the foreign ${_t} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[_t];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await Y(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}}},_b=async()=>{let e=on();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await B(e),n=t;for(let r of Kr)n=mP(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await Y(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}}},bP=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=Y_(e);if(!n)return t;let r=$o(n,bs),o=Z_();try{if(ve(r)){let a=yb(r,"utf8");if(a===o)return t;if(!a.includes(Cb))return{...t,messages:[`Left ${bs} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${Mp}"`]}}return F_(wb(r),{recursive:!0}),$p(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${bs} 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 ${bs} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},Pb=async()=>{let e=await hP(),t=await wP(),n=await bP();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Lp=async()=>{let e=await _b(),t=await Tb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},Db=async()=>{if(!ce()){let e=await Lp();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${Oe()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await B(on());for(let r of Kr)e=Ob(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await B(an());if(t.mcpServers!==void 0&&!ne(t.mcpServers))throw new Error("mcpServers is not an object");let n=ne(t.mcpServers)?t.mcpServers[_t]:void 0;return n!==void 0&&!Xc(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${an()} already contains a foreign ${_t} MCP registration. Rename or remove that entry explicitly, then re-run Connect.`],complete:!1}:{changedFiles:[],messages:[],complete:!0}}catch{return{changedFiles:[],messages:[`Cursor routing was not changed because its hook or MCP configuration could not be validated safely. Repair ${on()} and ${an()}, then re-run Connect.`],complete:!1}}},AP=async()=>{if(!ce())return!1;try{let e=await B(on());if(!ne(e.hooks)||!Kr.every(r=>Rb(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await B(an()),n=ne(t.mcpServers)?t.mcpServers[_t]:void 0;return Dp(n)}catch{return!1}},Lb=["openAIBaseUrl","useOpenAIKey"],Cs=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!ne(t))throw new Error("Cursor application-user settings are not an object");return t},CP=(e,t,n)=>{let r=Cs(e),o=Cs(t??void 0),a=n===void 0?void 0:Cs(n),s={...r},i=[];for(let c of Lb){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:ze}:{key:ze,value:JSON.stringify(s)},conflicts:i}},Pp=(e,t)=>{let n=Cs(e),r=Cs(t??void 0),o={...n};for(let a of Lb)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:ze}:{key:ze,value:JSON.stringify(o)}},Kc=e=>typeof e=="string"&&e.startsWith("ark_"),jc=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);ne(o)&&(n=o)}catch{}let r=Kc(t)||n!==null&&(Kc(n.useOpenAIKey)||Kc(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,Kc(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}},ot=(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.",...Lo];let n=ue(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.",...Lo]},Np=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!ce())return n;if(t.dryRun)return{status:"queued",messages:[`Cursor is running \u2014 would queue the ${o} and complete it automatically when Cursor quits.`]};let a;try{a=await gs("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]}},kP=async(e,t)=>{if(!Ee(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 or("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 Db();if(!n.complete)return{status:"manual",messages:n.messages};let r=ve(As())||ve(No());if(r&&Zc())return Np("native",t,{status:"manual",messages:["Cursor is running \u2014 fully quit it and re-run so Connect can restore the journaled BYOK override before enabling native subscription mode."]},["No native Claude/Opus request will be redirected: the queued operation restores Cursor\u2019s prior settings, then installs only Anyray hooks/MCP."]);if(!r){let c=Eb();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 ${ve(No())?No():As()}, 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 ${on()}, and register the Anyray retrieval MCP server in ${an()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await ks.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 Pb(),s=[];if(!t.preservePendingOp)try{await or("cursor")}catch{s.push("Could not clear Cursor's stale queue marker.")}return{status:a.complete&&s.length===0?"configured":"manual",changedFiles:[...new Set([...o?.changedFiles??[],...a.changedFiles])],messages:[...o?.messages??[],"Kept Cursor's native Team sign-in and Claude/Opus model route; no Anyray OpenAI override or model credential was written.",...a.messages,...s,"Claude/Opus inference remains Cursor-hosted and will not produce gateway inference traces. Anyray records content-free hook savings only when a supported oversized Shell/MCP result is actually reduced.",`Make it seamless org-wide: paste this into Cursor's dashboard Team Rules and mark it Required, so every member's agent uses Anyray's tools without being asked -- "${Mp}" (connect already writes ${bs} 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."]}},ks={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>Zc(),quitTarget:K_,needsTarget:e=>e!=="revert",async complete(e,t,n){return j_(e)?e!=="revert"&&t?ks.apply(t,n):ks.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=bb(),t=ve(e);return{installed:t,detail:t?Vr():"Cursor user dir not found"}},async mcpStatus(){let e=an();if(!await x(e))return{registered:!1,command:null};try{let t=await B(e),n=ne(t.mcpServers)?t.mcpServers[_t]:void 0;return Dp(n)?{registered:!0,command:gP(n)}:{registered:!1,command:null}}catch{return{registered:!1,command:null}}},async integrationStatus(){let e,t=!0,n=on();if(!await x(n))e="missing";else try{let s=await B(n);if(s.hooks===void 0)e="missing";else if(!ne(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(Kr.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=Kr.every(c=>Rb(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Kr.every(c=>fP(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=an();if(!await x(a))r="missing";else try{let s=await B(a);if(s.mcpServers===void 0)r="missing";else if(!ne(s.mcpServers))r="unreadable";else{let i=s.mcpServers[_t];r=i===void 0?"missing":Xc(i)?"owned":"foreign",r==="owned"&&(o=Dp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Lr()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await D();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(J_(e))return kP(e,t);let n=lP(e),r=Vr(),o=As(),a=No();if(!Ee(e.clientKey))return{status:"manual",messages:ot(n,"Cursor routing was not changed: a valid personal ark_ gateway key is required.")};let s={changedFiles:[],messages:[],complete:!0},i=y=>{let g=y.status==="configured"&&!s.complete;return{...y,status:g?"manual":y.status,changedFiles:[...y.changedFiles??[],...s.changedFiles],messages:[...y.messages,...s.messages,...g?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!Ib(n.openaiBaseUrl))return i({status:"manual",messages:[`Cursor routing was not changed: ${n.openaiBaseUrl} is not a public HTTPS gateway base URL. Cursor's servers make the BYOK request and cannot reach private or LAN addresses.`,"Publish the gateway behind trusted TLS, then re-run Connect.",...Lo]});let c=await Db();if(!c.complete)return{status:"manual",messages:c.messages};let l=hs();if(!l)return i({status:"manual",messages:ot(n,"No SQLite backend available (this runtime lacks node:sqlite and no sqlite3 CLI is on PATH) \u2014 automatic Cursor config needs one.")});if(!ve(r))return i({status:"manual",messages:ot(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(ve(a)){if(ve(o))return i({status:"manual",messages:ot(n,`Both a legacy Cursor Anyray backup (${a}) and a current value backup (${o}) exist \u2014 ambiguous which holds the real pre-Anyray values. Run 'anyray-connect --tools cursor --revert', then re-apply.`)});try{hb(a)?d="sqlite":(Do(a),d="value")}catch{d=null}if(!d)return i({status:"manual",messages:ot(n,`Legacy Cursor Anyray backup at ${a} is unreadable \u2014 refusing to delete unverified recovery data. Resolve or remove it by hand, then re-apply.`)})}let p;if(ve(o))try{p=Do(o)}catch{return i({status:"manual",messages:ot(n,`Existing Cursor backup at ${o} is invalid \u2014 refusing to write or replace recovery data.`)})}if(Zc())return i(await Np("apply",t,{status:"manual",messages:ot(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Lo,...d?[`The legacy Anyray backup at ${a} will be migrated automatically when the queued apply runs.`]:[]]));if(t.dryRun)return{status:"configured",messages:[...d?[`Would migrate the legacy Anyray backup at ${a}: restore the pre-Anyray values it held and remove it, before configuring.`]:[],`Would checkpoint ${r}, ${ve(o)?`retain the original value backup at ${o}`:`create a mode-0600 value backup at ${o}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${on()}, and register the Anyray retrieval MCP server in ${an()}.`,...Lo]};if(d){try{l.checkpointWal(r)}catch(g){return i({status:"manual",messages:ot(n,`Couldn't checkpoint Cursor's state DB at ${r} while migrating the legacy Anyray backup at ${a}${ms(g)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(d==="sqlite")y=jc(l.readItem(a,ze)??null,l.readItem(a,at)??null);else{let g=Do(a);y=jc(g.applicationUser,g.openAIKey)}}catch{return i({status:"manual",messages:ot(n,`Couldn't read the legacy Anyray backup at ${a} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{l.mutateRows(r,[Pp(l.readItem(r,ze),y.applicationUser),y.openAIKey===null?{key:at}:{key:at,value:y.openAIKey}])}catch{return i({status:"manual",messages:ot(n,`Couldn't restore the pre-Anyray values from the legacy backup at ${a} into Cursor's state DB \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}try{rn(a,{force:!0}),rn(`${a}-wal`,{force:!0}),rn(`${a}-shm`,{force:!0}),u=`Migrated the legacy Anyray backup at ${a}: restored the pre-Anyray values it held and removed it.`}catch{u=`Migrated the legacy Anyray backup at ${a}: restored the pre-Anyray values it held, but couldn't remove the file \u2014 delete it by hand or the next apply will refuse as ambiguous.`}}try{l.checkpointWal(r)}catch(y){return i({status:"manual",messages:ot(n,`Couldn't checkpoint Cursor's state DB at ${r}${ms(y)} \u2014 refusing to write; set it by hand:`)})}let f;try{f=l.readItem(r,ze)}catch{return i({status:"manual",messages:ot(n,"Couldn't read Cursor's exact application-user settings row \u2014 refusing to write; set it by hand:")})}let m=cP(f,n);if(!m)return i({status:"manual",messages:ot(n,"Cursor's exact application-user settings row is malformed \u2014 refusing to replace unrelated settings; set it by hand:")});let h={applicationUser:m.value,openAIKey:e.clientKey};if(ve(o))try{iP(o,h)}catch{return i({status:"manual",messages:ot(n,`Couldn't update three-way ownership in the protected Cursor backup at ${o} \u2014 refusing to write; set it by hand:`)})}else try{sP(l,o,r,h)}catch{return i({status:"manual",messages:ot(n,`Couldn't create the protected Cursor value backup at ${o} \u2014 refusing to write; set it by hand:`)})}try{l.mutateRows(r,[{key:ze,value:m.value},{key:at,value:e.clientKey}])}catch{let y=!0;if(p)try{vb(o,p)}catch{y=!1}return i({status:"manual",messages:[y?`Cursor rejected the exact-row transaction. No partial row or integration write was committed; the prior recovery ownership baseline remains at ${o}. Re-run Connect to converge the route, or run --revert to clean up.`:`Cursor rejected the exact-row transaction, and the recovery ownership baseline at ${o} could not be rolled back. The row transaction itself made no partial write; inspect the backup before re-applying or reverting.`]})}s=await Pb();let w=[];if(!t.preservePendingOp)try{await or("cursor")}catch{w.push("Cursor routing was configured, but its stale queue marker could not be cleared.")}return i({status:"configured",changedFiles:[r],messages:[...u?[u]:[],`Atomically configured Cursor's exact OpenAI settings and credential rows \u2192 base URL ${n.openaiBaseUrl} (mode-0600 value backup at ${o}).`,"Stored the API key in Cursor's credential row (not shown here).",...w,...Lo,"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await D().catch(()=>{}),n=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?ve(As())||ve(No())||Eb()!=="clear"?!1:AP():dP(e,n).routed},async revert(e){let t=Vr(),n=As(),r=No(),o=ve(n),a=ve(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 ${on()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${on()} and unregister its owned retrieval MCP server.`]};if((o||a)&&Zc()){if(e.fullRevert){let m=await Lp(),h=!0;try{await or("cursor")}catch{h=!1}return{status:"manual",changedFiles:m.changedFiles,messages:[...m.messages,...h?[]:["Could not clear Cursor's stale queue marker."],`Cursor is running, so its saved settings in ${a?r:n} were left in place and nothing was queued. Quit Cursor and re-run --revert to restore them.`]}}return Np("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=hs(),i=!1,c=!1,l,d=[];if(a)try{if(hb(r))if(ve(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let m=jc(s.readItem(r,ze)??null,s.readItem(r,at)??null);s.mutateRows(t,[Pp(s.readItem(t,ze),m.applicationUser),m.openAIKey===null?{key:at}:{key:at,value:m.openAIKey}]),c=!0}else i=!0,B_(r,t),rn(`${t}-wal`,{force:!0}),rn(`${t}-shm`,{force:!0});else{let m=Do(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!ve(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let h=jc(m.applicationUser,m.openAIKey);s.mutateRows(t,[Pp(s.readItem(t,ze),h.applicationUser),h.openAIKey===null?{key:at}:{key:at,value:h.openAIKey}]),c=!0}}catch(m){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${ms(m)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Do(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(!ve(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let m=CP(s.readItem(t,ze),l.applicationUser,l.lastWritten?.applicationUser);d.push(...m.conflicts);let h=[m.mutation],w=s.readItem(t,at);l.lastWritten&&w===l.lastWritten.openAIKey?h.push(l.openAIKey===null?{key:at}:{key:at,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,h)}catch(m){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${ms(m)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],p=!0;try{rn(r,{force:!0}),rn(`${r}-wal`,{force:!0}),rn(`${r}-shm`,{force:!0}),rn(n,{force:!0})}catch{p=!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 or("cursor")}catch{p=!1,u.push("Could not clear Cursor's stale queue marker.")}let f=await Lp();return p=p&&f.complete,{status:p?"reverted":"manual",changedFiles:[...o||a?[t]:[],...f.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(", ")}.`]:[],...f.messages,"Restart Cursor."]}}};import{chmod as ID,mkdir as ED,readFile as bA,rm as xD,writeFile as RD}from"node:fs/promises";import{randomUUID as OD}from"node:crypto";import{dirname as TD,join as AA}from"node:path";import{constants as IP,chmod as EP,copyFile as xP,readFile as Nb}from"node:fs/promises";import{applyEdits as RP,modify as OP}from"jsonc-parser";var vP=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]!==`
|
|
100
|
+
`;)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},SP=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},wt=e=>JSON.parse(SP(vP(e)));var zc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ke=async e=>{let t=await x(e),n=t?await Nb(e,"utf8"):`{}
|
|
101
|
+
`,r=n.trim()?wt(n):{};if(!zc(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},$b=(e,t,n=[])=>{if(zc(e)&&zc(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...$b(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}]},sn=async(e,t,n,r)=>{let o=$b(t.data,n);if(o.length===0)return!1;if(r&&!await x(`${e}.anyray-bak`))if(t.existed)try{await xP(e,`${e}.anyray-bak`,IP.COPYFILE_EXCL),await EP(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await we(`${e}.anyray-bak`,`{}
|
|
102
102
|
`);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
|
|
103
103
|
`)?`\r
|
|
104
104
|
`:`
|
|
105
|
-
`},s=t.raw;for(let i of o)s=
|
|
105
|
+
`},s=t.raw;for(let i of o)s=RP(s,OP(s,i.path,i.value,{formattingOptions:a}));return await we(e,s.endsWith(`
|
|
106
106
|
`)?s:`${s}
|
|
107
|
-
`),!0},
|
|
108
|
-
`;)t+=1;continue}if(n==="/"&&e[t+1]==="*"){let r=e.indexOf("*/",t+2);if(r===-1)return-1;t=r+2;continue}return n==="{"?t:-1}return-1},
|
|
107
|
+
`),!0},Mo=async e=>{try{let t=wt(await Nb(`${e}.anyray-bak`,"utf8"));return zc(t)?t:void 0}catch{return}};import{readFile as fD,writeFile as mD}from"node:fs/promises";import{dirname as hD,join as yD}from"node:path";import{mkdir as gD}from"node:fs/promises";var Mb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),TP=e=>{let t=0;for(;t<e.length;){let n=e[t];if(/\s/.test(n)){t+=1;continue}if(n==="/"&&e[t+1]==="/"){for(;t<e.length&&e[t]!==`
|
|
108
|
+
`;)t+=1;continue}if(n==="/"&&e[t+1]==="*"){let r=e.indexOf("*/",t+2);if(r===-1)return-1;t=r+2;continue}return n==="{"?t:-1}return-1},_P=(e,t)=>{let n=/\n([ \t]+)"/.exec(e.slice(t));return n?n[1]:" "},PP=(e,t)=>{let n=e.slice(t+1),r=n.indexOf("}");return r===-1?!1:n.slice(0,r).trim()===""},Wp=(e,t,n)=>{let r;try{r=wt(e)}catch{return{ok:!1,reason:"unsupported"}}if(!Mb(r))return{ok:!1,reason:"unsupported"};if(t in r)return{ok:!1,reason:"key-present"};let o=TP(e);if(o===-1)return{ok:!1,reason:"unsupported"};let a=_P(e,o),s=`${JSON.stringify(t)}: ${JSON.stringify(n)}`,i=e.slice(0,o+1),c=e.slice(o+1),l=PP(e,o)?`
|
|
109
109
|
${a}${s}
|
|
110
110
|
`:`
|
|
111
|
-
${a}${s},`,d=`${i}${l}${c}`;try{let u=gt(d);if(!Wb(u))return{ok:!1,reason:"unsupported"};for(let[p,f]of Object.entries(r))if(JSON.stringify(u[p])!==JSON.stringify(f))return{ok:!1,reason:"unsupported"};if(JSON.stringify(u[t])!==JSON.stringify(n))return{ok:!1,reason:"unsupported"}}catch{return{ok:!1,reason:"unsupported"}}return{ok:!0,text:d}};import{execFile as GP}from"node:child_process";import{readdirSync as VP,statSync as KP}from"node:fs";import{createHash as nA,randomBytes as jP,randomUUID as rA}from"node:crypto";import{chmod as ZP,lstat as Yp,mkdir as Jp,readdir as oA,readFile as ln,rm as aA,unlink as tl,writeFile as Xp}from"node:fs/promises";import{homedir as Uo,platform as zp}from"node:os";import{dirname as Kp,join as wt,posix as Qb,win32 as YP}from"node:path";import{promisify as JP}from"node:util";var cn="0.1.29";var ir="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",Qc="c341829c0dacfc512fa49fb951be4864ca3e7d6b46d6befbee84e663daa8e9a7",Hb="UEsDBBQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeItLyqXVXGwiynQiVAhVyfSwwIkcr1lyS4HBlKb++2F19WXGSSg5y2+XMvMf54COz96vSsiVGMt71eFdccYZOeW1c0eNVmnd+4+/zy4tsAuoJChyDM3OkxB63Idfiqg5aldZRjy9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AAGdXAAAAAA==";import{readFile as Vb}from"node:fs/promises";import{homedir as jr,platform as Fo}from"node:os";import{join as In,posix as MP,win32 as BP}from"node:path";var vs=["Code","Code - Insiders","VSCodium"],Hp="1.121.0",Ub=1,FP=121,Kb="1.102.0",Gb=1,WP=102,HP={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},el=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},Up=e=>{let t=el(e);return t?t.major!==Ub?t.major>Ub:t.minor>=FP:!1},jb=e=>{let t=el(e);return t?t.major!==Gb?t.major>Gb:t.minor>=WP:!1},UP=async e=>{if(Fo()!=="darwin")return;let t=In("/Applications",`${HP[e]}.app`,"Contents","Resources","app","package.json");if(await x(t))try{let n=JSON.parse(await Vb(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},Zb=(e,t=Fo(),n=jr(),r=process.env)=>{switch(t){case"darwin":return In(n,"Library","Application Support",e);case"win32":return In(r.APPDATA??In(n,"AppData","Roaming"),e);default:return In(n,".config",e)}},Gp=(e,t)=>e?t==="win32"?BP.join:MP.join:In,Wo=(e,t=!1,n=Fo(),r=jr(),o=process.env)=>t?Gp(t,n)(r,Ss[e],"data","User"):In(Zb(e,n,r,o),"User"),Yb=async(e,t=!1,n=Fo(),r=jr(),o=process.env)=>{try{let a=Gp(t,n)(Wo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await Vb(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[]}},Jb=async(e,t=Fo(),n=jr(),r=process.env)=>{let a=(await Yb(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},Xb=async(e,t=!1,n=Fo(),r=jr(),o=process.env)=>{let a=Gp(t,n),s=Wo(e,t,n,r,o),i=await Yb(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Ho=async()=>{for(let e of vs)if(await x(Zb(e)))return e},Ss={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},zb=(e,t=jr())=>In(t,Ss[e],"extensions"),Vp=async(e=jr())=>{for(let t of vs)if(await x(In(e,Ss[t])))return t},qb=async e=>{let t=e??await Ho();if(!t)return{status:"unknown"};let n=await UP(t);return n?{variant:t,version:n,status:Up(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var z="anyray.anyray-vscode",qp="vscode-handoffs",sA="vscode-receipts",Es=2,XP=JP(GP),xn={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"]}},zP={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"}},qP=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),iA=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&qP(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Is=e=>{if(iA(e))try{return new URL(e.trim()).origin}catch{return}},QP=(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)},eD=e=>{try{return VP(e)}catch{return[]}},tD=e=>{try{return KP(e).mtimeMs}catch{return}},nD=(e,t,n,r,o)=>{if(!Br(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=xn[e].commands[0],s=wt(t,Ss[e]),i=[];for(let{directory:c,suffix:l}of[{directory:wt(s,"bin"),suffix:["bin","remote-cli"]},{directory:wt(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=wt(c,d,...l,a),p=o(u);p!==void 0&&i.push({path:u,mtime:p})}return i.sort((c,l)=>l.mtime-c.mtime).map(({path:c})=>c)},rD=(e,t,n)=>{let{macAppName:r,commands:o}=xn[e],a=o[0],s=[];for(let i of["/Applications",Qb.join(t,"Applications")])for(let c of n(i))QP(c,r)&&s.push(Qb.join(i,c,"Contents/Resources/app/bin",a));return s},oD=(e,t=zp(),n=Uo(),r=process.env,o=eD,a=tD)=>{let s=nD(e,n,r,o,a);if(t==="darwin")return[...new Set([...xn[e].commands,...rD(e,n,o),...s])];if(t!=="win32"){let u=xn[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=zP[e],c=YP.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)),xn[e].commands[0],...s])]},cA={run:async(e,t)=>({stdout:(await XP(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>jP(24).toString("base64url"),home:"",commandCandidates:e=>oD(e)},Zr=(e,t)=>wt(e,".anyray",sA,`${t}.json`),Qp=(e,t)=>wt(e,".anyray",sA,`${t}.applied.json`),lA=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&el(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},jp=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()===z.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===cn}catch{return}},dA=async(e,t)=>{let n=await lA(e,t);if(n)return jp(n.command,t)},aD=async(e,t,n)=>{let r=wt(e,".anyray",qp);for(let o of n){if(!o.endsWith(".json"))continue;let a=wt(r,o);try{if(!(await Yp(a)).isFile()||JSON.parse(await ln(a,"utf8")).variant!==t)continue;await tl(a)}catch{}}},sD=async(e,t)=>{let n=wt(e,".anyray",qp),r;try{r=await oA(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=wt(n,o);try{if(!(await Yp(a)).isFile()||JSON.parse(await ln(a,"utf8")).variant!==t)continue;await tl(a)}catch{}}},iD=async(e,t)=>{try{let n=JSON.parse(await ln(Zr(e,t),"utf8"));return n.extensionVersion===cn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==ir}catch{return!1}},uA=250,cD=9e4,lD=cD/uA,dD=async(e,t,n,r)=>{for(let o=0;o<lD;o++){try{let a=JSON.parse(await ln(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Es&&a.action===n?"confirmed":a.extensionVersion!==cn||a.extensionDistSha256!==ir?"reload-required":a.version===Es&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(uA)}return"timeout"},uD=200,eA=(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,uD))}return r.join(": ")},pD=async e=>{try{let t=await Yp(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},tA=e=>nA("sha256").update(e).digest("hex"),fD=async(e=Uo())=>{let t=Buffer.from(Hb,"base64");if(t.length<4||t[0]!==80||t[1]!==75||tA(t)!==Qc)throw new Error("bundled VS Code extension failed integrity validation");let n=wt(e,".anyray","vscode-extension"),r=wt(n,`anyray-vscode-${cn}-${Qc.slice(0,12)}.vsix`);try{if(tA(await ln(r))===Qc)return r}catch{}await Jp(n,{recursive:!0,mode:448});let o=`${r}.${rA()}.tmp`;try{await Xp(o,t,{mode:384}),await me(o,r),zp()!=="win32"&&await ZP(r,384)}finally{await aA(o,{force:!0})}return r},Zp=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=>Zp(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Zp(t[n])}`).join(",")}}`},pA=(e,t,n)=>nA("sha256").update(Zp({gatewayUrl:Is(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:cn,extensionDistSha256:ir,profiles:[...n].sort()})).digest("hex"),hD=async(e,t,n,r,o,a)=>{let s=JSON.parse(await ln(Qp(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==pA(t,n,r))return!1;let i=JSON.parse(await ln(Zr(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===cn&&i.extensionDistSha256===ir&&i.gatewayUrl===Is(t.origin)?await dA(e,a)===!0:!1},mD=async(e,t,n,r)=>{let o=Qp(e,t),a=`${o}.${rA()}.tmp`;try{await Jp(Kp(o),{recursive:!0,mode:448}),await Xp(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
112
|
-
`,{mode:384}),await
|
|
113
|
-
`,{mode:384}),await
|
|
114
|
-
`,{flag:"wx",mode:384}),await me(n,e),await OD(e,384)}finally{await _D(n,{force:!0}).catch(()=>{})}},tf=e=>{if(!bt(e))return!1;let t=e,n=Object.keys(t).sort(),r=["apiType",...t.apiKey===void 0?[]:["apiKey"],"models","name","vendor"].sort();return n.length!==r.length||!n.every((o,a)=>o===r[a])||t.name!==cr||t.vendor!=="customendpoint"||t.apiType!=="chat-completions"||!(t.apiKey===void 0||typeof t.apiKey=="string"&&t.apiKey.length>0&&t.apiKey.length<=512&&!/[\u0000-\u001f\u007f]/.test(t.apiKey))||!Array.isArray(t.models)||t.models.length===0||t.models.length>64?!1:t.models.every(o=>{if(!bt(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!==IA(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!bt(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}},MD=async(e,t)=>{let n=Os(e),r=await al(n);if(r.kind==="missing")return{changedFiles:[],messages:[],manual:!1};if(r.kind==="unrecognized")return{changedFiles:[],manual:!0,messages:[`Could not recognize ${n}; left it untouched. Remove the legacy "${cr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=nf(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${cr}" Custom Endpoint from ${n}.`]};try{return await xA(n,o),await re(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${cr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${cr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},BD=async e=>{try{let t=gt(await kA(e,"utf-8"));if(bt(t))return EA(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Ts}.${sl} in ${e}, which uses JSONC that Connect will not rewrite; remove it manually.`]}:{changedFiles:[],messages:[],manual:!1}}catch{}return{changedFiles:[],manual:!0,messages:[`Could not parse ${e}; remove an old Anyray ${Ts}.${sl} value manually if present.`]}},RA=async(e,t)=>{let n=ND(e),r;try{r=await B(n)}catch{return BD(n)}let{next:o,removed:a}=EA(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 Y(n,o,{backup:!1}),await re(n),{changedFiles:[n],manual:!1,messages:[`Removed the retired Anyray Copilot debug override from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the retired Anyray Copilot debug override from ${n}; remove it manually.`]}}},FD=async(e,t)=>{let n=await MD(e,t),r=await RA(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},OA=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,SA]}},TA=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},_A=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),WD=e=>Array.isArray(e.args)&&e.args.at(-1)===SA,PA=(e,t)=>{if(!t.hookBinaryIsDurable()||!bt(e)||!TA(e,["type","command","args"]))return!1;let n=OA(t);return e.type==="stdio"&&e.command===n.command&&_A(e.args,n.args)},HD=(e,t)=>{if(!bt(e)||!TA(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&&_A(e.args,n.args))return!0;if(He(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===Jn&&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!He(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)=>PA(e,t)?"exact":bt(e)&&WD(e)||HD(e,t)?"stale-owned":"foreign",bA=e=>`MCP name conflict in ${e}: servers.${pn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,UD=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,p=[];for(let f of a)try{let h=await Ve(f),m=h.data;if(i){if("servers"in m&&!bt(m.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${f} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let b=bt(m.servers)?{...m.servers}:{},k=OA(o),C=b[pn],S=C===void 0?void 0:rf(C,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(bA(f));continue}if(t){d+=1;continue}b[pn]=k,p.push({path:f,document:h,next:{...m,servers:b},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!bt(m.servers)||!(pn in m.servers))continue;if(rf(m.servers[pn],o)==="foreign"){u=!0,l.push(bA(f));continue}if(t)continue;let y={...m.servers};delete y[pn];let g={...m};Object.keys(y).length===0?delete g.servers:g.servers=y,p.push({path:f,document:h,next:g,backup:!1,clearBackupAfter:!0})}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${f} (${h instanceof Error?h.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let f of p)try{await sn(f.path,f.document,f.next,f.backup),f.clearBackupAfter&&await re(f.path),c.push(f.path),i&&(d+=1)}catch(h){u=!0,l.push(`Could not update the Anyray MCP server in ${f.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 (${Kb}+).`),{changedFiles:c,messages:l,manual:u}},GD=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await x(c))try{let l=await Ve(c),d=l.data;if(!bt(d.servers)||!(pn in d.servers)||rf(d.servers[pn],r)==="foreign"||(i+=1,t))continue;let u={...d.servers};delete u[pn];let p={...d};Object.keys(u).length===0?delete p.servers:p.servers=u,await sn(c,l,p,!1),await re(c),a.push(c)}catch{}return t&&i>0?s.push(`would remove the Anyray retrieval MCP server from ${i} VS Code user profile config(s)`):a.length>0&&s.push("Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."),{changedFiles:a,messages:s,manual:!1}},DA=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.`]:[]],LA=()=>`${z} 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.)`,AA=e=>[`${z} 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."],NA=(e,t,n,r)=>({runMcp:o=>UD(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):FD(e,o)}),$A=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${z} 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 ${z} 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 ${z} 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 ${z} 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 ${Hp} 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 ${z} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${z} 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.`:`${z} 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 ${z} ${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 ${z} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},VD=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${z} 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 ${z} 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 ${z} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${z} 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 ${z} 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 ${z} 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 ${z} 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 ${z} 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 ${z} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},KD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=NA(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required for the authenticated Anyray VS Code provider. Re-run anyray-connect with --enroll, then apply Copilot again."]};if(n.dryRun){let h=await c(!0),m=await i(!0);return{status:h.manual||m.manual?"manual":"configured",messages:[`Would install the bundled ${z} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...AA(t),a?ef({status:"enabled",changed:!0},!0):`Would enable the VS Code Agents window in ${e}'s settings.json (two keys, each added only if absent).`,...m.messages,...h.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${z}; 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:[$A(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),p=await i(!1),f=a?void 0:await yA(e).catch(()=>({status:"manual",reason:"the settings file could not be read"}));return{status:u.manual||p.manual?"manual":"configured",changedFiles:[d.receipt,...p.changedFiles,...u.changedFiles,...f?.status==="enabled"&&f.changed?[xs(e)]:[]],messages:[...d.alreadyCurrent?[LA()]:[],...AA(t),ef(f??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:DA(d.profiles),...p.messages,...u.messages]}},CA=e=>[`${z} 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: ${Ps().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."],jD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=NA(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let f=await c(!0),h=await i(!0);return{status:f.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${z} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...CA(t),...h.messages,...f.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${z}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Ps().map(f=>({id:f,name:IA(f)}))});if(!d.ok)return{status:"manual",messages:[$A(d.reason,e,a,"gateway API configuration",d.detail)]};let u=await c(!1),p=await i(!1);return{status:u.manual||p.manual?"manual":"configured",changedFiles:[d.receipt,...p.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[LA()]:[],...CA(t),...d.alreadyCurrent?[]:DA(d.profiles),...p.messages,...u.messages]}},ZD=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 x(s))return{registered:!1,command:null};try{let{data:i}=await Ve(s),c=bt(i.servers)?i.servers[pn]:void 0;if(!PA(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 YD=async(e={installedVariant:Ho,remoteServerVariant:Vp,isRemoteDevContext:Br})=>{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}},JD={installedVariant:Ho,remoteServerVariant:Vp,detectVscodeLmProviderEligibility:qb,configureVscodeExtension:fA,vscodeExtensionPointsAt:hA,vscodeExtensionAwaitingReload:nl,vscodeExtensionReceiptMode:rl,hookBinaryIsDurable:ce,hookBinaryPath:Re,mcpServerCommand:Ue,vscodeUserMcpConfigPaths:Xb,isRemoteDevContext:Br},XD=(e={})=>{let t={...JD,...e},n=()=>YD(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Rs,quitTarget:ol},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Wo(r,!0)}`:Os(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Ee(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 ${Hp} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||jb(i.version);return ee(r,"copilot")?KD(a,r,o,t.configureVscodeExtension,c,s,t):jD(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?ZD(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Is(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await al(Os(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 al(Os(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 GD(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await RA(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${z} to clear its global configuration and SecretStorage key`);else{let g=await t.configureVscodeExtension(o,void 0,"reset");g.ok?(c=!0,d=g.receipt,u.push(`Cleared ${z} gateway configuration and secret.`)):(l=!0,u.push(VD(g.reason,o,a,g.detail)))}let p=Os(o),f=await al(p),h=f.kind==="missing"||f.kind==="array"&&!nf(f.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(f.kind==="unrecognized")return{status:"manual",changedFiles:m.length?m:void 0,messages:[...u,`Couldn't recognize ${p} \u2014 remove the "${cr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=nf(f.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${cr} Custom Endpoint from ${p}`]};await xA(p,w);let y=[...u,`Removed the ${cr} Custom Endpoint from ${p}.`];return await re(p),{status:l||i.manual?"manual":"reverted",changedFiles:[...m,p],messages:y}}}},MA=XD();import{accessSync as IL,constants as zA,statSync as xL}from"node:fs";import{readFile as qA,rm as Ls}from"node:fs/promises";import{homedir as hf,platform as sC}from"node:os";import{delimiter as RL,join as mf,resolve as OL}from"node:path";import{execFile as tL}from"node:child_process";import{readFile as nL}from"node:fs/promises";import{homedir as sf,platform as rL}from"node:os";import{join as Ds}from"node:path";import{join as zD}from"node:path";var of="Iv1.b507a08c87ecfe98",qD="https://github.com/login/device/code",QD="https://github.com/login/oauth/access_token",eL="read:user",BA=1e4,Go=()=>zD(Q(),"copilot-seat-login.json"),FA={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),WA=async(e={})=>{let t={...FA,...e};try{let n=await t.fetch(qD,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:of,scope:eL}),signal:AbortSignal.timeout(BA)});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}},HA=async(e,t={})=>{let n={...FA,...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(QD,{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(BA)})).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"}},UA=async(e,t)=>{let n=Go();return await we(n,`${JSON.stringify({token:e,clientId:of,mintedAtIso:t},null,2)}
|
|
115
|
-
`),n},
|
|
116
|
-
`))}`]:[],`export ${
|
|
117
|
-
`).map(
|
|
118
|
-
`)):de&&
|
|
111
|
+
${a}${s},`,d=`${i}${l}${c}`;try{let u=wt(d);if(!Mb(u))return{ok:!1,reason:"unsupported"};for(let[p,f]of Object.entries(r))if(JSON.stringify(u[p])!==JSON.stringify(f))return{ok:!1,reason:"unsupported"};if(JSON.stringify(u[t])!==JSON.stringify(n))return{ok:!1,reason:"unsupported"}}catch{return{ok:!1,reason:"unsupported"}}return{ok:!0,text:d}};import{execFile as FP}from"node:child_process";import{readdirSync as WP,statSync as HP}from"node:fs";import{createHash as Qb,randomBytes as UP,randomUUID as eA}from"node:crypto";import{chmod as GP,lstat as Yp,mkdir as Jp,readdir as tA,readFile as ln,rm as nA,unlink as el,writeFile as Xp}from"node:fs/promises";import{homedir as Ho,platform as zp}from"node:os";import{dirname as Kp,join as bt,posix as Xb,win32 as VP}from"node:path";import{promisify as KP}from"node:util";var cn="0.1.29";var ir="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",qc="c341829c0dacfc512fa49fb951be4864ca3e7d6b46d6befbee84e663daa8e9a7",Bb="UEsDBBQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeItLyqXVXGwiynQiVAhVyfSwwIkcr1lyS4HBlKb++2F19WXGSSg5y2+XMvMf54COz96vSsiVGMt71eFdccYZOeW1c0eNVmnd+4+/zy4tsAuoJChyDM3OkxB63Idfiqg5aldZRjy9SCjdSklpgCSRKo6InP09C+VJqXKL1AaNc0qrT+sjrq253E36jzwDoaCRTuBYnv7y4yMaYQEOC+uciG2p0yaQ1G4ErKiiwx9F1/p5yNtQ9Dm4dYd1ZkvIa+T6rK9EV179zNqlm1tAC49aVM9ni3hoKFtafoMS835jY3Ef2OGUDrzGTh/Y2AElFE5Lxrk73hgIo7PEQkTAuked9rRmugjXKJLaBLCDhM6xZ6TVaYj5uDJ3nCCGgZgMfjP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ulXS/XCjvQrsvNiYKL9o7GdJRIvwpit/5KLHjNQ4Gnk4icM5e7UEod154b48TrS7Vgu8iMxOLIlc6j1tasslSoUZwug+XxDgEtrsxlOZe1YiOaspCVDvSwESIVjUk8JsJSB4U0Y/6cutVmkl2m0qKc2ofazT8y/8FUEsHCKcyHPQDOQAAI6kAAFBLAQI/AxQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAAAAAAAAAAAC0gQAAAABleHRlbnNpb24udnNpeG1hbmlmZXN0UEsBAj8DFAAACAgAF1oYXVr3VFTSAAAAzgEAABMAAAAAAAAAAAAAALSBaAMAAFtDb250ZW50X1R5cGVzXS54bWxQSwECPwMUAAgICAAKWhhdcQ3Z86YCAAC7BQAAFgAAAAAAAAAAAAAApIFrBAAAZXh0ZW5zaW9uL3BhY2thZ2UuanNvblBLAQI/AxQACAgIAARaGF0wVq3AThEAACgTAAASAAAAAAAAAAAAAACkgVUHAABleHRlbnNpb24vaWNvbi5wbmdQSwECPwMUAAAICAAXWhhdC7fjr0sCAAB9BAAAEwAAAAAAAAAAAAAAtIHjGAAAZXh0ZW5zaW9uL3JlYWRtZS5tZFBLAQI/AxQACAgIAMtZGF2yhnqNeQIAACcEAAAVAAAAAAAAAAAAAACkgV8bAABleHRlbnNpb24vTElDRU5TRS50eHRQSwECPwMUAAgICAAXWhhdpzIc9AM5AAAjqQAAGwAAAAAAAAAAAAAApIEbHgAAZXh0ZW5zaW9uL2Rpc3QvZXh0ZW5zaW9uLmpzUEsFBgAAAAAHAAcA1gEAAGdXAAAAAA==";import{readFile as Hb}from"node:fs/promises";import{homedir as jr,platform as Bo}from"node:os";import{join as En,posix as DP,win32 as LP}from"node:path";var vs=["Code","Code - Insiders","VSCodium"],Hp="1.121.0",Fb=1,NP=121,Ub="1.102.0",Wb=1,$P=102,MP={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},Qc=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},Up=e=>{let t=Qc(e);return t?t.major!==Fb?t.major>Fb:t.minor>=NP:!1},Gb=e=>{let t=Qc(e);return t?t.major!==Wb?t.major>Wb:t.minor>=$P:!1},BP=async e=>{if(Bo()!=="darwin")return;let t=En("/Applications",`${MP[e]}.app`,"Contents","Resources","app","package.json");if(await x(t))try{let n=JSON.parse(await Hb(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},Vb=(e,t=Bo(),n=jr(),r=process.env)=>{switch(t){case"darwin":return En(n,"Library","Application Support",e);case"win32":return En(r.APPDATA??En(n,"AppData","Roaming"),e);default:return En(n,".config",e)}},Gp=(e,t)=>e?t==="win32"?LP.join:DP.join:En,Fo=(e,t=!1,n=Bo(),r=jr(),o=process.env)=>t?Gp(t,n)(r,Ss[e],"data","User"):En(Vb(e,n,r,o),"User"),Kb=async(e,t=!1,n=Bo(),r=jr(),o=process.env)=>{try{let a=Gp(t,n)(Fo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await Hb(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[]}},jb=async(e,t=Bo(),n=jr(),r=process.env)=>{let a=(await Kb(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},Zb=async(e,t=!1,n=Bo(),r=jr(),o=process.env)=>{let a=Gp(t,n),s=Fo(e,t,n,r,o),i=await Kb(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Wo=async()=>{for(let e of vs)if(await x(Vb(e)))return e},Ss={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},Yb=(e,t=jr())=>En(t,Ss[e],"extensions"),Vp=async(e=jr())=>{for(let t of vs)if(await x(En(e,Ss[t])))return t},Jb=async e=>{let t=e??await Wo();if(!t)return{status:"unknown"};let n=await BP(t);return n?{variant:t,version:n,status:Up(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var z="anyray.anyray-vscode",qp="vscode-handoffs",rA="vscode-receipts",Is=2,jP=KP(FP),xn={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"]}},ZP={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"}},YP=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),oA=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&YP(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Es=e=>{if(oA(e))try{return new URL(e.trim()).origin}catch{return}},JP=(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)},XP=e=>{try{return WP(e)}catch{return[]}},zP=e=>{try{return HP(e).mtimeMs}catch{return}},qP=(e,t,n,r,o)=>{if(!Br(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=xn[e].commands[0],s=bt(t,Ss[e]),i=[];for(let{directory:c,suffix:l}of[{directory:bt(s,"bin"),suffix:["bin","remote-cli"]},{directory:bt(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=bt(c,d,...l,a),p=o(u);p!==void 0&&i.push({path:u,mtime:p})}return i.sort((c,l)=>l.mtime-c.mtime).map(({path:c})=>c)},QP=(e,t,n)=>{let{macAppName:r,commands:o}=xn[e],a=o[0],s=[];for(let i of["/Applications",Xb.join(t,"Applications")])for(let c of n(i))JP(c,r)&&s.push(Xb.join(i,c,"Contents/Resources/app/bin",a));return s},eD=(e,t=zp(),n=Ho(),r=process.env,o=XP,a=zP)=>{let s=qP(e,n,r,o,a);if(t==="darwin")return[...new Set([...xn[e].commands,...QP(e,n,o),...s])];if(t!=="win32"){let u=xn[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=ZP[e],c=VP.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)),xn[e].commands[0],...s])]},aA={run:async(e,t)=>({stdout:(await jP(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>UP(24).toString("base64url"),home:"",commandCandidates:e=>eD(e)},Zr=(e,t)=>bt(e,".anyray",rA,`${t}.json`),Qp=(e,t)=>bt(e,".anyray",rA,`${t}.applied.json`),sA=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&Qc(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},jp=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()===z.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===cn}catch{return}},iA=async(e,t)=>{let n=await sA(e,t);if(n)return jp(n.command,t)},tD=async(e,t,n)=>{let r=bt(e,".anyray",qp);for(let o of n){if(!o.endsWith(".json"))continue;let a=bt(r,o);try{if(!(await Yp(a)).isFile()||JSON.parse(await ln(a,"utf8")).variant!==t)continue;await el(a)}catch{}}},nD=async(e,t)=>{let n=bt(e,".anyray",qp),r;try{r=await tA(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=bt(n,o);try{if(!(await Yp(a)).isFile()||JSON.parse(await ln(a,"utf8")).variant!==t)continue;await el(a)}catch{}}},rD=async(e,t)=>{try{let n=JSON.parse(await ln(Zr(e,t),"utf8"));return n.extensionVersion===cn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==ir}catch{return!1}},cA=250,oD=9e4,aD=oD/cA,sD=async(e,t,n,r)=>{for(let o=0;o<aD;o++){try{let a=JSON.parse(await ln(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Is&&a.action===n?"confirmed":a.extensionVersion!==cn||a.extensionDistSha256!==ir?"reload-required":a.version===Is&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(cA)}return"timeout"},iD=200,zb=(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,iD))}return r.join(": ")},cD=async e=>{try{let t=await Yp(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},qb=e=>Qb("sha256").update(e).digest("hex"),lD=async(e=Ho())=>{let t=Buffer.from(Bb,"base64");if(t.length<4||t[0]!==80||t[1]!==75||qb(t)!==qc)throw new Error("bundled VS Code extension failed integrity validation");let n=bt(e,".anyray","vscode-extension"),r=bt(n,`anyray-vscode-${cn}-${qc.slice(0,12)}.vsix`);try{if(qb(await ln(r))===qc)return r}catch{}await Jp(n,{recursive:!0,mode:448});let o=`${r}.${eA()}.tmp`;try{await Xp(o,t,{mode:384}),await he(o,r),zp()!=="win32"&&await GP(r,384)}finally{await nA(o,{force:!0})}return r},Zp=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=>Zp(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Zp(t[n])}`).join(",")}}`},lA=(e,t,n)=>Qb("sha256").update(Zp({gatewayUrl:Es(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:cn,extensionDistSha256:ir,profiles:[...n].sort()})).digest("hex"),dD=async(e,t,n,r,o,a)=>{let s=JSON.parse(await ln(Qp(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==lA(t,n,r))return!1;let i=JSON.parse(await ln(Zr(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===cn&&i.extensionDistSha256===ir&&i.gatewayUrl===Es(t.origin)?await iA(e,a)===!0:!1},uD=async(e,t,n,r)=>{let o=Qp(e,t),a=`${o}.${eA()}.tmp`;try{await Jp(Kp(o),{recursive:!0,mode:448}),await Xp(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
112
|
+
`,{mode:384}),await he(a,o)}catch{}finally{await nA(a,{force:!0})}},pD=async(e,t)=>{await el(Qp(e,t)).catch(()=>{})},dA=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...aA,...r,home:r.home??Ho()},s=xn[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!oA(t.origin))return{ok:!1,reason:"unsafe-gateway"};let i=(o.gatewayModels??[]).filter((b,k,C)=>typeof b.id=="string"&&b.id.length>0&&b.id.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.id)&&typeof b.name=="string"&&b.name.length>0&&b.name.length<=200&&!/[\u0000-\u001f\u007f]/.test(b.name)&&C.findIndex(S=>S.id===b.id)===k);if(n==="configure"&&o.mode==="gateway-api"&&i.length===0)return{ok:!1,reason:"failed"};let c=await sA(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!Up(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>jb(b,zp(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await dD(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:Zr(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let p=a.extensionPath;if(n==="configure"){try{p??=await lD(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await cD(p))return{ok:!1,reason:"extension-missing"}}let f=a.nonce(),m=bt(a.home,".anyray",qp,`${f}.json`),h=Zr(a.home,s.slug);await Jp(Kp(m),{recursive:!0,mode:448});let w=await tA(Kp(m)).catch(()=>[]);await Xp(m,`${JSON.stringify({version:Is,action:n,nonce:f,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:cn,expectedExtensionDistSha256:ir})}
|
|
113
|
+
`,{mode:384}),await tD(a.home,s.slug,w).catch(()=>{});let y={installed:[],failed:[]},g=!1;try{if(n==="configure"){let k=await rD(a.home,s.slug);if(k||await jp(l,a)!==!0)try{await a.run(l,["--install-extension",p,"--force"])}catch(C){return g=!0,{ok:!1,reason:"install-failed",detail:zb(C,f)}}for(let C of u)try{(k||await jp(l,a,C)!==!0)&&await a.run(l,["--profile",C,"--install-extension",p,"--force"]),y.installed.push(C)}catch{y.failed.push(C)}}try{await a.run(l,["--open-url",`${s.scheme}://${z}/configure?nonce=${encodeURIComponent(f)}`])}catch(k){return{ok:!1,reason:"handoff-undeliverable",detail:zb(k,f)}}let b=await sD(h,f,n,a);if(b!=="confirmed")return{ok:!1,reason:b==="reload-required"?"reload-required":"activation-timeout"};if(g=!0,n==="configure")y.failed.length===0&&await uD(a.home,s.slug,lA(t,o,u),f);else{await pD(a.home,s.slug),await nD(a.home,s.slug).catch(()=>{});for(let k of[void 0,...u])try{await a.run(l,[...k?["--profile",k]:[],"--uninstall-extension",z])}catch{}}return{ok:!0,receipt:h,profiles:y}}catch{return{ok:!1,reason:"failed"}}finally{g&&await el(m).catch(()=>{})}},tl=async(e,t=Ho())=>{try{let n=JSON.parse(await ln(Zr(t,xn[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==cn||n.extensionDistSha256!==ir)}catch{return!1}},nl=async(e,t=Ho())=>{try{let n=JSON.parse(await ln(Zr(t,xn[e].slug),"utf8"));return n.version!==Is||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},uA=async(e,t,n=Ho(),r={})=>{try{let o=Es(t);if(!o)return!1;let a=JSON.parse(await ln(Zr(n,xn[e].slug),"utf8"));if(!(a.version===Is&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===cn&&a.extensionDistSha256===ir))return!1;let i={...aA,...r,home:n};return await iA(e,i)===!0}catch{return!1}};var dn="extensions.supportAgentsWindow",un="chat.agentHost.byokModels.enabled",xs=e=>yD(Ve(e),"User","settings.json"),pA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wD=e=>pA(e)&&e[z]===!0,fA=async(e,t={})=>{let n=xs(e),r=t.read??(f=>fD(f,"utf-8")),o=t.exists??x,a=t.write??(async(f,m)=>{await gD(hD(f),{recursive:!0}),await mD(f,m,"utf-8")}),s=await o(n)?await r(n).catch(()=>{}):"{}";if(s===void 0)return{status:"manual",reason:`could not read ${n}`};s.trim()===""&&(s="{}");let i;try{i=wt(s)}catch{return{status:"manual",reason:`${n} is not valid JSON/JSONC, so it was left untouched`}}if(!pA(i))return{status:"manual",reason:`${n} is not a JSON object`};let c=s,l=!1;if(!(dn in i)){let f=Wp(c,dn,{[z]:!0});if(!f.ok)return{status:"manual",reason:`could not add ${dn} to ${n} without rewriting it`};c=f.text,l=!0}if(!(un in i)){let f=Wp(c,un,!0);if(!f.ok)return{status:"manual",reason:`could not add ${un} to ${n} without rewriting it`};c=f.text,l=!0}l&&await a(n,c);let d=l?wt(c):i,u=wD(d[dn]),p=d[un]===!0;return!u||!p?{status:"manual",reason:`${n} already sets ${u?un:dn} to something else; left as it is`}:{status:"enabled",changed:l}},ef=(e,t)=>t?"Agents window: it runs on your laptop with the extensions installed there, and VS Code registers no model bridge while the agent host is remote, so this run cannot reach it. Run anyray-connect on your laptop too. Chat in this window is already routed.":e.status==="manual"?`Agents window: not enabled (${e.reason}). Add "${dn}": {"${z}": true} and "${un}": true to that file to use Anyray models there.`:e.changed?"Agents window: enabled. It takes effect the next time VS Code starts.":"Agents window: already enabled.";import{spawnSync as bD}from"node:child_process";import{platform as AD}from"node:os";var mA={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},CD=(e,t,n)=>bD(e,t,n),hA=CD,kD,vD=()=>{let e=kD??AD();if(e==="win32"){let n=hA(ws("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],mA);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=hA("pgrep",[n,r],mA);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},SD=vD,Rs=()=>SD();var rl={darwinAppName:"Visual Studio Code",darwinBundleId:"com.microsoft.VSCode",win32Image:"Code.exe",linuxProcess:"code",win32Install:[{root:"localAppData",path:"Programs\\Microsoft VS Code\\Code.exe"},{root:"programFiles",path:"Microsoft VS Code\\Code.exe"},{root:"programFilesX86",path:"Microsoft VS Code\\Code.exe"}]};var cr="Anyray",pn="anyray",CA="--anyray-owner=vscode-profile-v1",Os=e=>AA(Ve(e),"User","chatLanguageModels.json"),_D=e=>AA(Ve(e),"User","settings.json"),Ts="github.copilot.advanced",al="debug.overrideCapiUrl",At=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),PD=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}},kA=e=>{let t=e[Ts];if(!At(t)||!PD(t[al]))return{next:e,removed:!1};let n={...t};delete n[al];let r={...e};return Object.keys(n).length>0?r[Ts]=n:delete r[Ts],{next:r,removed:!0}},_s="anyray-default",Ps=()=>{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:[_s]},vA=e=>e===_s?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),ol=async e=>{if(!await x(e))return{kind:"missing"};try{let t=await bA(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"}}},SA=async(e,t)=>{await ED(TD(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${OD()}`;try{await RD(n,`${JSON.stringify(t,null,2)}
|
|
114
|
+
`,{flag:"wx",mode:384}),await he(n,e),await ID(e,384)}finally{await xD(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!==cr||t.vendor!=="customendpoint"||t.apiType!=="chat-completions"||!(t.apiKey===void 0||typeof t.apiKey=="string"&&t.apiKey.length>0&&t.apiKey.length<=512&&!/[\u0000-\u001f\u007f]/.test(t.apiKey))||!Array.isArray(t.models)||t.models.length===0||t.models.length>64?!1:t.models.every(o=>{if(!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!==vA(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}},DD=async(e,t)=>{let n=Os(e),r=await ol(n);if(r.kind==="missing")return{changedFiles:[],messages:[],manual:!1};if(r.kind==="unrecognized")return{changedFiles:[],manual:!0,messages:[`Could not recognize ${n}; left it untouched. Remove the legacy "${cr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=nf(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${cr}" Custom Endpoint from ${n}.`]};try{return await SA(n,o),await re(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${cr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${cr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},LD=async e=>{try{let t=wt(await bA(e,"utf-8"));if(At(t))return kA(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Ts}.${al} in ${e}, which uses JSONC that Connect will not rewrite; remove it manually.`]}:{changedFiles:[],messages:[],manual:!1}}catch{}return{changedFiles:[],manual:!0,messages:[`Could not parse ${e}; remove an old Anyray ${Ts}.${al} value manually if present.`]}},IA=async(e,t)=>{let n=_D(e),r;try{r=await B(n)}catch{return LD(n)}let{next:o,removed:a}=kA(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 Y(n,o,{backup:!1}),await re(n),{changedFiles:[n],manual:!1,messages:[`Removed the retired Anyray Copilot debug override from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the retired Anyray Copilot debug override from ${n}; remove it manually.`]}}},ND=async(e,t)=>{let n=await DD(e,t),r=await IA(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},EA=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,CA]}},xA=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},RA=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),$D=e=>Array.isArray(e.args)&&e.args.at(-1)===CA,OA=(e,t)=>{if(!t.hookBinaryIsDurable()||!At(e)||!xA(e,["type","command","args"]))return!1;let n=EA(t);return e.type==="stdio"&&e.command===n.command&&RA(e.args,n.args)},MD=(e,t)=>{if(!At(e)||!xA(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&&RA(e.args,n.args))return!0;if(Ue(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===Jn&&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!Ue(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)=>OA(e,t)?"exact":At(e)&&$D(e)||MD(e,t)?"stale-owned":"foreign",yA=e=>`MCP name conflict in ${e}: servers.${pn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,BD=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,p=[];for(let f of a)try{let m=await Ke(f),h=m.data;if(i){if("servers"in h&&!At(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${f} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let b=At(h.servers)?{...h.servers}:{},k=EA(o),C=b[pn],S=C===void 0?void 0:rf(C,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(yA(f));continue}if(t){d+=1;continue}b[pn]=k,p.push({path:f,document:m,next:{...h,servers:b},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!At(h.servers)||!(pn in h.servers))continue;if(rf(h.servers[pn],o)==="foreign"){u=!0,l.push(yA(f));continue}if(t)continue;let y={...h.servers};delete y[pn];let g={...h};Object.keys(y).length===0?delete g.servers:g.servers=y,p.push({path:f,document:m,next:g,backup:!1,clearBackupAfter:!0})}catch(m){u=!0,l.push(`Could not update the Anyray MCP server in ${f} (${m instanceof Error?m.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let f of p)try{await sn(f.path,f.document,f.next,f.backup),f.clearBackupAfter&&await re(f.path),c.push(f.path),i&&(d+=1)}catch(m){u=!0,l.push(`Could not update the Anyray MCP server in ${f.path} (${m instanceof Error?m.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`);break}return i?l.unshift(t?d===a.length?`Would register the Anyray retrieval MCP server in ${a.length} VS Code user profile config(s).`:`Would register the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); resolve the conflicts below first.`:d===a.length?`Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) in ${a.length} VS Code user profile config(s).`:`Registered the Anyray retrieval MCP server in ${d} of ${a.length} VS Code user profile config(s); see the profile-specific errors below.`):n?l.unshift(t?`Would skip the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary.`:`Skipped the Anyray retrieval MCP server because ${o.hookBinaryPath()} is temporary; removed any stale owned registration. Re-run via the installer or a global install to enable retrieval.`):l.unshift(`${t?"Would skip":"Skipped"} the Anyray retrieval MCP server because this VS Code build predates profile-scoped mcp.json support (${Ub}+).`),{changedFiles:c,messages:l,manual:u}},FD=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await x(c))try{let l=await Ke(c),d=l.data;if(!At(d.servers)||!(pn in d.servers)||rf(d.servers[pn],r)==="foreign"||(i+=1,t))continue;let u={...d.servers};delete u[pn];let p={...d};Object.keys(u).length===0?delete p.servers:p.servers=u,await sn(c,l,p,!1),await re(c),a.push(c)}catch{}return t&&i>0?s.push(`would remove the Anyray retrieval MCP server from ${i} VS Code user profile config(s)`):a.length>0&&s.push("Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."),{changedFiles:a,messages:s,manual:!1}},TA=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.`]:[]],_A=()=>`${z} 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.)`,gA=e=>[`${z} 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."],PA=(e,t,n,r)=>({runMcp:o=>BD(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):ND(e,o)}),DA=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${z} 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 ${z} 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 ${z} 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 ${z} 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 ${Hp} 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 ${z} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${z} 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.`:`${z} 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 ${z} ${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 ${z} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},WD=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${z} 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 ${z} 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 ${z} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${z} 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 ${z} 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 ${z} 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 ${z} 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 ${z} 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 ${z} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},HD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=PA(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required for the authenticated Anyray VS Code provider. Re-run anyray-connect with --enroll, then apply Copilot again."]};if(n.dryRun){let m=await c(!0),h=await i(!0);return{status:m.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${z} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...gA(t),a?ef({status:"enabled",changed:!0},!0):`Would enable the VS Code Agents window in ${e}'s settings.json (two keys, each added only if absent).`,...h.messages,...m.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${z}; 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:[DA(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),p=await i(!1),f=a?void 0:await fA(e).catch(()=>({status:"manual",reason:"the settings file could not be read"}));return{status:u.manual||p.manual?"manual":"configured",changedFiles:[d.receipt,...p.changedFiles,...u.changedFiles,...f?.status==="enabled"&&f.changed?[xs(e)]:[]],messages:[...d.alreadyCurrent?[_A()]:[],...gA(t),ef(f??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:TA(d.profiles),...p.messages,...u.messages]}},wA=e=>[`${z} 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: ${Ps().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."],UD=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=PA(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let f=await c(!0),m=await i(!0);return{status:f.manual||m.manual?"manual":"configured",messages:[`Would install the bundled ${z} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...wA(t),...m.messages,...f.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${z}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Ps().map(f=>({id:f,name:vA(f)}))});if(!d.ok)return{status:"manual",messages:[DA(d.reason,e,a,"gateway API configuration",d.detail)]};let u=await c(!1),p=await i(!1);return{status:u.manual||p.manual?"manual":"configured",changedFiles:[d.receipt,...p.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[_A()]:[],...wA(t),...d.alreadyCurrent?[]:TA(d.profiles),...p.messages,...u.messages]}},GD=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 x(s))return{registered:!1,command:null};try{let{data:i}=await Ke(s),c=At(i.servers)?i.servers[pn]:void 0;if(!OA(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 VD=async(e={installedVariant:Wo,remoteServerVariant:Vp,isRemoteDevContext:Br})=>{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}},KD={installedVariant:Wo,remoteServerVariant:Vp,detectVscodeLmProviderEligibility:Jb,configureVscodeExtension:dA,vscodeExtensionPointsAt:uA,vscodeExtensionAwaitingReload:tl,vscodeExtensionReceiptMode:nl,hookBinaryIsDurable:ce,hookBinaryPath:Oe,mcpServerCommand:Ge,vscodeUserMcpConfigPaths:Zb,isRemoteDevContext:Br},jD=(e={})=>{let t={...KD,...e},n=()=>VD(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Rs,quitTarget:rl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${Fo(r,!0)}`:Os(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Ee(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 ${Hp} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||Gb(i.version);return ee(r,"copilot")?HD(a,r,o,t.configureVscodeExtension,c,s,t):UD(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?GD(r,o,t):{registered:!1,command:null}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Es(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await ol(Os(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 ol(Os(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 FD(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await IA(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${z} to clear its global configuration and SecretStorage key`);else{let g=await t.configureVscodeExtension(o,void 0,"reset");g.ok?(c=!0,d=g.receipt,u.push(`Cleared ${z} gateway configuration and secret.`)):(l=!0,u.push(WD(g.reason,o,a,g.detail)))}let p=Os(o),f=await ol(p),m=f.kind==="missing"||f.kind==="array"&&!nf(f.entries).removed,h=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),m)return r.dryRun||c?{status:i.manual?"manual":"reverted",changedFiles:h.length?h:void 0,messages:u}:l||i.manual?{status:"manual",changedFiles:h.length?h:void 0,messages:u}:i.changedFiles.length||s.changedFiles.length?{status:"reverted",changedFiles:h,messages:u}:{status:"not-found",messages:["nothing to revert"]};if(f.kind==="unrecognized")return{status:"manual",changedFiles:h.length?h:void 0,messages:[...u,`Couldn't recognize ${p} \u2014 remove the "${cr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=nf(f.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${cr} Custom Endpoint from ${p}`]};await SA(p,w);let y=[...u,`Removed the ${cr} Custom Endpoint from ${p}.`];return await re(p),{status:l||i.manual?"manual":"reverted",changedFiles:[...h,p],messages:y}}}},LA=jD();import{accessSync as kL,constants as YA,statSync as vL}from"node:fs";import{readFile as JA,rm as Ls}from"node:fs/promises";import{homedir as mf,platform as rC}from"node:os";import{delimiter as SL,join as hf,resolve as IL}from"node:path";import{execFile as zD}from"node:child_process";import{readFile as qD}from"node:fs/promises";import{homedir as sf,platform as QD}from"node:os";import{join as Ds}from"node:path";import{join as ZD}from"node:path";var of="Iv1.b507a08c87ecfe98",YD="https://github.com/login/device/code",JD="https://github.com/login/oauth/access_token",XD="read:user",NA=1e4,Uo=()=>ZD(Q(),"copilot-seat-login.json"),$A={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),MA=async(e={})=>{let t={...$A,...e};try{let n=await t.fetch(YD,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:of,scope:XD}),signal:AbortSignal.timeout(NA)});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}},BA=async(e,t={})=>{let n={...$A,...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(JD,{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(NA)})).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"}},FA=async(e,t)=>{let n=Uo();return await we(n,`${JSON.stringify({token:e,clientId:of,mintedAtIso:t},null,2)}
|
|
115
|
+
`),n},sl=async()=>{try{let e=await B(Uo());if(!af(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var eL=5e3,cf=5e3,tL=["copilot-cli","CopilotCLI"],nL="https://api.github.com/copilot_internal/user",HA="~/.copilot/config.json",UA="macOS Keychain (Copilot CLI)",GA=e=>e===HA||e===UA,Go=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),Kt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rL=()=>process.env.XDG_CONFIG_HOME?.trim()||Ds(sf(),".config"),oL=()=>process.env.XDG_DATA_HOME?.trim()||Ds(sf(),".local","share"),aL=async()=>{try{let e=await qD(Ds(sf(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return Go(t)?t:void 0}catch{}},sL=async e=>{try{let t=await B(Ds(rL(),"github-copilot",e));if(!Kt(t))return;for(let n of Object.values(t))if(Kt(n)&&Go(n.oauth_token))return n.oauth_token}catch{}},iL=async()=>{try{let e=await B(Ds(oL(),"opencode","auth.json")),t=Kt(e)?e["github-copilot"]:void 0;if(!Kt(t)||t.type!=="oauth")return;if(Go(t.access))return t.access;if(Go(t.refresh))return t.refresh}catch{}},cL=(e,t)=>new Promise((n,r)=>{try{zD(e,[...t],{timeout:eL},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),lL=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return Go(r)?r:void 0}catch{return}},dL=async(e=cL)=>{for(let t of tL){let n=await lL(t,e);if(n)return n}};var il={env:process.env,platform:QD,tokenFromDeviceLogin:sl,tokenFromCopilotCliConfig:aL,tokenFromSharedConfig:sL,tokenFromOpenCode:iL,tokenFromKeychain:dL,fetch:(...e)=>fetch(...e)},uL=new Set([401,403,404]),cl=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,VA=e=>{let t=e?.trim().toLowerCase()??"";return t&&t!=="default"&&cl.test(t)?t:"default"},pL=e=>e!=="default"&&cl.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",fL=e=>{if(typeof e!="string")return"default";let t=e.trim().match(/^https:\/\/api\.([a-z0-9-]{1,63})\.githubcopilot\.com\/?$/)?.[1];return t&&cl.test(t)?t:"default"},lf=async(e,t={})=>{let n={...il,...t},r=new AbortController,o=setTimeout(()=>r.abort(),cf);try{let a=await n.fetch(nL,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=Kt(i)&&Kt(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:fL(s)}}return{verdict:uL.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var Vo=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${cl.test(n)?n:"default"}/header/models`,a=await WA(o,e,r.clientKey,t);if(a.length>0)return a}return WA(`${pL(n)}/models`,e,void 0,t)},WA=async(e,t,n,r={})=>{let o={...il,...r},a=new AbortController,s=setTimeout(()=>a.abort(),cf);try{let i=await o.fetch(e,{headers:{authorization:`Bearer ${t}`,...n?{"x-anyray-api-key":n}:{}},signal:a.signal});if(!i.ok)return[];let c=await i.json(),l=Kt(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!Kt(u))continue;let p=u.id;if(typeof p!="string"||p.length===0||u.model_picker_enabled!==!0)continue;let f=u.policy;if(Kt(f)&&f.state!=="enabled")continue;let m=u.supported_endpoints,h=Array.isArray(m)?m.filter(S=>typeof S=="string"):[],w=u.capabilities,y=Kt(w)?w.limits:void 0,g=S=>{let I=Kt(y)?y[S]:void 0;return typeof I=="number"&&Number.isFinite(I)&&I>0?Math.floor(I):void 0},b={id:p,endpoints:h},k=g("max_prompt_tokens"),C=g("max_output_tokens");k!==void 0&&(b.maxPromptTokens=k),C!==void 0&&(b.maxOutputTokens=C),d.push(b)}return d}catch{return[]}finally{clearTimeout(s)}},ll=async(e,t,n,r={})=>{let o={...il,...r},a=new AbortController,s=setTimeout(()=>a.abort(),cf);try{let i=/\/responses\/?$/.test(new URL(e).pathname),c=await o.fetch(e,{method:"POST",headers:{...t,"content-type":"application/json"},body:JSON.stringify(i?{model:n,max_output_tokens:16,input:"ping"}:{model:n,max_tokens:1,messages:[{role:"user",content:"ping"}]}),signal:a.signal});return c.ok?"ok":c.status===400||c.status===404||c.status===422?"rejected":"unreachable"}catch{return"unreachable"}finally{clearTimeout(s)}},dl=async(e={},t={})=>{let n={...il,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return Go(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:UA,read:()=>n.tokenFromKeychain()}]:[],{source:HA,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await lf(s,t);if(i.verdict==="no-copilot"){o.push(a.source);continue}return{token:{token:s,source:a.source},rejected:o,capiSegment:i.capiSegment}}return{rejected:o}};import{homedir as ul,platform as jA}from"node:os";import{join as st}from"node:path";import{execFile as mL}from"node:child_process";import{readFile as hL,readdir as yL}from"node:fs/promises";var gL=3e3,wL="Claude Code-credentials",bL=["copilot-cli","CopilotCLI"],ZA=e=>new Promise(t=>{try{mL("security",["find-generic-password","-s",e],{timeout:gL},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),AL=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=st(ul(),".claude");return!!(await x(st(e,".oauth_token"))||await x(st(e,".credentials.json"))||jA()==="darwin"&&await ZA(wL))},CL=async()=>{let e=st(process.env.CODEX_HOME?.trim()||st(ul(),".codex"),"auth.json");if(!await x(e))return!1;try{let t=JSON.parse(await hL(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},KA=async e=>{try{return(await yL(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},df=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of vs){let n=st(Ve(t),"User","globalStorage");if(await x(st(n,"github.copilot-chat"))||await x(st(n,"github.copilot")))return!0}let e=st(ul(),".config","github-copilot");if(await x(st(e,"apps.json"))||await x(st(e,"hosts.json")))return!0;for(let t of[".vscode",".vscode-insiders"])if(await KA(st(ul(),t,"extensions")))return!0;for(let t of vs){if(await KA(Yb(t)))return!0;let n=st(Fo(t,!0),"globalStorage");if(await x(st(n,"github.copilot-chat"))||await x(st(n,"github.copilot")))return!0}if(jA()==="darwin"){for(let t of bL)if(await ZA(t))return!0}return!1},fn=async()=>{let[e,t,n]=await Promise.all([AL(),CL(),df()]);return{anthropic:e,openai:t,copilot:n}};var Xr="copilot-cli",mn="copilot-cli",EL=Rs,xL=()=>EL()?["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."]:[],oC=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],yf=()=>Object.fromEntries(oC.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),XA=()=>hf(mf(),".anyray","copilot-cli.sh"),aC="# Managed by anyray-connect. Do not source this file anywhere else.",zA=e=>e.split(/\r?\n/,1)[0]===aC,RL=["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"],pl="COPILOT_PROVIDER_API_KEY",qA=e=>e.startsWith(`export ${pl}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),On=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",OL=()=>Ps()[0],Ns=(e="default")=>`/copilot/${e}/header`,D9=Ns(),Yr=e=>e.replace(/\/+$/,""),TL=(e,t="default")=>`${Yr(e.openaiBaseUrl)}${Ns(t)}`,uf=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),ff="claude-sonnet-5",_L=()=>{let e=Ps()[0];return e===_s?ff:e},sC=e=>e.endpoints.includes(On(e.id)==="responses"?"/responses":"/chat/completions"),gf=e=>{let t=e.filter(sC),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)=>QA(a.version,s.version)?-1:QA(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var QA=(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},eC=(e,t,n,r,o,a="default")=>{let s=ue({...e.metadata,tool:Xr}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...oC];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ke(TL(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${On(t)}'`,`export COPILOT_MODEL=${ke(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=${ke(i.join(`
|
|
116
|
+
`))}`]:[],`export ${pl}=${ke(n)}`]},pf=(e,t,n)=>{let r=ue({...e.metadata,tool:Xr});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ke(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${On(t)}'`,`export COPILOT_MODEL=${ke(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${ke(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${pl}=${ke(n)}`]:[]]},PL=(e,t)=>t||!ee(e,"copilot"),tC=()=>{let e=RL.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).`]},nC=(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 ${Xr}\`), 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`."],DL=(e=process.env.PATH,t=rC())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(SL)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=IL(o,n);try{if(!vL(a).isFile())continue;return kL(a,t==="win32"?YA.F_OK:YA.X_OK),a}catch{}}},LL=()=>hf(mf(),".copilot","config.json"),Rn=()=>hf(mf(),".copilot","mcp-config.json"),Jr="anyray",NL=()=>({type:"local",...Ge("profile"),tools:["*"]}),lr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$L=async()=>{let e=Rn(),t;try{t=await B(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&&!lr(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=(lr(t.mcpServers)?t.mcpServers:{})[Jr];return r!==void 0&&!Gt(r,"profile")?{status:"skipped",message:`MCP name conflict in ${e}: mcpServers.${Jr} is not owned by Anyray Connect, so retrieval was skipped and the existing server was left untouched.`}:{status:"installable",json:t}},ML=async e=>{let t=Rn(),n=e.json,r=lr(n.mcpServers)?n.mcpServers:{};r[Jr]=NL(),n.mcpServers=r,await Y(t,n)},BL=async()=>{let e=Rn(),t;try{let r=await B(e);if(!lr(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!lr(n)||!(Jr in n)||!Gt(n[Jr],"profile")?!1:(delete n[Jr],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await Ls(e,{force:!0}):await Y(e,t,{backup:!1}),await re(e),!0)},FL={resolveCopilotCommand:DL,platform:rC,detectCopilotSeat:df,discoverSeatToken:dl,readDeviceLoginToken:sl,fetchSeatModelCatalog:Vo,probeSeatChatModel:ll},WL=e=>`'${e.replace(/'/g,"''")}'`,HL=e=>e.split(`
|
|
117
|
+
`).map(WL).join(" + [Environment]::NewLine + "),UL=(e={})=>{let t={...FL,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await Lc(gt(),mn))?.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&&Yr(s)===`${Yr(i)}/v1`,a=(s,i)=>s!==void 0&&uf(s)&&Yr(s).startsWith(`${Yr(i)}/v1/copilot/`);return{id:Xr,title:"GitHub Copilot CLI",automatic:!0,changesBilling:!1,quitGated:{isRunning:Rs,quitTarget:rl},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=LL();return await x(i)?{installed:!0,detail:i}:{installed:!1,detail:"no `copilot` on PATH and no ~/.copilot state"}},async apply(s,i){let c=gt(),l=async(S,I,E)=>{let R=S.filter(qA),P=S.filter(X=>!qA(X)),W=XA(),q=[...P,...R.length>0?[`[ -r ${ke(W)} ] && . ${ke(W)}`]:[]],de=await x(W),ie=de?await JA(W,"utf8"):void 0,K=ie===void 0||zA(ie);if(R.length>0&&!K)return{status:"manual",messages:[`Refused to overwrite user-managed ${W}; move or rename that file, then run Connect again.`]};let ge=ce(),me=ge?await $L():void 0,F=[`${c} \u2190 managed Anyray block (${mn})`,...I.map(X=>` ${X}`),...R.length>0?[`${W} \u2190 owner-only credential (mode 0600)`]:[],...E,me?.status==="skipped"?me.message:ge?`${Rn()} \u2190 Anyray retrieval MCP server (anyray_retrieve / anyray_recall)`:`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable retrieval.`,"Inline `copilot` completions and GitHub-hosted features stay native GitHub traffic.",`Run \`source ${c}\` or open a new terminal to apply.`,...xL()];if(i.dryRun)return{status:"configured",messages:F};let Z=!1;me?.status==="installable"&&(await ML(me),Z=!0);try{R.length>0?await we(W,[aC,...R,""].join(`
|
|
118
|
+
`)):de&&K&&await Ls(W,{force:!0}),await Dc(c,q,mn)}catch(X){try{ie!==void 0&&K?await we(W,ie):K&&await Ls(W,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw X}return{status:"configured",messages:F,changedFiles:[c,...R.length>0||de&&K?[W]:[],...Z?[Rn()]:[]]}},d=await r(),u=d!==void 0&&!uf(d),p=s.authMode==="placeholder",f=u,m=u&&(!f||!ee(s,"copilot")),h=p?void 0:await t.readDeviceLoginToken().catch(()=>{}),w=p||m&&!h?{rejected:[]}:await t.discoverSeatToken({allowKeychainPrompt:i.explicit===!0&&!i.dryRun}),y=w.token,g=w.rejected;if(y){let S=w.capiSegment??"default",I=_L(),E=I!==ff||!!process.env.ANYRAY_COPILOT_MODEL,R=await t.fetchSeatModelCatalog(y.token,{},S,{laneOrigin:Yr(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),P=R.find(F=>F.id===I);if(!E){let F=gf(R);if(P=F[0],!i.dryRun&&F.length>0){let Z=T=>`${Yr(s.origin)}/v1${Ns(S)}/${On(T)==="responses"?"responses":"chat/completions"}`,X={...yf(),authorization:`Bearer ${y.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},Ye=new Set,We;for(let T of F.slice(0,4)){let L=await t.probeSeatChatModel(Z(T.id),X,T.id);if(L==="ok"){We=T;break}if(L==="unreachable")break;Ye.add(T.id)}P=We??F.find(T=>!Ye.has(T.id))??F[0]}I=P?.id??ff}let W=s.clientKey??s.placeholderKey,q=W&&s.clientKey?Tt(W):W,de=eC(s,I,y.token,W,P,S),ie=eC(s,I,Tt(y.token),q,P,S),K=On(I),ge=R.filter(F=>sC(F)&&On(F.id)===K).map(F=>F.id).filter(F=>F!==I),me=[`Mode: Copilot seat \u2014 requests route through the gateway's Copilot carrier lane and stay billed to your Copilot plan (seat token from ${y.source}).`,`Model: ${I}${E?" (pinned via ANYRAY_COPILOT_MODEL)":R.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...R.length===0&&GA(y.source)?["GitHub served no current models for this sign-in \u2014 the Copilot CLI's own login is","entitled to legacy models only. Fix it with: `anyray-connect copilot-login`","(one browser step), then re-run this command."]:[],...ge.length>0?[`Your plan also serves: ${ge.slice(0,8).join(", ")}${ge.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",...ie.map(F=>{let Z=F.indexOf("="),X=F.slice(7,Z),Ye=F.slice(Z+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${X}', ${HL(Ye)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${y.source}, and the gateway key from \`anyray-connect print-key\`.)`,...me]}:l(de,ie,me)}if(!PL(s,m)){if(f&&!i.dryRun){let S=gt();if(await ps(S,mn))return{status:"reverted",changedFiles:[S],messages:[`removed a stale Anyray ${mn} block from ${S}`,"It routed the CLI on ORG API billing, which predates the Copilot","seat lane and is not a lane you chose. Nothing replaces it yet:",...nC(t.platform(),g),...tC()]}}return{status:"held",messages:[...f&&i.dryRun?[`would remove a stale Anyray ${mn} block from ${gt()} (org lane, not chosen)`]:[],...nC(t.platform(),g)]}}let b=OL(),k=s.clientKey??s.placeholderKey,C=k&&s.clientKey?Tt(k):k;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...pf(s,b,C).map(S=>{let[I,...E]=S.replace(/^export /,"").split("=");return` setx ${I} "${E.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${pl} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(pf(s,b,k),pf(s,b,C),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===_s?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=gt(),c=XA(),l=await x(c),d=l?zA(await JA(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${mn} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${Rn()} if registered`,...await x(Uo())?[`would remove the Copilot sign-in Connect minted (${Uo()})`]:[]]};let u=await ps(i,mn);d&&await Ls(c,{force:!0});let p=await BL(),f=Uo(),m=await x(f);m&&await Ls(f,{force:!0});let h=[...u?[i]:[],...d?[c]:[],...p?[Rn()]:[],...m?[f]:[]];return{status:h.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${mn} block from ${i}`:`no Anyray ${mn} block found in ${i}`,...d?[`removed owner-only credential ${c}`]:l?[`preserved user-managed ${c}`]:[],...m?[`removed the Copilot sign-in Connect minted (${f})`]:[],...p?[`removed the Anyray MCP server from ${Rn()}`]:[],...tC()],changedFiles:h.length>0?h:void 0}},async pointsAt(s){let i=await r();return o(i,s)||a(i,s)},async mcpStatus(){try{let s=await B(Rn()),i=lr(s)?s.mcpServers:void 0,c=lr(i)?i[Jr]:void 0;return!lr(c)||!Gt(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"]:uf(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(Xr)?!0:!await t.detectCopilotSeat()}}},iC=UL();import{homedir as mC}from"node:os";import{join as ur}from"node:path";import{readFile as hC}from"node:fs/promises";import{readFile as cC,rm as GL}from"node:fs/promises";var lC="// Managed by anyray-connect: OpenCode trim carrier v1",VL=5e3,wf=e=>`${lC}
|
|
119
119
|
import { spawn } from "node:child_process"
|
|
120
120
|
|
|
121
121
|
const hookCommand = ${JSON.stringify([e.command,...e.args])}
|
|
122
|
-
const hookTimeoutMs = ${
|
|
122
|
+
const hookTimeoutMs = ${VL}
|
|
123
123
|
|
|
124
124
|
const invokeHook = (payload) =>
|
|
125
125
|
new Promise((resolve) => {
|
|
@@ -186,24 +186,24 @@ export const AnyrayTrimPlugin = async () => ({
|
|
|
186
186
|
}
|
|
187
187
|
},
|
|
188
188
|
})
|
|
189
|
-
`,$s=async e=>await x(e)?(await
|
|
190
|
-
`)?"owned":"foreign":"absent",fC=async(e,t)=>{let n=wf(t),r=await $s(e);return r==="foreign"?"foreign":r==="owned"&&await uC(e,"utf-8")===n?"unchanged":(await we(e,n),"installed")},bf=async e=>{let t=await $s(e);return t!=="owned"?t:(await ZL(e,{force:!0}),"removed")};var Af="https://opencode.ai/config.json",Pn="x-anyray-metadata",_t="x-anyray-api-key",Cf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Tn="Authorization",dr=["anthropic","openai"],Dn="github-copilot",JL="header",_n="anyray",XL=()=>process.env.XDG_CONFIG_HOME?.trim()||ur(gC(),".config"),zL=()=>process.env.XDG_DATA_HOME?.trim()||ur(gC(),".local","share"),yl=()=>ur(XL(),"opencode"),hl=()=>ur(yl(),"plugins","anyrayTrim.js"),bC=()=>ur(zL(),"opencode"),AC=async()=>{try{let e=await wC(ur(bC(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return H(t)?{chatGptOAuth:H(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}}},hC=async()=>(await AC()).chatGptOAuth,qL=["opencode.jsonc","opencode.json","config.json"],jo=async()=>{let e=yl(),t=[];for(let n of qL){let r=ur(e,n);await x(r)&&t.push(r)}return t},mC=async()=>(await jo())[0]??ur(yl(),"opencode.json"),kf=()=>ZA(process.env.ANYRAY_COPILOT_PLAN),vf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${kf()}/${JL}`,H=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===dr[0]||n===dr[1]||n===Dn?[]:H(r)&&H(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`${dr[0]}/${o}`},Ef=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Ef(n,t);return t}if(!H(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},eN=(e,t,n)=>{if(!H(e)||!H(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(!H(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(!H(e)||!H(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},tN=e=>{if(H(e))for(let t of dr){let n=e[t];if(H(n)&&H(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Ms=e=>{if(!H(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Ut({command:t,args:n},"profile")},ml=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),nN=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return H(t)&&t.tool==="opencode"}catch{return!1}},Tf=e=>ee(e,"copilot")&&!!e.clientKey,rN=e=>e.byoUpstream?[]:ee(e,"anthropic")?[`Note: OpenCode can't route your personal Claude subscription \u2014 its Anthropic provider is api-key only, so this uses the gateway's server-held provider key (API billing). For your personal subscription use Claude Code; otherwise make sure an org provider key is set on the gateway, or requests will fail upstream with "invalid x-api-key".`]:[],oN=(e,t)=>ee(e,"openai")?[`OpenAI subscription: OpenCode's built-in ChatGPT Pro/Plus OAuth is ${t?"detected":"not signed in yet (run `opencode auth login`)"}. Its Codex endpoint is hard-coded to chatgpt.com, so provider.baseURL cannot redirect it. Connect leaves machine networking untouched. Use the Codex app/CLI/IDE for ChatGPT subscription pass-through, or sign OpenCode into an API-key/Copilot provider that Connect can route.`]:[],aN=e=>Tf(e)?["Tip: to spend your Copilot subscription (incl. Claude & GPT), pick the github-copilot/* models in OpenCode \u2014 e.g. github-copilot/claude-sonnet-4.5. The anthropic/* and openai/* entries are the direct providers (api-key mode, separate billing) \u2014 not your Copilot plan."]:[],sN=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Af);let o=!1;if(n)if("mcp"in r&&!H(r.mcp))o=!0;else{let g=H(r.mcp)?{...r.mcp}:{},b=g[_n];b!==void 0&&!Ms(b)?o=!0:(g[_n]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=g)}else if(H(r.mcp)&&Ms(r.mcp[_n])){let g={...r.mcp};delete g[_n],Object.keys(g).length===0?delete r.mcp:r.mcp=g}let a=H(r.provider)?{...r.provider}:{},s=QL(a,t.origin),i=s.every(g=>eN(a[g],e,g))?s:[],c=s.filter(g=>!i.includes(g)),l=[];if(i.length>0){for(let g of i)delete a[g];r=If(r,i,l)}let d=[],u=[],p=t.openaiBaseUrl,f=t.clientKey??t.placeholderKey,h=pe({...t.metadata,tool:"opencode"});for(let g of c){let b={...a[g]},k={...b.options};if("headers"in k&&!H(k.headers)){u.push(g);continue}let C=H(k.headers)?{...k.headers}:{},S=!1;for(let[E,I]of[[_t,f],...h?[[Pn,h]]:[]])E in C?(typeof C[E]!="string"||C[E].trim()==="")&&u.push(`${g}.${E}`):(C[E]=I,d.push(`${g}.${E}`),S=!0);S&&(k.headers=C,b.options=k,a[g]=b)}let m=c.length>0?[]:dr.filter(g=>g!=="openai"||!ee(t,"openai")),w=t.byoUpstream;for(let g of m){let b=H(a[g])?{...a[g]}:{},k=H(b.options)?{...b.options}:{};k.baseURL=p;let C=H(k.headers)?{...k.headers}:{};if(g==="anthropic"&&w)k.apiKey=w.key,C[Tn]=`Bearer ${w.key}`,C["x-anyray-provider"]="anthropic",C["x-anyray-auth-mode"]="passthrough",C["x-anyray-custom-host"]=w.url;else{k.apiKey=f,"x-anyray-custom-host"in C&&delete C[Tn];for(let S of Cf)delete C[S]}C[_t]=f,h&&(C[Pn]=h),k.headers=C,b.options=k,a[g]=b}let y=c.length===0&&Tf(t);if(y){let g=H(a[Dn])?{...a[Dn]}:{},b=H(g.options)?{...g.options}:{};b.baseURL=vf(t);let k=H(b.headers)?{...b.headers}:{};k[_t]=t.clientKey,h&&(k[Pn]=h),b.headers=k,g.options=b,a[Dn]=g}return Object.keys(a).length>0&&(r.provider=a),{next:r,copilot:y,customProviders:c,migratedProviders:i,modelRefsRemapped:l,customHeadersAdded:d,customHeaderConflicts:u,mcpConflict:o}},iN=["baseURL","apiKey"],yC=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!H(s)||!H(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=H(c.headers)?{...c.headers}:void 0,p=u?.[_t],f=ml(p);if(d&&(delete c.baseURL,l=!0),u&&(d||f)){let h=u,m=H(r)?r.options:void 0,w=H(m)&&H(m.headers)?m.headers:void 0;for(let y of[_t,Pn])w&&y in w?h[y]!==w[y]&&(h[y]=w[y],l=!0):y in h&&(delete h[y],l=!0);Object.keys(h).length===0?delete c.headers:c.headers=h}}else{let d=H(r)?r.options:void 0,u=H(d)?d:{},p=H(c.headers)?c.headers:{},f=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof p[_t]=="string"||typeof p[Pn]=="string"||Cf.some(h=>h in p);if(!o&&!f)return!1;for(let h of iN)h in u?c[h]!==u[h]&&(c[h]=u[h],l=!0):h in c&&(delete c[h],l=!0);if(H(c.headers)){let h={...c.headers},m=H(u.headers)?u.headers:{};"x-anyray-custom-host"in h&&Tn in h&&(Tn in m?h[Tn]!==m[Tn]&&(h[Tn]=m[Tn],l=!0):(delete h[Tn],l=!0));for(let w of[_t,Pn,...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},cN=(e,t,n)=>{let r=e[t];if(!H(r)||!H(r.options)||!H(n)||!H(n.options))return!1;let o={...r.options};if(!H(o.headers)||"headers"in n.options&&!H(n.options.headers))return!1;let a={...o.headers},s=H(n.options.headers)?n.options.headers:{},i=!1;return!(_t in s)&&ml(a[_t])&&(delete a[_t],i=!0),!(Pn in s)&&nN(a[Pn])&&(delete a[Pn],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},lN=(e,t)=>{let n={...e},r=!1,o=tN(e.provider);if(H(n.mcp)&&Ms(n.mcp[_n])){let c={...n.mcp};delete c[_n],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!H(n.provider))return{next:n,removed:r};let a={...n.provider},s=H(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===Af&&dr.every(c=>{let l=a[c];return H(l)&&H(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of dr)yC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...dr,Dn]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;cN(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&H(u)&&H(u.options)&&Rf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=xf(n,t,l))}return yC(a,Dn,!0,s[Dn])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===Af&&(delete n.$schema,r=!0),{next:n,removed:r}},kC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=yl(),t=bC(),n=await x(e)||await x(t),r=n&&await hC();return{installed:n,detail:n?`${await mC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await mC(),r=e.openaiBaseUrl,o=pe({...e.metadata,tool:"opencode"}),a=Tf(e),s=ee(e,"openai"),i=await hC(),c;try{c=await Ve(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": { "${_t}": "<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 Lr()?Ue("profile"):void 0,{next:d,customProviders:u,migratedProviders:p,modelRefsRemapped:f,customHeadersAdded:h,customHeaderConflicts:m,mcpConflict:w}=sN(c.data,e,l),y=u.length>0,g=p.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${p.map(I=>`provider.${I}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...f.length>0?[`Updated model references: ${f.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=y?[`${n} already routes through ${e.origin} via ${u.map(I=>`provider.${I}`).join(", ")}; existing provider values were preserved.`,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."]:[...g,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)"}`,...rN(e),...oN(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. ${kf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${kf()} 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).",...aN(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 k=m.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let S=await sn(n,c,d,!0)?[n]:[],E=hl();if(ce())try{let I=await fC(E,es(Je,["opencode"]));I==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${E} already exists and is not owned by Anyray.`):(I==="installed"&&S.push(E),b.push(`The OpenCode tool.execute.after carrier is active in ${E}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${E}. Gateway-side optimization remains active.`)}else{try{await bf(E)==="removed"&&S.push(E)}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:k,messages:b,changedFiles:S}},async pointsAt(e){for(let t of await jo())try{let{data:n}=await Ve(t);if(!H(n.provider))continue;for(let r of Object.values(n.provider))if(!(!H(r)||!H(r.options))&&Rf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await jo())try{let{data:t}=await Ve(e);if(!H(t.mcp))continue;let n=t.mcp[_n];if(!Ms(n)||!H(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 $s(hl());e=i==="absent"?"missing":i,e==="owned"&&(t=await wC(hl(),"utf-8")===wf(es(Je,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await jo()){let c;try{c=await Ve(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!H(c.data.mcp)){o=!0;continue}let l=c.data.mcp[_n];if(l!==void 0)if(Ms(l))if(n=!0,!H(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;oc({command:d,args:u},"profile")||(a=!1)}else r=!0}return{hook_registration:e,mcp_registration:o?"unreadable":r?"foreign":n?"owned":"missing",hook_binary:t&&a&&await Lr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await AC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await jo()){let{data:o}=await Ve(r);if(H(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!H(s)||!H(s.options)){e.add("unknown");continue}let i=s.options,c=H(i.headers)?i.headers:{};if(a===Dn&&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===Dn&&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(ml(c[_t])||ml(i.apiKey)||typeof i.apiKey=="string"&&i.apiKey.length>0||typeof c.Authorization=="string"&&c.Authorization.length>0){e.add("api_key");continue}e.add("unknown")}}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=await jo(),n=hl(),r="absent";try{r=await $s(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 Ve(i)}catch{s.push(i);continue}let{next:l,removed:d}=lN(c.data,await Bo(i));d&&(await sn(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await re(i)}for(let i of s)o.push(`Couldn't parse ${i} \u2014 if you added Anyray settings there by hand, remove the baseURL/apiKey from provider.anthropic, provider.openai, and provider.github-copilot yourself.`);if(r==="owned")try{await 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 Mf}from"node:os";import{join as kl}from"node:path";import{homedir as dN}from"node:os";import{dirname as uN,join as pr}from"node:path";import{mkdir as pN,readdir as fN,readFile as SC,rm as EC}from"node:fs/promises";var _f="48ff8bb9a7afde1d9e8468d632f84b46f199e6a28657833b113de93698d9ac63",vC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyNTYwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0KICAgICAgICBdCiAgICAgIH0KICAgIH0KICB9LAogICJjb25maWdTY2hlbWEiOiB7CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogZmFsc2UsCiAgICAicmVxdWlyZWQiOiBbImdhdGV3YXlVcmwiXSwKICAgICJwcm9wZXJ0aWVzIjogewogICAgICAiZ2F0ZXdheVVybCI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBbnlyYXkgZ2F0ZXdheSBvcmlnaW4sIGUuZy4gaHR0cHM6Ly9nYXRld2F5LmV4YW1wbGUuYW55cmF5LmFpIChubyAvdjEgc3VmZml4KS4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiUGVyc29uYWwgQW55cmF5IGNsaWVudCBrZXkgKGFya1/igKYpLiBTdXBwb3J0cyAke0VOVl9WQVJ9IHN1YnN0aXR1dGlvbjsgZGVmYXVsdHMgdG8gJHtBTllSQVlfQ0xJRU5UX0tFWX0uIgogICAgICB9LAogICAgICAidXNlciI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB1c2VyIChjb250ZW50LWZyZWU7IHVzdWFsbHkgYW4gZW1haWwpLiBPcHRpb25hbCDigJQgdGhlIGNsaWVudCBrZXkgYWxyZWFkeSBhdHRyaWJ1dGVzIHRoZSBlbnJvbGxlZCB1c2VyLiIKICAgICAgfSwKICAgICAgInRlYW0iOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiQXR0cmlidXRpb24gdGVhbSAoY29udGVudC1mcmVlKS4gT3B0aW9uYWwuIgogICAgICB9CiAgICB9LAogICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIjIwMjYuNy4xIgogICAgfQogIH0sCiAgInBlZXJEZXBlbmRlbmNpZXMiOiB7CiAgICAib3BlbmNsYXciOiAiPj0yMDI2LjcuMSIKICB9LAogICJkZXZEZXBlbmRlbm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KICAgICAgPyBnYXRld2F5UHJvdmlkZXJGb3JNb2RlbChtb2RlbC5pZCkKICAgICAgOiB1bmRlZmluZWQ7CiAgICBpZiAoZ2F0ZXdheVByb3ZpZGVyICYmIGhlYWRlcnNbJ3gtYW55cmF5LXByb3ZpZGVyJ10gPT09IHVuZGVmaW5lZCkgewogICAgICBoZWFkZXJzWyd4LWFueXJheS1wcm92aWRlciddID0gZ2F0ZXdheVByb3ZpZGVyOwogICAgfQogICAgb3B0cy5oZWFkZXJzID0gaGVhZGVyczsKICAgIGNvbnN0IHNlc3Npb25JZCA9CiAgICAgIHR5cGVvZiBvcHRzLnNlc3Npb25JZCA9PT0gJ3N0cmluZycgPyBvcHRzLnNlc3Npb25JZCA6IHVuZGVmaW5lZDsKICAgIGNvbnN0IGNhbGxlck9uUGF5bG9hZCA9IG9wdHMub25QYXlsb2FkOwogICAgb3B0cy5vblBheWxvYWQgPSBhc3luYyAocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA9PiB7CiAgICAgIGlmIChwYXlsb2FkICYmIHR5cGVvZiBwYXlsb2FkID09PSAnb2JqZWN0JyAmJiAhQXJyYXkuaXNBcnJheShwYXlsb2FkKSkgewogICAgICAgIHBhdGNoUGF5bG9hZFNlc3Npb25JZGVudGl0eSgKICAgICAgICAgIHBheWxvYWQgYXMgUmVjb3JkPHN0cmluZywgdW5rbm93bj4sCiAgICAgICAgICBzZXNzaW9uSWQKICAgICAgICApOwogICAgICB9CiAgICAgIHJldHVybiBjYWxsZXJPblBheWxvYWQgPyBjYWxsZXJPblBheWxvYWQocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA6IHBheWxvYWQ7CiAgICB9OwogICAgcmV0dXJuIGlubmVyKG1vZGVsLCBjb250ZXh0LCBvcHRzKTsKICB9OwogIHJldHVybiB3cmFwcGVkOwp9Owo="}];var Pf=".anyray-source-sha",mn=()=>pr(dN(),".anyray","openclaw-plugin"),IC=async(e=mn())=>{try{if((await SC(pr(e,Pf),"utf8")).trim()===_f)return"current"}catch{}for(let t of vC){let n=pr(e,t.path);await pN(uN(n),{recursive:!0,mode:448}),await we(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await we(pr(e,Pf),`${_f}
|
|
191
|
-
`),"installed"},Bs=async(e,t=[])=>{let n=[],r=async a=>{let s=pr(a,"plugins","anyray","catalog.json");try{await EC(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await fN(pr(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(pr(e,"agents",a,"agent"));return n},gl=async(e=mn())=>{try{await SC(pr(e,Pf),"utf8")}catch{return!1}return await EC(e,{recursive:!0,force:!0}),!0};var Lf="x-anyray-metadata",Jo="x-anyray-api-key",Nf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],zr="Authorization",qr="anthropic-beta",bl="interleaved-thinking-2025-05-14",Al=["anthropic","openai"],RC="short",Bf="anthropic-messages",Ff=32e3,Cl="anthropic/claude-sonnet-4-5",Wf=["anthropic/claude-haiku-4-5"],Hf="anyray/claude-sonnet-4-5",Uf=["anyray/claude-haiku-4-5"],hN=[Cl,Hf],mN=[Wf,Uf],ze="anyray",fr="ANYRAY_API_KEY",Fs="openclaw",Yo=()=>process.env.OPENCLAW_STATE_DIR?.trim()||kl(Mf(),".openclaw"),Zo=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||kl(Yo(),"openclaw.json"),L=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},$f=e=>{if(!L(e))return{};let t=e.models;return!L(t)||!L(t.providers)?{}:t.providers},yN=e=>e==="~"||e.startsWith("~/")?kl(Mf(),e.slice(1)):e,wl=e=>{if(!L(e))return[];let t=e.agents;if(!L(t)||!Array.isArray(t.list))return[];let n=[];for(let r of t.list){if(!L(r))continue;let o=typeof r.agentDir=="string"?r.agentDir.trim():"";o&&n.push(yN(o))}return n},gN=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=pe({...t.metadata,tool:Fs}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!L(l.models)&&d.push("models");let u=L(l.models)?{...l.models}:{};if("providers"in u&&!L(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let p=L(u.providers)?{...u.providers}:{},f=!1;if(n){let C=L(l.plugins)?{...l.plugins}:{},S=L(C.load)?{...C.load}:{},E=L(C.entries)?{...C.entries}:{},I=L(E[ze])?{...E[ze]}:{},R=L(I.config)?{...I.config}:{};if("plugins"in l&&!L(l.plugins)||"load"in C&&!L(C.load)||"paths"in S&&!Array.isArray(S.paths)||"entries"in C&&!L(C.entries)||ze in E&&!L(E[ze])||"config"in I&&!L(I.config)||"env"in l&&!L(l.env))d.push("plugins");else{let P=Array.isArray(S.paths)?[...S.paths]:[];P.includes(n)||P.push(n),S.paths=P,C.load=S,I.enabled=!0,R.gatewayUrl=t.anthropicBaseUrl,R.apiKey=r;let W=t.metadata.user,q=t.metadata.team;W&&(R.user=W),q&&(R.team=q),I.config=R,E[ze]=I,C.entries=E,l.plugins=C;let de=L(l.env)?{...l.env}:{};de[fr]=r,l.env=de,f=!0}}let h=Al.filter(C=>C!=="openai"||!ee(t,"openai"));for(let C of h){if(C in p&&!L(p[C])){d.push(`models.providers.${C}`);continue}let S=L(p[C])?{...p[C]}:{};if("headers"in S&&!L(S.headers)){i.push(C);continue}let E=L(S.headers)?{...S.headers}:{};if(S.baseUrl=C==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,C==="anthropic"&&(S.api=Bf,(typeof S.maxTokens!="number"||S.maxTokens<=0)&&(S.maxTokens=Ff)),C==="anthropic"&&a)S.apiKey=a.key,E[zr]=`Bearer ${a.key}`,E["x-anyray-provider"]="anthropic",E["x-anyray-auth-mode"]="passthrough",E["x-anyray-custom-host"]=a.url;else{S.apiKey=r,"x-anyray-custom-host"in E&&delete E[zr];for(let I of Nf)delete E[I]}E[Jo]=r,o&&(E[Lf]=o),C==="anthropic"&&(qr in E?c=E[qr]!==bl:E[qr]=bl),S.headers=E,p[C]=S,s.push(C)}u.providers=p,l.models=u;let m=!1,w=!1,y=!1,g,b=[],k="agents"in l&&!L(l.agents)||L(l.agents)&&"defaults"in l.agents&&!L(l.agents.defaults)||L(l.agents)&&L(l.agents.defaults)&&("params"in l.agents.defaults&&!L(l.agents.defaults.params)||"model"in l.agents.defaults&&!L(l.agents.defaults.model));if(k&&d.push("agents.defaults"),s.includes("anthropic")&&!k){let C=L(l.agents)?{...l.agents}:{},S=L(C.defaults)?{...C.defaults}:{},E=L(S.params)?{...S.params}:{};"cacheRetention"in E||(E.cacheRetention=RC,m=!0,S.params=E);let I=L(S.model)?{...S.model}:{},R=f?[...s,ze]:s,P=W=>typeof W=="string"&&R.some(q=>W.startsWith(`${q}/`));typeof I.primary!="string"||I.primary.trim()===""?(I.primary=f?Hf:Cl,w=!0,S.model=I,"fallbacks"in I||(I.fallbacks=f?[...Uf]:[...Wf],y=!0)):P(I.primary)||(g=I.primary),b=(Array.isArray(I.fallbacks)?I.fallbacks:[]).filter(W=>typeof W=="string"&&!P(W)),(m||w)&&(C.defaults=S,l.agents=C)}return{next:l,routed:s,cacheRetentionSeeded:m,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:y,unroutedPrimary:g,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:f}},wN=["baseUrl","apiKey","api","maxTokens"],Df=(e,t,n=Al,r)=>{let o={...e},a=!("models"in o)||L(o.models)&&(!("providers"in o.models)||L(o.models.providers)),s=L(o.models)?{...o.models}:{},i=L(s.providers)?{...s.providers}:{},c=$f(t),l=!1;for(let u of a?n:[]){let p=i[u];if(!L(p))continue;let f={...p},h=L(f.headers)?{...f.headers}:{};if(!(t!==void 0||typeof h[Jo]=="string"||typeof h[Lf]=="string"||typeof f.apiKey=="string"&&f.apiKey.startsWith("ark_")||Nf.some(C=>C in h)))continue;let w=L(c[u])?c[u]:{},y=L(w.headers)?w.headers:{},g="x-anyray-custom-host"in h,b=C=>C==="api"?f.api===Bf:C==="maxTokens"?f.maxTokens===Ff:C==="apiKey"?g||typeof f.apiKey=="string"&&f.apiKey.startsWith("ark_"):!0;for(let C of wN)b(C)&&(C in w?f[C]!==w[C]&&(f[C]=w[C],l=!0):C in f&&(delete f[C],l=!0));let k=[Jo,Lf,...Nf,..."x-anyray-custom-host"in h?[zr]:[]];h[qr]===bl&&k.push(qr);for(let C of k)C in y?h[C]!==y[C]&&(h[C]=y[C],l=!0):C in h&&(delete h[C],l=!0);zr in y&&!(zr in h)&&(h[zr]=y[zr],l=!0),Object.keys(h).length===0?delete f.headers:f.headers=h,Object.keys(f).length===0?delete i[u]:i[u]=f}if(a&&(Object.keys(i).length===0?delete s.providers:s.providers=i,Object.keys(s).length===0?delete o.models:o.models=s),r&&n.includes("anthropic")){let u=L(o.plugins)?{...o.plugins}:{},p=L(u.load)?{...u.load}:{},f=L(u.entries)?{...u.entries}:{};if((!("plugins"in o)||L(o.plugins))&&(!("load"in u)||L(u.load))&&(!("paths"in p)||Array.isArray(p.paths))&&(!("entries"in u)||L(u.entries))){if(Array.isArray(p.paths)&&p.paths.includes(r)){let w=p.paths.filter(y=>y!==r);w.length===0?delete p.paths:p.paths=w,l=!0}let m=f[ze];if(L(m)){let w=L(m.config)?m.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let g=L(t?.plugins)?t.plugins:{},b=L(g.entries)?g.entries:{};ze in b?JSON.stringify(f[ze])!==JSON.stringify(b[ze])&&(f[ze]=b[ze],l=!0):(delete f[ze],l=!0)}}if(Object.keys(p).length===0?delete u.load:u.load=p,Object.keys(f).length===0?delete u.entries:u.entries=f,Object.keys(u).length===0?delete o.plugins:o.plugins=u,L(o.env)){let w={...o.env},y=w[fr];if(typeof y=="string"&&y.startsWith("ark_")){let g=L(t?.env)?t.env:{};fr in g?w[fr]!==g[fr]&&(w[fr]=g[fr],l=!0):(delete w[fr],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}let d=!("agents"in o)||L(o.agents)&&(!("defaults"in o.agents)||L(o.agents.defaults)&&(!("params"in o.agents.defaults)||L(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||L(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=L(o.agents)?{...o.agents}:{},p=L(u.defaults)?{...u.defaults}:{},f=L(p.params)?{...p.params}:{},h=L(t.agents)?t.agents:{},m=L(h.defaults)?h.defaults:{},w=L(m.params)?m.params:{};f.cacheRetention===RC&&("cacheRetention"in w?f.cacheRetention!==w.cacheRetention&&(f.cacheRetention=w.cacheRetention,l=!0):(delete f.cacheRetention,l=!0));let y=L(p.model)?{...p.model}:{},g=L(m.model)?m.model:{};hN.includes(y.primary)&&("primary"in g?y.primary!==g.primary&&(y.primary=g.primary,l=!0):(delete y.primary,l=!0)),mN.some(b=>JSON.stringify(y.fallbacks)===JSON.stringify(b))&&("fallbacks"in g?JSON.stringify(y.fallbacks)!==JSON.stringify(g.fallbacks)&&(y.fallbacks=g.fallbacks,l=!0):(delete y.fallbacks,l=!0)),Object.keys(y).length===0?delete p.model:p.model=y,Object.keys(f).length===0?delete p.params:p.params=f,Object.keys(p).length===0?delete u.defaults:u.defaults=p,Object.keys(u).length===0?delete o.agents:o.agents=u}return{next:o,removed:l}},OC={id:Fs,title:"OpenClaw",automatic:!0,async detect(){let e=await x(Zo())||await x(Yo());return{installed:e,detail:e?Zo():`no ${kl(Mf(),".openclaw")} state dir`}},async apply(e,t){let n=Zo();if(!e.byoUpstream&&ee(e,"anthropic")){let S=["OpenClaw stays on its native Claude sign-in \u2014 the Anyray seat","passthrough lane for OpenClaw is not yet supported, and routing it","would move inference onto the org API bill. Opt in explicitly with",`\`--org --tools ${Fs}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],E;try{E=await Ve(n)}catch{return{status:"held",messages:S}}let{next:I,removed:R}=Df(E.data,await Bo(n),Al,mn());return R?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...S]}:(await sn(n,E,I,!1),await re(n),await gl(),await Bs(Yo(),wl(I)),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...S]}):(t.dryRun||(await gl(),await Bs(Yo(),wl(I))),{status:"held",messages:S})}let r=mn(),o=!1;if(!t.dryRun)try{await IC(r)}catch{r=void 0,o=!0}let a;try{a=await Ve(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Bf}", "maxTokens": ${Ff}, "apiKey": "<your personal ark_ key>", "headers": { "${Jo}": "<your personal ark_ key>", "${qr}": "${bl}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${Jo}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${Cl}") 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:p,unroutedPrimary:f,unroutedFallbacks:h,structureConflicts:m,pluginConfigured:w}=gN(a.data,e,r),y=s,g=!1;if(!i.includes("openai")){let S=Df(y,await Bo(n),["openai"]);S.removed&&(y=S.next,g=!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: ${pe({...e.metadata,tool:Fs})??"(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 ${qr} 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?Hf:Cl} (none was set; routing is inert until the primary resolves to a routed provider).`,...p?[`Seeded agents.defaults.model.fallbacks = [${(w?Uf:Wf).join(", ")}] so failover stays on a routed provider.`]:[]]:[],...f!==void 0?[`Your primary model (${f}) 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.`]:[],...g?["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 (${mn()}) and registered it under plugins.entries.${ze}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${mn()}; 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."],k=d.length>0||m.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let C=await sn(n,a,y,!0);return w&&await Bs(Yo(),wl(y)),{status:k,messages:b,changedFiles:C?[n]:[]}},async pointsAt(e){try{let{data:t}=await Ve(Zo());for(let a of Object.values($f(t)))if(L(a)&&xC(a.baseUrl,e))return!0;let n=L(t.plugins)?t.plugins:{},o=(L(n.entries)?n.entries:{})[ze];if(L(o)&&L(o.config)&&xC(o.config.gatewayUrl,e))return!0}catch{}return!1},async routingExpected(e){return e.includes(Fs)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Ve(Zo());for(let a of Object.values($f(t))){if(!L(a))continue;let s=L(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[Jo]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=L(t.plugins)?t.plugins:{},o=(L(n.entries)?n.entries:{})[ze];if(L(o)&&L(o.config)){let a=o.config.apiKey;typeof a=="string"&&a.startsWith("ark_")&&e.add("api_key")}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=Zo();if(!await x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await Ve(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}=Df(n.data,await Bo(t),Al,mn()),a=await gl();return await Bs(Yo(),wl(r)),o?(await sn(t,n,r,!1),await re(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${mn()}`]:[]],changedFiles:[t]}):(await re(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${mn()}`]:[]]})}};import{execFile as cB}from"node:child_process";import{readFile as lB}from"node:fs/promises";import{homedir as oi,platform as gr}from"node:os";import{join as bn}from"node:path";import{isDeepStrictEqual as Rh,promisify as dB}from"node:util";var Ws=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},vl=(e,t)=>{let n=Ws(e),r=Ws(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 EM}from"node:crypto";import{promises as Hk}from"node:fs";import{platform as IM,tmpdir as xM}from"node:os";import{join as Hl}from"node:path";import{execFile as bN}from"node:child_process";import{promises as Hs}from"node:fs";import{homedir as AN,platform as CN}from"node:os";import{delimiter as kN,join as Sl}from"node:path";import{promisify as vN}from"node:util";var SN=vN(bN),EN=15*6e4,IN=64*1024*1024,xN=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],TC=async(e={})=>{let t=(e.home??AN)(),n=e.env??process.env,r=xN(e.runtimePlatform??CN()),o=[Sl(t,".local","bin"),Sl(t,".claude","local"),...(n.PATH??"").split(kN).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Sl(a,`claude${s}`);try{return await Hs.access(i),i}catch{}}return null},RN=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},ON=async e=>{let t=Sl(e,"projects"),n;try{n=(await Hs.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(!PN.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},TN=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],p=o[d];if(typeof u!="string"||typeof p!="string"||u.length===0||p.length===0)continue;let f=a[d];l.push({sessionId:u,transcriptPath:p,title:typeof f=="string"&&f.length>0?f:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:RN(n.projectList)}},_N=async e=>{let t,n;try{let r=await Hs.readFile(e,"utf8");for(let o of r.split(`
|
|
192
|
-
`)){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}},
|
|
193
|
-
`).filter(d=>d.trim().length>0),i=TN(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 _N(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await ON(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as NN}from"node:crypto";import{promises as Ln}from"node:fs";import{homedir as $N,platform as MN}from"node:os";import{join as At}from"node:path";var PC=448,Nn="local_",BN="local-agent-mode-sessions",Gf="-3p",FN="cowork_account_settings.json",Qr=(e={})=>{let t=(e.home??$N)(),n=e.runtimePlatform??MN(),r=e.env??process.env;if(n==="darwin")return At(t,"Library","Application Support",`Claude${Gf}`);if(n==="win32"){let o=r.LOCALAPPDATA??At(t,"AppData","Local");return At(o,`Claude${Gf}`)}return null},Us=(e={})=>{let t=Qr(e);return t?t.slice(0,-Gf.length):null},Vf=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)}`},El=async e=>{let t=At(e,BN),n;try{n=(await Ln.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 Ln.readdir(At(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=At(t,o,s);try{await Ln.access(At(i,FN)),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]}},Kf=async e=>{try{let t=await Ln.readdir(e);return new Set(t.filter(n=>n.startsWith(Nn)&&n.endsWith(".json")).map(n=>n.slice(Nn.length,-5)))}catch{return new Set}},Xo=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),WN=async(e,t)=>{let n=`${Nn}${t.sessionId}`,r=At(e,n),o=At(r,"outputs"),a=At(r,".claude"),s=At(a,"projects",Vf(o));await Ln.mkdir(o,{recursive:!0,mode:PC}),await Ln.mkdir(s,{recursive:!0,mode:PC});let i=At(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${NN()}`;await Ln.copyFile(t.transcriptPath,c),await Ln.chmod(c,384),await Ln.rename(c,i);let l=t.createdAt??Date.now();await Y(At(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})},DC=async(e,t)=>{let n=await Kf(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!Xo(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await WN(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as zo}from"node:fs";import{homedir as HN}from"node:os";import{dirname as UN,join as Gs}from"node:path";var GN=448,VN=["Documents","Claude","Projects"],KN="spaces.json",jN=(e={})=>Gs((e.home??HN)(),...VN),ZN=async e=>{try{let t=JSON.parse(await zo.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}}},YN=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},jf=async e=>{try{return await zo.access(e),!0}catch{return!1}},JN=async(e,t,n)=>{let r=Gs(t,YN(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await jf(r)?o:r;return a===o&&await jf(o)?null:(await zo.mkdir(UN(a),{recursive:!0}),await zo.cp(e,a,{recursive:!0}),a)},XN=async e=>{try{let t=(await zo.readFile(Gs(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},LC=async e=>{let t=jN({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=Gs(e.storageDir,KN),{spaces:a,readable:s}=await ZN(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=Gs(e.stagedProjectsDir,l.dirName);try{if(!await jf(d)){n.failed+=1;continue}let u=await JN(d,t,l);if(!u){n.skippedCollision+=1;continue}let p=await XN(u);c.push({id:l.uuid,name:l.name,folders:[{path:u}],projects:[],links:[],...p?{instructions:p}:{},origin:"user",createdAt:e.now,updatedAt:e.now}),n.imported+=1}catch{n.failed+=1}}return c.length>0&&(await zo.mkdir(e.storageDir,{recursive:!0,mode:GN}),await Y(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as e$}from"node:crypto";import{execFile as t$,spawnSync as KC}from"node:child_process";import{constants as jC}from"node:fs";import{access as _l,chmod as n$,mkdir as r$,readdir as o$,readFile as Yf,rename as a$,rm as qo,stat as ZC,writeFile as s$}from"node:fs/promises";import{homedir as i$,platform as c$,userInfo as l$}from"node:os";import{basename as d$,dirname as YC,isAbsolute as Qo,join as Pt,resolve as FC}from"node:path";import{isDeepStrictEqual as Ks,promisify as u$}from"node:util";var hr="__anyray-claude-desktop-credential",Vs="__anyray-claude-desktop-bootstrap-headers";var Il=["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>`."],xl=["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."],NC="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 Rl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],$C=["allowOptionalClientAuth","allowedPluginMarketplaces","allowedWorkspaceFolders","autoModeEnabled","autoUpdaterEnforcementHours","banner","bootstrapEnabled","bootstrapHeaders","bootstrapHeadersHelper","bootstrapOidc","bootstrapUrl","builtinToolPolicy","chatAdvancedFileAnalysisEnabled","chatTabEnabled","claudeAiImport","coworkEgressAllowedHosts","coworkTabEnabled","deploymentDisplayName","deploymentDisplaySubtitle","deploymentOrganizationUuid","disableAutoUpdates","disableBundledSkills","disableDeepLinkRegistration","disableDeploymentModeChooser","disableEssentialTelemetry","disableFeatureDiscovery","disableNonessentialServices","disableNonessentialTelemetry","disableWslSessions","disabledBuiltinTools","enduserAttribution","forceLoginOrgUUID","hardwareBuddyEnabled","inferenceAnthropicApiKey","inferenceBedrockAwsCliPath","inferenceBedrockAwsDir","inferenceBedrockBaseUrl","inferenceBedrockBearerToken","inferenceBedrockProfile","inferenceBedrockRegion","inferenceBedrockServiceTier","inferenceBedrockSsoAccountId","inferenceBedrockSsoRegion","inferenceBedrockSsoRoleName","inferenceBedrockSsoStartUrl","inferenceCredentialHelper","inferenceCredentialHelperSilentRefreshEnabled","inferenceCredentialHelperTimeoutSec","inferenceCredentialHelperTtlSec","inferenceCredentialKind","inferenceCustomHeaders","inferenceFoundryApiKey","inferenceFoundryAuthFlow","inferenceFoundryClientId","inferenceFoundryResource","inferenceFoundryTenantId","inferenceGatewayApiKey","inferenceGatewayAuthScheme","inferenceGatewayBaseUrl","inferenceGatewayOidc","inferenceMaxTokensPerWindow","inferenceModels","inferenceProvider","inferenceSessionLifetimeSec","inferenceTokenWindowHours","inferenceVertexBaseUrl","inferenceVertexCredentialsFile","inferenceVertexOAuthClientId","inferenceVertexOAuthClientSecret","inferenceVertexOAuthLoginHint","inferenceVertexOAuthScopes","inferenceVertexProjectId","inferenceVertexRegion","inferenceVertexWorkforceAudience","inferenceVertexWorkforceOidc","inferenceVertexWorkforceUserProject","isClaudeCodeForDesktopEnabled","isDesktopExtensionDirectoryEnabled","isDesktopExtensionEnabled","isDesktopExtensionSignatureRequired","isLocalDevMcpEnabled","loginSsoOrgDomain","managedMcpServers","mcpPersistentAlwaysAllowEnabled","microsoftAuthBroker","modelDiscoveryEnabled","orgPluginSettings","organizationPluginsUrl","otlpContentCapture","otlpDesktopLogLevel","otlpEndpoint","otlpHeaders","otlpProtocol","otlpResourceAttributes","otlpTracesEnabled","requireCoworkFullVmSandbox","secureVmFeaturesEnabled","toolSearchEnabled","userContentRendererUrl"],zN=new Set($C),qN=new Set($C.map(e=>e.toLowerCase())),QN=new Set(Rl.map(e=>e.toLowerCase())),Ol=(e,t=!1)=>(t?qN:zN).has(t?e.toLowerCase():e),MC=(e,t=!1)=>t?QN.has(e.toLowerCase()):Rl.some(n=>n===e),BC=["*"],eo=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...BC]}),mr=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var js=/^[a-f0-9-]{36}$/,JC="Anyray",Jf=4,Js=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],Xs=["deploymentMode","awaitingSignIn"],XC=[...Js,...Xs,"configLibrary","_meta.json"],yn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),it=e=>structuredClone(e),Zs=async e=>{try{return await _l(e),!0}catch{return!1}},p$=async e=>{try{let t=await o$(YC(e)),n=d$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},f$=async e=>{try{return await _l(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":p$(e)}},Kt=(e={})=>{let t=(e.home??i$)(),n=(e.username??(()=>l$().username))(),r=Pt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Pt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Pt(r,"configLibrary"),meta:Pt(r,"configLibrary","_meta.json"),appConfig:Pt(r,"claude_desktop_config.json"),helper:Pt(t,".anyray","bin","claude-desktop-credential-helper"),journal:Pt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Pl=()=>{let e=KC("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},zC=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],h$=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...zC(t)]}},Xf=(e="json")=>{let t=en(zC(e)),n=FC(t.command),r=FC(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)}},m$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,zf=e=>[e.command,...e.args].map(m$).join(" "),y$=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!Qo(e.command))throw new Error("the credential helper executable is not absolute")},qC=(e,t)=>{y$(e);let n=Dl(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!Qo(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},QC=e=>(qC(e,"--json"),`#!/bin/sh
|
|
189
|
+
`,$s=async e=>await x(e)?(await cC(e,"utf-8")).startsWith(`${lC}
|
|
190
|
+
`)?"owned":"foreign":"absent",dC=async(e,t)=>{let n=wf(t),r=await $s(e);return r==="foreign"?"foreign":r==="owned"&&await cC(e,"utf-8")===n?"unchanged":(await we(e,n),"installed")},bf=async e=>{let t=await $s(e);return t!=="owned"?t:(await GL(e,{force:!0}),"removed")};var Af="https://opencode.ai/config.json",Pn="x-anyray-metadata",Pt="x-anyray-api-key",Cf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Tn="Authorization",dr=["anthropic","openai"],Dn="github-copilot",KL="header",_n="anyray",jL=()=>process.env.XDG_CONFIG_HOME?.trim()||ur(mC(),".config"),ZL=()=>process.env.XDG_DATA_HOME?.trim()||ur(mC(),".local","share"),hl=()=>ur(jL(),"opencode"),fl=()=>ur(hl(),"plugins","anyrayTrim.js"),yC=()=>ur(ZL(),"opencode"),gC=async()=>{try{let e=await hC(ur(yC(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return H(t)?{chatGptOAuth:H(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}}},uC=async()=>(await gC()).chatGptOAuth,YL=["opencode.jsonc","opencode.json","config.json"],Ko=async()=>{let e=hl(),t=[];for(let n of YL){let r=ur(e,n);await x(r)&&t.push(r)}return t},pC=async()=>(await Ko())[0]??ur(hl(),"opencode.json"),kf=()=>VA(process.env.ANYRAY_COPILOT_PLAN),vf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${kf()}/${KL}`,H=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}/`)},JL=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===dr[0]||n===dr[1]||n===Dn?[]:H(r)&&H(r.options)&&Rf(r.options.baseURL,t)?[n]:[]),Sf=/claude/i,Of=["model","small_model"],wC=(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`${dr[0]}/${o}`},If=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)If(n,t);return t}if(!H(e))return t;for(let[n,r]of Object.entries(e))Of.includes(n)&&typeof r=="string"?t.push(r):If(r,t);return t},XL=(e,t,n)=>{if(!H(e)||!H(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 If(t).filter(a=>a.startsWith(o)).every(a=>Sf.test(a.slice(o.length)))},Ef=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>Ef(o,t,n));if(!H(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Of.includes(o)?wC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=Ef(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(!H(e)||!H(t))return e;let r={};for(let[o,a]of Object.entries(e))Of.includes(o)&&typeof a=="string"&&wC(t[o],n)===a?r[o]=t[o]:r[o]=xf(a,t[o],n);return r},zL=e=>{if(H(e))for(let t of dr){let n=e[t];if(H(n)&&H(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Ms=e=>{if(!H(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Gt({command:t,args:n},"profile")},ml=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),qL=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return H(t)&&t.tool==="opencode"}catch{return!1}},Tf=e=>ee(e,"copilot")&&!!e.clientKey,QL=e=>e.byoUpstream?[]:ee(e,"anthropic")?[`Note: OpenCode can't route your personal Claude subscription \u2014 its Anthropic provider is api-key only, so this uses the gateway's server-held provider key (API billing). For your personal subscription use Claude Code; otherwise make sure an org provider key is set on the gateway, or requests will fail upstream with "invalid x-api-key".`]:[],eN=(e,t)=>ee(e,"openai")?[`OpenAI subscription: OpenCode's built-in ChatGPT Pro/Plus OAuth is ${t?"detected":"not signed in yet (run `opencode auth login`)"}. Its Codex endpoint is hard-coded to chatgpt.com, so provider.baseURL cannot redirect it. Connect leaves machine networking untouched. Use the Codex app/CLI/IDE for ChatGPT subscription pass-through, or sign OpenCode into an API-key/Copilot provider that Connect can route.`]:[],tN=e=>Tf(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."]:[],nN=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Af);let o=!1;if(n)if("mcp"in r&&!H(r.mcp))o=!0;else{let g=H(r.mcp)?{...r.mcp}:{},b=g[_n];b!==void 0&&!Ms(b)?o=!0:(g[_n]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=g)}else if(H(r.mcp)&&Ms(r.mcp[_n])){let g={...r.mcp};delete g[_n],Object.keys(g).length===0?delete r.mcp:r.mcp=g}let a=H(r.provider)?{...r.provider}:{},s=JL(a,t.origin),i=s.every(g=>XL(a[g],e,g))?s:[],c=s.filter(g=>!i.includes(g)),l=[];if(i.length>0){for(let g of i)delete a[g];r=Ef(r,i,l)}let d=[],u=[],p=t.openaiBaseUrl,f=t.clientKey??t.placeholderKey,m=ue({...t.metadata,tool:"opencode"});for(let g of c){let b={...a[g]},k={...b.options};if("headers"in k&&!H(k.headers)){u.push(g);continue}let C=H(k.headers)?{...k.headers}:{},S=!1;for(let[I,E]of[[Pt,f],...m?[[Pn,m]]:[]])I in C?(typeof C[I]!="string"||C[I].trim()==="")&&u.push(`${g}.${I}`):(C[I]=E,d.push(`${g}.${I}`),S=!0);S&&(k.headers=C,b.options=k,a[g]=b)}let h=c.length>0?[]:dr.filter(g=>g!=="openai"||!ee(t,"openai")),w=t.byoUpstream;for(let g of h){let b=H(a[g])?{...a[g]}:{},k=H(b.options)?{...b.options}:{};k.baseURL=p;let C=H(k.headers)?{...k.headers}:{};if(g==="anthropic"&&w)k.apiKey=w.key,C[Tn]=`Bearer ${w.key}`,C["x-anyray-provider"]="anthropic",C["x-anyray-auth-mode"]="passthrough",C["x-anyray-custom-host"]=w.url;else{k.apiKey=f,"x-anyray-custom-host"in C&&delete C[Tn];for(let S of Cf)delete C[S]}C[Pt]=f,m&&(C[Pn]=m),k.headers=C,b.options=k,a[g]=b}let y=c.length===0&&Tf(t);if(y){let g=H(a[Dn])?{...a[Dn]}:{},b=H(g.options)?{...g.options}:{};b.baseURL=vf(t);let k=H(b.headers)?{...b.headers}:{};k[Pt]=t.clientKey,m&&(k[Pn]=m),b.headers=k,g.options=b,a[Dn]=g}return Object.keys(a).length>0&&(r.provider=a),{next:r,copilot:y,customProviders:c,migratedProviders:i,modelRefsRemapped:l,customHeadersAdded:d,customHeaderConflicts:u,mcpConflict:o}},rN=["baseURL","apiKey"],fC=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!H(s)||!H(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=H(c.headers)?{...c.headers}:void 0,p=u?.[Pt],f=ml(p);if(d&&(delete c.baseURL,l=!0),u&&(d||f)){let m=u,h=H(r)?r.options:void 0,w=H(h)&&H(h.headers)?h.headers:void 0;for(let y of[Pt,Pn])w&&y in w?m[y]!==w[y]&&(m[y]=w[y],l=!0):y in m&&(delete m[y],l=!0);Object.keys(m).length===0?delete c.headers:c.headers=m}}else{let d=H(r)?r.options:void 0,u=H(d)?d:{},p=H(c.headers)?c.headers:{},f=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof p[Pt]=="string"||typeof p[Pn]=="string"||Cf.some(m=>m in p);if(!o&&!f)return!1;for(let m of rN)m in u?c[m]!==u[m]&&(c[m]=u[m],l=!0):m in c&&(delete c[m],l=!0);if(H(c.headers)){let m={...c.headers},h=H(u.headers)?u.headers:{};"x-anyray-custom-host"in m&&Tn in m&&(Tn in h?m[Tn]!==h[Tn]&&(m[Tn]=h[Tn],l=!0):(delete m[Tn],l=!0));for(let w of[Pt,Pn,...Cf])w in h?m[w]!==h[w]&&(m[w]=h[w],l=!0):w in m&&(delete m[w],l=!0);Object.keys(m).length===0?delete c.headers:c.headers=m}}return l?(Object.keys(c).length===0?delete i.options:i.options=c,Object.keys(i).length===0?delete e[t]:e[t]=i,!0):!1},oN=(e,t,n)=>{let r=e[t];if(!H(r)||!H(r.options)||!H(n)||!H(n.options))return!1;let o={...r.options};if(!H(o.headers)||"headers"in n.options&&!H(n.options.headers))return!1;let a={...o.headers},s=H(n.options.headers)?n.options.headers:{},i=!1;return!(Pt in s)&&ml(a[Pt])&&(delete a[Pt],i=!0),!(Pn in s)&&qL(a[Pn])&&(delete a[Pn],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},aN=(e,t)=>{let n={...e},r=!1,o=zL(e.provider);if(H(n.mcp)&&Ms(n.mcp[_n])){let c={...n.mcp};delete c[_n],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!H(n.provider))return{next:n,removed:r};let a={...n.provider},s=H(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===Af&&dr.every(c=>{let l=a[c];return H(l)&&H(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of dr)fC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...dr,Dn]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;oN(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&H(u)&&H(u.options)&&Rf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=xf(n,t,l))}return fC(a,Dn,!0,s[Dn])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===Af&&(delete n.$schema,r=!0),{next:n,removed:r}},bC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=hl(),t=yC(),n=await x(e)||await x(t),r=n&&await uC();return{installed:n,detail:n?`${await pC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await pC(),r=e.openaiBaseUrl,o=ue({...e.metadata,tool:"opencode"}),a=Tf(e),s=ee(e,"openai"),i=await uC(),c;try{c=await Ke(n)}catch{return e.clientKey?{status:"manual",messages:[`Couldn't parse ${n} \u2014 set it by hand. Under "provider", add:`,e.byoUpstream?` "anthropic": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your upstream key>", "headers": { "Authorization": "Bearer <your upstream key>", "x-anyray-auth-mode": "passthrough", "x-anyray-provider": "anthropic", "x-anyray-custom-host": ${JSON.stringify(e.byoUpstream.url)}, "x-anyray-api-key": "<your personal ark_ key>" } } }`:` "anthropic": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your personal ark_ key>" } }`,...s?[]:[` "openai": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your personal ark_ key>" } }`],...a?[` "github-copilot": { "options": { "baseURL": ${JSON.stringify(vf(e))}, "headers": { "${Pt}": "<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 Lr()?Ge("profile"):void 0,{next:d,customProviders:u,migratedProviders:p,modelRefsRemapped:f,customHeadersAdded:m,customHeaderConflicts:h,mcpConflict:w}=nN(c.data,e,l),y=u.length>0,g=p.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${p.map(E=>`provider.${E}`).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.`,...f.length>0?[`Updated model references: ${f.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=y?[`${n} already routes through ${e.origin} via ${u.map(E=>`provider.${E}`).join(", ")}; existing provider values were preserved.`,m.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${m.join(", ")}.`:"Existing Anyray authentication and attribution headers were preserved.",...h.length>0?[`Could not safely add required headers at ${h.join(", ")} because the existing values have incompatible shapes. Fix those values manually; no existing value was replaced.`]:[],"Canonical anthropic, openai, and github-copilot provider blocks were left untouched.","Restart OpenCode (or start a new session) to pick up the change."]:[...g,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)"}`,...QL(e),...eN(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. ${kf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${kf()} 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).",...tN(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 k=h.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let S=await sn(n,c,d,!0)?[n]:[],I=fl();if(ce())try{let E=await dC(I,es(Xe,["opencode"]));E==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${I} already exists and is not owned by Anyray.`):(E==="installed"&&S.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"&&S.push(I)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${Oe()}). Re-run via the installer or a global install to enable cache-safe source trimming.`)}return{status:k,messages:b,changedFiles:S}},async pointsAt(e){for(let t of await Ko())try{let{data:n}=await Ke(t);if(!H(n.provider))continue;for(let r of Object.values(n.provider))if(!(!H(r)||!H(r.options))&&Rf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){for(let e of await Ko())try{let{data:t}=await Ke(e);if(!H(t.mcp))continue;let n=t.mcp[_n];if(!Ms(n)||!H(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 $s(fl());e=i==="absent"?"missing":i,e==="owned"&&(t=await hC(fl(),"utf-8")===wf(es(Xe,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await Ko()){let c;try{c=await Ke(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!H(c.data.mcp)){o=!0;continue}let l=c.data.mcp[_n];if(l!==void 0)if(Ms(l))if(n=!0,!H(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;rc({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 Lr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await gC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await Ko()){let{data:o}=await Ke(r);if(H(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!H(s)||!H(s.options)){e.add("unknown");continue}let i=s.options,c=H(i.headers)?i.headers:{};if(a===Dn&&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===Dn&&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(ml(c[Pt])||ml(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 Ko(),n=fl(),r="absent";try{r=await $s(n)}catch{}if(t.length===0&&r!=="owned")return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[...t.map(i=>`would remove Anyray provider settings from ${i}`),...r==="owned"?[`would remove the Anyray OpenCode trim carrier from ${n}`]:[]]};let o=[],a=[],s=[];for(let i of t){let c;try{c=await Ke(i)}catch{s.push(i);continue}let{next:l,removed:d}=aN(c.data,await Mo(i));d&&(await sn(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await re(i)}for(let i of s)o.push(`Couldn't parse ${i} \u2014 if you added Anyray settings there by hand, remove the baseURL/apiKey from provider.anthropic, provider.openai, and provider.github-copilot yourself.`);if(r==="owned")try{await 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 Mf}from"node:os";import{join as Cl}from"node:path";import{homedir as sN}from"node:os";import{dirname as iN,join as pr}from"node:path";import{mkdir as cN,readdir as lN,readFile as CC,rm as kC}from"node:fs/promises";var _f="48ff8bb9a7afde1d9e8468d632f84b46f199e6a28657833b113de93698d9ac63",AC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyNTYwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnM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ICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIjIwMjYuNy4xIgogICAgfQogIH0sCi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XR1cm4gewogICAgLy8gQmFyZSBvcmlnaW46IHRoZSBhbnRocm9waWMtbWVzc2FnZXMgdHJhbnNwb3J0IGFwcGVuZHMgL3YxL21lc3NhZ2VzLgogICAgYmFzZVVybDogZ2F0ZXdheVVybC5yZXBsYWNlKC9cLyskLywgJycpLAogICAgYXBpOiAnYW50aHJvcGljLW1lc3NhZ2VzJywKICAgIC4uLihhcGlLZXkgPyB7IGFwaUtleSB9IDoge30pLAogICAgaGVhZGVyczogewogICAgICAnYW50aHJvcGljLWJldGEnOiBBTlRIUk9QSUNfQkVUQSwKICAgICAgLi4uKGFwaUtleSA/IHsgJ3gtYW55cmF5LWFwaS1rZXknOiBhcGlLZXkgfSA6IHt9KSwKICAgICAgLi4uKGF0dHJpYnV0aW9uID8geyAneC1hbnlyYXktbWV0YWRhdGEnOiBhdHRyaWJ1dGlvbiB9IDoge30pLAogICAgfSwKICAgIG1vZGVsczogTU9ERUxTLAogIH07Cn07Cg=="},{path:"src/sessionIdentity.ts",contentBase64:"LyoqCiAqIFBlci1zZXNzaW9uIGlkZW50aXR5IGZvciB0aGUgQW55cmF5IGdhdGV3YXksIGluamVjdGVkIGludG8gdGhlIEFudGhyb3BpYwogKiBNZXNzYWdlcyBib2R5IGFzIGBtZXRhZGF0YS51c2VyX2lkYC4KICoKICogVGhlIGdhdGV3YXkgZGVyaXZlcyBpdHMgb3B0aW1pemVyIHNlc3Npb24gZnJvbSBhIGBfc2Vzc2lvbl88dXVpZD5gIHN1ZmZpeCBvbgogKiBgbWV0YWRhdGEudXNlcl9pZGAgKHRoZSBDbGF1ZGUgQ29kZSBjb252ZW50aW9uOyBnYXRld2F5CiAqIGBjbGllbnRTZXNzaW9uLnRzI21ldGFkYXRhU2Vzc2lvblV1aWRgKS4gV2l0aG91dCBpdCwgT3BlbkNsYXcgdHJhZmZpYyBmYWxscwogKiB0byBhIGNvbnZlcnNhdGlvbi1hbmNob3IgZmluZ2VycHJpbnQsIGFuZCBjb25jdXJyZW50IGNvb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Owp9Owo="}];var Pf=".anyray-source-sha",hn=()=>pr(sN(),".anyray","openclaw-plugin"),vC=async(e=hn())=>{try{if((await CC(pr(e,Pf),"utf8")).trim()===_f)return"current"}catch{}for(let t of AC){let n=pr(e,t.path);await cN(iN(n),{recursive:!0,mode:448}),await we(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await we(pr(e,Pf),`${_f}
|
|
191
|
+
`),"installed"},Bs=async(e,t=[])=>{let n=[],r=async a=>{let s=pr(a,"plugins","anyray","catalog.json");try{await kC(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await lN(pr(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(pr(e,"agents",a,"agent"));return n},yl=async(e=hn())=>{try{await CC(pr(e,Pf),"utf8")}catch{return!1}return await kC(e,{recursive:!0,force:!0}),!0};var Lf="x-anyray-metadata",Yo="x-anyray-api-key",Nf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],zr="Authorization",qr="anthropic-beta",wl="interleaved-thinking-2025-05-14",bl=["anthropic","openai"],IC="short",Bf="anthropic-messages",Ff=32e3,Al="anthropic/claude-sonnet-4-5",Wf=["anthropic/claude-haiku-4-5"],Hf="anyray/claude-sonnet-4-5",Uf=["anyray/claude-haiku-4-5"],dN=[Al,Hf],uN=[Wf,Uf],qe="anyray",fr="ANYRAY_API_KEY",Fs="openclaw",Zo=()=>process.env.OPENCLAW_STATE_DIR?.trim()||Cl(Mf(),".openclaw"),jo=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||Cl(Zo(),"openclaw.json"),N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),SC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},$f=e=>{if(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},pN=e=>e==="~"||e.startsWith("~/")?Cl(Mf(),e.slice(1)):e,gl=e=>{if(!N(e))return[];let t=e.agents;if(!N(t)||!Array.isArray(t.list))return[];let n=[];for(let r of t.list){if(!N(r))continue;let o=typeof r.agentDir=="string"?r.agentDir.trim():"";o&&n.push(pN(o))}return n},fN=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=ue({...t.metadata,tool:Fs}),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 p=N(u.providers)?{...u.providers}:{},f=!1;if(n){let C=N(l.plugins)?{...l.plugins}:{},S=N(C.load)?{...C.load}:{},I=N(C.entries)?{...C.entries}:{},E=N(I[qe])?{...I[qe]}:{},R=N(E.config)?{...E.config}:{};if("plugins"in l&&!N(l.plugins)||"load"in C&&!N(C.load)||"paths"in S&&!Array.isArray(S.paths)||"entries"in C&&!N(C.entries)||qe in I&&!N(I[qe])||"config"in E&&!N(E.config)||"env"in l&&!N(l.env))d.push("plugins");else{let P=Array.isArray(S.paths)?[...S.paths]:[];P.includes(n)||P.push(n),S.paths=P,C.load=S,E.enabled=!0,R.gatewayUrl=t.anthropicBaseUrl,R.apiKey=r;let W=t.metadata.user,q=t.metadata.team;W&&(R.user=W),q&&(R.team=q),E.config=R,I[qe]=E,C.entries=I,l.plugins=C;let de=N(l.env)?{...l.env}:{};de[fr]=r,l.env=de,f=!0}}let m=bl.filter(C=>C!=="openai"||!ee(t,"openai"));for(let C of m){if(C in p&&!N(p[C])){d.push(`models.providers.${C}`);continue}let S=N(p[C])?{...p[C]}:{};if("headers"in S&&!N(S.headers)){i.push(C);continue}let I=N(S.headers)?{...S.headers}:{};if(S.baseUrl=C==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,C==="anthropic"&&(S.api=Bf,(typeof S.maxTokens!="number"||S.maxTokens<=0)&&(S.maxTokens=Ff)),C==="anthropic"&&a)S.apiKey=a.key,I[zr]=`Bearer ${a.key}`,I["x-anyray-provider"]="anthropic",I["x-anyray-auth-mode"]="passthrough",I["x-anyray-custom-host"]=a.url;else{S.apiKey=r,"x-anyray-custom-host"in I&&delete I[zr];for(let E of Nf)delete I[E]}I[Yo]=r,o&&(I[Lf]=o),C==="anthropic"&&(qr in I?c=I[qr]!==wl:I[qr]=wl),S.headers=I,p[C]=S,s.push(C)}u.providers=p,l.models=u;let h=!1,w=!1,y=!1,g,b=[],k="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(k&&d.push("agents.defaults"),s.includes("anthropic")&&!k){let C=N(l.agents)?{...l.agents}:{},S=N(C.defaults)?{...C.defaults}:{},I=N(S.params)?{...S.params}:{};"cacheRetention"in I||(I.cacheRetention=IC,h=!0,S.params=I);let E=N(S.model)?{...S.model}:{},R=f?[...s,qe]:s,P=W=>typeof W=="string"&&R.some(q=>W.startsWith(`${q}/`));typeof E.primary!="string"||E.primary.trim()===""?(E.primary=f?Hf:Al,w=!0,S.model=E,"fallbacks"in E||(E.fallbacks=f?[...Uf]:[...Wf],y=!0)):P(E.primary)||(g=E.primary),b=(Array.isArray(E.fallbacks)?E.fallbacks:[]).filter(W=>typeof W=="string"&&!P(W)),(h||w)&&(C.defaults=S,l.agents=C)}return{next:l,routed:s,cacheRetentionSeeded:h,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:y,unroutedPrimary:g,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:f}},mN=["baseUrl","apiKey","api","maxTokens"],Df=(e,t,n=bl,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=$f(t),l=!1;for(let u of a?n:[]){let p=i[u];if(!N(p))continue;let f={...p},m=N(f.headers)?{...f.headers}:{};if(!(t!==void 0||typeof m[Yo]=="string"||typeof m[Lf]=="string"||typeof f.apiKey=="string"&&f.apiKey.startsWith("ark_")||Nf.some(C=>C in m)))continue;let w=N(c[u])?c[u]:{},y=N(w.headers)?w.headers:{},g="x-anyray-custom-host"in m,b=C=>C==="api"?f.api===Bf:C==="maxTokens"?f.maxTokens===Ff:C==="apiKey"?g||typeof f.apiKey=="string"&&f.apiKey.startsWith("ark_"):!0;for(let C of mN)b(C)&&(C in w?f[C]!==w[C]&&(f[C]=w[C],l=!0):C in f&&(delete f[C],l=!0));let k=[Yo,Lf,...Nf,..."x-anyray-custom-host"in m?[zr]:[]];m[qr]===wl&&k.push(qr);for(let C of k)C in y?m[C]!==y[C]&&(m[C]=y[C],l=!0):C in m&&(delete m[C],l=!0);zr in y&&!(zr in m)&&(m[zr]=y[zr],l=!0),Object.keys(m).length===0?delete f.headers:f.headers=m,Object.keys(f).length===0?delete i[u]:i[u]=f}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}:{},p=N(u.load)?{...u.load}:{},f=N(u.entries)?{...u.entries}:{};if((!("plugins"in o)||N(o.plugins))&&(!("load"in u)||N(u.load))&&(!("paths"in p)||Array.isArray(p.paths))&&(!("entries"in u)||N(u.entries))){if(Array.isArray(p.paths)&&p.paths.includes(r)){let w=p.paths.filter(y=>y!==r);w.length===0?delete p.paths:p.paths=w,l=!0}let h=f[qe];if(N(h)){let w=N(h.config)?h.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let g=N(t?.plugins)?t.plugins:{},b=N(g.entries)?g.entries:{};qe in b?JSON.stringify(f[qe])!==JSON.stringify(b[qe])&&(f[qe]=b[qe],l=!0):(delete f[qe],l=!0)}}if(Object.keys(p).length===0?delete u.load:u.load=p,Object.keys(f).length===0?delete u.entries:u.entries=f,Object.keys(u).length===0?delete o.plugins:o.plugins=u,N(o.env)){let w={...o.env},y=w[fr];if(typeof y=="string"&&y.startsWith("ark_")){let g=N(t?.env)?t.env:{};fr in g?w[fr]!==g[fr]&&(w[fr]=g[fr],l=!0):(delete w[fr],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}:{},p=N(u.defaults)?{...u.defaults}:{},f=N(p.params)?{...p.params}:{},m=N(t.agents)?t.agents:{},h=N(m.defaults)?m.defaults:{},w=N(h.params)?h.params:{};f.cacheRetention===IC&&("cacheRetention"in w?f.cacheRetention!==w.cacheRetention&&(f.cacheRetention=w.cacheRetention,l=!0):(delete f.cacheRetention,l=!0));let y=N(p.model)?{...p.model}:{},g=N(h.model)?h.model:{};dN.includes(y.primary)&&("primary"in g?y.primary!==g.primary&&(y.primary=g.primary,l=!0):(delete y.primary,l=!0)),uN.some(b=>JSON.stringify(y.fallbacks)===JSON.stringify(b))&&("fallbacks"in g?JSON.stringify(y.fallbacks)!==JSON.stringify(g.fallbacks)&&(y.fallbacks=g.fallbacks,l=!0):(delete y.fallbacks,l=!0)),Object.keys(y).length===0?delete p.model:p.model=y,Object.keys(f).length===0?delete p.params:p.params=f,Object.keys(p).length===0?delete u.defaults:u.defaults=p,Object.keys(u).length===0?delete o.agents:o.agents=u}return{next:o,removed:l}},EC={id:Fs,title:"OpenClaw",automatic:!0,async detect(){let e=await x(jo())||await x(Zo());return{installed:e,detail:e?jo():`no ${Cl(Mf(),".openclaw")} state dir`}},async apply(e,t){let n=jo();if(!e.byoUpstream&&ee(e,"anthropic")){let S=["OpenClaw stays on its native Claude sign-in \u2014 the Anyray seat","passthrough lane for OpenClaw is not yet supported, and routing it","would move inference onto the org API bill. Opt in explicitly with",`\`--org --tools ${Fs}\` 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 Ke(n)}catch{return{status:"held",messages:S}}let{next:E,removed:R}=Df(I.data,await Mo(n),bl,hn());return R?t.dryRun?{status:"held",messages:[`would remove the stale Anyray route from ${n} (org lane, not the lane in effect for this seat)`,...S]}:(await sn(n,I,E,!1),await re(n),await yl(),await Bs(Zo(),gl(E)),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...S]}):(t.dryRun||(await yl(),await Bs(Zo(),gl(E))),{status:"held",messages:S})}let r=hn(),o=!1;if(!t.dryRun)try{await vC(r)}catch{r=void 0,o=!0}let a;try{a=await Ke(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Bf}", "maxTokens": ${Ff}, "apiKey": "<your personal ark_ key>", "headers": { "${Yo}": "<your personal ark_ key>", "${qr}": "${wl}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${Yo}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${Al}") 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:p,unroutedPrimary:f,unroutedFallbacks:m,structureConflicts:h,pluginConfigured:w}=fN(a.data,e,r),y=s,g=!1;if(!i.includes("openai")){let S=Df(y,await Mo(n),["openai"]);S.removed&&(y=S.next,g=!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: ${ue({...e.metadata,tool:Fs})??"(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 ${qr} 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?Hf:Al} (none was set; routing is inert until the primary resolves to a routed provider).`,...p?[`Seeded agents.defaults.model.fallbacks = [${(w?Uf:Wf).join(", ")}] so failover stays on a routed provider.`]:[]]:[],...f!==void 0?[`Your primary model (${f}) resolves to a provider Connect does not route, so those requests bypass the gateway. Pick an anthropic/* or openai/* model to route them; your setting was kept.`]:[],...m.length>0?[`Fallback model(s) ${m.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...g?["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 (${hn()}) and registered it under plugins.entries.${qe}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${hn()}; routing continues via the provider entries alone (anthropic/* models).`]:[],...h.length>0?[`Left ${h.join(", ")} untouched: the existing value has the wrong shape (array or null where an object belongs), and OpenClaw's strict schema will refuse it as-is. Fix the shape and re-run.`]:[],"OpenClaw hot-reloads model config; run `openclaw config validate` to confirm the merged config passes its strict schema."],k=d.length>0||h.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let C=await sn(n,a,y,!0);return w&&await Bs(Zo(),gl(y)),{status:k,messages:b,changedFiles:C?[n]:[]}},async pointsAt(e){try{let{data:t}=await Ke(jo());for(let a of Object.values($f(t)))if(N(a)&&SC(a.baseUrl,e))return!0;let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[qe];if(N(o)&&N(o.config)&&SC(o.config.gatewayUrl,e))return!0}catch{}return!1},async routingExpected(e){return e.includes(Fs)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Ke(jo());for(let a of Object.values($f(t))){if(!N(a))continue;let s=N(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[Yo]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[qe];if(N(o)&&N(o.config)){let a=o.config.apiKey;typeof a=="string"&&a.startsWith("ark_")&&e.add("api_key")}}catch{e.add("unknown")}return e.size>0?[...e]:["unknown"]},async revert(e){let t=jo();if(!await x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await Ke(t)}catch{return{status:"manual",messages:[`Couldn't parse ${t} \u2014 if you added Anyray settings there by hand, remove baseUrl/apiKey and the x-anyray-* headers from models.providers.anthropic and models.providers.openai yourself.`]}}let{next:r,removed:o}=Df(n.data,await Mo(t),bl,hn()),a=await yl();return await Bs(Zo(),gl(r)),o?(await sn(t,n,r,!1),await re(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${hn()}`]:[]],changedFiles:[t]}):(await re(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${hn()}`]:[]]})}};import{execFile as oB}from"node:child_process";import{readFile as aB}from"node:fs/promises";import{homedir as oi,platform as gr}from"node:os";import{join as bn}from"node:path";import{isDeepStrictEqual as Rm,promisify as sB}from"node:util";var Ws=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},kl=(e,t)=>{let n=Ws(e),r=Ws(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 CM}from"node:crypto";import{promises as Bk}from"node:fs";import{platform as kM,tmpdir as vM}from"node:os";import{join as Wl}from"node:path";import{execFile as hN}from"node:child_process";import{promises as Hs}from"node:fs";import{homedir as yN,platform as gN}from"node:os";import{delimiter as wN,join as vl}from"node:path";import{promisify as bN}from"node:util";var AN=bN(hN),CN=15*6e4,kN=64*1024*1024,vN=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],xC=async(e={})=>{let t=(e.home??yN)(),n=e.env??process.env,r=vN(e.runtimePlatform??gN()),o=[vl(t,".local","bin"),vl(t,".claude","local"),...(n.PATH??"").split(wN).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=vl(a,`claude${s}`);try{return await Hs.access(i),i}catch{}}return null},SN=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},IN=async e=>{let t=vl(e,"projects"),n;try{n=(await Hs.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(!RN.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},EN=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],p=o[d];if(typeof u!="string"||typeof p!="string"||u.length===0||p.length===0)continue;let f=a[d];l.push({sessionId:u,transcriptPath:p,title:typeof f=="string"&&f.length>0?f:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:SN(n.projectList)}},xN=async e=>{let t,n;try{let r=await Hs.readFile(e,"utf8");for(let o of r.split(`
|
|
192
|
+
`)){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}},RN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ON=/\.(?:cmd|bat)$/i,TN=(e,t)=>ON.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},RC=async(e,t={})=>{let n=t.exec??AN,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 Hs.mkdir(e.configDir,{recursive:!0,mode:448}),await Hs.mkdir(e.workDir,{recursive:!0,mode:448});let o=TN(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:CN,maxBuffer:kN,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(`
|
|
193
|
+
`).filter(d=>d.trim().length>0),i=EN(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 xN(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await IN(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as _N}from"node:crypto";import{promises as Ln}from"node:fs";import{homedir as PN,platform as DN}from"node:os";import{join as Ct}from"node:path";var OC=448,Nn="local_",LN="local-agent-mode-sessions",Gf="-3p",NN="cowork_account_settings.json",Qr=(e={})=>{let t=(e.home??PN)(),n=e.runtimePlatform??DN(),r=e.env??process.env;if(n==="darwin")return Ct(t,"Library","Application Support",`Claude${Gf}`);if(n==="win32"){let o=r.LOCALAPPDATA??Ct(t,"AppData","Local");return Ct(o,`Claude${Gf}`)}return null},Us=(e={})=>{let t=Qr(e);return t?t.slice(0,-Gf.length):null},Vf=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)}`},Sl=async e=>{let t=Ct(e,LN),n;try{n=(await Ln.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 Ln.readdir(Ct(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=Ct(t,o,s);try{await Ln.access(Ct(i,NN)),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]}},Kf=async e=>{try{let t=await Ln.readdir(e);return new Set(t.filter(n=>n.startsWith(Nn)&&n.endsWith(".json")).map(n=>n.slice(Nn.length,-5)))}catch{return new Set}},Jo=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),$N=async(e,t)=>{let n=`${Nn}${t.sessionId}`,r=Ct(e,n),o=Ct(r,"outputs"),a=Ct(r,".claude"),s=Ct(a,"projects",Vf(o));await Ln.mkdir(o,{recursive:!0,mode:OC}),await Ln.mkdir(s,{recursive:!0,mode:OC});let i=Ct(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${_N()}`;await Ln.copyFile(t.transcriptPath,c),await Ln.chmod(c,384),await Ln.rename(c,i);let l=t.createdAt??Date.now();await Y(Ct(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})},TC=async(e,t)=>{let n=await Kf(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!Jo(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await $N(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as Xo}from"node:fs";import{homedir as MN}from"node:os";import{dirname as BN,join as Gs}from"node:path";var FN=448,WN=["Documents","Claude","Projects"],HN="spaces.json",UN=(e={})=>Gs((e.home??MN)(),...WN),GN=async e=>{try{let t=JSON.parse(await Xo.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}}},VN=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},jf=async e=>{try{return await Xo.access(e),!0}catch{return!1}},KN=async(e,t,n)=>{let r=Gs(t,VN(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await jf(r)?o:r;return a===o&&await jf(o)?null:(await Xo.mkdir(BN(a),{recursive:!0}),await Xo.cp(e,a,{recursive:!0}),a)},jN=async e=>{try{let t=(await Xo.readFile(Gs(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},_C=async e=>{let t=UN({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=Gs(e.storageDir,HN),{spaces:a,readable:s}=await GN(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=Gs(e.stagedProjectsDir,l.dirName);try{if(!await jf(d)){n.failed+=1;continue}let u=await KN(d,t,l);if(!u){n.skippedCollision+=1;continue}let p=await jN(u);c.push({id:l.uuid,name:l.name,folders:[{path:u}],projects:[],links:[],...p?{instructions:p}:{},origin:"user",createdAt:e.now,updatedAt:e.now}),n.imported+=1}catch{n.failed+=1}}return c.length>0&&(await Xo.mkdir(e.storageDir,{recursive:!0,mode:FN}),await Y(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as XN}from"node:crypto";import{execFile as zN,spawnSync as UC}from"node:child_process";import{constants as GC}from"node:fs";import{access as Tl,chmod as qN,mkdir as QN,readdir as e$,readFile as Yf,rename as t$,rm as zo,stat as VC,writeFile as n$}from"node:fs/promises";import{homedir as r$,platform as o$,userInfo as a$}from"node:os";import{basename as s$,dirname as KC,isAbsolute as qo,join as Dt,resolve as $C}from"node:path";import{isDeepStrictEqual as Ks,promisify as i$}from"node:util";var mr="__anyray-claude-desktop-credential",Vs="__anyray-claude-desktop-bootstrap-headers";var Il=["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>`."],El=["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."],PC="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 xl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],DC=["allowOptionalClientAuth","allowedPluginMarketplaces","allowedWorkspaceFolders","autoModeEnabled","autoUpdaterEnforcementHours","banner","bootstrapEnabled","bootstrapHeaders","bootstrapHeadersHelper","bootstrapOidc","bootstrapUrl","builtinToolPolicy","chatAdvancedFileAnalysisEnabled","chatTabEnabled","claudeAiImport","coworkEgressAllowedHosts","coworkTabEnabled","deploymentDisplayName","deploymentDisplaySubtitle","deploymentOrganizationUuid","disableAutoUpdates","disableBundledSkills","disableDeepLinkRegistration","disableDeploymentModeChooser","disableEssentialTelemetry","disableFeatureDiscovery","disableNonessentialServices","disableNonessentialTelemetry","disableWslSessions","disabledBuiltinTools","enduserAttribution","forceLoginOrgUUID","hardwareBuddyEnabled","inferenceAnthropicApiKey","inferenceBedrockAwsCliPath","inferenceBedrockAwsDir","inferenceBedrockBaseUrl","inferenceBedrockBearerToken","inferenceBedrockProfile","inferenceBedrockRegion","inferenceBedrockServiceTier","inferenceBedrockSsoAccountId","inferenceBedrockSsoRegion","inferenceBedrockSsoRoleName","inferenceBedrockSsoStartUrl","inferenceCredentialHelper","inferenceCredentialHelperSilentRefreshEnabled","inferenceCredentialHelperTimeoutSec","inferenceCredentialHelperTtlSec","inferenceCredentialKind","inferenceCustomHeaders","inferenceFoundryApiKey","inferenceFoundryAuthFlow","inferenceFoundryClientId","inferenceFoundryResource","inferenceFoundryTenantId","inferenceGatewayApiKey","inferenceGatewayAuthScheme","inferenceGatewayBaseUrl","inferenceGatewayOidc","inferenceMaxTokensPerWindow","inferenceModels","inferenceProvider","inferenceSessionLifetimeSec","inferenceTokenWindowHours","inferenceVertexBaseUrl","inferenceVertexCredentialsFile","inferenceVertexOAuthClientId","inferenceVertexOAuthClientSecret","inferenceVertexOAuthLoginHint","inferenceVertexOAuthScopes","inferenceVertexProjectId","inferenceVertexRegion","inferenceVertexWorkforceAudience","inferenceVertexWorkforceOidc","inferenceVertexWorkforceUserProject","isClaudeCodeForDesktopEnabled","isDesktopExtensionDirectoryEnabled","isDesktopExtensionEnabled","isDesktopExtensionSignatureRequired","isLocalDevMcpEnabled","loginSsoOrgDomain","managedMcpServers","mcpPersistentAlwaysAllowEnabled","microsoftAuthBroker","modelDiscoveryEnabled","orgPluginSettings","organizationPluginsUrl","otlpContentCapture","otlpDesktopLogLevel","otlpEndpoint","otlpHeaders","otlpProtocol","otlpResourceAttributes","otlpTracesEnabled","requireCoworkFullVmSandbox","secureVmFeaturesEnabled","toolSearchEnabled","userContentRendererUrl"],ZN=new Set(DC),YN=new Set(DC.map(e=>e.toLowerCase())),JN=new Set(xl.map(e=>e.toLowerCase())),Rl=(e,t=!1)=>(t?YN:ZN).has(t?e.toLowerCase():e),LC=(e,t=!1)=>t?JN.has(e.toLowerCase()):xl.some(n=>n===e),NC=["*"],eo=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...NC]}),hr=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var js=/^[a-f0-9-]{36}$/,jC="Anyray",Jf=4,Js=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],Xs=["deploymentMode","awaitingSignIn"],ZC=[...Js,...Xs,"configLibrary","_meta.json"],yn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),it=e=>structuredClone(e),Zs=async e=>{try{return await Tl(e),!0}catch{return!1}},c$=async e=>{try{let t=await e$(KC(e)),n=s$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},l$=async e=>{try{return await Tl(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":c$(e)}},jt=(e={})=>{let t=(e.home??r$)(),n=(e.username??(()=>a$().username))(),r=Dt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Dt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Dt(r,"configLibrary"),meta:Dt(r,"configLibrary","_meta.json"),appConfig:Dt(r,"claude_desktop_config.json"),helper:Dt(t,".anyray","bin","claude-desktop-credential-helper"),journal:Dt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},_l=()=>{let e=UC("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},YC=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],d$=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...YC(t)]}},Xf=(e="json")=>{let t=en(YC(e)),n=$C(t.command),r=$C(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)}},u$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,zf=e=>[e.command,...e.args].map(u$).join(" "),p$=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!qo(e.command))throw new Error("the credential helper executable is not absolute")},JC=(e,t)=>{p$(e);let n=Pl(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!qo(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},XC=e=>(JC(e,"--json"),`#!/bin/sh
|
|
194
194
|
exec ${zf(e)}
|
|
195
|
-
`),
|
|
196
|
-
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,
|
|
197
|
-
`)},
|
|
195
|
+
`),f$=`#!/bin/sh
|
|
196
|
+
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,zC=e=>{JC(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),mr]};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 ${zf(t)}`,""].join(`
|
|
197
|
+
`)},m$=e=>e.args.at(-1)==="--passthrough-headers"?zC(e):XC(e),Pl=e=>/[\\/](node|node\.exe)$/i.test(e),qf=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++}},h$=e=>{let t=`#!/bin/sh
|
|
198
198
|
exec `;if(!e.startsWith(t)||!e.endsWith(`
|
|
199
199
|
`))return;let n=e.slice(t.length,-1);if(n.includes(`
|
|
200
|
-
`)||n.includes("\r"))return;let r=qf(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=
|
|
201
|
-
# Anyray subscription pass-through credential helper`,
|
|
202
|
-
`)},
|
|
203
|
-
`,384)},gn=async e=>{if(!await Zs(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await Yf(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!yn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},zs=async e=>{if(!await Zs(e))return{present:!1};let t=await
|
|
204
|
-
`,384)},Ys=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!js.test(t)||!Array.isArray(n))throw new Error("Claude config-library metadata has an invalid shape");let r=new Set;for(let o of n){if(!yn(o)||typeof o.id!="string"||!js.test(o.id)||typeof o.name!="string"||r.has(o.id))throw new Error("Claude config-library metadata has an invalid entry");r.add(o.id)}if(!r.has(t))throw new Error("Claude config-library appliedId is not in entries");return t},N$=async(e,t,n)=>{let r=await gn(e.meta);if(t){if(!r.present){if(t.metaFileExisted)throw new Error("Claude config-library metadata disappeared after apply");return{configId:t.configId,meta:r,metaFileExisted:!1,metaEntry:it(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[it(t.metaEntry)]}}}let c=Ys(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!Ks(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:it(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...it(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=Ys(r.value);let c=Pt(e.library,`${o}.json`);if(!await Zs(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=it(r.value.entries)}let s=n();if(!js.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await Zs(Pt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:JC};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?it(r.value):{},appliedId:s,entries:[...a,i]}}},$$=(e,t)=>{let n=eo(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},rk=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),M$=async(e,t,n,r,o,a,s)=>{let i=rk(),c=Object.fromEntries(Js.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(Xs.map(d=>[d,{original:s?.deployment[d].original??nk(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??it(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await zs(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Tl=e=>({status:"manual",messages:[e]}),B$=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}`)]}},F$=u$(t$),W$=new Set(Rl),H$=async e=>{try{let{stdout:t}=await F$("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return yn(n)?Object.keys(n):void 0}catch{return}},to=async(e,t={})=>{let n=t.readManagedPolicyKeys??H$;for(let r of e.managedPolicies){let o=await f$(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=>Ol(i)&&!W$.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},th=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.`},nh=e=>(e.platform??c$)()==="darwin",ok=async(e,t,n={})=>{if(!nh(n))return Tl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Pl)()&&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=Kt(n),a=await to(o,n);if(a&&r.push({audience:"admin",message:th(a)}),r.length>0)return B$(r);let s=!1,i=!1,c=[o.journal];try{let l=ee(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??S$)())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=h$((n.credentialCommand??(()=>Xf(d)))(),d),p=w$(u),f=await eh(o),h=await zs(o.helper);if(f&&h.present&&h.content!==f.helper.lastWritten&&h.content!==f.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!f&&h.present&&h.content!==p)throw new Error("the Claude Desktop credential helper path contains a foreign file");let m=await N$(o,f,n.randomUUID??e$),w=Pt(o.library,`${m.configId}.json`);c=[o.journal,o.helper,w,...m.metaToWrite?[o.meta]:[],o.appConfig];let y=await gn(w),g=await gn(o.appConfig),b=$$(e,o.helper),k=await M$(o,m,y,g,p,b,f);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 GC(o.journal,k),i=!0,await Ll(o.helper,p,448),k.helper.previousWritten!==void 0&&(delete k.helper.previousWritten,await GC(o.journal,k));let C=it(y.value);for(let I of Js)Zf(C,I,b[I]);await $n(w,C),m.metaToWrite&&await $n(o.meta,m.metaToWrite);let S=it(g.value),E=rk();for(let I of Xs)Zf(S,I,E[I]);return await $n(o.appConfig,S),{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.",...Il]}}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.`]}:Tl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},VC=(e,t,n,r)=>{let o=it(e);for(let a of n){let s=t[a];Ks(nk(e,a),s.lastWritten)?Zf(o,a,s.original):r.push(a)}return o},ak=async(e,t={})=>{if(!nh(t))return{status:"not-found",messages:[]};if((t.appRunning??Pl)())return Tl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=Kt(t);try{let r=await eh(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Pt(n.library,`${r.configId}.json`);if(e.dryRun)return{status:"reverted",messages:[`Would restore Anyray-owned Claude Desktop fields from ${n.journal}, preserving user changes.`]};let a=[],s=await gn(o),i=s.value;s.present&&(i=VC(s.value,r.config,Js,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await gn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let h=Ys(l.value),m=it(l.value.entries),w=m.findIndex(b=>b.id===r.configId),y=w>=0?m[w]:void 0,g=y!==void 0&&Ks(y,r.metaEntry);if(y!==void 0&&!g&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=it(l.value),h===r.configId){let b=r.originalAppliedId;b&&m.some(k=>k.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&g?(m.splice(w,1),d.entries=m):c&&y===void 0&&(d.entries=m)}else{let b=Ks(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&h!==r.configId?(g&&m.splice(w,1),d={...it(l.value),entries:m}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await qo(o,{force:!0}):await $n(o,i)),l.present&&(u?await qo(n.meta,{force:!0}):Ks(l.value,d)||await $n(n.meta,d));let p=await gn(n.appConfig);if(p.present){let h=VC(p.value,r.deployment,Xs,a);!r.deploymentFileExisted&&Object.keys(h).length===0?await qo(n.appConfig,{force:!0}):await $n(n.appConfig,h)}else r.deploymentFileExisted&&a.push("deployment config file");let f=await zs(n.helper);return f.present&&(f.content===r.helper.lastWritten||f.content===r.helper.previousWritten)?r.helper.original.present?await Ll(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await qo(n.helper,{force:!0}):(f.present||r.helper.original.present)&&a.push("credential helper"),await qo(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?[]:xl]}}catch(r){return Tl(`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.`)}},rh=async(e,t={})=>{if(!nh(t))return!1;let n=Kt(t);if(await to(n,t))return!1;try{let r=await gn(n.meta);if(!r.present)return!1;let o=Ys(r.value),a=await gn(Pt(n.library,`${o}.json`)),s=await gn(n.appConfig);if(!a.present||!s.present)return!1;await _l(n.helper,jC.X_OK);let i=Wt(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}},sk=async(e={})=>{try{let t=Kt(e),n=await zs(t.helper);if(!n.present||typeof n.content!="string")return;let r=tk(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},ik=async(e,t={})=>{if(!await rh(e,t))return!1;let n=Kt(t);try{let r=await eh(n);if(!r)return!1;let o=await gn(n.meta);if(!o.present||Ys(o.value)!==r.configId)return!1;let a=await zs(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=tk(a.content??"");return s?await(t.helperLauncherAvailable??E$)(s):!1}catch{return!1}};import{createHash as vk,randomUUID as Sk}from"node:crypto";import{spawn as U$,spawnSync as G$}from"node:child_process";import{link as dh,mkdir as oh,open as Ek,readFile as ah,readdir as Ik,rename as xk,rm as jt,stat as Rk}from"node:fs/promises";import{homedir as uh}from"node:os";import{basename as Ok,dirname as Qs,join as sa,win32 as V$}from"node:path";import{isDeepStrictEqual as ea}from"node:util";var Oe="HKCU\\SOFTWARE\\Policies\\Claude",qs="HKLM\\SOFTWARE\\Policies\\Claude",Bl=5,ia="inferenceGatewayApiKey",Te=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ia],ck=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ia],lk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ia],dk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ia],Tk="Managed by anyray-connect; dynamic credential only.",K$=e=>/^[A-Za-z]:[\\/]/.test(e)&&V$.isAbsolute(e),uk=e=>{if(!K$(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)},_k=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!uk(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&&!uk(e.args[0]))throw new Error("the credential helper does not use print-key --json")},ph=(e={})=>sa((e.home??uh)(),".anyray","bin","claude-desktop-credential-helper.cmd"),j$=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},Z$=e=>(_k(e),["@echo off",`REM ${Tk}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(j$).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
205
|
-
`)),
|
|
206
|
-
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${
|
|
200
|
+
`)||n.includes("\r"))return;let r=qf(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Pl(o);if(!qo(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!qo(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return XC(i)===e?i:void 0}catch{return}},y$=e=>{if(!e.startsWith(f$))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=qf(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==mr)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return zC(a)===e?a:void 0}catch{return}},g$=`#!/bin/sh
|
|
201
|
+
# Anyray subscription pass-through credential helper`,w$=e=>{let t=Pl(e.command);if(!(!qo(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!qo(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=$(${zf(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(`
|
|
202
|
+
`)},b$=e=>{if(!e.startsWith(g$))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=qf(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return w$(a)===e?a:void 0},qC=e=>h$(e)??y$(e)??b$(e),A$=async()=>{let e=UC("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},C$=async e=>{let t=[e.command,...Pl(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>VC(r)))).every(r=>r.isFile())?(await Tl(e.command,GC.X_OK),!0):!1}catch{return!1}},k$=0,Dl=async(e,t,n)=>{await QN(KC(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${k$++}.tmp`;try{await n$(r,t,{mode:n}),await qN(r,n),await t$(r,e)}catch(o){throw await zo(r,{force:!0}).catch(()=>{}),o}},$n=async(e,t)=>{await Dl(e,`${JSON.stringify(t,null,2)}
|
|
203
|
+
`,384)},gn=async e=>{if(!await Zs(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await Yf(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!yn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},zs=async e=>{if(!await Zs(e))return{present:!1};let t=await VC(e);return{present:!0,content:await Yf(e,"utf-8"),mode:t.mode&511}},QC=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:it(e[t])}:{present:!1},Zf=(e,t,n)=>{n.present?e[t]=it(n.value):delete e[t]},MC=e=>yn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),v$=e=>yn(e)&&MC(e.original)&&MC(e.lastWritten),S$=e=>yn(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),BC=(e,t)=>yn(e)&&t.every(n=>v$(e[n])),I$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],E$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],Qf=(e,t,n,r)=>!(!yn(e)||e.version!==n||typeof e.configId!="string"||!js.test(e.configId)||typeof e.metaFileExisted!="boolean"||e.originalAppliedId!==void 0&&(typeof e.originalAppliedId!="string"||!js.test(e.originalAppliedId))||e.metaFileExisted!==(e.originalAppliedId!==void 0)||!yn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==jC||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!BC(e.config,r)||r.some(o=>e.config[o].original.present)||!BC(e.deployment,Xs)||!yn(e.helper)||e.helper.path!==t.helper||!S$(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),x$=(e,t)=>Qf(e,t,Jf,Js),R$=(e,t)=>Qf(e,t,2,I$),O$=(e,t)=>Qf(e,t,3,E$),T$=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),FC=e=>({...e,version:Jf,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),em=async e=>{if(!await Zs(e.journal))return;let t;try{t=JSON.parse(await Yf(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(x$(t,e))return t;if(O$(t,e))return FC(t);if(R$(t,e))return FC(T$(t));throw new Error(`${e.journal} is not a valid ownership journal`)},WC=async(e,t)=>{await Dl(e,`${JSON.stringify(t,null,2)}
|
|
204
|
+
`,384)},Ys=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!js.test(t)||!Array.isArray(n))throw new Error("Claude config-library metadata has an invalid shape");let r=new Set;for(let o of n){if(!yn(o)||typeof o.id!="string"||!js.test(o.id)||typeof o.name!="string"||r.has(o.id))throw new Error("Claude config-library metadata has an invalid entry");r.add(o.id)}if(!r.has(t))throw new Error("Claude config-library appliedId is not in entries");return t},_$=async(e,t,n)=>{let r=await gn(e.meta);if(t){if(!r.present){if(t.metaFileExisted)throw new Error("Claude config-library metadata disappeared after apply");return{configId:t.configId,meta:r,metaFileExisted:!1,metaEntry:it(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[it(t.metaEntry)]}}}let c=Ys(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!Ks(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:it(t.metaEntry),...c===t.configId?{}:{metaToWrite:{...it(r.value),appliedId:t.configId}}}}let o,a=[];if(r.present){o=Ys(r.value);let c=Dt(e.library,`${o}.json`);if(!await Zs(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=it(r.value.entries)}let s=n();if(!js.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await Zs(Dt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:jC};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?it(r.value):{},appliedId:s,entries:[...a,i]}}},P$=(e,t)=>{let n=eo(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},ek=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),D$=async(e,t,n,r,o,a,s)=>{let i=ek(),c=Object.fromEntries(Js.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(Xs.map(d=>[d,{original:s?.deployment[d].original??QC(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??it(t.metaEntry),configFileExisted:!1,config:c,deploymentFileExisted:s?.deploymentFileExisted??r.present,deployment:l,helper:{path:e.helper,original:s?.helper.original??await zs(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Ol=e=>({status:"manual",messages:[e]}),L$=e=>{let t=[...e.filter(n=>n.audience==="user"),...e.filter(n=>n.audience==="admin")];return{status:"manual",manualAudience:t.some(n=>n.audience==="user")?"user":"admin",messages:t.length===1?[t[0].message]:[`Not configured \u2014 ${t.length} things are in the way:`,...t.map((n,r)=>`${r+1}. ${n.message}`)]}},N$=i$(zN),$$=new Set(xl),M$=async e=>{try{let{stdout:t}=await N$("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return yn(n)?Object.keys(n):void 0}catch{return}},to=async(e,t={})=>{let n=t.readManagedPolicyKeys??M$;for(let r of e.managedPolicies){let o=await l$(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=>Rl(i)&&!$$.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},tm=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.`},nm=e=>(e.platform??o$)()==="darwin",tk=async(e,t,n={})=>{if(!nm(n))return Ol("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??_l)()&&r.push({audience:"user",message:"Claude Desktop is running. Fully quit it, then re-run connect so its cached state cannot overwrite the change."});let o=jt(n),a=await to(o,n);if(a&&r.push({audience:"admin",message:tm(a)}),r.length>0)return L$(r);let s=!1,i=!1,c=[o.journal];try{let l=ee(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??A$)())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=d$((n.credentialCommand??(()=>Xf(d)))(),d),p=m$(u),f=await em(o),m=await zs(o.helper);if(f&&m.present&&m.content!==f.helper.lastWritten&&m.content!==f.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!f&&m.present&&m.content!==p)throw new Error("the Claude Desktop credential helper path contains a foreign file");let h=await _$(o,f,n.randomUUID??XN),w=Dt(o.library,`${h.configId}.json`);c=[o.journal,o.helper,w,...h.metaToWrite?[o.meta]:[],o.appConfig];let y=await gn(w),g=await gn(o.appConfig),b=P$(e,o.helper),k=await D$(o,h,y,g,p,b,f);if(t.dryRun)return{status:"configured",messages:[`Would create or update Claude Desktop's dedicated Anyray profile ${h.configId} for ${e.anthropicBaseUrl}, activate it in third-party mode, and install a ${l?"subscription pass-through":"dynamic API-billed"} credential helper at ${o.helper}.`]};s=!0,await WC(o.journal,k),i=!0,await Dl(o.helper,p,448),k.helper.previousWritten!==void 0&&(delete k.helper.previousWritten,await WC(o.journal,k));let C=it(y.value);for(let E of Js)Zf(C,E,b[E]);await $n(w,C),h.metaToWrite&&await $n(o.meta,h.metaToWrite);let S=it(g.value),I=ek();for(let E of Xs)Zf(S,E,I[E]);return await $n(o.appConfig,S),{status:"configured",changedFiles:[o.journal,o.helper,w,...h.metaToWrite?[o.meta]:[],o.appConfig],messages:[`Configured Claude Desktop's native local gateway profile \u2192 ${e.anthropicBaseUrl}.`,l?`Installed a subscription pass-through credential helper at ${o.helper}; the helper reads your Claude Code subscription token on demand and no credential is stored in Claude's config.`:`Installed a dynamic credential helper at ${o.helper}; no gateway key is stored in Claude's config.`,l?"Claude Desktop Gateway requests now ride your Claude subscription through Anyray for content-free metering and optimization. Stay signed in to Claude Code so the token remains available.":"Claude Desktop uses its API-billed third-party inference lane; its first-party subscription remains separate.","Fully quit and reopen Claude Desktop to load the change.",...Il]}}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.`]}:Ol(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},HC=(e,t,n,r)=>{let o=it(e);for(let a of n){let s=t[a];Ks(QC(e,a),s.lastWritten)?Zf(o,a,s.original):r.push(a)}return o},nk=async(e,t={})=>{if(!nm(t))return{status:"not-found",messages:[]};if((t.appRunning??_l)())return Ol("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=jt(t);try{let r=await em(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Dt(n.library,`${r.configId}.json`);if(e.dryRun)return{status:"reverted",messages:[`Would restore Anyray-owned Claude Desktop fields from ${n.journal}, preserving user changes.`]};let a=[],s=await gn(o),i=s.value;s.present&&(i=HC(s.value,r.config,Js,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await gn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let m=Ys(l.value),h=it(l.value.entries),w=h.findIndex(b=>b.id===r.configId),y=w>=0?h[w]:void 0,g=y!==void 0&&Ks(y,r.metaEntry);if(y!==void 0&&!g&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=it(l.value),m===r.configId){let b=r.originalAppliedId;b&&h.some(k=>k.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&g?(h.splice(w,1),d.entries=h):c&&y===void 0&&(d.entries=h)}else{let b=Ks(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&m!==r.configId?(g&&h.splice(w,1),d={...it(l.value),entries:h}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await zo(o,{force:!0}):await $n(o,i)),l.present&&(u?await zo(n.meta,{force:!0}):Ks(l.value,d)||await $n(n.meta,d));let p=await gn(n.appConfig);if(p.present){let m=HC(p.value,r.deployment,Xs,a);!r.deploymentFileExisted&&Object.keys(m).length===0?await zo(n.appConfig,{force:!0}):await $n(n.appConfig,m)}else r.deploymentFileExisted&&a.push("deployment config file");let f=await zs(n.helper);return f.present&&(f.content===r.helper.lastWritten||f.content===r.helper.previousWritten)?r.helper.original.present?await Dl(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await zo(n.helper,{force:!0}):(f.present||r.helper.original.present)&&a.push("credential helper"),await zo(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?[]:El]}}catch(r){return Ol(`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.`)}},rm=async(e,t={})=>{if(!nm(t))return!1;let n=jt(t);if(await to(n,t))return!1;try{let r=await gn(n.meta);if(!r.present)return!1;let o=Ys(r.value),a=await gn(Dt(n.library,`${o}.json`)),s=await gn(n.appConfig);if(!a.present||!s.present)return!1;await Tl(n.helper,GC.X_OK);let i=Ht(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}},rk=async(e={})=>{try{let t=jt(e),n=await zs(t.helper);if(!n.present||typeof n.content!="string")return;let r=qC(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},ok=async(e,t={})=>{if(!await rm(e,t))return!1;let n=jt(t);try{let r=await em(n);if(!r)return!1;let o=await gn(n.meta);if(!o.present||Ys(o.value)!==r.configId)return!1;let a=await zs(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=qC(a.content??"");return s?await(t.helperLauncherAvailable??C$)(s):!1}catch{return!1}};import{createHash as Ak,randomUUID as Ck}from"node:crypto";import{spawn as B$,spawnSync as F$}from"node:child_process";import{link as dm,mkdir as om,open as kk,readFile as am,readdir as vk,rename as Sk,rm as Zt,stat as Ik}from"node:fs/promises";import{homedir as um}from"node:os";import{basename as Ek,dirname as Qs,join as aa,win32 as W$}from"node:path";import{isDeepStrictEqual as Qo}from"node:util";var Te="HKCU\\SOFTWARE\\Policies\\Claude",qs="HKLM\\SOFTWARE\\Policies\\Claude",Ml=5,sa="inferenceGatewayApiKey",Pe=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",sa],ak=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",sa],sk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",sa],ik=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",sa],xk="Managed by anyray-connect; dynamic credential only.",H$=e=>/^[A-Za-z]:[\\/]/.test(e)&&W$.isAbsolute(e),ck=e=>{if(!H$(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)},Rk=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!ck(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&&!ck(e.args[0]))throw new Error("the credential helper does not use print-key --json")},pm=(e={})=>aa((e.home??um)(),".anyray","bin","claude-desktop-credential-helper.cmd"),U$=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},G$=e=>(Rk(e),["@echo off",`REM ${xk}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(U$).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
205
|
+
`)),V$=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},Ok=e=>{let t=e.split(`\r
|
|
206
|
+
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${xk}`||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(V$);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return Rk(s),s}catch{return}},K$=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>Ik(r)))).every(r=>r.isFile())}catch{return!1}},j$=async(e,t)=>{let n=Ok(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??K$)(n)}catch{return!1}},sm=e=>({sha256:no(e),content:e}),lk=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Lt(t,["sha256","content"])&&eM(t.sha256)&&typeof t.content=="string"&&no(t.content)===t.sha256&&Ok(t.content)!==void 0},fm=()=>{let e=F$("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??"")},Z$=async(e,t)=>{await om(Qs(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await kk(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await dm(n,e)}finally{await Zt(n,{force:!0}).catch(()=>{})}},Y$=e=>`${Ek(e)}.anyray-old-`,J$=e=>`${e}.anyray-old-${process.pid}-${Ck()}`,Tk=async(e,t)=>{try{await dm(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await Zt(t,{force:!0}),!0},Nl=async(e,t,n,r,o)=>{let a=J$(e),s=n===void 0?void 0:no(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${Ck()}`,c=!1;try{if(i&&n!==void 0){let d=await kk(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 Sk(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await ra(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await dm(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await oa(e)!==s))throw new Error("credential helper publication verification failed");await Zt(a,{force:!0}),c=!1}catch(l){throw c&&await Tk(e,a).catch(()=>!1),l}finally{i&&await Zt(i,{force:!0}).catch(()=>{})}},im=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,X$=String.raw`
|
|
207
207
|
$ErrorActionPreference = 'Stop'
|
|
208
208
|
try {
|
|
209
209
|
$request = ConvertFrom-Json ([Console]::In.ReadToEnd())
|
|
@@ -272,16 +272,16 @@ try {
|
|
|
272
272
|
exit 5
|
|
273
273
|
} catch {
|
|
274
274
|
exit 6
|
|
275
|
-
}`,Bn=async e=>new Promise((t,n)=>{let r=
|
|
276
|
-
`)}catch(a){if(a.code!=="EEXIST")throw await
|
|
277
|
-
`;t.writeJournalFile?await t.writeJournalFile(n,r):await we(n,r)},pM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,fM=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),hM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),mM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),yM=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===mM(t).toUpperCase(),Ck=(e,t,n,r,o)=>{let a=Te.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},gM=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,wM=(e,t)=>{if(!Ol(e,!0))return!1;let n=gM(t);if(hM.has(n))return!1;if(fM.has(n))return n==="REG_EXPAND_SZ"?!0:!MC(e,!0)},bM=(e,t)=>{let n=Lk(),r=!1,o=!1,a=!1,s=t.toUpperCase()===qs.toUpperCase(),i=(l,d)=>{if(!s)return;let u=wM(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),Ck(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||yM(d,t))continue;let u=pM.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),Ck(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Mn=async(e,t=Oe)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:Lk(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return bM(n.stdout,t)},yr=async e=>{let t=await Mn(e,qs);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...Te.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},wh=e=>e.unparsed?`This machine may have a Claude policy under ${qs} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${qs} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${qs} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Wl=(e,t)=>mr(eo(e,t)),Nk=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],AM=(e,t)=>{let n=Wl(e,t);return Object.fromEntries(Te.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},CM=(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}}),kM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,ch=e=>Object.fromEntries(Te.map(t=>[t,rM(t,e[t])])),kk=(e,t,n,r)=>({version:Bl,registryKey:Oe,keyExisted:e,lastWritten:ch(t),helper:{path:n,lastWritten:sh(r)}}),vM=(e,t,n,r,o,a)=>({version:Bl,registryKey:Oe,keyExisted:e,lastWritten:ch(t),pending:ch(n),helper:{path:r,...o?{lastWritten:sh(o)}:{},pending:sh(a)}}),lh=(e,t,n)=>ta(n,e.lastWritten[t])||e.pending!==void 0&&ta(n,e.pending[t]),oa=async e=>{try{let t=await ah(e,"utf8");return{content:t,sha256:no(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},aa=async e=>(await oa(e))?.sha256,na=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Ml=async(e,t)=>{let n=q$(e),r;try{r=await Ik(Qs(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>sa(Qs(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([oa(e),oa(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!na(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await Dk(e,a))throw new Error("credential helper changed during recovery");return}if(t&&na(t,s.sha256)&&na(t,i.sha256)){await jt(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},bh=async(e,t,n)=>(n.present?await e(Nk(Oe,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Oe,"/v",t,"/f"])).code===0,SM=async(e,t,n)=>{let r=!0,o=await Mn(e);for(let a of Te)if(!ea(o.values[a],t[a])){if(!ea(o.values[a],n[a])){r=!1;continue}await bh(e,a,t[a])||(r=!1),o=await Mn(e)}return r&&Te.every(a=>ea(o.values[a],t[a]))},qe=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Lt(n)]}}),$k=async(e,t,n,r={})=>{if(!Ee(t))return qe("A valid personal ark_ gateway key is required.",!1,r);let o=ph(r),a;try{a=Z$((r.credentialCommand??Xf)())}catch{return qe("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=no(a),i=r.runReg??Bn,c=Lt(r),l;if(!n.dryRun)try{l=await hh(r)}catch(m){return qe(m instanceof ra?"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,p,f,h=!1;try{let m=await yr(i);if(m)return qe(wh(m),!1,r);let w=await gh(r,!n.dryRun);n.dryRun||await Ml(o,w);let y=await Mn(i),g=AM(e,o),b=await oa(o),k=b?.sha256,C=!1;if(d=w,u=y,p=g,w){let I=Te.find(R=>!lh(w,R,y.values[R]));if(I)return qe(`Claude's ${I} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(k!==void 0&&!na(w,k))return qe(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);C=kM(w)}else{if(k!==void 0&&k!==s)return qe(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let I=y.foreignState||Te.some(W=>y.values[W].present),R=Te.every(W=>ea(y.values[W],g[W])),P=Te.every(W=>ea(y.values[W],CM(e,t.trim())[W]));if(I&&!R&&!P)return qe(`Existing Claude third-party-inference policy values under ${Oe} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(C=P,R&&k===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Oe} into an owner-only journal without rewriting them.`]}:(await Nl(kk(y.keyPresent,g,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Oe} into the ownership journal.`]})}if(C){let I=!0;try{I=(r.appRunning??fh)()}catch{}if(I)return qe("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let S=vM(w?.keyExisted??y.keyPresent,y.values,g,o,b?.content,a);if(f=S,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${Oe}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Nl(S,r),h=!0;for(let I of Te){let R=await Mn(i);if(!ta(R.values[I],S.lastWritten[I])&&!ta(R.values[I],S.pending[I]))throw new Error("registry value changed during apply");if(!ea(R.values[I],g[I])&&!await bh(i,I,g[I]))throw new Error("registry write failed")}let E=await Mn(i);if(!Te.every(I=>ta(E.values[I],S.pending[I])))throw new Error("registry verification failed");if(k!==s&&(k===void 0?await z$(o,a):await $l(o,k,a,"apply",r)),await aa(o)!==s)throw new Error("credential helper verification failed");return await Nl(kk(S.keyExisted,g,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Oe}.`,`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.",...Il]}}catch{if(!h||!u||!p||!f)return qe("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Ml(o,f);let m=!0,w=await oa(o),y=f.helper.pending;if(w?.sha256!==f.helper.lastWritten?.sha256&&(y!==void 0&&w?.sha256===y.sha256?f.helper.lastWritten?(await $l(o,y.sha256,f.helper.lastWritten.content,"rollback",r),m=await aa(o)===f.helper.lastWritten.sha256):await $l(o,y.sha256,void 0,"rollback",r):m=w===void 0&&f.helper.lastWritten===void 0),m&&await SM(i,u.values,p))return d?await Nl(d,r):await jt(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?.()}},Mk=async(e,t={})=>{let n=t.runReg??Bn,r=Lt(t),o;if(!e.dryRun)try{o=await hh(t)}catch(a){return qe(a instanceof ra?"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 gh(t,!e.dryRun);a&&!e.dryRun&&await Ml(a.helper.path,a);let s=await Mn(n);if(!a)return Te.filter(h=>s.values[h].present).length>0?qe(`Claude policy values exist under ${Oe}, 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=Te.filter(f=>s.values[f].present&&!lh(a,f,s.values[f])),c=await aa(a.helper.path),l=c!==void 0&&!na(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Oe}.`,`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 f of Te){let m=(await Mn(n)).values[f];if(m.present){if(!lh(a,f,m)){u.add(f);continue}await bh(n,f,{present:!1})||(d=!0)}}let p=await aa(a.helper.path);if(p!==void 0)if(na(a,p))try{await $l(a.helper.path,p,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 jt(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Oe}.`,"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?[]:xl]})}catch{return qe(`Could not safely inspect or revert ${Oe}; no unproven value was removed.`,!1,t)}finally{await o?.()}},Bk=async(e,t={})=>{let n=t.runReg??Bn;if(!await x(Lt(t)))return;let r;try{r=await hh(t);let o=await gh(t);if(o&&await Ml(o.helper.path,o),!o||o.pending||await yr(n)!==void 0)return;let a=await Mn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Wt(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&Te.every(l=>ta(a.values[l],o.lastWritten[l]))))return;let i=await aa(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 X$(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?.()}},Fk=async(e,t={})=>await Bk(e,t)!==void 0,Wk=async(e,t={})=>await Bk(e,t)==="dynamic";var ca=(e=IM())=>e==="win32"?fh:Pl,Ah="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",Ul=async(e,t={})=>{let n=(t.profileRoot??Qr)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Ah};if((t.appRunning??ca(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await Hk.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 El(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 "+Ah}:{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??TC)();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=Hl(t.stagingRoot??xM(),`anyray-history-${process.pid}-${EM()}`);try{let s=await(t.runImporter??_C)({binary:o,exportPath:e,configDir:Hl(a,"config"),workDir:Hl(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. "+Ah};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 DC(r.dir,s.conversations),c=await LC({stagedProjectsDir:Hl(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 Hk.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as kt}from"node:fs";import{homedir as JM}from"node:os";import{join as Yt,sep as XM}from"node:path";import{isDeepStrictEqual as jl}from"node:util";import{constants as RM}from"node:fs";import{promises as G}from"node:fs";import{dirname as la,isAbsolute as kh,join as te,relative as Gl,resolve as Zt,sep as ei}from"node:path";import{randomUUID as Zl}from"node:crypto";var wn=448,ti=384,Kk=448,OM=4,vh=3e4,jk=5e3,TM=10*6e4,Ch=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),ct=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ni=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),Zk=(e,t)=>{let n=Gl(Zt(e),Zt(t));return n===""||!n.startsWith(`..${ei}`)&&n!==".."&&!kh(n)},ro=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return ct(n)?{raw:t,value:n}:void 0}catch(t){return Ct(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},Ct=e=>e instanceof Error&&"code"in e,_M=e=>{try{return process.kill(e,0),!0}catch(t){return Ct(t)&&t.code==="EPERM"}},Yk=e=>e===0?"owner.json":`owner.${e}.json`,Vl=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 p=Number(u[1]);return Number.isSafeInteger(p)&&p>0?{name:d,generation:p}: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"));ct(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}},Jk=e=>{if(e.pid===void 0||!_M(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>vh&&t-e.createdAtMs>TM},PM=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(la(t),{recursive:!0,mode:wn});let n=Zl(),r,o=!1;try{await G.mkdir(t,{mode:wn}),o=!0}catch(i){if(!Ct(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Vl(t);if(d){if(!Jk(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await G.stat(t).then(p=>Date.now()-p.mtimeMs).catch(()=>0)<=vh)return}let l=te(t,Yk(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
278
|
-
`,{flag:"wx",mode:ti}),r=l}catch(d){if(
|
|
279
|
-
`,{mode:ti,flag:"wx"}),await G.rename(a,e)}catch(s){try{await G.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},
|
|
280
|
-
`,{flag:"wx",mode:ti}),o=u}catch(p){if(
|
|
281
|
-
`)}},Ih=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),cv=async e=>{let t=[];for(let n of QM)t.push({lane:n,sources:await tB(e,n)});return t},lv=async(e={})=>{let t=(e.firstPartyRoot??(()=>Us()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([cv(t),Sh(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=Ih(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}},oo=async(e={})=>{let t=(e.home??JM)(),n=(e.firstPartyRoot??(()=>Us()))(),r=(e.thirdPartyRoot??(()=>Qr()))();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??ca())())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([cv(n),Sh(n)]),s;if(e.account){let f=e.account;for(let w of o)w.sources=w.sources.filter(y=>y.account.startsWith(f));let h=a.accounts.filter(w=>w.startsWith(f));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 "${f}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let m=Ih(o);for(let w of h)m.add(w);if(m.size>1)return av(o,e.command??"anyray-connect desktop --migrate",`"${f}" matches ${m.size} accounts`,h);s=[...m]}else if(!e.allAccounts){let f=Ih(o);for(let h of a.accounts)f.add(h);if(f.size>1)return av(o,e.command??"anyray-connect desktop --migrate",`the previous Claude Desktop profile holds local data for ${f.size} accounts`,a.accounts);s=[...f]}let i=e.command??"anyray-connect desktop --migrate",c=!await zM(r),l=await rv(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:f,sources:h}of o){if(h.length===0){d.push(Eh(f));continue}let m=await nB(r,f);if("missing"in m){u.push({lane:f,reason:m.missing,waiting:h.reduce((w,y)=>w+y.ids.length,0)}),d.push(Eh(f));continue}d.push(await aB(f,h,m.dir,t))}if(!(d.some(f=>f.migrated>0||f.alreadyPresent>0)||l.outcomes.some(f=>f.migrated>0||f.alreadyPresent>0||f.conflicts>0))&&(u.length>0||l.blocked.length>0)){let f=u[0];return f?{ok:!1,kind:f.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:f.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${f.lane} store`:`Claude Desktop has no ${f.lane} store in its third-party profile yet`,remedy:xh(f.reason,f.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 iB=e=>[Ge(e)],dv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...iB(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await x(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var uv="1.21459.0",uB=dB(cB),pB=async e=>{try{let{stdout:t}=await uB("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},fB=async e=>{try{return await lB(e)}catch{return}},pv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",hB=["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."],da=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(fv??=hv({}),fv):hv(e),fv,hv=async e=>{let t=(e.home??oi)(),n=["/Applications/Claude.app",bn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??pB,o=e.readClaudeAppBundle??fB;for(let a of n){let s=await r(bn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${pv}`}),c=vl(s,uv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${uv} or newer.`);let l=await o(bn(a,"Contents","Resources","app.asar"));return l?XC.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. ${pv}`}},Xl="anyray",gv="--anyray-owner=claude-desktop-v1",zl=(e={})=>{let t=(e.platform??gr)(),n=(e.home??oi)();return t==="darwin"?Kt(e).appConfig:t==="win32"?bn(process.env.APPDATA??bn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):bn(n,".config","Claude","claude_desktop_config.json")},Ph=(e={})=>bn((e.home??oi)(),"Library","Application Support","Claude","claude_desktop_config.json"),wv=()=>{let e=Ue("profile");return{command:e.command,args:[...e.args,gv]}},ao=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),bv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},mB=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),yB=e=>{if(!ao(e)||!bv(e,["command","args"]))return!1;let t=wv();return e.command===t.command&&mB(e.args,t.args)},gB=e=>ao(e)&&Array.isArray(e.args)&&e.args.at(-1)===gv,wB=e=>{if(!ao(e)||!bv(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||He(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===Jn&&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!He(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},bB=e=>e===void 0?"absent":yB(e)?"exact":gB(e)||wB(e)?"stale-owned":"foreign",$e=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},so=async e=>{let t=await x(e),n;try{n=await B(e)}catch{throw new $e(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!ao(n.mcpServers))throw new $e(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(ao(n.mcpServers)?n.mcpServers:void 0)?.[Xl];return{path:e,fileExisted:t,json:n,entry:o,ownership:bB(o)}},ql=e=>{if(e.ownership==="foreign")throw new $e(`MCP name conflict in ${e.path}: mcpServers.${Xl} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},Av=(e,t)=>{let n={...e},r=ao(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[Xl]:r[Xl]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Oh=async(e,t)=>{if(Rh(e.entry,t))return;let n=await so(e.path);if(!Rh(n.entry,e.entry))throw new $e(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await $n(e.path,Av(n.json,t)),{reading:e,afterEntry:t}},Th=async e=>{let t=await so(e.reading.path);if(!Rh(t.entry,e.afterEntry))throw new $e(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=Av(t.json,e.reading.entry);await $n(e.reading.path,n)},AB=async e=>{if(!ce())throw new $e(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Re()} is temporary); no inference setting was changed.`);let t=await so(zl(e));ql(t);let n=Ph(e),r=(e.platform??gr)()==="darwin"&&n!==t.path?await so(n):void 0;return r&&ql(r),{active:t,...r?{legacy:r}:{}}},mv=async e=>{let t=await so(zl(e));ql(t);let n=Ph(e),r=(e.platform??gr)()==="darwin"&&n!==t.path?await so(n):void 0;return r&&ql(r),{active:t,...r?{legacy:r}:{}}},CB=async e=>{let t=[];try{let n=await Oh(e.active,wv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Oh(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Th(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new $e(`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 Th(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new $e(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},kB=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Oh(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Th(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new $e(`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)},yv=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)."]},vB={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},Ql="claude-desktop",_h="migrate",Cv=new Set(["app-running","store-missing"]),SB={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},EB={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"}},IB="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",kv=e=>{let t=(e.platform??gr)(),n=e.home??oi;return{home:n,appRunning:e.appRunning??ca(t),firstPartyRoot:()=>Us({home:n,runtimePlatform:t}),thirdPartyRoot:()=>Qr({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},vv=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=SB[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.`:"")},Sv=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=EB[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.`:"")},ri=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=kv(e),r=await(e.pendingDesktopMigrationCount??lv)(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??oo)(n);if(a.ok){let c=vv(a.lanes),l=Sv(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,p=(a.blocked??[]).filter(g=>g.reason!=="ambiguous"),f=a.blockedAssets??[],h=a.retryableAssets??[];if(p.length===0&&f.length===0&&h.length===0)return[c,l,u].filter(g=>!!g);if(t.preservePendingOp)return[c,l,u].filter(g=>!!g);await gs(Ql,_h);let m=p.reduce((g,b)=>g+b.waiting,0),w=[m>0?`${m} more session${m===1?"":"s"}`:"",f.length>0?`${f.length} extension ${f.length===1?"store":"stores"}`:""].filter(Boolean),y=[...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]:[],...y]}if(!Cv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
|
|
282
|
-
${a.remedy}`];if(t.preservePendingOp)return[];await gs(Ql,_h);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."]}},xB=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await or(Ql),[]}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."]}},RB=e=>dv({id:Ql,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??gr)(),n=(e.home??oi)();return t==="darwin"?["/Applications/Claude.app",bn(n,"Applications","Claude.app")]:t==="win32"?[bn(process.env.LOCALAPPDATA??bn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>ee(t,"anthropic")?["Claude Desktop subscription routing requires automatic setup on a verified macOS build and a Claude Code sign-in in Keychain.","This platform/build has no verified subscription helper seam, so Connect left inference unchanged instead of silently switching you to API billing.","To opt into the API-billed Gateway lane instead, re-run Connect in org/API mode and use:",...yv(t)]:["Claude desktop org/API lane:",...yv(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`."]}),OB=(e={})=>{let t=RB(e),n=()=>(e.platform??gr)()==="darwin",r=()=>(e.platform??gr)()==="win32",o=(s,i)=>n()?ok(s,i,e):$k(s,s.clientKey??"",i,e),a=s=>n()?ak(s,e):Mk(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??ca((e.platform??gr)()))(),quitTarget:vB,needsTarget:()=>!1,async complete(s){if(s!==_h)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??oo)(kv(e));if(i.ok){let c=vv(i.lanes),l=Sv(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 p=(i.blocked??[]).filter(m=>m.reason!=="ambiguous"),f=i.blockedAssets??[],h=i.retryableAssets??[];return p.length>0||f.length>0||h.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...p.length>0||f.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 Cv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?ik(s,e):r()?Wk(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let p=Kt(e),f=await to(p,e);if(f)return{status:"manual",manualAudience:"admin",messages:[th(f),...await ri(e,i)]}}if(r()){let p;try{p=await yr(e.runReg??Bn)}catch{return{status:"manual",manualAudience:"admin",messages:[IB,...await ri(e,i)]}}if(p)return{status:"manual",manualAudience:"admin",messages:[wh(p),...await ri(e,i)]}}if(r()&&ee(s,"anthropic"))return{status:"manual",messages:["Claude Desktop subscription routing is not available on Windows: Connect could not verify a supported Claude subscription credential source, so inference was left unchanged instead of switching to API billing.","Use org/API mode for the Windows Gateway lane, or run subscription mode on a verified macOS build after signing in to Claude Code."]};if(n()){let p=await da(e);if(!p.supported)return{status:"manual",messages:[p.message??"Claude Desktop version is unsupported."]}}let c;try{c=await AB(e)}catch(p){let f=p instanceof $e?p.changedFiles:[];return{status:"manual",...f.length>0?{changedFiles:f}:{},messages:[p instanceof $e?p.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 p=c.legacy;return{...l,messages:[...l.messages,`Would register the ownership-marked Anyray retrieval MCP server in ${c.active.path}.`,...p&&p.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${p.path}.`]:[],...await ri(e,i)]}}let d;try{d=await CB(c)}catch(p){let f=p instanceof $e?p.changedFiles:[];return{status:"manual",...f.length>0?{changedFiles:f}:{},messages:[p instanceof $e?p.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 ri(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?hB:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=zl(e),c=await xB(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 mv(e)}catch(m){return l({status:"manual",messages:[m instanceof $e?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 p=await a({dryRun:!1});if(p.status==="manual"){let m=r()?Lt(e):void 0;if(!(m!==void 0&&p.changedFiles?.includes(m)===!0&&!await x(m)))return l(p)}let f;try{f=await kB(await mv(e))}catch(m){let w=m instanceof $e?m.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...p.changedFiles??[],...w])],messages:[...p.messages,m instanceof $e?m.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await re(i);let h=Ph(e);return n()&&h!==i&&await re(h),l({...p,messages:[...p.messages,...f.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...p.changedFiles??[],...f])]})},async mcpStatus(){if(!ce())return{registered:!1,command:null};try{let s=await so(zl(e));return s.ownership!=="exact"||!ao(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 da(e)).supported?rh(s,e):!1:r()?Fk(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await da(e)).supported)return["unknown"];let s=await sk(e);return s?[s]:["unknown"]}if(r())return await x(Lt(e))?await yr(e.runReg??Bn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=Kt(e);return!await x(s.journal)||await to(s,e)?!1:(await da(e)).supported}return r()&&await x(Lt(e))?!await yr(e.runReg??Bn):!1}catch{return!1}}}},Ev=OB();import{homedir as rF}from"node:os";import{join as oF}from"node:path";import{rm as cd}from"node:fs/promises";import{constants as Iv,accessSync as TB,statSync as _B}from"node:fs";import{platform as Dh}from"node:os";import{delimiter as PB,posix as DB,resolve as LB,win32 as NB}from"node:path";var $B="0.59.0",MB="1.1.4",Fn="Anyray \xB7 Claude",Wn="Anyray \xB7 Codex",ed="__anyray-acp-agent",xv=(e,t,n)=>{let{command:r,args:o}=en([ed,e,t,n]);return{command:r,args:o,env:{}}},td=(e=Dh())=>e==="win32"?"npx.cmd":"npx",nd=(e=process.env.PATH,t=Dh())=>{if(!e)return;let n=td(t);for(let r of e.split(PB)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=LB(o,n);try{if(!_B(a).isFile())continue;return TB(a,t==="win32"?Iv.F_OK:Iv.X_OK),a}catch{}}},rd=(e,t=Dh())=>{let n=t==="win32"?NB:DB;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==td(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},BB="https://chatgpt.com/backend-api/codex",FB="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",Rv="ANYRAY_ACP_CODEX_AUTHORIZATION",Ov="ANYRAY_ACP_CODEX_CLIENT_KEY",Tv="ANYRAY_ACP_CODEX_METADATA",_v=e=>pe({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),WB=(e,t={})=>{let n=ee(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":BB,"x-anyray-forward-headers":FB}:{},o=n?{...e.clientKey?{"x-anyray-api-key":Ov}:{}}:{Authorization:Rv};return _v(e)&&(o["x-anyray-metadata"]=Tv),{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}}}:{}}},HB=e=>{let t=ee(e,"openai"),n=_v(e);return{...t?e.clientKey?{[Ov]:e.clientKey}:{}:{[Rv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[Tv]:n}:{}}},Pv=(e,t=td(),n={})=>({[Fn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${$B}`],env:tn(e).env},[Wn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${MB}`],env:{CODEX_CONFIG:JSON.stringify(WB(e,n)),...HB(e)}}}),ai=(e=td(),t="jetbrains")=>({[Fn]:xv("claude",e,t),[Wn]:xv("codex",e,t)}),io=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),od=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as UB}from"node:zlib";import{open as GB,readFile as Bh,readdir as id}from"node:fs/promises";import{dirname as Dv,join as fe}from"node:path";import{homedir as Mv,platform as Fh}from"node:os";var ad="2025.3.2",ua="253.30387.147",si="com.intellij.ml.llm",Lh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),VB=1e4,KB=256*1024*1024,jB=16*1024*1024,Nh=1024*1024,$h=22,ZB=$h+65535,Mh=vl,YB=()=>{let e=Mv(),t=fe(e,".cache","JetBrains","RemoteDev");switch(Fh()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:fe(e,"Applications"),layout:"app-bundles"},{path:fe(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:fe(process.env.LOCALAPPDATA??fe(e,"AppData","Local"),"Programs"),layout:"children"},{path:fe(process.env.LOCALAPPDATA??fe(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:fe(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:fe(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},JB=()=>Fh()==="linux"?fe(Mv(),".local","share","JetBrains"):Ge("JetBrains"),XB=()=>Fh()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),zB=async(e,t=VB)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await id(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=fe(r.path,i.name),l=r.layout==="app-bundles"?fe(c,"Contents","Resources","product-info.json"):fe(c,"product-info.json");await x(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=fe(s,"product-info.json"),l=fe(s,"Contents","Resources","product-info.json");if(await x(c)){n.push(c);return}if(await x(l)){n.push(l);return}let d;try{d=await id(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let p=fe(s,u.name);(u.isDirectory()||u.isSymbolicLink())&&!["bin","jbr","lib","plugins","Contents"].includes(u.name)&&await a(p,i-1)}};await a(r.path,7)}return[...new Set(n)]},qB=e=>{let t=Dv(e);return t.endsWith(`${fe("Contents","Resources")}`)?Dv(t):t},QB=async e=>{try{let t=JSON.parse(await Bh(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!Ws(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:qB(e)}}catch{return}},sd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},eF=async(e,t)=>{let n;try{n=await GB(e,"r");let{size:r}=await n.stat();if(r<$h||r>KB)return;let o=Math.min(r,ZB),a=await sd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-$h;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>jB||c+i>r)return;let l=await sd(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),p=l.readUInt32LE(d+20),f=l.readUInt32LE(d+24),h=l.readUInt16LE(d+28),m=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),y=l.readUInt32LE(d+42),g=d+46+h+m+w;if(g>l.length)return;let b=l.subarray(d+46,d+46+h).toString("utf8");if(d=g,b!==t)continue;if(p===4294967295||f===4294967295||p>Nh||f>Nh)return;let k=await sd(n,30,y);if(!k||k.readUInt32LE(0)!==67324752)return;let C=k.readUInt16LE(26),S=k.readUInt16LE(28),E=await sd(n,p,y+30+C+S);return E?u===0?E.toString("utf8"):u===8?UB(E,{maxOutputLength:Nh}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},Lv=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!Ws(n)))return{id:t,version:n}},tF=async(e,t)=>{let n=fe(e,"META-INF","plugin.xml");if(await x(n))try{let o=Lv(await Bh(n,"utf8"));return{present:o?.id===si||t,descriptor:o?.id===si?o:void 0}}catch{return{present:t}}let r=[];try{r=(await id(fe(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=>fe(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await eF(o,"META-INF/plugin.xml"),s=a?Lv(a):void 0;if(s?.id===si)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},Nv=async e=>{let t;try{t=await id(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Lh.has(o.name.toLowerCase()),i=Lh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Lh.has(o.name.toLowerCase());if(!a){let i=fe(e,o.name,"META-INF","plugin.xml");if(!await x(i))continue}let s=await tF(fe(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},nF=async e=>{try{return(await Bh(fe(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(si)}catch{return!1}},$v=e=>e.reduce((t,n)=>t?(Mh(n,t)??-1)>0?n:t:n,void 0),Bv=async(e={})=>{let t=e.configRoot??Ge("JetBrains"),n=e.userPluginsRoot??JB(),r=await zB(e.productRoots?e.productRoots.map(h=>({path:h,layout:"recursive"})):YB(),e.scanBudget),o=(await Promise.all(r.map(h=>QB(h)))).filter(h=>h!==void 0),a=o.length>0||await x(t);if(e.wsl??XB())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=>(Mh(h.version,ad)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let h of s){let m=fe(t,h.dataDirectoryName);if(!await x(m)){d=!0;continue}let w=[fe(m,"plugins"),fe(n,h.dataDirectoryName),fe(n,h.dataDirectoryName,"plugins")],y;for(let g of[...new Set(w)]){let b=await Nv(g);if(b.present){y=b;break}}if(y??=await Nv(fe(h.root,"plugins")),y.present&&!y.descriptor){l=!0;continue}if(!(!y.descriptor||y.descriptor.id!==si)){if(i.push(y.descriptor.version),await nF(m)){c=!0;continue}if(!((Mh(y.descriptor.version,ua)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${h.version}; AI Assistant ${y.descriptor.version}; ACP supported`,ideVersion:h.version,pluginVersion:y.descriptor.version}}}let u=$v(o.map(h=>h.version)),p=$v(i),f;return a?u?s.length===0?f=`JetBrains IDE ${u} is below the ACP minimum ${ad}; no ACP config was written.`:d?f=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${ad}+ once, enable AI Assistant ${ua}+, then run Connect again. No ACP config was written.`:c?f=`JetBrains AI Assistant is disabled; enable version ${ua}+ and run Connect again. No ACP config was written.`:p?f=`JetBrains AI Assistant ${p} is below the ACP minimum ${ua}; no ACP config was written.`:l?f=`Could not verify the local JetBrains AI Assistant version; require ${ua}+ before running Connect. No ACP config was written.`:f=`JetBrains AI Assistant ${ua}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:f=`Could not prove JetBrains IDE ${ad}+ from local product-info.json; no ACP config was written.`:f="JetBrains IDE config or installation not found",{installed:a,capable:!1,detail:f,ideVersion:u,pluginVersion:p}};var aF=[Fn,Wn],Wh=()=>oF(rF(),".jetbrains","acp.json"),co=()=>`${Wh()}.anyray-state`,sF=(e,t,n="npx")=>{let r=io(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,ai(n,"jetbrains")),{...e,agent_servers:r}},iF=(e,t,n)=>{if(!io(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=io(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of aF)if(c in r){if(!od(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}},cF=(e=Bv)=>({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=Wh(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=nd();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await x(r),c;try{c=await B(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=ai(a,"jetbrains");return await Yi({configPath:r,current:c,next:sF(c,t,a),journalPath:co(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,co()]}},async revert(t){let n=Wh(),r=async()=>{if(!await x(n))return t.dryRun||(await re(n),await cd(co(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await B(n)}catch{return t.dryRun||(await re(n),await cd(co(),{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 B(co());(u.version===1||u.version===2)&&io(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await x(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await B(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await _r(n);let l=iF(o,c,a),d=[];return l.removed.length&&d.push(`Removed ${l.removed.join(", ")} from ${n}.`),l.conflicts.length&&d.push(`Preserved user-modified ACP entries: ${l.conflicts.join(", ")}.`),!t.dryRun&&l.removed.length&&(s&&Object.keys(l.next).length===0?await cd(n,{force:!0}):await Y(n,l.next,{backup:!1})),t.dryRun||(await re(n),await cd(co(),{force:!0}).catch(()=>{})),{status:l.conflicts.length?"manual":"reverted",messages:d.length?d:["No Anyray ACP entries found."],changedFiles:!t.dryRun&&l.removed.length?[n]:void 0}};return t.dryRun?r():Zi(n,co(),r)}}),Fv=cF();import{homedir as dd}from"node:os";import{join as ud}from"node:path";import{rm as Hh}from"node:fs/promises";var Uh="1.0.0",pd=["anyray-claude-acp","anyray-codex-acp"],lF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Gh=()=>ud(dd(),".windsurf","acp","registry.json"),Vh=()=>ud(dd(),".windsurf-next","acp","registry.json"),pa=e=>`${e}.anyray-state`,Wv=e=>({binary:Object.fromEntries(lF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Uv=(e="npx")=>{let t=ai(e,"windsurf");return[{id:pd[0],name:Fn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Wv(t[Fn])},{id:pd[1],name:Wn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Wv(t[Wn])}]},ld=e=>!Array.isArray(e)||e.some(t=>!io(t)||typeof t.id!="string")?null:e,dF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Uh||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:ld(e.agents);if(!n)return null;let r=new Set(pd);return{...e,version:typeof e.version=="string"?e.version:Uh,agents:[...n.filter(o=>!r.has(o.id)),...Uv(t)],extensions:e.extensions??[]}},uF=(e,t,n)=>{let r=ld(e.agents);if(!r)return null;let o=ld(t.agents)??[],a=new Map((ld(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!pd.includes(u.id)){l.push(u);continue}if(!od(u,a.get(u.id))){c.push(u.id),l.push(u);continue}let p=s.get(u.id);p&&l.push(p),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===Uh&&delete d.version,!Object.prototype.hasOwnProperty.call(t,"extensions")&&Array.isArray(d.extensions)&&d.extensions.length===0&&delete d.extensions,{next:d,removed:i,conflicts:c}},Hv=async()=>{let e=[];return(await x(Vh())||await x(ud(dd(),".windsurf-next")))&&e.push(Vh()),(await x(Gh())||await x(ud(dd(),".windsurf"))||await x(Ge("Devin"))||await x(Ge("Windsurf")))&&e.push(Gh()),e},Gv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await Hv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await Hv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=nd();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 B(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=dF(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await x(s),d=Uv(r);await Yi({configPath:s,current:i,next:c,journalPath:pa(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,pa(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(),Vh()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await x(a)){e.dryRun||(await re(a),await Hh(pa(a),{force:!0}).catch(()=>{}));return}let i;try{i=await B(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 f=await B(pa(a));(f.version===1||f.version===2)&&Array.isArray(f.agents)&&(c=f.agents,l=f.version===2&&f.fileExisted===!1,d=f.version===2&&f.fileExisted===!0)}catch{}let u;if(d){let f=`${a}.anyray-bak`;if(!await x(f)){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 B(f)}catch{n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is malformed. Repair it or remove the agents manually.`),o=!0;return}}else u=await _r(a);let p=uF(i,u,c);if(!p){n.push(`Unrecognized ACP registry shape in ${a}; left it unchanged.`),o=!0;return}p.removed.length&&(n.push(`Removed ${p.removed.join(", ")} from ${a}.`),e.dryRun||(l&&Object.keys(p.next).length===0?await Hh(a,{force:!0}):await Y(a,p.next,{backup:!1}),r.push(a))),p.conflicts.length?(n.push(`Preserved user-modified agents: ${p.conflicts.join(", ")}.`),o=!0):e.dryRun||(await re(a),await Hh(pa(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await Zi(a,pa(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var le=[qn,Dw,ks,MA,dC,kC,OC,Fv,Ev,Gv,Hw],pt=e=>le.find(t=>t.id===e);var Me=async(e=D,t=fn)=>{let n=await e();if(!n.gateway||!n.clientKey)return;let r=await t().catch(()=>{});return{target:Ie({origin:n.gateway,clientKey:n.clientKey,subscription:n.authMode==="subscription",placeholder:n.authMode==="placeholder",byoUpstream:n.byoUpstream,seat:r,user:n.name,team:n.team})}};var Kh=5e3,Vv=3e4,pF=1440*60*1e3,fF=e=>new Promise(t=>setTimeout(t,e)),hF=async(e=D,t=fn)=>(await Me(e,t))?.target,mF=e=>pt(e)?.quitGated,Kv=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??mF,o=t.readPending??Gc,a=t.clearPending??Tp,s=t.targetFromProfile??hF,i=t.sleep??fF,c=t.now??Date.now,l=t.maxWaitMs??pF;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),p=c(),f=Kh;for(;;){let h=await o(n);if(!h||c()-p>l)return 0;if(d.isRunning()){await i(f),f=Math.min(Vv,f*2);continue}let m;if(d.needsTarget?.(h.op)&&(m=await s(),!m)){if(await a(n,h)!=="superseded")return 0;await i(f),f=Kh;continue}if((await u(h.op,m,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(f),f=Math.min(Vv,f*2);continue}if(await a(n,h)!=="superseded")return 0;await i(f),f=Kh}}catch{return 0}};import{writeFileSync as pW}from"node:fs";import{chmod as rm,stat as fW}from"node:fs/promises";import{platform as mS}from"node:os";import{dirname as yS,isAbsolute as hW}from"node:path";var yF="https://app.anyray.ai",gF=new Set(["localhost","::1","[::1]"]),wF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,bF=e=>gF.has(e)||wF.test(e),jh=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&bF(t.hostname)},AF=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Hn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!jh(e)?yF:AF(e)};import{createHash as UF,generateKeyPairSync as GF,randomBytes as Jh}from"node:crypto";import{spawn as CF}from"node:child_process";import{createPrivateKey as kF,createPublicKey as vF,sign as SF}from"node:crypto";var EF="/usr/local/lib/anyray-connect/anyray-device-proof",Zh="anyray-device-key-reference:v1:keychain",IF=1e4,xF=96*1024,jv=64*1024,RF=64*1024,OF=4*1024,TF=512,_F=/^[A-Za-z0-9_-]+$/,Yh=async e=>{if(Buffer.byteLength(e,"utf8")>xF)throw new Error("device key helper input is too large");return await new Promise((t,n)=>{let r=CF(EF,[],{stdio:["pipe","pipe","ignore"]}),o=[],a=0,s=!1,i=l=>{s||(s=!0,clearTimeout(c),l())},c=setTimeout(()=>{r.kill("SIGKILL"),i(()=>n(new Error("device key helper timed out")))},IF);r.stdout.on("data",l=>{if(a+=l.length,a>jv){r.kill("SIGKILL"),i(()=>n(new Error("device key helper output is too large")));return}o.push(l)}),r.once("error",()=>{i(()=>n(new Error("could not start the device key helper")))}),r.once("close",l=>{i(()=>{if(l!==0){n(new Error("device key helper refused the request"));return}t(Buffer.concat(o).toString("utf8"))})}),r.stdin.on("error",()=>{i(()=>n(new Error("could not write to the device key helper")))}),r.stdin.end(e)})},PF=e=>e===Zh,fd=e=>{if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>OF)return!1;try{let t=vF(e);return t.type==="public"&&t.asymmetricKeyType==="ec"&&t.asymmetricKeyDetails?.namedCurve==="prime256v1"}catch{return!1}},DF=(e,t)=>typeof e!="string"||e.length===0||e.length>t||!_F.test(e)?!1:Buffer.from(e,"base64url").toString("base64url")===e,lo=class extends Error{constructor(){super("the stored device certificate no longer matches the Mac Keychain key"),this.name="DeviceKeyMismatchError"}},LF=e=>{if(!(Buffer.byteLength(e,"utf8")>jv))try{let t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)||Object.keys(t).length!==4||Object.keys(t).some(n=>!["v","operation","devPublicKey","signature"].includes(n))||t.v!==1||t.operation!=="sign"||!fd(t.devPublicKey)||!DF(t.signature,TF)?void 0:{devPublicKey:t.devPublicKey,signature:t.signature}}catch{return}};var wr=async(e,t,n,r={invokeHelper:Yh})=>{if(!PF(t)){let i=kF(t);return SF(null,new TextEncoder().encode(e),i).toString("base64url")}let o=Buffer.from(e,"utf8");if(o.length===0||o.length>RF)throw new Error("device key signing data is outside the safe limit");if(!fd(n))throw new Error("device key certificate has an invalid public key");let a=await r.invokeHelper(JSON.stringify({v:1,operation:"sign",data:o.toString("base64url")})),s=LF(a);if(!s)throw new Error("device key helper returned an invalid response");if(s.devPublicKey!==n)throw new lo;return s.signature};var NF=["HTTPS_PROXY","https_proxy"],Zv=new Set(["SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_UNTRUSTED"]),Yv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Jv=new Set(["ENOTFOUND","EAI_AGAIN"]),Xv=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),zv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),$F=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 MF(e)},MF=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...Zv,...Yv,...Jv,...Xv,...zv])if(t.includes(n))return n}},BF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",FF=e=>NF.filter(t=>(e[t]??"").trim()!==""),WF=(e,t=process.env)=>{let n=$F(e),r=FF(t);return{kind:n&&Zv.has(n)?"tls-unknown-issuer":n&&Yv.has(n)?"tls-invalid-cert":n&&Jv.has(n)?"dns":BF(e)||n&&zv.has(n)?"timeout":n&&Xv.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},HF=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}},ft=(e,t=process.env)=>HF(WF(e,t));var Xh=1e4,uo=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(uo).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${uo(e[n])}`).join(",")}}`,qv="stable-key-heartbeat-v1",Qv="key-heartbeat",VF=["reapply_config","remint","revert"],zh=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var eS=e=>UF("sha256").update(e).digest("hex"),Ke=e=>typeof e=="string"&&e.trim()?e.trim():void 0,KF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],tS={no_mdm_server_registered:"no MDM server is registered in the Anyray console",agent_missing:"the Anyray endpoint agent is not reporting for this machine",mdm_not_verified:"this machine is not enrolled in the registered MDM",endpoint_unreachable:"the endpoint service could not be reached"},jF=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${tS[e]}. Ask your IT admin.`,ZF=e=>typeof e=="string"&&e in tS,qh=async e=>{try{let t=await e.json(),n=Ke(t?.message),r=Ke(t?.error),o=ZF(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:jF(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},YF=async e=>(await qh(e)).message,ht=class extends Error{status;policyCode;reason;constructor(t,n){let r=typeof n=="string"?{message:n}:n;super(r.code==="managed_device_required"?r.message:`the gateway rejected this enrollment (HTTP ${t}): ${r.message}`),this.name="GatewayVerifyError",this.status=t,this.policyCode=r.code,this.reason=r.reason}},fa=class extends Error{status;policyCode;reason;constructor(t,n){let r=typeof n=="string"?{message:n}:n;super(r.code==="managed_device_required"?r.message:`the gateway rejected this credential heartbeat (HTTP ${t}): ${r.message}`),this.name="GatewayHeartbeatError",this.status=t,this.policyCode=r.code,this.reason=r.reason}},Qh=async(e,t,n,r,o)=>{try{return await o(uo(e),t,n)}catch(a){throw a instanceof lo?a:new Error(`developer ${r} failed: could not sign the challenge with the provided private key`)}},hd=()=>{let{publicKey:e,privateKey:t}=GF("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},Jt=async(e,t,n,r={})=>{let o=r.timeoutMs??Xh,a=`${e}/connect/verify`,s=Ke(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:Jh(16).toString("hex"),...zh(t,r.machineUuid)},c=await Qh(i,n,t.payload.devPublicKey,"verification",r.signer??wr),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":Ae},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(g){let b=g instanceof Error&&g.name==="AbortError"?` no response within ${o}ms.`:ft(g);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:g})}finally{clearTimeout(d)}if(!u.ok)throw new ht(u.status,await qh(u));let p;try{p=await u.text()}catch{p=""}let f;try{f=JSON.parse(p)}catch{let g=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(g)||/^\s*<(?:!doctype|html)/i.test(p);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=Ke(f?.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=Ke(f.user);if(!m)throw new Error("developer verification failed: the gateway response is missing the user");let w=JF(f.directive),y=KF(f.capabilities);return{key:h,user:m,team:Ke(f.team),expiresAt:Ke(f.expiresAt),...y.length>0?{capabilities:y}:{},...w?{directive:w}:{}}},nS=async(e,t,n,r,o={})=>{let a=o.timeoutMs??Xh,s=`${e}/connect/key/heartbeat`,i=Ke(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:Jh(16).toString("hex"),purpose:Qv,...zh(n,o.machineUuid)},l=await Qh(c,r,n.payload.devPublicKey,"heartbeat",o.signer??wr),d=new AbortController,u=setTimeout(()=>d.abort(),a),p;try{p=await fetch(s,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":Ae},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.`:ft(m);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:m})}finally{clearTimeout(u)}if(!p.ok)throw new fa(p.status,await qh(p));let f;try{f=await p.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let h=Ke(f.expiresAt);if(!h||!Number.isFinite(Date.parse(h))||f.credentialMode!==qv||f.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:h,credentialMode:qv}},rS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??Xh,i=`${e.replace(/\/$/,"")}/connect/machine`,c=Ke(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Jh(16).toString("hex"),purpose:Qv,...zh(n,o)},d=await Qh(l,r,n.payload.devPublicKey,"heartbeat",a.signer??wr),u=new AbortController,p=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":Ae},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(f){return console.error("connect machine report skipped:",f instanceof Error?f.name:"error"),!1}finally{clearTimeout(p)}},JF=e=>{if(e===null||typeof e!="object")return null;let t=e,n=Ke(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!VF.includes(r)?null:{id:n,kind:r}},XF=1e4,zF=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!Ke(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!Ke(r.deploymentId)&&!!Ke(r.user)&&!!Ke(r.devPublicKey)&&!!Ke(r.issuedAt)&&!!Ke(r.expiresAt)},qF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??XF,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.deviceProof?{deviceProof:r.deviceProof}:{},...r.deploymentId?{deploymentId:r.deploymentId}:{}}),signal:i.signal})}catch(u){let p=u instanceof Error&&u.name==="AbortError"?` no response within ${a}ms.`:ft(u);throw new Error(`could not reach the control plane at ${s}.${p}`)}finally{clearTimeout(c)}if(!l.ok)throw new Error(`enrollment failed: ${await YF(l)}`);let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!zF(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},oS=(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())},aS=async e=>{let t={timeoutMs:e.timeoutMs,machineUuid:e.machineUuid,signer:e.signer},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=e.deviceProofFor?await e.deviceProofFor():void 0,i=s?void 0:hd(),c=s?.devPublicKey??i.publicKeyPem;return{cert:await qF(e.cpOrigin,e.token,c,{email:s?.email??e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId,deviceProof:s?.proof},t),privateKeyPem:s?Zh:i.privateKeyPem,publicKeyPem:c}})(),a=await Jt(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};var em=1e4,QF=900*1e3,iS="tnt_",eW=/^\/sso\/([^/]+)\/?$/,tW=/^\/i\/([^/]+)\/?$/,nW=e=>{let t=e.match(eW);if(t)return t[1];let n=e.match(tW);return n?.[1].startsWith(iS)?n[1]:void 0},vt=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=nW(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(iS))return{cpOrigin:Hn(),tenantId:t}},po=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Nt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},tm=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)}},rW=e=>new Promise(t=>setTimeout(t,e)),md=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??hd)(),a;try{a=await tm(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},em,n)}catch(h){throw new po("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ft(h)}`)}if(a.status!==200){let h=a.status===404,m=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new po(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 po("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??QF,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),p={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},f=e.log??(()=>{});return f("To finish, sign in with your organization at:"),f(` ${p.verificationUriComplete}`),f(`Confirm this code matches your browser: ${p.userCode}`),oW(p.verificationUriComplete,e.cpOrigin)&&e.open?.(p.verificationUriComplete),p},oW=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},yd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??rW,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 tm(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},em,o)}catch(c){throw new Nt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ft(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 Nt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Nt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Nt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var sS="sdc_",cS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(sS))return{cpOrigin:Hn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!jh(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(sS)))return{cpOrigin:n.origin,claim:r}},lS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??hd)(),o;try{o=await tm(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},em,t)}catch(s){throw new Nt("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ft(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 Nt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Nt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Nt("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};import{readFile as aW}from"node:fs/promises";import{isAbsolute as sW,posix as dS,win32 as nm}from"node:path";var ii=(e=process.platform,t=process.env)=>e==="darwin"?dS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?nm.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):dS.join("/etc","anyray","bootstrap.json"),iW=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),uS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(sW(e)||nm.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),cW=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}},br=async(e=ii())=>{try{let t=await aW(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!iW(n)||n.v!==1||typeof n.sso!="string")return;let r=vt(n.sso);if(!r)return;let o=cW(n.gateway)?n.gateway:void 0,a=uS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},pS=(e,t,n)=>{let r=vt(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!uS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&nm.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)}
|
|
283
|
-
`};var
|
|
284
|
-
${V(e)}`),$=e=>console.log(v(e)),M=e=>console.log(`${
|
|
275
|
+
}`,Bn=async e=>new Promise((t,n)=>{let r=B$("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",X$],{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(im(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(im({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),Nt=(e={})=>aa((e.home??um)(),".anyray","claude-desktop-windows.json"),z$=e=>aa((e.home??um)(),".anyray","claude-desktop-windows.lock"),na=class extends Error{},q$=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},mm=async e=>{let t=z$(e);await om(Qs(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=Ak("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=aa(t,"owner.json");try{await om(t,{mode:448}),await we(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
276
|
+
`)}catch(a){if(a.code!=="EEXIST")throw await Zt(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await am(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!q$(i.pid)}catch{try{s=Date.now()-(await Ik(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new na;await Zt(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await am(o,"utf8")).nonce===r&&await Zt(t,{recursive:!0,force:!0})}catch{}}}throw new na},_k=()=>Object.fromEntries(Pe.map(e=>[e,{present:!1}])),no=e=>Ak("sha256").update(e).digest("hex"),Q$=(e,t)=>t.present?e===sa?{present:!0,type:t.type,sha256:no(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},ea=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?no(e.value??"")===t.sha256:e.value===t.value:!0,Lt=(e,t)=>Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),Bl=(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===sa?Lt(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:Lt(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},dk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Lt(e,Pe)&&Pe.every(t=>Bl(e[t],t)),uk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Lt(e,ak)&&ak.every(t=>Bl(e[t],t)),eM=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),hm=(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 Lt(n,r)&&n.path===pm(t)&&(n.lastWritten===void 0||lk(n.lastWritten))&&(n.pending===void 0||lk(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},tM=(e,t)=>Lt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Ml&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&dk(e.lastWritten)&&(e.pending===void 0||dk(e.pending))&&hm(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),nM=e=>Lt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&uk(e.lastWritten)&&(e.pending===void 0||uk(e.pending)),pk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Lt(e,sk)&&sk.every(t=>Bl(e[t],t)),rM=(e,t)=>Lt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===3&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&pk(e.lastWritten)&&(e.pending===void 0||pk(e.pending))&&hm(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),fk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Lt(e,ik)&&ik.every(t=>Bl(e[t],t)),oM=(e,t)=>Lt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===4&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&fk(e.lastWritten)&&(e.pending===void 0||fk(e.pending))&&hm(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),mk=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),ym=e=>{let{pending:t,...n}=e;return{...n,version:Ml,lastWritten:mk(e.lastWritten),...t?{pending:mk(t)}:{}}},hk=e=>({...e,chatTabEnabled:{present:!1}}),aM=e=>{let{pending:t,...n}=e;return ym({...n,version:4,lastWritten:hk(e.lastWritten),...t?{pending:hk(t)}:{}})},yk=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),sM=(e,t)=>ym({version:4,registryKey:Te,keyExisted:e.keyExisted,lastWritten:yk(e.lastWritten),...e.pending?{pending:yk(e.pending)}:{},helper:{path:pm(t)}}),gm=async(e,t=!0)=>{let n=Nt(e),r=Qs(n),o=`${Ek(n)}.anyray-old-`,a=(await vk(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>aa(r,l)),s=n;if(!await x(n)){if(a.length===0)return;if(a.length!==1)throw new Error("ambiguous Windows ownership journal recovery files");t?await Sk(a[0],n):s=a[0]}let i=await B(s),c=nM(i)?sM(i,e):rM(i,e)?aM(i):oM(i,e)?ym(i):tM(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>Zt(l,{force:!0}))),c},gk=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),iM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:Te,keyExisted:e.keyExisted,lastWritten:gk(e.lastWritten),...e.pending?{pending:gk(e.pending)}:{}}:e,Ll=async(e,t)=>{let n=Nt(t),r=`${JSON.stringify(iM(e),null,2)}
|
|
277
|
+
`;t.writeJournalFile?await t.writeJournalFile(n,r):await we(n,r)},cM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,lM=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),dM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),uM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),pM=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===uM(t).toUpperCase(),wk=(e,t,n,r,o)=>{let a=Pe.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},fM=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,mM=(e,t)=>{if(!Rl(e,!0))return!1;let n=fM(t);if(dM.has(n))return!1;if(lM.has(n))return n==="REG_EXPAND_SZ"?!0:!LC(e,!0)},hM=(e,t)=>{let n=_k(),r=!1,o=!1,a=!1,s=t.toUpperCase()===qs.toUpperCase(),i=(l,d)=>{if(!s)return;let u=mM(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),wk(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||pM(d,t))continue;let u=cM.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),wk(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Mn=async(e,t=Te)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:_k(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return hM(n.stdout,t)},yr=async e=>{let t=await Mn(e,qs);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...Pe.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},wm=e=>e.unparsed?`This machine may have a Claude policy under ${qs} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${qs} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${qs} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var Fl=(e,t)=>hr(eo(e,t)),Pk=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],yM=(e,t)=>{let n=Fl(e,t);return Object.fromEntries(Pe.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},gM=(e,t)=>({inferenceProvider:{present:!0,type:"REG_SZ",value:"gateway"},inferenceGatewayBaseUrl:{present:!0,type:"REG_SZ",value:e.anthropicBaseUrl},inferenceGatewayAuthScheme:{present:!0,type:"REG_SZ",value:"bearer"},chatTabEnabled:{present:!1},coworkEgressAllowedHosts:{present:!1},inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},inferenceGatewayApiKey:{present:!0,type:"REG_SZ",value:t}}),wM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,cm=e=>Object.fromEntries(Pe.map(t=>[t,Q$(t,e[t])])),bk=(e,t,n,r)=>({version:Ml,registryKey:Te,keyExisted:e,lastWritten:cm(t),helper:{path:n,lastWritten:sm(r)}}),bM=(e,t,n,r,o,a)=>({version:Ml,registryKey:Te,keyExisted:e,lastWritten:cm(t),pending:cm(n),helper:{path:r,...o?{lastWritten:sm(o)}:{},pending:sm(a)}}),lm=(e,t,n)=>ea(n,e.lastWritten[t])||e.pending!==void 0&&ea(n,e.pending[t]),ra=async e=>{try{let t=await am(e,"utf8");return{content:t,sha256:no(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},oa=async e=>(await ra(e))?.sha256,ta=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,$l=async(e,t)=>{let n=Y$(e),r;try{r=await vk(Qs(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>aa(Qs(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([ra(e),ra(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!ta(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await Tk(e,a))throw new Error("credential helper changed during recovery");return}if(t&&ta(t,s.sha256)&&ta(t,i.sha256)){await Zt(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},bm=async(e,t,n)=>(n.present?await e(Pk(Te,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Te,"/v",t,"/f"])).code===0,AM=async(e,t,n)=>{let r=!0,o=await Mn(e);for(let a of Pe)if(!Qo(o.values[a],t[a])){if(!Qo(o.values[a],n[a])){r=!1;continue}await bm(e,a,t[a])||(r=!1),o=await Mn(e)}return r&&Pe.every(a=>Qo(o.values[a],t[a]))},Qe=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Nt(n)]}}),Dk=async(e,t,n,r={})=>{if(!Ee(t))return Qe("A valid personal ark_ gateway key is required.",!1,r);let o=pm(r),a;try{a=G$((r.credentialCommand??Xf)())}catch{return Qe("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=no(a),i=r.runReg??Bn,c=Nt(r),l;if(!n.dryRun)try{l=await mm(r)}catch(h){return Qe(h instanceof na?"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,p,f,m=!1;try{let h=await yr(i);if(h)return Qe(wm(h),!1,r);let w=await gm(r,!n.dryRun);n.dryRun||await $l(o,w);let y=await Mn(i),g=yM(e,o),b=await ra(o),k=b?.sha256,C=!1;if(d=w,u=y,p=g,w){let E=Pe.find(R=>!lm(w,R,y.values[R]));if(E)return Qe(`Claude's ${E} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(k!==void 0&&!ta(w,k))return Qe(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);C=wM(w)}else{if(k!==void 0&&k!==s)return Qe(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let E=y.foreignState||Pe.some(W=>y.values[W].present),R=Pe.every(W=>Qo(y.values[W],g[W])),P=Pe.every(W=>Qo(y.values[W],gM(e,t.trim())[W]));if(E&&!R&&!P)return Qe(`Existing Claude third-party-inference policy values under ${Te} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(C=P,R&&k===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Te} into an owner-only journal without rewriting them.`]}:(await Ll(bk(y.keyPresent,g,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Te} into the ownership journal.`]})}if(C){let E=!0;try{E=(r.appRunning??fm)()}catch{}if(E)return Qe("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let S=bM(w?.keyExisted??y.keyPresent,y.values,g,o,b?.content,a);if(f=S,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${Te}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Ll(S,r),m=!0;for(let E of Pe){let R=await Mn(i);if(!ea(R.values[E],S.lastWritten[E])&&!ea(R.values[E],S.pending[E]))throw new Error("registry value changed during apply");if(!Qo(R.values[E],g[E])&&!await bm(i,E,g[E]))throw new Error("registry write failed")}let I=await Mn(i);if(!Pe.every(E=>ea(I.values[E],S.pending[E])))throw new Error("registry verification failed");if(k!==s&&(k===void 0?await Z$(o,a):await Nl(o,k,a,"apply",r)),await oa(o)!==s)throw new Error("credential helper verification failed");return await Ll(bk(S.keyExisted,g,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Te}.`,`Installed or updated the dynamic credential helper at ${o}; no personal key is stored in policy or the ownership journal.`,"Fully quit and reopen Claude Desktop to load the policy.",...Il]}}catch{if(!m||!u||!p||!f)return Qe("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await $l(o,f);let h=!0,w=await ra(o),y=f.helper.pending;if(w?.sha256!==f.helper.lastWritten?.sha256&&(y!==void 0&&w?.sha256===y.sha256?f.helper.lastWritten?(await Nl(o,y.sha256,f.helper.lastWritten.content,"rollback",r),h=await oa(o)===f.helper.lastWritten.sha256):await Nl(o,y.sha256,void 0,"rollback",r):h=w===void 0&&f.helper.lastWritten===void 0),h&&await AM(i,u.values,p))return d?await Ll(d,r):await Zt(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?.()}},Lk=async(e,t={})=>{let n=t.runReg??Bn,r=Nt(t),o;if(!e.dryRun)try{o=await mm(t)}catch(a){return Qe(a instanceof na?"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 gm(t,!e.dryRun);a&&!e.dryRun&&await $l(a.helper.path,a);let s=await Mn(n);if(!a)return Pe.filter(m=>s.values[m].present).length>0?Qe(`Claude policy values exist under ${Te}, but Anyray has no ownership journal. Remove them manually only if you know they came from an older Connect run.`,!1,t):{status:"not-found",messages:["No Windows Claude setup to revert."]};let i=Pe.filter(f=>s.values[f].present&&!lm(a,f,s.values[f])),c=await oa(a.helper.path),l=c!==void 0&&!ta(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Te}.`,`Would remove the Anyray-owned credential helper at ${a.helper.path}.`,...i.length||l?[`Would preserve changed values: ${[...i,...l?["credential helper"]:[]].join(", ")}.`]:[]]};let d=!1,u=new Set(i);for(let f of Pe){let h=(await Mn(n)).values[f];if(h.present){if(!lm(a,f,h)){u.add(f);continue}await bm(n,f,{present:!1})||(d=!0)}}let p=await oa(a.helper.path);if(p!==void 0)if(ta(a,p))try{await Nl(a.helper.path,p,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 Zt(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Te}.`,"Removed the Anyray-owned dynamic credential helper when its content still matched the journal.",...u.size?[`Preserved values changed after Connect: ${[...u].join(", ")}.`]:[],...u.size?[]:El]})}catch{return Qe(`Could not safely inspect or revert ${Te}; no unproven value was removed.`,!1,t)}finally{await o?.()}},Nk=async(e,t={})=>{let n=t.runReg??Bn;if(!await x(Nt(t)))return;let r;try{r=await mm(t);let o=await gm(t);if(o&&await $l(o.helper.path,o),!o||o.pending||await yr(n)!==void 0)return;let a=await Mn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Ht(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&Pe.every(l=>ea(a.values[l],o.lastWritten[l]))))return;let i=await oa(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 j$(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?.()}},$k=async(e,t={})=>await Nk(e,t)!==void 0,Mk=async(e,t={})=>await Nk(e,t)==="dynamic";var ia=(e=kM())=>e==="win32"?fm:_l,Am="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",Hl=async(e,t={})=>{let n=(t.profileRoot??Qr)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Am};if((t.appRunning??ia(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await Bk.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 Sl(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 "+Am}:{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??xC)();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=Wl(t.stagingRoot??vM(),`anyray-history-${process.pid}-${CM()}`);try{let s=await(t.runImporter??RC)({binary:o,exportPath:e,configDir:Wl(a,"config"),workDir:Wl(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. "+Am};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 TC(r.dir,s.conversations),c=await _C({stagedProjectsDir:Wl(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 Bk.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as vt}from"node:fs";import{homedir as KM}from"node:os";import{join as Jt,sep as jM}from"node:path";import{isDeepStrictEqual as Kl}from"node:util";import{constants as SM}from"node:fs";import{promises as G}from"node:fs";import{dirname as ca,isAbsolute as km,join as te,relative as Ul,resolve as Yt,sep as ei}from"node:path";import{randomUUID as jl}from"node:crypto";var wn=448,ti=384,Uk=448,IM=4,vm=3e4,Gk=5e3,EM=10*6e4,Cm=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),ct=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ni=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),Vk=(e,t)=>{let n=Ul(Yt(e),Yt(t));return n===""||!n.startsWith(`..${ei}`)&&n!==".."&&!km(n)},ro=async e=>{try{let t=await G.readFile(e,"utf8"),n=JSON.parse(t);return ct(n)?{raw:t,value:n}:void 0}catch(t){return kt(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},kt=e=>e instanceof Error&&"code"in e,xM=e=>{try{return process.kill(e,0),!0}catch(t){return kt(t)&&t.code==="EPERM"}},Kk=e=>e===0?"owner.json":`owner.${e}.json`,Gl=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 p=Number(u[1]);return Number.isSafeInteger(p)&&p>0?{name:d,generation:p}: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"));ct(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}},jk=e=>{if(e.pid===void 0||!xM(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>vm&&t-e.createdAtMs>EM},RM=async e=>{let t=`${e}.anyray-lock`;await G.mkdir(ca(t),{recursive:!0,mode:wn});let n=jl(),r,o=!1;try{await G.mkdir(t,{mode:wn}),o=!0}catch(i){if(!kt(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await Gl(t);if(d){if(!jk(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await G.stat(t).then(p=>Date.now()-p.mtimeMs).catch(()=>0)<=vm)return}let l=te(t,Kk(c));try{await G.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
278
|
+
`,{flag:"wx",mode:ti}),r=l}catch(d){if(kt(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(!ct(i)||i.nonce!==n)return;let c=new Date;await G.utimes(a,c,c)}catch{}})()},Gk);return s.unref(),async()=>{clearInterval(s);try{(await Gl(t))?.nonce===n&&await G.rm(t,{recursive:!0,force:!0})}catch{}}},OM=async(e,t,n)=>{await G.mkdir(ca(e),{recursive:!0,mode:wn});let r=await RM(e);if(!r)return!1;try{let o;try{o=await G.readFile(e,"utf8")}catch(s){if(!kt(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${jl()}`;try{await G.writeFile(a,`${JSON.stringify(n,null,2)}
|
|
279
|
+
`,{mode:ti,flag:"wx"}),await G.rename(a,e)}catch(s){try{await G.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},Zl=async(e,t)=>{for(let n=0;n<IM;n+=1){let r=await ro(e);if(!r)return"failed";let o=t(r.value);if(!o||Kl(o,r.value))return"unchanged";try{if(await OM(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},Fk=async e=>{try{return(await G.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},Yl=async e=>{let t=[];for(let n of await Fk(e))for(let r of await Fk(te(e,n)))t.push(te(e,n,r));return t},TM=e=>Array.isArray(e.skills)?e.skills.filter(t=>ct(t)&&ni(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],_M=async e=>{let t=te(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await Yl(t)){let o=await ro(te(r,"manifest.json"));if(!o)continue;let a=r.split(ei).at(-1)??"";for(let s of TM(o.value))n.push({account:a,packageDir:r,entry:s})}return n},PM=async e=>{let t=await ro(te(e,".claude-plugin","plugin.json"));return!!t&&ni(t.value.name)},DM=(e,t)=>{let n=km(t)?Yt(t):Yt(e,t);if(!Vk(e,n)||n===Yt(e))return;let r=Ul(Yt(e),n);return r.length>0?{absolute:n,relative:r}:void 0},LM=async e=>{let t=await Yl(te(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(ei).includes("skills-plugin"))continue;let o=te(r,"cowork_plugins"),a=await ro(te(o,"installed_plugins.json"));if(!a||!ct(a.value.plugins))continue;let s=r.split(ei).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!ni(i)||!Array.isArray(c)))for(let l of c){if(!ct(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=DM(o,l.installPath);!d||!await PM(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},NM=async e=>{let t=await ro(te(e,"claude_desktop_config.json"));return!t||!ct(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>ni(n)&&n.toLowerCase()!=="anyray"&&ct(r)))},Zk=async e=>{let[t,n,r]=await Promise.all([_M(e),LM(e),NM(e)]);return{skills:t,plugins:n,localMcpServers:r}},Sm=async e=>{let t=await Zk(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)}},Wk=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(!ni(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)},$M=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,wn);else if(o.isFile()){let s=await G.stat(a);await G.chmod(a,(s.mode&73)!==0?Uk:ti)}}};await t(e),await G.chmod(e,wn)},Yk=async(e,t)=>{try{let[n,r]=await Promise.all([G.readFile(e),G.readFile(t)]);return n.equals(r)}catch{return!1}},Vl=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(!Kl(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 Vl(te(e,s),te(t,s)))return!1}else if(!i.isFile()||!await Yk(te(e,s),te(t,s)))return!1}return!0}catch{return!1}},Jk=e=>`${e}.anyray-incomplete`,Xk=async(e,t)=>{let n=!1;if(t){await G.mkdir(ca(e),{recursive:!0,mode:wn});try{await G.mkdir(e,{mode:wn}),n=!0}catch(l){if(!kt(l)||l.code!=="EEXIST")return}}else try{let l=await G.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=jl(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let p;try{p=await Gl(e)}catch{return}if(p){if(!jk(p)||!Number.isSafeInteger(p.generation+1))return;d=p.generation+1}else if(await G.stat(e).then(m=>Date.now()-m.mtimeMs).catch(()=>0)<=vm)return}let u=te(e,Kk(d));try{await G.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
280
|
+
`,{flag:"wx",mode:ti}),o=u}catch(p){if(kt(p)&&p.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(!ct(l)||l.nonce!==r)return;let d=new Date;await G.utimes(a,d,d)}catch{}})()},Gk);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await Gl(e))?.nonce===r&&await G.rm(e,{recursive:!0,force:!0})}catch{}}}},zk=async e=>{let t=await Xk(e,!1);t&&await t.complete()},MM=async(e,t,n)=>{let r=Jk(t),o=!1;try{let c=await G.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await Vl(e,t))return await zk(r),"present"}catch(c){if(!kt(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 Xk(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await G.mkdir(t,{mode:wn})}catch(c){if(!kt(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 p=te(c,u.name),f=te(l,u.name);try{if(u.isDirectory()){try{await G.mkdir(f,{mode:wn})}catch(h){if(!kt(h)||h.code!=="EEXIST")throw h;let w=await G.lstat(f);if(!w.isDirectory()||w.isSymbolicLink())return"conflict"}let m=await s(p,f);if(m!=="copied")return m}else if(u.isFile())try{await G.copyFile(p,f,SM.COPYFILE_EXCL);let m=await G.stat(p);await G.chmod(f,(m.mode&73)!==0?Uk:ti)}catch(m){if(!kt(m)||m.code!=="EEXIST")throw m;if(!await Yk(p,f))return"conflict"}else return"failed"}catch(m){return kt(m)&&m.code==="EEXIST"?"conflict":"failed"}}return"copied"},i=await s(e,t);return i==="failed"?(a.abandon(),"failed"):i==="conflict"?(await a.complete(),"conflict"):await Vl(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},qk=async(e,t,n,r)=>{if(!await Wk(e))return"invalid";try{let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await Vl(e,t))return await zk(Jk(t)),"present"}catch(a){if(!kt(a)||a.code!=="ENOENT")return"failed"}await G.mkdir(ca(t),{recursive:!0,mode:wn});let o=te(ca(t),`.anyray-stage-${jl()}`);try{return await G.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await Wk(o)?(await $M(o),await n?.(t),await MM(o,t,r)):"invalid"}catch{return"failed"}finally{try{await G.rm(o,{recursive:!0,force:!0})}catch{}}},Hk=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),BM=async e=>{let t=await Yl(te(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await ro(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"}},FM=async e=>{let t=await Yl(te(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(ei).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"}},WM=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 qk(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 Zl(a,p=>{let f=Array.isArray(p.skills)?p.skills:[];if(f.find(h=>ct(h)&&typeof h.name=="string"&&h.name.toLowerCase()===s.entry.name.toLowerCase())){d=!0;return}return{...p,skills:[...f,s.entry]}})==="failed"?n.failed+=1:d||l==="present"?n.alreadyPresent+=1:n.migrated+=1}},Qk=(e,t)=>({...e,installPath:t}),HM=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=km(r.installPath)?Yt(r.installPath):Yt(o,r.installPath),s=Qk(e,Ul(Yt(t),Yt(n))),i={...r,installPath:Ul(Yt(o),a)};return Kl(s,i)},UM=async(e,t,n)=>{let r=await ro(e);if(!r||!ct(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":Zl(t,a=>{let s=ct(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},GM=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(!Vk(a,l)){n.invalid+=1;continue}let d=await qk(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,p=!1;await Zl(s,m=>{let h=ct(m.plugins)?m.plugins:{},w=h[c.id],y=Array.isArray(w)?w:[],g=y.find(k=>ct(k)&&k.scope==="user");if(g){u=HM(c.entry,ca(c.settingsFile),c.packageDir,g,t),p=!u;return}let b=Qk(c.entry,l);return{...m,version:typeof m.version=="number"?m.version:2,plugins:{...h,[c.id]:[...y,b]}}})==="failed"?n.failed+=1:p?n.conflicts+=1:await UM(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},VM=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 Zl(r,c=>{let l=ct(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=Kl(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}},ev=async(e,t,n={})=>{let r=await Zk(e),o=Cm("skill"),a=Cm("plugin"),s=Cm("local-mcp"),i=[],c=[],l=Hk(r.skills,n.account,n.allAccounts),d=Hk(r.plugins,n.account,n.allAccounts);if(n.allowedAccounts&&!n.allAccounts){let p=new Set(n.allowedAccounts);if([...new Set([...l.map(m=>m.account),...d.map(m=>m.account)])].some(m=>!p.has(m)))return{outcomes:[o,a,s],blocked:i,ambiguous:c,sourceChanged:!0,retryable:[]}}if(l.length>0){let p=await BM(t);p.state==="found"?await WM(l,p.path,o,n.beforeDirectoryPublish,n.afterDirectoryClaim):p.state==="missing"?i.push("skill"):(o.conflicts+=l.length,c.push("skill"))}if(d.length>0){let p=await FM(t);p.state==="found"?await GM(d,p.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):p.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await VM(r.localMcpServers,t,s);let u=[o,a,s];return{outcomes:u,blocked:i,ambiguous:c,sourceChanged:!1,retryable:u.filter(p=>p.failed>0).map(p=>p.kind)}};var ZM=async e=>{try{return await vt.access(e),!0}catch{return!1}},tv=448,YM=384,rv={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},JM=["code","cowork"],xm=(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.",Im=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),ov=async e=>{let t;try{t=(await vt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&Jo(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await vt.readdir(Jt(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&Jo(a.name)).map(a=>a.name);for(let a of o)n.push(Jt(e,r,a))}catch{}return n},XM=async e=>{try{return(await vt.readdir(e)).filter(t=>t.startsWith(Nn)&&t.endsWith(".json")).map(t=>t.slice(Nn.length,-5)).filter(Jo)}catch{return[]}},zM=async(e,t)=>{let n=await ov(Jt(e,rv[t])),r=[];for(let o of n){let a=await XM(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(jM).slice(-2)[0]})}return r},qM=async(e,t)=>{if(t==="cowork"){let r=await Sl(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await ov(Jt(e,rv.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},QM=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await vt.copyFile(e,n),await vt.chmod(n,YM),await vt.rename(n,t)},eB=async(e,t)=>{try{let n=JSON.parse(await vt.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||!Jo(o)?!1:(await vt.access(Jt(t,".claude","projects",Vf(r),`${o}.jsonl`)),!0)}catch{return!1}},tB=async(e,t,n,r)=>{let o=Im(e),a=await Kf(n);for(let s of t)await nB(e,s,n,r,a,o);return o},nB=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${Nn}${s}.json`,c=Jt(t.dir,i);try{if(e==="code"){if(!await eB(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=Jt(t.dir,`${Nn}${s}`),d=Jt(n,`${Nn}${s}`),u=await vt.readdir(l);await vt.mkdir(d,{mode:tv});for(let p of u)await vt.cp(Jt(l,p),Jt(d,p),{recursive:!0,force:!1,errorOnExist:!0});await vt.chmod(d,tv)}await QM(c,Jt(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},nv=(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(`
|
|
281
|
+
`)}},Em=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),av=async e=>{let t=[];for(let n of JM)t.push({lane:n,sources:await zM(e,n)});return t},sv=async(e={})=>{let t=(e.firstPartyRoot??(()=>Us()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([av(t),Sm(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=Em(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}},oo=async(e={})=>{let t=(e.home??KM)(),n=(e.firstPartyRoot??(()=>Us()))(),r=(e.thirdPartyRoot??(()=>Qr()))();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??ia())())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([av(n),Sm(n)]),s;if(e.account){let f=e.account;for(let w of o)w.sources=w.sources.filter(y=>y.account.startsWith(f));let m=a.accounts.filter(w=>w.startsWith(f));if(o.every(w=>w.sources.length===0)&&m.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${f}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let h=Em(o);for(let w of m)h.add(w);if(h.size>1)return nv(o,e.command??"anyray-connect desktop --migrate",`"${f}" matches ${h.size} accounts`,m);s=[...h]}else if(!e.allAccounts){let f=Em(o);for(let m of a.accounts)f.add(m);if(f.size>1)return nv(o,e.command??"anyray-connect desktop --migrate",`the previous Claude Desktop profile holds local data for ${f.size} accounts`,a.accounts);s=[...f]}let i=e.command??"anyray-connect desktop --migrate",c=!await ZM(r),l=await ev(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:f,sources:m}of o){if(m.length===0){d.push(Im(f));continue}let h=await qM(r,f);if("missing"in h){u.push({lane:f,reason:h.missing,waiting:m.reduce((w,y)=>w+y.ids.length,0)}),d.push(Im(f));continue}d.push(await tB(f,m,h.dir,t))}if(!(d.some(f=>f.migrated>0||f.alreadyPresent>0)||l.outcomes.some(f=>f.migrated>0||f.alreadyPresent>0||f.conflicts>0))&&(u.length>0||l.blocked.length>0)){let f=u[0];return f?{ok:!1,kind:f.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:f.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${f.lane} store`:`Claude Desktop has no ${f.lane} store in its third-party profile yet`,remedy:xm(f.reason,f.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 rB=e=>[Ve(e)],iv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...rB(e.appDir),...e.detectPaths?.()??[]];for(let n of t)if(await x(n))return{installed:!0,detail:n};return{installed:!1,detail:`${e.appDir} not found`}},async apply(t){return{status:"manual",messages:e.steps(t)}},async revert(t){return{status:"manual",messages:e.revertMessages??[`${e.title}: clear the custom OpenAI base URL / key in its settings to revert.`]}}});var cv="1.21459.0",iB=sB(oB),cB=async e=>{try{let{stdout:t}=await iB("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},lB=async e=>{try{return await aB(e)}catch{return}},lv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",dB=["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."],la=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(dv??=uv({}),dv):uv(e),dv,uv=async e=>{let t=(e.home??oi)(),n=["/Applications/Claude.app",bn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??cB,o=e.readClaudeAppBundle??lB;for(let a of n){let s=await r(bn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${lv}`}),c=kl(s,cv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${cv} or newer.`);let l=await o(bn(a,"Contents","Resources","app.asar"));return l?ZC.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. ${lv}`}},Jl="anyray",mv="--anyray-owner=claude-desktop-v1",Xl=(e={})=>{let t=(e.platform??gr)(),n=(e.home??oi)();return t==="darwin"?jt(e).appConfig:t==="win32"?bn(process.env.APPDATA??bn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):bn(n,".config","Claude","claude_desktop_config.json")},Pm=(e={})=>bn((e.home??oi)(),"Library","Application Support","Claude","claude_desktop_config.json"),hv=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,mv]}},ao=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),yv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},uB=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),pB=e=>{if(!ao(e)||!yv(e,["command","args"]))return!1;let t=hv();return e.command===t.command&&uB(e.args,t.args)},fB=e=>ao(e)&&Array.isArray(e.args)&&e.args.at(-1)===mv,mB=e=>{if(!ao(e)||!yv(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||Ue(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===Jn&&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!Ue(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},hB=e=>e===void 0?"absent":pB(e)?"exact":fB(e)||mB(e)?"stale-owned":"foreign",Me=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},so=async e=>{let t=await x(e),n;try{n=await B(e)}catch{throw new Me(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!ao(n.mcpServers))throw new Me(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(ao(n.mcpServers)?n.mcpServers:void 0)?.[Jl];return{path:e,fileExisted:t,json:n,entry:o,ownership:hB(o)}},zl=e=>{if(e.ownership==="foreign")throw new Me(`MCP name conflict in ${e.path}: mcpServers.${Jl} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},gv=(e,t)=>{let n={...e},r=ao(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[Jl]:r[Jl]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Om=async(e,t)=>{if(Rm(e.entry,t))return;let n=await so(e.path);if(!Rm(n.entry,e.entry))throw new Me(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await $n(e.path,gv(n.json,t)),{reading:e,afterEntry:t}},Tm=async e=>{let t=await so(e.reading.path);if(!Rm(t.entry,e.afterEntry))throw new Me(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=gv(t.json,e.reading.entry);await $n(e.reading.path,n)},yB=async e=>{if(!ce())throw new Me(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${Oe()} is temporary); no inference setting was changed.`);let t=await so(Xl(e));zl(t);let n=Pm(e),r=(e.platform??gr)()==="darwin"&&n!==t.path?await so(n):void 0;return r&&zl(r),{active:t,...r?{legacy:r}:{}}},pv=async e=>{let t=await so(Xl(e));zl(t);let n=Pm(e),r=(e.platform??gr)()==="darwin"&&n!==t.path?await so(n):void 0;return r&&zl(r),{active:t,...r?{legacy:r}:{}}},gB=async e=>{let t=[];try{let n=await Om(e.active,hv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Om(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Tm(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Me(`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 Tm(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new Me(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},wB=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Om(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Tm(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new Me(`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)},fv=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)."]},bB={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},ql="claude-desktop",_m="migrate",wv=new Set(["app-running","store-missing"]),AB={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},CB={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"}},kB="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",bv=e=>{let t=(e.platform??gr)(),n=e.home??oi;return{home:n,appRunning:e.appRunning??ia(t),firstPartyRoot:()=>Us({home:n,runtimePlatform:t}),thirdPartyRoot:()=>Qr({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},Av=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=AB[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.`:"")},Cv=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=CB[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.`:"")},ri=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=bv(e),r=await(e.pendingDesktopMigrationCount??sv)(n),o=r.userSkills+r.userPlugins+r.localMcpServers;if(r.sessions+o===0)return[];if(t.dryRun)return[`Would bring ${[r.sessions>0?`${r.sessions} existing Claude Desktop session${r.sessions===1?"":"s"}`:"",o>0?`${o} portable configuration ${o===1?"entry":"entries"}`:""].filter(Boolean).join(" and ")} into Claude Desktop's third-party profile, now or automatically the next time Claude Desktop is fully quit.`];let a=await(e.migrateDesktopProfile??oo)(n);if(a.ok){let c=Av(a.lanes),l=Cv(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,p=(a.blocked??[]).filter(g=>g.reason!=="ambiguous"),f=a.blockedAssets??[],m=a.retryableAssets??[];if(p.length===0&&f.length===0&&m.length===0)return[c,l,u].filter(g=>!!g);if(t.preservePendingOp)return[c,l,u].filter(g=>!!g);await gs(ql,_m);let h=p.reduce((g,b)=>g+b.waiting,0),w=[h>0?`${h} more session${h===1?"":"s"}`:"",f.length>0?`${f.length} extension ${f.length===1?"store":"stores"}`:""].filter(Boolean),y=[...w.length>0?[`Queued: ${w.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...m.length>0?[`Queued: ${m.length} portable configuration ${m.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...y]}if(!wv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
|
|
282
|
+
${a.remedy}`];if(t.preservePendingOp)return[];await gs(ql,_m);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."]}},vB=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await or(ql),[]}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."]}},SB=e=>iv({id:ql,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??gr)(),n=(e.home??oi)();return t==="darwin"?["/Applications/Claude.app",bn(n,"Applications","Claude.app")]:t==="win32"?[bn(process.env.LOCALAPPDATA??bn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>ee(t,"anthropic")?["Claude Desktop subscription routing requires automatic setup on a verified macOS build and a Claude Code sign-in in Keychain.","This platform/build has no verified subscription helper seam, so Connect left inference unchanged instead of silently switching you to API billing.","To opt into the API-billed Gateway lane instead, re-run Connect in org/API mode and use:",...fv(t)]:["Claude desktop org/API lane:",...fv(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`."]}),IB=(e={})=>{let t=SB(e),n=()=>(e.platform??gr)()==="darwin",r=()=>(e.platform??gr)()==="win32",o=(s,i)=>n()?tk(s,i,e):Dk(s,s.clientKey??"",i,e),a=s=>n()?nk(s,e):Lk(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??ia((e.platform??gr)()))(),quitTarget:bB,needsTarget:()=>!1,async complete(s){if(s!==_m)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??oo)(bv(e));if(i.ok){let c=Av(i.lanes),l=Cv(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 p=(i.blocked??[]).filter(h=>h.reason!=="ambiguous"),f=i.blockedAssets??[],m=i.retryableAssets??[];return p.length>0||f.length>0||m.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...p.length>0||f.length>0?["Still waiting on Claude Desktop to create the remaining third-party stores, which appear the first time those parts of the app are opened."]:[],...m.length>0?["A recoverable local-copy interruption remains; the migration will retry automatically."]:[]]}:{status:"configured",messages:c||l?[c,l].filter(h=>!!h):["No portable Claude Desktop data was left to bring across."]}}return wv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?ok(s,e):r()?Mk(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let p=jt(e),f=await to(p,e);if(f)return{status:"manual",manualAudience:"admin",messages:[tm(f),...await ri(e,i)]}}if(r()){let p;try{p=await yr(e.runReg??Bn)}catch{return{status:"manual",manualAudience:"admin",messages:[kB,...await ri(e,i)]}}if(p)return{status:"manual",manualAudience:"admin",messages:[wm(p),...await ri(e,i)]}}if(r()&&ee(s,"anthropic"))return{status:"manual",messages:["Claude Desktop subscription routing is not available on Windows: Connect could not verify a supported Claude subscription credential source, so inference was left unchanged instead of switching to API billing.","Use org/API mode for the Windows Gateway lane, or run subscription mode on a verified macOS build after signing in to Claude Code."]};if(n()){let p=await la(e);if(!p.supported)return{status:"manual",messages:[p.message??"Claude Desktop version is unsupported."]}}let c;try{c=await yB(e)}catch(p){let f=p instanceof Me?p.changedFiles:[];return{status:"manual",...f.length>0?{changedFiles:f}:{},messages:[p instanceof Me?p.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 p=c.legacy;return{...l,messages:[...l.messages,`Would register the ownership-marked Anyray retrieval MCP server in ${c.active.path}.`,...p&&p.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${p.path}.`]:[],...await ri(e,i)]}}let d;try{d=await gB(c)}catch(p){let f=p instanceof Me?p.changedFiles:[];return{status:"manual",...f.length>0?{changedFiles:f}:{},messages:[p instanceof Me?p.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 ri(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?dB:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=Xl(e),c=await vB(s),l=h=>c.length===0?h:{...h,messages:[...h.messages,...c]};if(!n()&&!r())return l(await t.revert(s));let d;try{d=await pv(e)}catch(h){return l({status:"manual",messages:[h instanceof Me?h.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no setting was removed."]})}let u=await a({dryRun:!0});if(s.dryRun){let h=d.legacy;return l({...u,messages:[...u.messages,...d.active.ownership!=="absent"?[`Would remove the owned Anyray retrieval MCP server from ${i}.`]:[],...h&&h.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${h.path}.`]:[]]})}let p=await a({dryRun:!1});if(p.status==="manual"){let h=r()?Nt(e):void 0;if(!(h!==void 0&&p.changedFiles?.includes(h)===!0&&!await x(h)))return l(p)}let f;try{f=await wB(await pv(e))}catch(h){let w=h instanceof Me?h.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...p.changedFiles??[],...w])],messages:[...p.messages,h instanceof Me?h.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await re(i);let m=Pm(e);return n()&&m!==i&&await re(m),l({...p,messages:[...p.messages,...f.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...p.changedFiles??[],...f])]})},async mcpStatus(){if(!ce())return{registered:!1,command:null};try{let s=await so(Xl(e));return s.ownership!=="exact"||!ao(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 la(e)).supported?rm(s,e):!1:r()?$k(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await la(e)).supported)return["unknown"];let s=await rk(e);return s?[s]:["unknown"]}if(r())return await x(Nt(e))?await yr(e.runReg??Bn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=jt(e);return!await x(s.journal)||await to(s,e)?!1:(await la(e)).supported}return r()&&await x(Nt(e))?!await yr(e.runReg??Bn):!1}catch{return!1}}}},kv=IB();import{homedir as QB}from"node:os";import{join as eF}from"node:path";import{rm as id}from"node:fs/promises";import{constants as vv,accessSync as EB,statSync as xB}from"node:fs";import{platform as Dm}from"node:os";import{delimiter as RB,posix as OB,resolve as TB,win32 as _B}from"node:path";var PB="0.59.0",DB="1.1.4",Fn="Anyray \xB7 Claude",Wn="Anyray \xB7 Codex",Ql="__anyray-acp-agent",Sv=(e,t,n)=>{let{command:r,args:o}=en([Ql,e,t,n]);return{command:r,args:o,env:{}}},ed=(e=Dm())=>e==="win32"?"npx.cmd":"npx",td=(e=process.env.PATH,t=Dm())=>{if(!e)return;let n=ed(t);for(let r of e.split(RB)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=TB(o,n);try{if(!xB(a).isFile())continue;return EB(a,t==="win32"?vv.F_OK:vv.X_OK),a}catch{}}},nd=(e,t=Dm())=>{let n=t==="win32"?_B:OB;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==ed(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},LB="https://chatgpt.com/backend-api/codex",NB="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",Iv="ANYRAY_ACP_CODEX_AUTHORIZATION",Ev="ANYRAY_ACP_CODEX_CLIENT_KEY",xv="ANYRAY_ACP_CODEX_METADATA",Rv=e=>ue({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),$B=(e,t={})=>{let n=ee(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":LB,"x-anyray-forward-headers":NB}:{},o=n?{...e.clientKey?{"x-anyray-api-key":Ev}:{}}:{Authorization:Iv};return Rv(e)&&(o["x-anyray-metadata"]=xv),{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}}}:{}}},MB=e=>{let t=ee(e,"openai"),n=Rv(e);return{...t?e.clientKey?{[Ev]:e.clientKey}:{}:{[Iv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[xv]:n}:{}}},Ov=(e,t=ed(),n={})=>({[Fn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${PB}`],env:tn(e).env},[Wn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${DB}`],env:{CODEX_CONFIG:JSON.stringify($B(e,n)),...MB(e)}}}),ai=(e=ed(),t="jetbrains")=>({[Fn]:Sv("claude",e,t),[Wn]:Sv("codex",e,t)}),io=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rd=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as BB}from"node:zlib";import{open as FB,readFile as Bm,readdir as sd}from"node:fs/promises";import{dirname as Tv,join as fe}from"node:path";import{homedir as Lv,platform as Fm}from"node:os";var od="2025.3.2",da="253.30387.147",si="com.intellij.ml.llm",Lm=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),WB=1e4,HB=256*1024*1024,UB=16*1024*1024,Nm=1024*1024,$m=22,GB=$m+65535,Mm=kl,VB=()=>{let e=Lv(),t=fe(e,".cache","JetBrains","RemoteDev");switch(Fm()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:fe(e,"Applications"),layout:"app-bundles"},{path:fe(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:fe(process.env.LOCALAPPDATA??fe(e,"AppData","Local"),"Programs"),layout:"children"},{path:fe(process.env.LOCALAPPDATA??fe(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:fe(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:fe(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},KB=()=>Fm()==="linux"?fe(Lv(),".local","share","JetBrains"):Ve("JetBrains"),jB=()=>Fm()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),ZB=async(e,t=WB)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await sd(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=fe(r.path,i.name),l=r.layout==="app-bundles"?fe(c,"Contents","Resources","product-info.json"):fe(c,"product-info.json");await x(l)&&n.push(l)}continue}let o=0,a=async(s,i)=>{if(i<0||o>=t)return;let c=fe(s,"product-info.json"),l=fe(s,"Contents","Resources","product-info.json");if(await x(c)){n.push(c);return}if(await x(l)){n.push(l);return}let d;try{d=await sd(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let p=fe(s,u.name);(u.isDirectory()||u.isSymbolicLink())&&!["bin","jbr","lib","plugins","Contents"].includes(u.name)&&await a(p,i-1)}};await a(r.path,7)}return[...new Set(n)]},YB=e=>{let t=Tv(e);return t.endsWith(`${fe("Contents","Resources")}`)?Tv(t):t},JB=async e=>{try{let t=JSON.parse(await Bm(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!Ws(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:YB(e)}}catch{return}},ad=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},XB=async(e,t)=>{let n;try{n=await FB(e,"r");let{size:r}=await n.stat();if(r<$m||r>HB)return;let o=Math.min(r,GB),a=await ad(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-$m;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>UB||c+i>r)return;let l=await ad(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),p=l.readUInt32LE(d+20),f=l.readUInt32LE(d+24),m=l.readUInt16LE(d+28),h=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),y=l.readUInt32LE(d+42),g=d+46+m+h+w;if(g>l.length)return;let b=l.subarray(d+46,d+46+m).toString("utf8");if(d=g,b!==t)continue;if(p===4294967295||f===4294967295||p>Nm||f>Nm)return;let k=await ad(n,30,y);if(!k||k.readUInt32LE(0)!==67324752)return;let C=k.readUInt16LE(26),S=k.readUInt16LE(28),I=await ad(n,p,y+30+C+S);return I?u===0?I.toString("utf8"):u===8?BB(I,{maxOutputLength:Nm}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},_v=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!Ws(n)))return{id:t,version:n}},zB=async(e,t)=>{let n=fe(e,"META-INF","plugin.xml");if(await x(n))try{let o=_v(await Bm(n,"utf8"));return{present:o?.id===si||t,descriptor:o?.id===si?o:void 0}}catch{return{present:t}}let r=[];try{r=(await sd(fe(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=>fe(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await XB(o,"META-INF/plugin.xml"),s=a?_v(a):void 0;if(s?.id===si)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},Pv=async e=>{let t;try{t=await sd(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=Lm.has(o.name.toLowerCase()),i=Lm.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Lm.has(o.name.toLowerCase());if(!a){let i=fe(e,o.name,"META-INF","plugin.xml");if(!await x(i))continue}let s=await zB(fe(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},qB=async e=>{try{return(await Bm(fe(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(si)}catch{return!1}},Dv=e=>e.reduce((t,n)=>t?(Mm(n,t)??-1)>0?n:t:n,void 0),Nv=async(e={})=>{let t=e.configRoot??Ve("JetBrains"),n=e.userPluginsRoot??KB(),r=await ZB(e.productRoots?e.productRoots.map(m=>({path:m,layout:"recursive"})):VB(),e.scanBudget),o=(await Promise.all(r.map(m=>JB(m)))).filter(m=>m!==void 0),a=o.length>0||await x(t);if(e.wsl??jB())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(m=>(Mm(m.version,od)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let m of s){let h=fe(t,m.dataDirectoryName);if(!await x(h)){d=!0;continue}let w=[fe(h,"plugins"),fe(n,m.dataDirectoryName),fe(n,m.dataDirectoryName,"plugins")],y;for(let g of[...new Set(w)]){let b=await Pv(g);if(b.present){y=b;break}}if(y??=await Pv(fe(m.root,"plugins")),y.present&&!y.descriptor){l=!0;continue}if(!(!y.descriptor||y.descriptor.id!==si)){if(i.push(y.descriptor.version),await qB(h)){c=!0;continue}if(!((Mm(y.descriptor.version,da)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${m.version}; AI Assistant ${y.descriptor.version}; ACP supported`,ideVersion:m.version,pluginVersion:y.descriptor.version}}}let u=Dv(o.map(m=>m.version)),p=Dv(i),f;return a?u?s.length===0?f=`JetBrains IDE ${u} is below the ACP minimum ${od}; no ACP config was written.`:d?f=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${od}+ once, enable AI Assistant ${da}+, then run Connect again. No ACP config was written.`:c?f=`JetBrains AI Assistant is disabled; enable version ${da}+ and run Connect again. No ACP config was written.`:p?f=`JetBrains AI Assistant ${p} is below the ACP minimum ${da}; no ACP config was written.`:l?f=`Could not verify the local JetBrains AI Assistant version; require ${da}+ before running Connect. No ACP config was written.`:f=`JetBrains AI Assistant ${da}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:f=`Could not prove JetBrains IDE ${od}+ from local product-info.json; no ACP config was written.`:f="JetBrains IDE config or installation not found",{installed:a,capable:!1,detail:f,ideVersion:u,pluginVersion:p}};var tF=[Fn,Wn],Wm=()=>eF(QB(),".jetbrains","acp.json"),co=()=>`${Wm()}.anyray-state`,nF=(e,t,n="npx")=>{let r=io(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,ai(n,"jetbrains")),{...e,agent_servers:r}},rF=(e,t,n)=>{if(!io(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=io(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of tF)if(c in r){if(!rd(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}},oF=(e=Nv)=>({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=Wm(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=td();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await x(r),c;try{c=await B(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=ai(a,"jetbrains");return await Zi({configPath:r,current:c,next:nF(c,t,a),journalPath:co(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,co()]}},async revert(t){let n=Wm(),r=async()=>{if(!await x(n))return t.dryRun||(await re(n),await id(co(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await B(n)}catch{return t.dryRun||(await re(n),await id(co(),{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 B(co());(u.version===1||u.version===2)&&io(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await x(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await B(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await _r(n);let l=rF(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 id(n,{force:!0}):await Y(n,l.next,{backup:!1})),t.dryRun||(await re(n),await id(co(),{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():ji(n,co(),r)}}),$v=oF();import{homedir as ld}from"node:os";import{join as dd}from"node:path";import{rm as Hm}from"node:fs/promises";var Um="1.0.0",ud=["anyray-claude-acp","anyray-codex-acp"],aF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Gm=()=>dd(ld(),".windsurf","acp","registry.json"),Vm=()=>dd(ld(),".windsurf-next","acp","registry.json"),ua=e=>`${e}.anyray-state`,Mv=e=>({binary:Object.fromEntries(aF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Fv=(e="npx")=>{let t=ai(e,"windsurf");return[{id:ud[0],name:Fn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Mv(t[Fn])},{id:ud[1],name:Wn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Mv(t[Wn])}]},cd=e=>!Array.isArray(e)||e.some(t=>!io(t)||typeof t.id!="string")?null:e,sF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Um||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:cd(e.agents);if(!n)return null;let r=new Set(ud);return{...e,version:typeof e.version=="string"?e.version:Um,agents:[...n.filter(o=>!r.has(o.id)),...Fv(t)],extensions:e.extensions??[]}},iF=(e,t,n)=>{let r=cd(e.agents);if(!r)return null;let o=cd(t.agents)??[],a=new Map((cd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!ud.includes(u.id)){l.push(u);continue}if(!rd(u,a.get(u.id))){c.push(u.id),l.push(u);continue}let p=s.get(u.id);p&&l.push(p),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===Um&&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}},Bv=async()=>{let e=[];return(await x(Vm())||await x(dd(ld(),".windsurf-next")))&&e.push(Vm()),(await x(Gm())||await x(dd(ld(),".windsurf"))||await x(Ve("Devin"))||await x(Ve("Windsurf")))&&e.push(Gm()),e},Wv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await Bv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await Bv();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=td();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 B(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=sF(i,r);if(!c){o.push(`Refused unrecognized ACP registry shape in ${s}.`);continue}if(o.push(`${s} \u2190 registered Anyray Claude and Codex ACP agents.`),!t.dryRun){let l=await x(s),d=Fv(r);await Zi({configPath:s,current:i,next:c,journalPath:ua(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,ua(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=[Gm(),Vm()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await x(a)){e.dryRun||(await re(a),await Hm(ua(a),{force:!0}).catch(()=>{}));return}let i;try{i=await B(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 f=await B(ua(a));(f.version===1||f.version===2)&&Array.isArray(f.agents)&&(c=f.agents,l=f.version===2&&f.fileExisted===!1,d=f.version===2&&f.fileExisted===!0)}catch{}let u;if(d){let f=`${a}.anyray-bak`;if(!await x(f)){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 B(f)}catch{n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is malformed. Repair it or remove the agents manually.`),o=!0;return}}else u=await _r(a);let p=iF(i,u,c);if(!p){n.push(`Unrecognized ACP registry shape in ${a}; left it unchanged.`),o=!0;return}p.removed.length&&(n.push(`Removed ${p.removed.join(", ")} from ${a}.`),e.dryRun||(l&&Object.keys(p.next).length===0?await Hm(a,{force:!0}):await Y(a,p.next,{backup:!1}),r.push(a))),p.conflicts.length?(n.push(`Preserved user-modified agents: ${p.conflicts.join(", ")}.`),o=!0):e.dryRun||(await re(a),await Hm(ua(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await ji(a,ua(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var le=[qn,Tw,ks,LA,iC,bC,EC,$v,kv,Wv,Bw],mt=e=>le.find(t=>t.id===e);var Be=async(e=D,t=fn)=>{let n=await e();if(!n.gateway||!n.clientKey)return;let r=await t().catch(()=>{});return{target:xe({origin:n.gateway,clientKey:n.clientKey,subscription:n.authMode==="subscription",placeholder:n.authMode==="placeholder",byoUpstream:n.byoUpstream,seat:r,user:n.name,team:n.team})}};var Km=5e3,Hv=3e4,cF=1440*60*1e3,lF=e=>new Promise(t=>setTimeout(t,e)),dF=async(e=D,t=fn)=>(await Be(e,t))?.target,uF=e=>mt(e)?.quitGated,Uv=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??uF,o=t.readPending??Uc,a=t.clearPending??Tp,s=t.targetFromProfile??dF,i=t.sleep??lF,c=t.now??Date.now,l=t.maxWaitMs??cF;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),p=c(),f=Km;for(;;){let m=await o(n);if(!m||c()-p>l)return 0;if(d.isRunning()){await i(f),f=Math.min(Hv,f*2);continue}let h;if(d.needsTarget?.(m.op)&&(h=await s(),!h)){if(await a(n,m)!=="superseded")return 0;await i(f),f=Km;continue}if((await u(m.op,h,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(f),f=Math.min(Hv,f*2);continue}if(await a(n,m)!=="superseded")return 0;await i(f),f=Km}}catch{return 0}};import{writeFileSync as QF}from"node:fs";import{chmod as rh,stat as eW}from"node:fs/promises";import{platform as bS}from"node:os";import{dirname as AS,isAbsolute as tW}from"node:path";var pF="https://app.anyray.ai",fF=new Set(["localhost","::1","[::1]"]),mF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,hF=e=>fF.has(e)||mF.test(e),jm=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&hF(t.hostname)},yF=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Hn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!jm(e)?pF:yF(e)};import{createHash as OF,generateKeyPairSync as TF,randomBytes as Jm}from"node:crypto";import{createPrivateKey as gF,sign as wF}from"node:crypto";var wr=async(e,t)=>{let n=gF(t);return wF(null,new TextEncoder().encode(e),n).toString("base64url")};var bF=["HTTPS_PROXY","https_proxy"],Gv=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"]),Vv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Kv=new Set(["ENOTFOUND","EAI_AGAIN"]),jv=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Zv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),AF=e=>{let t=e;for(let n=0;n<5&&t;n++){let r=t.code;if(typeof r=="string"&&r)return r;t=t.cause}return CF(e)},CF=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...Gv,...Vv,...Kv,...jv,...Zv])if(t.includes(n))return n}},kF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",vF=e=>bF.filter(t=>(e[t]??"").trim()!==""),SF=(e,t=process.env)=>{let n=AF(e),r=vF(t);return{kind:n&&Gv.has(n)?"tls-unknown-issuer":n&&Vv.has(n)?"tls-invalid-cert":n&&Kv.has(n)?"dns":kF(e)||n&&Zv.has(n)?"timeout":n&&jv.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},IF=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}},ht=(e,t=process.env)=>IF(SF(e,t));var EF="enl_",Yv="enp_",Jv=e=>e.startsWith(EF)||e.startsWith(Yv),Zm=e=>e.startsWith(Yv),xF=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],Ym=e=>xF.find(t=>e.startsWith(t.prefix)),Xv=/^\/enroll\/([^/]+)\/?$/,zv=/^\/i\/([^/]+)\/?$/,qv=e=>{let t=e.match(Xv);if(t)return Ym(t[1])?void 0:t[1];let n=e.match(zv);return n&&Jv(n[1])?n[1]:void 0},RF=1e4,pd=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=qv(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!Ym(t))return{cpOrigin:Hn(),token:t}},Qv=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(Xv)??o.pathname.match(zv);if(!a)return;n=a[1]}catch{}let r=Ym(n);return r?{flag:r.flag,what:r.what}:void 0},ci=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:qv(n.pathname)!==void 0}catch{return Jv(t)}},pa=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},ii=e=>typeof e=="string"&&e.trim()?e.trim():void 0,eS=async(e,t={})=>{let n=t.timeoutMs??RF,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 p=u instanceof Error&&u.name==="AbortError"?` no response within ${n}ms.`:ht(u);throw new Error(`could not reach the enrollment page at ${e.cpOrigin}.${p}`)}finally{clearTimeout(a)}if(!s.ok){let u=`enrollment link lookup failed: ${e.cpOrigin} responded ${s.status} \u2014 the link may be expired or revoked; ask your admin for a fresh one.`;throw s.status>=400&&s.status<500&&s.status!==429?new pa(u):new Error(u)}let i;try{i=await s.json()}catch{throw new Error(`enrollment link lookup failed: ${e.cpOrigin} returned a malformed response`)}let l=(Array.isArray(i?.gateways)?i.gateways:[]).find(u=>u!==null&&typeof u=="object"&&ii(u.url)!==void 0),d=ii(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:ii(l?.deploymentId),org:ii(i.org),email:ii(i.email),seatMode:i.seatMode===!0,...i.provisioningKind==="manual"||i.provisioningKind==="mdm"?{provisioningKind:i.provisioningKind}:{},...i.provisioningProofMode==="managed-preference"?{provisioningProofMode:i.provisioningProofMode}:{},...Array.isArray(i.allowedDomains)?{allowedDomains:i.allowedDomains.filter(u=>typeof u=="string"&&u.length>0)}:{}}};var Xm=1e4,lo=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(lo).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${lo(e[n])}`).join(",")}}`,tS="stable-key-heartbeat-v1",nS="key-heartbeat",_F=["reapply_config","remint","revert"],zm=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var rS=e=>OF("sha256").update(e).digest("hex"),je=e=>typeof e=="string"&&e.trim()?e.trim():void 0,PF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],oS={no_mdm_server_registered:"no MDM server is registered in the Anyray console",agent_missing:"the Anyray endpoint agent is not reporting for this machine",mdm_not_verified:"this machine is not enrolled in the registered MDM",endpoint_unreachable:"the endpoint service could not be reached"},DF=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${oS[e]}. Ask your IT admin.`,LF=e=>typeof e=="string"&&e in oS,qm=async e=>{try{let t=await e.json(),n=je(t?.message),r=je(t?.error),o=LF(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:DF(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},NF=async e=>(await qm(e)).message,lt=class extends Error{status;policyCode;reason;constructor(t,n){let r=typeof n=="string"?{message:n}:n;super(r.code==="managed_device_required"?r.message:`the gateway rejected this enrollment (HTTP ${t}): ${r.message}`),this.name="GatewayVerifyError",this.status=t,this.policyCode=r.code,this.reason=r.reason}},aS=e=>e instanceof pa||e instanceof lt&&e.policyCode==="sso_required",fa=class extends Error{status;policyCode;reason;constructor(t,n){let r=typeof n=="string"?{message:n}:n;super(r.code==="managed_device_required"?r.message:`the gateway rejected this credential heartbeat (HTTP ${t}): ${r.message}`),this.name="GatewayHeartbeatError",this.status=t,this.policyCode=r.code,this.reason=r.reason}},Qm=async(e,t,n,r)=>{try{return await r(lo(e),t)}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},fd=()=>{let{publicKey:e,privateKey:t}=TF("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},Xt=async(e,t,n,r={})=>{let o=r.timeoutMs??Xm,a=`${e}/connect/verify`,s=je(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:Jm(16).toString("hex"),...zm(t,r.machineUuid)},c=await Qm(i,n,"verification",r.signer??wr),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":Ae},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(g){let b=g instanceof Error&&g.name==="AbortError"?` no response within ${o}ms.`:ht(g);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:g})}finally{clearTimeout(d)}if(!u.ok)throw new lt(u.status,await qm(u));let p;try{p=await u.text()}catch{p=""}let f;try{f=JSON.parse(p)}catch{let g=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(g)||/^\s*<(?:!doctype|html)/i.test(p);throw new Error(b?`developer verification failed: ${a} returned an HTML page, not the gateway \u2014 /connect/* is being routed to the console/proxy. Ask your admin to route /connect/* to the gateway service (:8787), the same as /v1/*.`:"developer verification failed: the gateway returned a malformed response")}let m=je(f?.key);if(!m)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(m))throw new Error("developer verification failed: the gateway returned a malformed key");let h=je(f.user);if(!h)throw new Error("developer verification failed: the gateway response is missing the user");let w=$F(f.directive),y=PF(f.capabilities);return{key:m,user:h,team:je(f.team),expiresAt:je(f.expiresAt),...y.length>0?{capabilities:y}:{},...w?{directive:w}:{}}},sS=async(e,t,n,r,o={})=>{let a=o.timeoutMs??Xm,s=`${e}/connect/key/heartbeat`,i=je(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:Jm(16).toString("hex"),purpose:nS,...zm(n,o.machineUuid)},l=await Qm(c,r,"heartbeat",o.signer??wr),d=new AbortController,u=setTimeout(()=>d.abort(),a),p;try{p=await fetch(s,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":Ae},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(h){let w=h instanceof Error&&h.name==="AbortError"?` no response within ${a}ms.`:ht(h);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:h})}finally{clearTimeout(u)}if(!p.ok)throw new fa(p.status,await qm(p));let f;try{f=await p.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let m=je(f.expiresAt);if(!m||!Number.isFinite(Date.parse(m))||f.credentialMode!==tS||f.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:m,credentialMode:tS}},iS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??Xm,i=`${e.replace(/\/$/,"")}/connect/machine`,c=je(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Jm(16).toString("hex"),purpose:nS,...zm(n,o)},d=await Qm(l,r,"heartbeat",a.signer??wr),u=new AbortController,p=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":Ae},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(f){return console.error("connect machine report skipped:",f instanceof Error?f.name:"error"),!1}finally{clearTimeout(p)}},$F=e=>{if(e===null||typeof e!="object")return null;let t=e,n=je(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!_F.includes(r)?null:{id:n,kind:r}},MF=1e4,BF=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!je(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!je(r.deploymentId)&&!!je(r.user)&&!!je(r.devPublicKey)&&!!je(r.issuedAt)&&!!je(r.expiresAt)},FF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??MF,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 p=u instanceof Error&&u.name==="AbortError"?` no response within ${a}ms.`:ht(u);throw new Error(`could not reach the control plane at ${s}.${p}`)}finally{clearTimeout(c)}if(!l.ok){let u=`enrollment failed: ${await NF(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new pa(u):new Error(u)}let d;try{d=await l.json()}catch{throw new Error("enrollment failed: the control plane returned a malformed response")}if(!BF(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},cS=(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())},lS=async e=>{let t={timeoutMs:e.timeoutMs,machineUuid:e.machineUuid,signer:e.signer},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=fd();return{cert:await FF(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),...s}})(),a=await Xt(e.gatewayOrigin,n,r,t);return{clientKey:a.key,user:a.user,team:a.team,expiresAt:a.expiresAt,...a.capabilities?{capabilities:a.capabilities}:{},cert:n,privateKeyPem:r,publicKeyPem:o}};var eh=1e4,WF=900*1e3,uS="tnt_",HF=/^\/sso\/([^/]+)\/?$/,UF=/^\/i\/([^/]+)\/?$/,GF=e=>{let t=e.match(HF);if(t)return t[1];let n=e.match(UF);return n?.[1].startsWith(uS)?n[1]:void 0},St=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=GF(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(uS))return{cpOrigin:Hn(),tenantId:t}},uo=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},$t=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},th=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)}},VF=e=>new Promise(t=>setTimeout(t,e)),md=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??fd)(),a;try{a=await th(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},eh,n)}catch(m){throw new uo("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ht(m)}`)}if(a.status!==200){let m=a.status===404,h=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new uo(m?"sso-unavailable":"cp-unreachable",`SSO is not available for this organization (${h}). Ask your admin to confirm SSO is configured.`,a.status)}let s=a.json;if(!s.device_code||!s.user_code||!s.verification_uri_complete)throw new uo("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??WF,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),p={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},f=e.log??(()=>{});return f("To finish, sign in with your organization at:"),f(` ${p.verificationUriComplete}`),f(`Confirm this code matches your browser: ${p.userCode}`),KF(p.verificationUriComplete,e.cpOrigin)&&e.open?.(p.verificationUriComplete),p},KF=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},hd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??VF,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 th(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},eh,o)}catch(c){throw new $t("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ht(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 $t("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new $t("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new $t("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var dS="sdc_",pS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(dS))return{cpOrigin:Hn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!jm(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(dS)))return{cpOrigin:n.origin,claim:r}},fS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??fd)(),o;try{o=await th(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},eh,t)}catch(s){throw new $t("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ht(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 $t("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new $t("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new $t("denied","This enrollment link was already used or is not valid. Open your organization\u2019s Anyray link again to get a new one.")};import{readFile as jF}from"node:fs/promises";import{isAbsolute as ZF,posix as mS,win32 as nh}from"node:path";var li=(e=process.platform,t=process.env)=>e==="darwin"?mS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?nh.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):mS.join("/etc","anyray","bootstrap.json"),YF=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})&&(ZF(e)||nh.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),JF=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}},br=async(e=li())=>{try{let t=await jF(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!YF(n)||n.v!==1||typeof n.sso!="string")return;let r=St(n.sso);if(!r)return;let o=JF(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}},yS=(e,t,n)=>{let r=St(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&&nh.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)}
|
|
283
|
+
`};var ma=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,yd=ma(process.stdout,process.env),gS=ma(process.stderr,process.env),ha=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,V=e=>ha("1",e,yd),v=e=>ha("2",e,yd),XF=e=>ha("32",e,yd),zF=e=>ha("33",e,gS),qF=e=>ha("31",e,gS),et=e=>ha("36",e,yd),A=e=>console.log(e),U=e=>console.log(`
|
|
284
|
+
${V(e)}`),$=e=>console.log(v(e)),M=e=>console.log(`${XF("\u2713")} ${e}`),_=e=>console.error(`${zF("!")} ${e}`),O=e=>console.error(`${qF("\u2717")} ${e}`);var oh=`${V("anyray-connect managed")} \u2014 fleet-wide Claude Code routing via managed-settings.json
|
|
285
285
|
|
|
286
286
|
Emit or install the OS \`managed-settings.json\` that points a managed fleet's
|
|
287
287
|
Claude Code at the Anyray gateway. It reads at a HIGHER precedence than a user's
|
|
@@ -364,15 +364,15 @@ ${V("Examples")}
|
|
|
364
364
|
anyray-connect managed --print --tool jetbrains --bin /usr/local/bin/anyray-connect --npx /usr/local/bin/npx > acp.json
|
|
365
365
|
|
|
366
366
|
# Shell/SDK fleet snippet (base URLs only; keys stay per-user):
|
|
367
|
-
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,
|
|
368
|
-
`)},
|
|
369
|
-
`),
|
|
370
|
-
`),
|
|
371
|
-
`),
|
|
372
|
-
`+
|
|
373
|
-
`+
|
|
367
|
+
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,wS=["claude-code","jetbrains","shell","bootstrap"],nW=e=>{let t={help:!1};for(let n=0;n<e.length;n++){let r=e[n],o=()=>{let a=e[++n];if(!a)throw new Error(`missing value for ${r}`);return a};switch(r){case"--print":t.mode="print";break;case"--write":t.mode="write";break;case"--revert":t.mode="revert";break;case"--gateway":t.gateway=o();break;case"--user":t.user=o();break;case"--team":t.team=o();break;case"--intent":t.intent=o();break;case"--intent-label":t.intentLabel=o();break;case"--session":t.session=o();break;case"--key":throw new Error("--key is not valid for managed settings: fleet files never embed credentials; enroll each user instead");case"--scrub-direct-mode":t.scrubDirectMode=!0;break;case"--sso":t.sso=o();break;case"--bin":t.bin=o();break;case"--npx":t.npx=o();break;case"--out":t.out=o();break;case"--tool":{let a=o();if(!wS.includes(a))throw new Error(`unknown --tool ${a} (expected ${wS.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&&!St(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};function gd(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:[kn(Qa(t.binaryPath,[Xe]),{matcher:"*"})],UserPromptSubmit:[kn(Qa(t.binaryPath,o),{timeout:30}),kn(Qa(t.binaryPath,[Zn]))],SessionStart:[kn(Qa(t.binaryPath,[...o,"--session-start"]),{async:!0})]}}}let{env:r}=tn(e,{includeAuthToken:!1,includeClientKey:!1});return n.scrubDirectMode?{env:{...Object.fromEntries(vn.map(o=>[o.name,""])),...r}}:{env:r}}var rW=(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 Nr)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},oW=e=>{let t=e.env,n=Ku(e);if(t){for(let r of Nr)r in t&&(delete t[r],n=!0);for(let{name:r}of vn)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return n},CS=async e=>{let t=async n=>{try{return(await eW(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(AS(e))!==void 0}},kS=async(e,t)=>(t.dirExisted||await rh(AS(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await rh(e,420),{mode:420,keptRestricted:!1}):(await rh(e,t.mode),{mode:t.mode,keptRestricted:!0})),vS=(e,t)=>{t.keptRestricted&&(_(`${e} was already restricted to mode ${t.mode.toString(8).padStart(3,"0")} and keeps it \u2014 widening it would expose whatever else that file holds to every local account.`),A(v(" Claude Code reads this file as the developer, so the routing will NOT take effect until it is readable. Move any secret out of it, then `chmod 644` it.")))},SS=()=>process.getuid?.()===0,Ze=e=>{process.stderr.write(`${e}
|
|
368
|
+
`)},wd=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}QF(e.out,t,"utf8"),Ze(v(`# Wrote ${e.out}`))},ah=e=>xe({origin:e.gateway??"http://localhost:8787",subscription:!!e.sso,user:e.user,team:e.team,intent:e.intent??"",intentLabel:e.intentLabel??"",session:e.session??""}),sh=e=>tW(e)||/^[A-Za-z]:[\\/]/.test(e),IS=e=>{if(!e.sso)return;let t=St(e.sso);if(!t)throw new Error("invalid --sso link");let n=e.bin??Oe();if(!e.bin&&!ce())throw new Error("--bin is required because the running binary path is temporary; use a fleet-stable path such as /usr/local/bin/anyray-connect");if(!sh(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}},ES=e=>[`Gateway: ${e.origin}`,"Fleet mode: api-key (routing + headers only \u2014 per-dev keys stay in user settings)",`Attribution: ${ue(e.metadata)??"(none \u2014 pass --team)"}`],ih=(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{}},aW=(e,t)=>({agent_servers:{[Fn]:{command:e,args:[Ql,"claude",t,"jetbrains"],env:{}},[Wn]:{command:e,args:[Ql,"codex",t,"jetbrains"],env:{}}}}),sW=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=${ke(e.openaiBaseUrl)}`,`export ANTHROPIC_BASE_URL=${ke(e.anthropicBaseUrl)}`,""].join(`
|
|
369
|
+
`),iW=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(!sh(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(!nd(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return wd(e,`${JSON.stringify(aW(e.bin,e.npx),null,2)}
|
|
370
|
+
`),Ze(v("# acp.json for ~/.jetbrains/acp.json (per user).")),Ze(v(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ze(v("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ze(v("# An MDM file drop REPLACES the file \u2014 deploy at provision time, or merge agent_servers in your config tool if devs add their own agents.")),0},cW=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&&!sh(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return wd(e,yS(e.sso,e.gateway,e.bin)),Ze(v(`# Fleet bootstrap for ${li("linux")}`)),Ze(v(`# macOS: ${li("darwin")}`)),Ze(v(`# Windows: ${li("win32",{ProgramData:"C:\\ProgramData"})}`)),Ze(v("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},lW=e=>{if(e.sso||e.bin||e.npx||e.user||e.team||e.intent||e.intentLabel||e.session)throw new Error("--tool shell takes only --gateway: the snippet carries base URLs only (keys and attribution ride each user\u2019s enrollment)");let t=ah(e);return wd(e,sW(t)),Ze(v("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),ih(t,Ze),0},dW=e=>{let t=ah(e),n=IS(e),r=n?gd(t,n):gd(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(wd(e,`${JSON.stringify(r,null,2)}
|
|
371
|
+
`),Ze(v(`# managed-settings.json for ${Ot()}`)),n)Ze(v("# Deferred SSO: hooks only; no credential or managed env block.")),Ze(v(`# Push the binary to ${n.binaryPath} before this file.`)),Ze(v("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of ES(t))Ze(v(`# ${o}`));ih(t,Ze)}return 0},uW=async e=>{let t=bS();if(t!=="darwin"&&t!=="linux")return O("`managed --write` is supported on macOS and Linux only. Use `managed --print` and deploy the JSON via your MDM."),1;if(!SS())return O("Refusing to write the system managed-settings.json without root \u2014 re-run with `sudo` (it lives under a system-owned path)."),A(v(" For MDM packaging, use `managed --print` instead and push the file with Jamf / Intune / Ansible.")),1;let n=ah(e),r=IS(e);r||ih(n,u=>_(u.replace(/^!\s*/,"")));let o=Ot(t),a=await B(o),s=r?gd(n,r):gd(n,void 0,{scrubDirectMode:e.scrubDirectMode}),i=e.scrubDirectMode?vn.filter(({name:u})=>{let p=a.env?.[u];return typeof p=="string"&&p.trim()!==""}):[],c=rW(a,s),l=await CS(o);await Y(o,c);let d=await kS(o,l);M(`Wrote ${o}`),vS(o,d);for(let{name:u,cloud:p}of i)_(`${u} was set in this file and is now pinned empty \u2014 Claude Code no longer talks to ${p} directly. The gateway serves it instead; re-add the key here to undo.`);if(r)A(v(` Push the binary to ${r.binaryPath} first; no credential is embedded.`)),A(v(" Configure SSO in the portal before rollout; first-prompt sign-in happens inside Claude Code."));else for(let u of ES(n))A(` ${v(u)}`);return A(v(" Managed settings outrank a user\u2019s ~/.claude/settings.json. Restart Claude Code sessions to pick it up.")),0},pW=async()=>{let e=bS();if(e!=="darwin"&&e!=="linux")return O("`managed --revert` is supported on macOS and Linux only (remove the deployed file via your MDM elsewhere)."),1;if(!SS())return O("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=Ot(e);if(!await x(t))return A(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=await B(t);if(!oW(n))return A(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await CS(t);await Y(t,n);let o=await kS(t,r);return M(`Removed Anyray-owned keys from ${t} (other keys left intact).`),vS(t,o),0},xS=async e=>{let t;try{t=nW(e)}catch(n){return O(n instanceof Error?n.message:"invalid managed arguments"),A(`
|
|
372
|
+
`+oh),1}if(t.help||e.length===0&&!t.mode)return A(oh),0;if(!t.mode)return O("Specify a mode: --print, --write, or --revert."),A(`
|
|
373
|
+
`+oh),1;if(t.out!==void 0&&t.mode!=="print")return O(`--out is valid with --print only, not --${t.mode}.`),1;if(t.scrubDirectMode){let n=t.sso!==void 0?"--sso emits a hooks-only file with no env block":(t.tool??"claude-code")!=="claude-code"?`--tool ${t.tool} does not write Claude Code env`:t.mode==="revert"?"--revert already removes the pin (and leaves a truthy value alone)":void 0;if(n)return O(`--scrub-direct-mode cannot be combined with this mode: ${n}.`),1}try{let n=t.tool??"claude-code";return n!=="claude-code"?t.mode!=="print"?(O(`--tool ${n} supports --print only; deploy the artifact with your MDM.`),1):n==="jetbrains"?iW(t):n==="bootstrap"?cW(t):lW(t):t.mode==="print"?dW(t):t.mode==="write"?await uW(t):await pW()}catch(n){return O(n instanceof Error?n.message:"managed settings failed"),1}};import{spawn as bH}from"node:child_process";import{homedir as AH}from"node:os";import{join as pI}from"node:path";import{readFile as CH,writeFile as fI,chmod as kH,stat as vH,unlink as nI}from"node:fs/promises";var fW=["hook_registration","mcp_registration","hook_binary","beacon_target"],po=e=>e.status==="configured"||e.status==="queued",fo=async(e,t=le)=>{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},ya=async(e,t,n=le)=>{let r=[];for(let o of await fo(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},ch=async(e,t=le)=>{let n=[];for(let r of await fo(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(fW.map(o=>[o,"unreadable"]))})}return n},RS=e=>e.filter(t=>!t.integrationStatus),mW=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=mW(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 yW,writeFile as gW}from"node:fs/promises";import{join as TS}from"node:path";import{z as De}from"zod";var ga="required",hW=e=>e==="subscription"?"subscription":"placeholder",OS=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?hW(t.lane):void 0,a=o!=null&&o!==e.authMode;return{routingUpdated:n,teamUpdated:r,laneUpdated:a,...n?{gateway:t.routingOrigin}:{},...r?{team:t.team}:{},...a?{authMode:o}:{}}},bd=(e,t,n)=>{let r=new Set(t.enabled??[]),o=e.managedTools??[],a=o.filter(u=>r.has(u)||n),s=new Set(e.revertedTools??[]),i=e.revertedTools!=null,c=u=>t.tiers?.[u]??ga,l=[],d=[];for(let u of r){if(o.includes(u))continue;let p=c(u);if(p!=="optional"){if(p!=="locked"){if(!i)continue;if(s.has(u)){p==="required"&&d.push(u);continue}}l.push(u)}}return{candidateIds:a,freshIds:l,tombstonedIds:d}};var wW=1e4,bW=1,AW=De.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),CW=De.object({id:AW,name:De.string().min(1),version:De.string().min(1),body:De.string()}),kW=De.object({version:De.literal(bW).optional(),skills:De.array(CW),updatedAt:De.string().min(1).optional(),routing:De.object({origin:De.string().min(1)}).optional(),team:De.string().min(1).optional(),lane:De.enum(["subscription","org"]).optional().catch(void 0),tools:De.object({enabled:De.array(De.string().min(1)),tiers:De.record(De.string().min(1),De.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional()}),wa=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="TeamPolicyFetchError"}},lh=e=>e instanceof wa&&e.kind==="auth",vW=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",dh=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",ba=async(e,t,n={})=>{let r=n.timeoutMs??wW,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.`:ht(l);throw new wa("unavailable",`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new wa(i.status===401||i.status===403?"auth":"unavailable",`team policy fetch failed: the gateway responded ${i.status} at ${o}`);let c;try{c=await i.json()}catch{throw new wa("malformed","team policy fetch failed: the gateway returned a malformed response")}return kW.parse(c)},_S=/^[a-z0-9][a-z0-9-]{0,31}$/,PS=64,SW=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>_S.test(o)).slice(0,PS).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>_S.test(o)).slice(0,PS).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},di=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??ga)==="locked":!1},Aa=async(e,t={})=>{let n=t.loadProfile??D,r=t.saveProfile??oe,o=t.targetFromProfile??Be,a=t.adapters??le,s=t.repairTools??Mt,i=t.recordManaged??Vn,c=await n(),l={...c},d=OS(c,{routingOrigin:e.routing?.origin?Qt(e.routing.origin):void 0,team:e.team,lane:e.lane}),{routingUpdated:u,teamUpdated:p,laneUpdated:f}=d;(u||p||f)&&(l={...await n()},d.gateway!=null&&(l.gateway=d.gateway),d.team!=null&&(l.team=d.team),d.authMode!=null&&(l.authMode=d.authMode),await r(l));let m=bd(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||p||f),{candidateIds:h,freshIds:w}=m,y=0,g=0,b=0;if(h.length>0||w.length>0){let S=await o(async()=>l);if(S){let I;if(u||p||f){let P=new Set(h);I=[];for(let W of a)if(P.has(W.id))try{(await W.detect()).installed&&I.push(W)}catch{}}else I=await ya(h,S.target.origin,a);let E=new Set(w),R=[];for(let P of a)if(E.has(P.id))try{(await P.detect()).installed&&R.push(P)}catch{}if(y=I.length+R.length,y>0){let P=await s([...I,...R],S.target);g=P.filter(po).length;let W=P.filter(q=>E.has(q.id));if(b=W.filter(po).length,W.length>0)try{await i(W,!1)}catch{}}}}let k=SW(e),C=await n();if(JSON.stringify(k??null)!==JSON.stringify(C.fleetToolPolicy??null)){let{fleetToolPolicy:S,...I}=C;await r({...I,...k?{fleetToolPolicy:k}:{}})}return{routingUpdated:u,teamUpdated:p,laneUpdated:f,toolsRequested:y,toolsApplied:g,toolsEnrolled:b,toolsTombstoned:m.tombstonedIds,profileUpdated:u||p||f}},DS=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!vW(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=TS(d,i.id),p=TS(u,"SKILL.md");await yW(u,{recursive:!0}),await gW(p,IW(i.body),"utf-8"),l.push(p)}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}},IW=e=>e.endsWith(`
|
|
374
374
|
`)?e:`${e}
|
|
375
|
-
`;import{randomBytes as FW}from"node:crypto";var WW=1e4,HW="machine:",TS=e=>e.startsWith(HW),UW="cert-renew",GW=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)},_S=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Hn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:FW(16).toString("hex"),purpose:UW},c;try{c=await(n.signer??wr)(uo(i),t,e.payload.devPublicKey)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),WW),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 f=(await u.json().catch(()=>null))?.cert;return GW(f)?{ok:!0,cert:f}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var um=async(e,t=e.origin,n=le)=>{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}},pm=async(e,t=e.origin,n=le)=>(await um(e,t,n)).complete;var VW=["claude","codex","cursor","opencode"],KW=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],jW=new Set(["missing_key","key_expired"]);var ZW=600*1e3,YW=600*1e3,PS=1440*60*1e3,JW=1440*60*1e3,XW=10080*60*1e3,zW=3600*1e3,qW=720*60*1e3,QW=e=>Math.min(qW,zW*2**Math.max(0,e-1)),li=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ca=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,DS=e=>typeof e=="string"&&KW.includes(e),An=e=>{if(!li(e))return{};let t={};if(Ca(e.watchSince)&&(t.watchSince=e.watchSince),li(e.invoked)){let n={};for(let r of VW){let o=e.invoked[r];Ca(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return li(e.authFailure)&&Ca(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...DS(e.authFailure.code)?{code:e.authFailure.code}:{}}),li(e.repair)&&Ca(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,...Ca(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Cd=e=>{try{let n=JSON.parse(e);if(li(n)&&DS(n.code)&&n.code!=="key_invalid")return n.code}catch{}let t=e.toLowerCase();if(t.includes("valid client key required"))return"key_invalid";if(t.includes("client key required"))return"missing_key"},fm=e=>e!==void 0&&jW.has(e),hm=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=ZW},LS=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),mm=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=YW},NS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),$S=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,MS=(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},BS=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>PS||!fm(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<QW(r.failures??1))},kd=e=>{let t=Object.values(e?.invoked??{}).filter(Ca);return t.length>0?Math.max(...t):null},ym=(e,t)=>{if(kd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=XW},FS=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=JW)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=PS)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var gm="x-anyray-retrieve-probe",vd=8e3,eH=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",WS=(e,t)=>{let n=Gt(e);return t?.probe&&(n[gm]="1"),n},ka=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(),vd);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:WS(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=eH(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)}},Sd=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(),vd);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:WS(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 tH=5e3,nH=2048,rH=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}"`))},va=async(e={})=>{let t=e.readTarget??nt,n=e.fetch??fetch,r=e.timeoutMs??tH,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=Gt(o);i["content-type"]="application/json",i[gm]="1";let c=await n(`${o.origin}/connect/optimize-output`,{method:"POST",headers:i,body:JSON.stringify({}),signal:a.signal});if(c.status===401||c.status===403){let u=(await c.text().catch(()=>"")).slice(0,nH);if(!rH(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let p=Cd(u);return{verdict:"dark",reason:"key_rejected",status:c.status,...p?{code:p}:{}}}if(!c.ok)return{verdict:"indeterminate",reason:c.status>=500?"unreachable":"unsupported",status:c.status};let l;try{l=await c.json()}catch{return{verdict:"indeterminate",reason:"unsupported",status:c.status}}return typeof l=="object"&&l!==null&&l.handled===!0?{verdict:"live",reason:"ok",status:c.status}:{verdict:"indeterminate",reason:"gateway_mismatch",status:c.status}}catch{return{verdict:"indeterminate",reason:"unreachable"}}finally{clearTimeout(s)}},wm=(e,t)=>e.verdict==="dark"?e.reason==="target_null"?{...e,detail:"Hook lane dark: no gateway target resolves on this machine, so the hook sends nothing.",remedy:["Fix: run `anyray-connect` once to (re)write the tool settings and the connect profile.","A hand-templated machine has no ~/.anyray profile and no base URL in the client settings \u2014 the hook silently no-ops."]}:{...e,detail:"Hook lane dark: the gateway rejected this machine\u2019s client key on /connect/optimize-output.",remedy:["The next scheduled refresh re-mints from the enrollment cert automatically and rewrites the tool configs.","If it keeps failing (revoked key, deactivated user, or a key pasted from elsewhere), re-enroll: run `anyray-connect` and follow the enrollment steer above."]}:e.verdict==="live"&&t.hookRegistered&&t.neverInvoked?{verdict:"dark",reason:"never_invoked",...e.status!==void 0?{status:e.status}:{},detail:"Hook lane dark: the hook is installed and the gateway answers, but nothing has invoked the hook here.",remedy:["Installed is not the same as firing \u2014 this seat has produced no hook run in the observation window.","OpenCode: its plugin turns a spawn failure into empty output silently \u2014 check the binary path in the generated plugin and restart OpenCode.","Claude Code / Codex: restart the tool so it re-reads its settings, then run a tool call that produces a large output."]}:e.verdict==="live"?{...e,detail:"Hook lane live: the gateway accepted this machine\u2019s key and answered the optimize probe.",remedy:[]}:{...e,detail:e.reason==="gateway_mismatch"?"Hook lane undetermined: the gateway answered but did not confirm it read the request (it predates the current hook protocol).":e.reason==="unreachable"?"Hook lane undetermined: could not reach the gateway for the probe.":"Hook lane undetermined: the response did not come from a gateway that serves /connect/optimize-output.",remedy:[e.reason==="gateway_mismatch"?"Fix: update the gateway image \u2014 this one predates the gzip-aware optimize-output contract.":"Not counted as a problem. Check the gateway origin and any proxy in front of it (see the Gateway section above)."]};import{randomBytes as sH}from"node:crypto";import{execSync as bm}from"node:child_process";import{hostname as oH}from"node:os";var aH=e=>{try{if(e==="darwin"){let t=bm("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=bm('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 bm("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Ed=(e={platform:process.platform,read:()=>aH(process.platform),hostname:oH})=>e.read().trim()||e.hostname().trim();var Mt=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();if(t)return t.toLowerCase();if((e.platform??process.platform)==="darwin"){let r=e.readMacUuid??(()=>Ed());try{return r().trim().toLowerCase()}catch{return""}}return""};var iH=500,HS=2e3,cH=2e3,lH=250,US=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),iH);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)}},dH=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},uH=e=>new Promise(t=>setTimeout(t,e)),pH=async(e,t,n=uH)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),HS),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=dH(i)??lH,s>cH))return!1}finally{clearTimeout(a)}await n(s)}},fH=async(e,t={})=>{try{let r=(await(t.loadProfile??D)()).enrolledCert,o=await(t.loadDevKey??Ne)(),a=r?.payload?.deploymentId;if(!r||!o||!a)return!1;let s={deploymentId:a,issuedAt:new Date().toISOString(),nonce:sH(16).toString("hex"),events:e},i;try{i=await(t.signer??wr)(uo(s),o,r.payload.devPublicKey)}catch{return!1}return await(t.post??pH)(`${t.origin??Hn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},hH=async(e,t,n={})=>{try{let o=(await(n.loadProfile??D)()).enrolledCert,a=await(n.loadDevKey??Ne)();if(!o||!a)return;await(n.verify??Jt)(e,o,a,{timeoutMs:HS,machineUuid:(n.machineUuid??Mt)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},GS=async(e,t)=>{if(e.length!==0)try{let n=await nt(),r=n&&await US(n.origin,Gt(n),e,t);if(n&&await hH(n.origin,e),r)return;await fH(e)}catch{}},Am=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 yo=["hook_registration","mcp_registration","hook_binary","beacon_target"];var KS=128,jS=300*1e3,mH=["repaired","repair_failed","flapping","pending"],yH=["settings_not_writable","apply_unconfirmed","apply_threw"],ZS=["rebroke_same_day","repeat_days"],YS=new Set(le.map(e=>e.id)),mo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ui=(e,t)=>typeof e=="string"&&t.some(n=>n===e),JS=e=>ui(e,yo),Id=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},Ar=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,di=e=>{if(!(!Array.isArray(e)||!e.every(JS)))return Un(e)},gH=e=>{if(!mo(e))return;let t=di(e.checks);if(!(!Ar(e.since)||!ui(e.reason,ZS)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},wH=e=>{if(!mo(e))return;let t={};Id(e.day)&&(t.day=e.day),Ar(e.attempts)&&(t.attempts=e.attempts);let n=di(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=di(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=di(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=di(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Id(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Ar(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),mo(e.lastRepaired)){let i={};for(let c of yo){let l=e.lastRepaired[c];Ar(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=gH(e.flapping);return s&&(t.flapping=s),t},bH=e=>{if(!mo(e)||!Id(e.day)||!Ar(e.sequence)||e.sequence===0||typeof e.tool!="string"||!YS.has(e.tool)||!JS(e.checkId)||!ui(e.status,mH)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!ui(e.errorClass,yH))return;t=e.errorClass}else if(e.status==="flapping"){if(!ui(e.errorClass,ZS))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,...Ar(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},VS=e=>{if(!mo(e))return{};let t={};if(mo(e.adapters)){let n={};for(let r of YS){let o=wH(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(bH).filter(n=>n!==void 0).slice(-KS)),Ar(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),mo(e.report)&&Id(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Ar(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},AH=e=>new Date(e).toISOString().slice(0,10),CH=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,Un=e=>[...new Set(e)],xd=(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}:{}}},pi=(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(-KS),nextSequence:r}},kH=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),vH=async e=>await Me(async()=>e)??null,SH=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=xd(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)},XS=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:CH(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:Un([...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:Un([...i?.checks??[],...t])}}:{}},slowFlap:a}},EH=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=xd(d,n),p=u.awaiting??[],f=a.get(l);if(p.length===0||t.has(l)||!f){c[l]=u;continue}let h=p.filter(g=>f.checks[g]==="owned"),m=p.filter(g=>{let b=f.checks[g];return b==="missing"||b==="foreign"}),w=p.filter(g=>{let b=f.checks[g];return b===void 0||b==="unreadable"}),y=XS(u,h,n,r);c[l]={...y.adapter,awaiting:w.length>0?w:void 0},i=pi(i,n,[...h.map(g=>({tool:l,checkId:g,status:"repaired"})),...m.map(g=>({tool:l,checkId:g,status:"repair_failed",errorClass:"apply_unconfirmed"})),...y.slowFlap?h.map(g=>({tool:l,checkId:g,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},IH=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=xd(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],p=t.filter(y=>!d.includes(y)||u.includes(y)),f=p.filter(y=>u.includes(y)),h=l.attempts??0;if(h>=2||p.length===0&&!n){let y=f.filter(k=>!(l.brokenReportedChecks??[]).includes(k));if(y.length===0)return{result:void 0};let g=l.flapping;return c[e]={...l,brokenReportedChecks:Un([...l.brokenReportedChecks??[],...y]),flapping:{since:g?.since??a,reason:"rebroke_same_day",checks:Un([...g?.checks??[],...y])}},{next:pi({...i,adapters:c},o,y.map(k=>({tool:e,checkId:k,status:"flapping",errorClass:"rebroke_same_day"}))),result:void 0}}let m=l.flapping;return c[e]={...l,attempts:h+1,attemptedChecks:Un([...d,...p]),confirmedChecks:u.filter(y=>!p.includes(y)),brokenReportedChecks:Un([...l.brokenReportedChecks??[],...f]),...f.length>0?{flapping:{since:m?.since??a,reason:"rebroke_same_day",checks:Un([...m?.checks??[],...f])}}:{}},{next:pi({...i,adapters:c},o,f.map(y=>({tool:e,checkId:y,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:p,fastFlaps:f}}},void 0),xH=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=xd(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:Un([...l.awaiting??[],...t])},{next:pi({...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:[],p=XS(l,d,o,a);c[e]=p.adapter;let f=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:pi({...i,adapters:c},o,[...d.map(h=>({tool:e,checkId:h,status:"repaired"})),...u.map(h=>({tool:e,checkId:h,status:"repair_failed",errorClass:f})),...p.slowFlap?d.map(h=>({tool:e,checkId:h,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},RH=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>=jS));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(kH),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)},OH=async(e,t,n,r,o,a)=>{let s=[],i=!1,c=new Set(n.map(u=>u.adapter));for(let{adapter:u,checks:p}of t){let f=r.adapters?.[u.id];for(let h of yo){let m=p[h];if(!m||m==="unreadable")continue;let w,y;f?.awaiting?.includes(h)&&c.has(u.id)?w="pending":m==="missing"&&f?.flapping?.checks.includes(h)?(w="flapping",y=f.flapping.reason):w=m==="owned"?"ok":m,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:h,status:w,...y?{errorClass:y}:{}})}}let l=Date.parse(e.enrolledCert?.payload.expiresAt??e.enrolledCertExpiry??"");e.enrolledCert&&Number.isFinite(l)&&(l<=o?(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"expired"})):l-o<=336*60*60*1e3&&(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"problems",errorClass:"cert_expiring"}))),e.refreshSchedulerEnabled&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??Po)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??ar)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=FS(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},TH=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<jS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await OH(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)},zS=async(e,t,n)=>{let r=n.now??Date.now,o=AH(r()),a=e.managedTools??[],s={...n,readState:async()=>VS(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(VS(l)),c)};try{let i=await(s.findIntegrations??cm)(a);await SH(i,o,s);let c=await(s.listPending??rr)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await EH(i,l,o,r(),s);let d=await(s.resolveTarget??vH)(e),u=d?await(s.findDrifted??ya)(a,d.target.origin):[],p=new Set(u.map(y=>y.id)),f=new Map(i.map(y=>[y.adapter.id,y]));for(let y of u)f.has(y.id)||f.set(y.id,{adapter:y,checks:{}});let h=!1,m=(s.runtimeDurable??ce)();if(d)for(let{adapter:y,checks:g}of f.values()){let b=m?yo.filter(P=>g[P]==="missing"):[];if(b.length===0&&!p.has(y.id))continue;let k=g;if(y.integrationStatus)try{k=await y.integrationStatus()}catch{k=Object.fromEntries(yo.map(P=>[P,"unreadable"]))}let C=b.filter(P=>k[P]==="missing"),S=p.has(y.id);if(S&&y.pointsAt&&(S=!await y.pointsAt(d.target.origin).catch(()=>!0)),C.length===0&&!S)continue;let E=await IH(y.id,C,S,l.has(y.id),o,r(),s);if(!E)continue;let[I]=await(s.repair??$t)([y],d.target);if(!I)continue;h=!0;let R;I.status==="configured"&&y.integrationStatus&&(R=await y.integrationStatus().catch(()=>{})),await xH(y.id,E.checks,I,R,o,r(),s)}await RH(o,r(),t,s),i=await(s.findIntegrations??cm)(a);let w=await(s.listPending??rr)().catch(()=>[]);return await TH(e,i,w,o,r(),t,s),h}catch{return!1}};var MH=14,BH=.35,FH=900*1e3,QS=360*60*1e3,WH=.2,HH=1800*1e3,eE=3600*1e3,UH=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),GH=300*1e3,VH=30*1e3,KH=900*1e3,jH=(e=0)=>Math.min(KH,VH*2**Math.max(0,e)),tE=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}},nE=1440*60*1e3,ZH=300*1e3,YH=.25,JH=.5,rE=3600*1e3,XH=720*60*60*1e3,zH=360*60*1e3,qH=1440*60*1e3,QH=()=>cE(DH(),".anyray"),Cm=()=>cE(QH(),"refresh-state.json"),km=e=>process.env?.[e],dE=()=>km("ANYRAY_REFRESH_DISABLE")==="true",vm=()=>{let e=km("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:MH)*qH},Od=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},uE=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),eU=10080*60*1e3,pE=(e,t,n=Date.now())=>{let r=[],o=Od(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)<=eU},Sm=e=>{let t=vm(),n=e?Od(e):void 0;if(!n)return t;let r=Math.max(FH,Math.round(n*BH));return Math.min(t,r)},tU=e=>{let t=km("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(QS,Math.max(HH,Math.round(e*WH))):QS},St=async()=>{try{let e=await LH(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 lE(n,JSON.stringify(e),{mode:384}),await me(n,t),await NH(t,384).catch(()=>{})}catch{}},nU=3e4,rU=()=>`${Cm()}.lock`,oE=async e=>{try{return await lE(e,String(process.pid),{flag:"wx",mode:384}),!0}catch(t){if(t.code!=="EEXIST")throw t;return!1}},lt=async(e,t,n={})=>{let r=n.now??Date.now,o=n.readState??St,a=n.writeState??Td,s=rU(),i=!1;try{if(i=await oE(s),!i){if(await $H(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<nU)return t;await qS(s).catch(()=>{}),i=await oE(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await qS(s).catch(()=>{})}},Rd=async(e,t={})=>{await lt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Sa=async(e={},t={})=>{let n=t.now??Date.now,r=e.expiresAt?Date.parse(e.expiresAt):NaN,o=e.keyTtlMs??(Number.isFinite(r)&&r-n()>0?r-n():void 0);await lt(({lastError:a,...s})=>({next:{...s,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??s.keyTtlMs},result:void 0}),void 0,t).catch(()=>{})},go=async(e={})=>{let t=e.now??Date.now;await lt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},oU=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(XH,Math.max(rE,Math.round(o*JH))):rE},fE=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,Em=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??oe,a=n.loadProfile??D,s=n.loadDevKey??Ne,i=n.renew??_S,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(TS(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()>oU(e))return{outcome:"not-due",profile:e};if(!await lt(w=>r()-(w.lastCertRenewAt??0)<zH?{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 p=await a().catch(()=>e);if(!p.enrolledCert)return{outcome:"failed",profile:e};if(!await fE(p,c.sig,t,s))return{outcome:"superseded",profile:p};let f=u.cert.payload.expiresAt,h=Date.parse(f)-r(),m={...p,enrolledCert:u.cert,enrolledCertExpiry:f,...Number.isFinite(h)&&h>0?{enrolledCertLifetimeMs:h}:{}};return await o(m),{outcome:"renewed",profile:m}},aE=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*YH):nE,r=Math.min(nE,n);return Math.min(r,ZH*2**Math.max(0,e-1))},aU=()=>{let{command:e,args:t}=Qn(Yn);return{exe:e,args:t}},Cr=async(e={})=>{if(dE())return;let t=e.now??Date.now,n=e.readState??St,r=e.writeState??Td,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=aU();PH(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await lt(s=>t()-(s.lastSpawnAt??0)<tU(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},sU=pm,iU=async(e,t=!1)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await Me(async()=>e);if(!r)return!1;let o=await ya(n,r.target.origin),a=t?SS(o):o;return a.length===0?!1:(await $t(a,r.target),!0)}catch{return!1}},cU=async(e,t,n,r,o)=>{try{let a=new Set(e.managedTools??[]),s=le.filter(d=>a.has(d.id));if(s.length===0)return!1;let i=await r().catch(()=>{}),c=Ie({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:i,user:e.name,team:e.team}),l=await o(c,c.origin,s);return l.matched>0&&l.complete}catch{return!1}},lU=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??St,a=t.writeState??Td;return zS(e,Ae,{now:r,deadWatcherObserved:n,readHookLane:()=>_d({now:r,readState:o,writeState:a}),readState:async()=>(await o()).selfcheck??{},claimState:async(s,i)=>lt(c=>{let l=s(c.selfcheck??{});return{...l.next?{next:{...c,selfcheck:l.next}}:{},result:l.result}},i,{now:r,readState:o,writeState:a})})},_d=async(e={})=>{let n=await(e.readState??St)().catch(()=>({}));return An(n.hookLane)},hE=async(e,t={})=>{try{let n=t.now??Date.now,r=await _d(t);if(!hm(r,e,n()))return;await lt(o=>{let a=An(o.hookLane);return hm(a,e,n())?{next:{...o,hookLane:LS(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},mE=async(e,t={})=>{try{let n=t.now??Date.now,r=await _d(t);if(!mm(r,n()))return;await lt(o=>{let a=An(o.hookLane);return mm(a,n())?{next:{...o,hookLane:NS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},dU=async(e={})=>{try{let t=e.now??Date.now;if((await _d(e)).watchSince!==void 0)return;await lt(n=>{let r=An(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:$S(r,t())},result:void 0}},void 0,e)}catch{}},sE=async(e,t={})=>{try{let n=t.now??Date.now;await lt(r=>{let o=An(r.hookLane),a=MS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},yE=async(e={})=>{try{if((await(e.readState??St)()).repathedAt)return"skipped";let n=e.now??Date.now,r=async()=>lt(c=>c.repathedAt?{result:!1}:{next:{...c,repathedAt:n()},result:!0},!1,e).catch(()=>!1);if(!(e.launcherBacked??Lg)())return await r()?"stamped":"skipped";let o=await(e.load??D)(),s=await(e.findTools??ho)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await Me(async()=>o);return!i||!await r()?"skipped":(await(e.repair??$t)(s,i.target),"repathed")}catch{return"skipped"}},gE=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??St)()).appliedRevision;if((r??0)>=t)return"skipped";let o=async()=>lt(d=>(d.appliedRevision??0)>=t?{result:!1}:{next:{...d,appliedRevision:t},result:!0},!1,e).catch(()=>!1),a=await(e.load??D)(),i=await(e.findTools??ho)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await Me(async()=>a);return!c||!await o()?"skipped":(await(e.repair??$t)(i,c.target)).some(d=>d.status==="failed")?(await lt(d=>{if(d.appliedRevision!==t)return{result:void 0};let u={...d};return r===void 0?delete u.appliedRevision:u.appliedRevision=r,{next:u,result:void 0}},void 0,e).catch(()=>{}),"retry"):"swept"}catch{return"skipped"}},uU=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await ba(e.gateway,e.clientKey),n=await Aa(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},iE=async(e,t,n)=>{let o=await(t.reconcilePolicy??uU)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>iU(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},Xt=async(e={})=>{if(dE())return"disabled";let t=e.now??Date.now,n=e.loadProfile??D,r=e.saveProfile??oe,o=e.loadDevKey??Ne,a=e.readState??St,s=e.writeState??Td,i=e.remint??Jt,c=e.heartbeat??nS,l=e.detectSeat??fn,d=e.rewriteTools??sU,u=e.rewriteHookLaneTools??um,p=e.probeHookLane??va,f=e.classifyBeacon??lc,h=e.force===!0,m=!1,w=!1,y=!1,g=!1;e.hookLaneRepair===!0&&(h=!0,g=!0);let b=async C=>{if(!g){C==="repaired"&&await sE("none",{now:t,readState:a,writeState:s});return}let S=C;if(C==="repaired"){let E=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));S=E.verdict==="live"?"repaired":E.verdict==="dark"?"repair_failed":"unverified"}await sE(S,{now:t,readState:a,writeState:s})},k=async()=>{if(!e.runAmbientSelfcheck||w||!m)return!1;w=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(E=>lU(E,{now:t,readState:a,writeState:s},y)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await rr().then(F=>F.some(Z=>!ar(Z.watcherPid))).catch(()=>!1),await dU({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??tb)();let C=await n();if(m=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let S=C.gateway,E=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(E)||E<=t())return"cert-expired";let I=await o();if(!I)return"not-enrolled";let R=(e.resolveMachineUuid??Mt)()||void 0,P=await Em(C,I,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=P.profile;let W=P.outcome==="renewed",q=C.enrolledCert;if(!q)return"not-enrolled";let de=Date.parse(C.clientKeyExpiresAt??""),ie=Number.isFinite(de)?de-t():0,j=await a(),ge=!C.clientKey||ie<=Sm(C);if(!h&&BS(An(j.hookLane),t())&&await f().catch(()=>"unreadable")!=="foreign"&&(h=!0,g=!0),C.clientKey&&(h||ge)){let F=await lt(Z=>{let X=t()-(Z.lastAttemptAt??0);return X<eE?{result:"throttled"}:Z.failureCount&&X<aE(Z.failureCount,Z.keyTtlMs)?{result:"backoff"}:{next:{...Z,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(F!=="ok")return F;try{let Z=await c(S,C.clientKey,q,I,{machineUuid:R}),X=await n().catch(()=>C);return X.clientKey!==C.clientKey||X.enrolledCert?.sig!==q.sig?"failed":(await r({...X,clientKeyExpiresAt:Z.expiresAt}),await Rd(({lastError:Ze,...Fe})=>({...Fe,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Od(C)??Fe.keyTtlMs}),{now:t,readState:a,writeState:s}),g?await b(await cU(C,S,C.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Z){let X=tE(Z);return await Rd(Ze=>({...Ze,lastAttemptAt:t(),failureCount:(Ze.failureCount??0)+1,lastError:{name:Z instanceof Error?Z.name:"Error",...X!==void 0?{code:X}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),Z instanceof fa&&Z.policyCode==="managed_device_required"&&console.error(Z.message),Z instanceof fa?Z.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!h&&C.clientKey&&!ge){let F=await iE(C,e,n),Z=await k();return F||Z?"repaired":W?"cert-renewed":"not-due"}let he=await lt(F=>{let Z=t()-(F.lastAttemptAt??0);if(h)return Z<jH(F.failureCount)?{result:"throttled"}:{next:{...F,lastAttemptAt:t()},result:"ok"};let X=F.lastError?.code!==void 0&&UH.has(F.lastError.code)?GH:eE;return Z<X?{result:"throttled"}:F.failureCount&&Z<aE(F.failureCount,F.keyTtlMs)?{result:"backoff"}:{next:{...F,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(he!=="ok")return he;try{let F=await i(S,q,I,{machineUuid:R}),Z=await l().catch(()=>{}),X=Ie({origin:S,clientKey:F.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Z,user:C.name,team:C.team});if(await d(X,X.origin)===!1)throw new Error("one or more configured tools rejected the refreshed key");let Fe=await n().catch(()=>C),T=null;Fe.enrolledCert&&await fE(Fe,q.sig,I,o)&&(T={...Fe,clientKey:F.key,clientKeyExpiresAt:F.expiresAt??Fe.clientKeyExpiresAt},await r(T));let N=F.expiresAt?Date.parse(F.expiresAt):NaN,J=Od(C)??(Number.isFinite(N)&&N-t()>0?N-t():void 0);return await Rd(({lastError:ue,...qt})=>({...qt,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:J??qt.keyTtlMs}),{now:t,readState:a,writeState:s}),T&&await iE(T,e,n),await b(T?"repaired":"repair_failed"),await k(),"refreshed"}catch(F){let Z=tE(F);return await Rd(X=>({...X,lastAttemptAt:t(),failureCount:(X.failureCount??0)+1,lastError:{name:F instanceof Error?F.name:"Error",...Z!==void 0?{code:Z}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),F instanceof ht&&F.policyCode==="managed_device_required"&&console.error(F.message),F instanceof ht?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await k()}catch{}}};var pU=`anyray-connect print-key [--json | --passthrough-headers]
|
|
375
|
+
`;import{randomBytes as EW}from"node:crypto";var xW=1e4,RW="machine:",LS=e=>e.startsWith(RW),OW="cert-renew",TW=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)},NS=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Hn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:EW(16).toString("hex"),purpose:OW},c;try{c=await(n.signer??wr)(lo(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),xW),u;try{u=await r(`${a}/v1/cert/renew`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({cert:e,challenge:i,sig:c}),signal:l.signal})}finally{clearTimeout(d)}if(!u.ok)return{ok:!1,refused:u.status>=400&&u.status<500&&u.status!==429};let f=(await u.json().catch(()=>null))?.cert;return TW(f)?{ok:!0,cert:f}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var uh=async(e,t=e.origin,n=le)=>{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}},ph=async(e,t=e.origin,n=le)=>(await uh(e,t,n)).complete;var _W=["claude","codex","cursor","opencode"],PW=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],DW=new Set(["missing_key","key_expired"]);var LW=600*1e3,NW=600*1e3,$S=1440*60*1e3,$W=1440*60*1e3,MW=10080*60*1e3,BW=3600*1e3,FW=720*60*1e3,WW=e=>Math.min(FW,BW*2**Math.max(0,e-1)),ui=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ca=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,MS=e=>typeof e=="string"&&PW.includes(e),An=e=>{if(!ui(e))return{};let t={};if(Ca(e.watchSince)&&(t.watchSince=e.watchSince),ui(e.invoked)){let n={};for(let r of _W){let o=e.invoked[r];Ca(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return ui(e.authFailure)&&Ca(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...MS(e.authFailure.code)?{code:e.authFailure.code}:{}}),ui(e.repair)&&Ca(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,...Ca(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Ad=e=>{try{let n=JSON.parse(e);if(ui(n)&&MS(n.code)&&n.code!=="key_invalid")return n.code}catch{}let t=e.toLowerCase();if(t.includes("valid client key required"))return"key_invalid";if(t.includes("client key required"))return"missing_key"},fh=e=>e!==void 0&&DW.has(e),mh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=LW},BS=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),hh=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=NW},FS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),WS=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,HS=(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},US=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>$S||!fh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<WW(r.failures??1))},Cd=e=>{let t=Object.values(e?.invoked??{}).filter(Ca);return t.length>0?Math.max(...t):null},yh=(e,t)=>{if(Cd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=MW},GS=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=$W)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=$S)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var gh="x-anyray-retrieve-probe",kd=8e3,HW=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",VS=(e,t)=>{let n=Vt(e);return t?.probe&&(n[gh]="1"),n},ka=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(),kd);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:VS(e,n),body:JSON.stringify({handle:t,...n?.startLine!==void 0&&{startLine:n.startLine},...n?.endLine!==void 0&&{endLine:n.endLine},...n?.grep!==void 0&&{grep:n.grep}}),signal:r.signal});if(a.status===404)return await a.json().then(c=>typeof c=="object"&&c!==null).catch(()=>!1)?{ok:!1,kind:"not-found",message:`No stashed content for handle ${t} (unknown or expired).`}:{ok:!1,kind:"unsupported",message:"Gateway has no /connect/retrieve route (update the gateway image)."};if(!a.ok){let i=await a.json().catch(()=>{}),c=HW(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)}},vd=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(),kd);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:VS(e,r),body:JSON.stringify({query:t,...typeof n=="number"?{k:n}:{}}),signal:o.signal});if(!s.ok)return{ok:!1,kind:s.status===401||s.status===403?"auth":"unavailable",message:`Recall unavailable (gateway returned HTTP ${s.status}).`};let i;try{i=await s.json()}catch{return{ok:!1,kind:"malformed",message:"Recall returned malformed JSON."}}return Array.isArray(i?.matches)?{ok:!0,matches:i.matches}:{ok:!1,kind:"malformed",message:"Recall returned no matches list."}}catch(s){let i=s instanceof Error&&s.name==="AbortError";return{ok:!1,kind:i?"timeout":"network",message:i?"Recall timed out.":`Recall failed: ${s instanceof Error?s.message:String(s)}`}}finally{clearTimeout(a)}};var UW=5e3,GW=2048,VW=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}"`))},va=async(e={})=>{let t=e.readTarget??nt,n=e.fetch??fetch,r=e.timeoutMs??UW,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=Vt(o);i["content-type"]="application/json",i[gh]="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,GW);if(!VW(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let p=Ad(u);return{verdict:"dark",reason:"key_rejected",status:c.status,...p?{code:p}:{}}}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)}},wh=(e,t)=>e.verdict==="dark"?e.reason==="target_null"?{...e,detail:"Hook lane dark: no gateway target resolves on this machine, so the hook sends nothing.",remedy:["Fix: run `anyray-connect` once to (re)write the tool settings and the connect profile.","A hand-templated machine has no ~/.anyray profile and no base URL in the client settings \u2014 the hook silently no-ops."]}:{...e,detail:"Hook lane dark: the gateway rejected this machine\u2019s client key on /connect/optimize-output.",remedy:["The next scheduled refresh re-mints from the enrollment cert automatically and rewrites the tool configs.","If it keeps failing (revoked key, deactivated user, or a key pasted from elsewhere), re-enroll: run `anyray-connect` and follow the enrollment steer above."]}:e.verdict==="live"&&t.hookRegistered&&t.neverInvoked?{verdict:"dark",reason:"never_invoked",...e.status!==void 0?{status:e.status}:{},detail:"Hook lane dark: the hook is installed and the gateway answers, but nothing has invoked the hook here.",remedy:["Installed is not the same as firing \u2014 this seat has produced no hook run in the observation window.","OpenCode: its plugin turns a spawn failure into empty output silently \u2014 check the binary path in the generated plugin and restart OpenCode.","Claude Code / Codex: restart the tool so it re-reads its settings, then run a tool call that produces a large output."]}:e.verdict==="live"?{...e,detail:"Hook lane live: the gateway accepted this machine\u2019s key and answered the optimize probe.",remedy:[]}:{...e,detail:e.reason==="gateway_mismatch"?"Hook lane undetermined: the gateway answered but did not confirm it read the request (it predates the current hook protocol).":e.reason==="unreachable"?"Hook lane undetermined: could not reach the gateway for the probe.":"Hook lane undetermined: the response did not come from a gateway that serves /connect/optimize-output.",remedy:[e.reason==="gateway_mismatch"?"Fix: update the gateway image \u2014 this one predates the gzip-aware optimize-output contract.":"Not counted as a problem. Check the gateway origin and any proxy in front of it (see the Gateway section above)."]};import{randomBytes as ZW}from"node:crypto";import{execSync as bh}from"node:child_process";import{hostname as KW}from"node:os";var jW=e=>{try{if(e==="darwin"){let t=bh("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=bh('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 bh("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Sd=(e={platform:process.platform,read:()=>jW(process.platform),hostname:KW})=>e.read().trim()||e.hostname().trim();var Bt=(e={})=>{let t=(e.envUuid??process.env.ANYRAY_MACHINE_UUID??"").trim();if(t)return t.toLowerCase();if((e.platform??process.platform)==="darwin"){let r=e.readMacUuid??(()=>Sd());try{return r().trim().toLowerCase()}catch{return""}}return""};var YW=500,KS=2e3,JW=2e3,XW=250,jS=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),YW);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)}},zW=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},qW=e=>new Promise(t=>setTimeout(t,e)),QW=async(e,t,n=qW)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),KS),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=zW(i)??XW,s>JW))return!1}finally{clearTimeout(a)}await n(s)}},eH=async(e,t={})=>{try{let r=(await(t.loadProfile??D)()).enrolledCert,o=await(t.loadDevKey??$e)(),a=r?.payload?.deploymentId;if(!r||!o||!a)return!1;let s={deploymentId:a,issuedAt:new Date().toISOString(),nonce:ZW(16).toString("hex"),events:e},i;try{i=await(t.signer??wr)(lo(s),o)}catch{return!1}return await(t.post??QW)(`${t.origin??Hn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},tH=async(e,t,n={})=>{try{let o=(await(n.loadProfile??D)()).enrolledCert,a=await(n.loadDevKey??$e)();if(!o||!a)return;await(n.verify??Xt)(e,o,a,{timeoutMs:KS,machineUuid:(n.machineUuid??Bt)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},ZS=async(e,t)=>{if(e.length!==0)try{let n=await nt(),r=n&&await jS(n.origin,Vt(n),e,t);if(n&&await tH(n.origin,e),r)return;await eH(e)}catch{}},Ah=async(e,t,n={readTarget:()=>nt("profile"),post:jS})=>{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 ho=["hook_registration","mcp_registration","hook_binary","beacon_target"];var JS=128,XS=300*1e3,nH=["repaired","repair_failed","flapping","pending"],rH=["settings_not_writable","apply_unconfirmed","apply_threw"],zS=["rebroke_same_day","repeat_days"],qS=new Set(le.map(e=>e.id)),mo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fi=(e,t)=>typeof e=="string"&&t.some(n=>n===e),QS=e=>fi(e,ho),Id=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},Ar=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,pi=e=>{if(!(!Array.isArray(e)||!e.every(QS)))return Un(e)},oH=e=>{if(!mo(e))return;let t=pi(e.checks);if(!(!Ar(e.since)||!fi(e.reason,zS)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},aH=e=>{if(!mo(e))return;let t={};Id(e.day)&&(t.day=e.day),Ar(e.attempts)&&(t.attempts=e.attempts);let n=pi(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=pi(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=pi(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=pi(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Id(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Ar(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),mo(e.lastRepaired)){let i={};for(let c of ho){let l=e.lastRepaired[c];Ar(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=oH(e.flapping);return s&&(t.flapping=s),t},sH=e=>{if(!mo(e)||!Id(e.day)||!Ar(e.sequence)||e.sequence===0||typeof e.tool!="string"||!qS.has(e.tool)||!QS(e.checkId)||!fi(e.status,nH)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!fi(e.errorClass,rH))return;t=e.errorClass}else if(e.status==="flapping"){if(!fi(e.errorClass,zS))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,...Ar(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},YS=e=>{if(!mo(e))return{};let t={};if(mo(e.adapters)){let n={};for(let r of qS){let o=aH(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(sH).filter(n=>n!==void 0).slice(-JS)),Ar(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),mo(e.report)&&Id(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Ar(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},iH=e=>new Date(e).toISOString().slice(0,10),cH=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,Un=e=>[...new Set(e)],Ed=(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}:{}}},mi=(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(-JS),nextSequence:r}},lH=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),dH=async e=>await Be(async()=>e)??null,uH=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=Ed(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)},eI=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:cH(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:Un([...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:Un([...i?.checks??[],...t])}}:{}},slowFlap:a}},pH=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=Ed(d,n),p=u.awaiting??[],f=a.get(l);if(p.length===0||t.has(l)||!f){c[l]=u;continue}let m=p.filter(g=>f.checks[g]==="owned"),h=p.filter(g=>{let b=f.checks[g];return b==="missing"||b==="foreign"}),w=p.filter(g=>{let b=f.checks[g];return b===void 0||b==="unreadable"}),y=eI(u,m,n,r);c[l]={...y.adapter,awaiting:w.length>0?w:void 0},i=mi(i,n,[...m.map(g=>({tool:l,checkId:g,status:"repaired"})),...h.map(g=>({tool:l,checkId:g,status:"repair_failed",errorClass:"apply_unconfirmed"})),...y.slowFlap?m.map(g=>({tool:l,checkId:g,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},fH=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Ed(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],p=t.filter(y=>!d.includes(y)||u.includes(y)),f=p.filter(y=>u.includes(y)),m=l.attempts??0;if(m>=2||p.length===0&&!n){let y=f.filter(k=>!(l.brokenReportedChecks??[]).includes(k));if(y.length===0)return{result:void 0};let g=l.flapping;return c[e]={...l,brokenReportedChecks:Un([...l.brokenReportedChecks??[],...y]),flapping:{since:g?.since??a,reason:"rebroke_same_day",checks:Un([...g?.checks??[],...y])}},{next:mi({...i,adapters:c},o,y.map(k=>({tool:e,checkId:k,status:"flapping",errorClass:"rebroke_same_day"}))),result:void 0}}let h=l.flapping;return c[e]={...l,attempts:m+1,attemptedChecks:Un([...d,...p]),confirmedChecks:u.filter(y=>!p.includes(y)),brokenReportedChecks:Un([...l.brokenReportedChecks??[],...f]),...f.length>0?{flapping:{since:h?.since??a,reason:"rebroke_same_day",checks:Un([...h?.checks??[],...f])}}:{}},{next:mi({...i,adapters:c},o,f.map(y=>({tool:e,checkId:y,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:p,fastFlaps:f}}},void 0),mH=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Ed(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:Un([...l.awaiting??[],...t])},{next:mi({...i,adapters:c},o,t.map(m=>({tool:e,checkId:m,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(m=>r[m]==="owned"):[],u=n.status==="configured"&&r?t.filter(m=>{let h=r[m];return h==="missing"||h==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],p=eI(l,d,o,a);c[e]=p.adapter;let f=n.status==="failed"?n.errorClass??"apply_threw":"apply_unconfirmed";return{next:mi({...i,adapters:c},o,[...d.map(m=>({tool:e,checkId:m,status:"repaired"})),...u.map(m=>({tool:e,checkId:m,status:"repair_failed",errorClass:f})),...p.slowFlap?d.map(m=>({tool:e,checkId:m,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},hH=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>=XS));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??Ah)(o.map(lH),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)},yH=async(e,t,n,r,o,a)=>{let s=[],i=!1,c=new Set(n.map(u=>u.adapter));for(let{adapter:u,checks:p}of t){let f=r.adapters?.[u.id];for(let m of ho){let h=p[m];if(!h||h==="unreadable")continue;let w,y;f?.awaiting?.includes(m)&&c.has(u.id)?w="pending":h==="missing"&&f?.flapping?.checks.includes(m)?(w="flapping",y=f.flapping.reason):w=h==="owned"?"ok":h,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:m,status:w,...y?{errorClass:y}:{}})}}let l=Date.parse(e.enrolledCert?.payload.expiresAt??e.enrolledCertExpiry??"");e.enrolledCert&&Number.isFinite(l)&&(l<=o?(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"expired"})):l-o<=336*60*60*1e3&&(i=!0,s.push({tool:"connect",checkId:"enrollment_cert",status:"problems",errorClass:"cert_expiring"}))),e.refreshSchedulerEnabled&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??_o)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??ar)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=GS(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},gH=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<XS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await yH(e,t,n,c,o,s);await(s.report??Ah)(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)},tI=async(e,t,n)=>{let r=n.now??Date.now,o=iH(r()),a=e.managedTools??[],s={...n,readState:async()=>YS(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(YS(l)),c)};try{let i=await(s.findIntegrations??ch)(a);await uH(i,o,s);let c=await(s.listPending??rr)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await pH(i,l,o,r(),s);let d=await(s.resolveTarget??dH)(e),u=d?await(s.findDrifted??ya)(a,d.target.origin):[],p=new Set(u.map(y=>y.id)),f=new Map(i.map(y=>[y.adapter.id,y]));for(let y of u)f.has(y.id)||f.set(y.id,{adapter:y,checks:{}});let m=!1,h=(s.runtimeDurable??ce)();if(d)for(let{adapter:y,checks:g}of f.values()){let b=h?ho.filter(P=>g[P]==="missing"):[];if(b.length===0&&!p.has(y.id))continue;let k=g;if(y.integrationStatus)try{k=await y.integrationStatus()}catch{k=Object.fromEntries(ho.map(P=>[P,"unreadable"]))}let C=b.filter(P=>k[P]==="missing"),S=p.has(y.id);if(S&&y.pointsAt&&(S=!await y.pointsAt(d.target.origin).catch(()=>!0)),C.length===0&&!S)continue;let I=await fH(y.id,C,S,l.has(y.id),o,r(),s);if(!I)continue;let[E]=await(s.repair??Mt)([y],d.target);if(!E)continue;m=!0;let R;E.status==="configured"&&y.integrationStatus&&(R=await y.integrationStatus().catch(()=>{})),await mH(y.id,I.checks,E,R,o,r(),s)}await hH(o,r(),t,s),i=await(s.findIntegrations??ch)(a);let w=await(s.listPending??rr)().catch(()=>[]);return await gH(e,i,w,o,r(),t,s),m}catch{return!1}};var SH=14,IH=.35,EH=900*1e3,rI=360*60*1e3,xH=.2,RH=1800*1e3,oI=3600*1e3,OH=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),TH=300*1e3,_H=30*1e3,PH=900*1e3,DH=(e=0)=>Math.min(PH,_H*2**Math.max(0,e)),aI=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}},sI=1440*60*1e3,LH=300*1e3,NH=.25,$H=.5,iI=3600*1e3,MH=720*60*60*1e3,BH=360*60*1e3,FH=1440*60*1e3,WH=()=>pI(AH(),".anyray"),Ch=()=>pI(WH(),"refresh-state.json"),kh=e=>process.env?.[e],mI=()=>kh("ANYRAY_REFRESH_DISABLE")==="true",vh=()=>{let e=kh("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:SH)*FH},Rd=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},hI=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),HH=10080*60*1e3,yI=(e,t,n=Date.now())=>{let r=[],o=Rd(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)<=HH},Sh=e=>{let t=vh(),n=e?Rd(e):void 0;if(!n)return t;let r=Math.max(EH,Math.round(n*IH));return Math.min(t,r)},UH=e=>{let t=kh("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(rI,Math.max(RH,Math.round(e*xH))):rI},It=async()=>{try{let e=await CH(Ch(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Od=async e=>{try{let t=Ch(),n=`${t}.${process.pid}.tmp`;await fI(n,JSON.stringify(e),{mode:384}),await he(n,t),await kH(t,384).catch(()=>{})}catch{}},GH=3e4,VH=()=>`${Ch()}.lock`,cI=async e=>{try{return await fI(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??It,a=n.writeState??Od,s=VH(),i=!1;try{if(i=await cI(s),!i){if(await vH(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<GH)return t;await nI(s).catch(()=>{}),i=await cI(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await nI(s).catch(()=>{})}},xd=async(e,t={})=>{await dt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Sa=async(e={},t={})=>{let n=t.now??Date.now,r=e.expiresAt?Date.parse(e.expiresAt):NaN,o=e.keyTtlMs??(Number.isFinite(r)&&r-n()>0?r-n():void 0);await dt(({lastError:a,...s})=>({next:{...s,lastAttemptAt:n(),lastSuccessAt:n(),failureCount:0,keyTtlMs:o??s.keyTtlMs},result:void 0}),void 0,t).catch(()=>{})},yo=async(e={})=>{let t=e.now??Date.now;await dt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},KH=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(MH,Math.max(iI,Math.round(o*$H))):iI},gI=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,Ih=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??oe,a=n.loadProfile??D,s=n.loadDevKey??$e,i=n.renew??NS,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(LS(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()>KH(e))return{outcome:"not-due",profile:e};if(!await dt(w=>r()-(w.lastCertRenewAt??0)<BH?{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 p=await a().catch(()=>e);if(!p.enrolledCert)return{outcome:"failed",profile:e};if(!await gI(p,c.sig,t,s))return{outcome:"superseded",profile:p};let f=u.cert.payload.expiresAt,m=Date.parse(f)-r(),h={...p,enrolledCert:u.cert,enrolledCertExpiry:f,...Number.isFinite(m)&&m>0?{enrolledCertLifetimeMs:m}:{}};return await o(h),{outcome:"renewed",profile:h}},lI=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*NH):sI,r=Math.min(sI,n);return Math.min(r,LH*2**Math.max(0,e-1))},jH=()=>{let{command:e,args:t}=Qn(Yn);return{exe:e,args:t}},Cr=async(e={})=>{if(mI())return;let t=e.now??Date.now,n=e.readState??It,r=e.writeState??Od,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=jH();bH(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await dt(s=>t()-(s.lastSpawnAt??0)<UH(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},ZH=ph,YH=async(e,t=!1)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await Be(async()=>e);if(!r)return!1;let o=await ya(n,r.target.origin),a=t?RS(o):o;return a.length===0?!1:(await Mt(a,r.target),!0)}catch{return!1}},JH=async(e,t,n,r,o)=>{try{let a=new Set(e.managedTools??[]),s=le.filter(d=>a.has(d.id));if(s.length===0)return!1;let i=await r().catch(()=>{}),c=xe({origin:t,clientKey:n,subscription:e.authMode==="subscription",placeholder:e.authMode==="placeholder",byoUpstream:e.byoUpstream,seat:i,user:e.name,team:e.team}),l=await o(c,c.origin,s);return l.matched>0&&l.complete}catch{return!1}},XH=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??It,a=t.writeState??Od;return tI(e,Ae,{now:r,deadWatcherObserved:n,readHookLane:()=>Td({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})})},Td=async(e={})=>{let n=await(e.readState??It)().catch(()=>({}));return An(n.hookLane)},wI=async(e,t={})=>{try{let n=t.now??Date.now,r=await Td(t);if(!mh(r,e,n()))return;await dt(o=>{let a=An(o.hookLane);return mh(a,e,n())?{next:{...o,hookLane:BS(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},bI=async(e,t={})=>{try{let n=t.now??Date.now,r=await Td(t);if(!hh(r,n()))return;await dt(o=>{let a=An(o.hookLane);return hh(a,n())?{next:{...o,hookLane:FS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},zH=async(e={})=>{try{let t=e.now??Date.now;if((await Td(e)).watchSince!==void 0)return;await dt(n=>{let r=An(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:WS(r,t())},result:void 0}},void 0,e)}catch{}},dI=async(e,t={})=>{try{let n=t.now??Date.now;await dt(r=>{let o=An(r.hookLane),a=HS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},AI=async(e={})=>{try{if((await(e.readState??It)()).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??D)(),s=await(e.findTools??fo)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await Be(async()=>o);return!i||!await r()?"skipped":(await(e.repair??Mt)(s,i.target),"repathed")}catch{return"skipped"}},CI=async(e={})=>{try{let t=e.revision??1,r=(await(e.readState??It)()).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??D)(),i=await(e.findTools??fo)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await Be(async()=>a);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"}},qH=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await ba(e.gateway,e.clientKey),n=await Aa(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},uI=async(e,t,n)=>{let o=await(t.reconcilePolicy??qH)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>YH(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},zt=async(e={})=>{if(mI())return"disabled";let t=e.now??Date.now,n=e.loadProfile??D,r=e.saveProfile??oe,o=e.loadDevKey??$e,a=e.readState??It,s=e.writeState??Od,i=e.remint??Xt,c=e.heartbeat??sS,l=e.detectSeat??fn,d=e.rewriteTools??ZH,u=e.rewriteHookLaneTools??uh,p=e.probeHookLane??va,f=e.classifyBeacon??cc,m=e.force===!0,h=!1,w=!1,y=!1,g=!1;e.hookLaneRepair===!0&&(m=!0,g=!0);let b=async C=>{if(!g){C==="repaired"&&await dI("none",{now:t,readState:a,writeState:s});return}let S=C;if(C==="repaired"){let I=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));S=I.verdict==="live"?"repaired":I.verdict==="dark"?"repair_failed":"unverified"}await dI(S,{now:t,readState:a,writeState:s})},k=async()=>{if(!e.runAmbientSelfcheck||w||!h)return!1;w=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(I=>XH(I,{now:t,readState:a,writeState:s},y)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await rr().then(F=>F.some(Z=>!ar(Z.watcherPid))).catch(()=>!1),await zH({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??qw)();let C=await n();if(h=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let S=C.gateway,I=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(I)||I<=t())return"cert-expired";let E=await o();if(!E)return"not-enrolled";let R=(e.resolveMachineUuid??Bt)()||void 0,P=await Ih(C,E,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=P.profile;let W=P.outcome==="renewed",q=C.enrolledCert;if(!q)return"not-enrolled";let de=Date.parse(C.clientKeyExpiresAt??""),ie=Number.isFinite(de)?de-t():0,K=await a(),ge=!C.clientKey||ie<=Sh(C);if(!m&&US(An(K.hookLane),t())&&await f().catch(()=>"unreadable")!=="foreign"&&(m=!0,g=!0),C.clientKey&&(m||ge)){let F=await dt(Z=>{let X=t()-(Z.lastAttemptAt??0);return X<oI?{result:"throttled"}:Z.failureCount&&X<lI(Z.failureCount,Z.keyTtlMs)?{result:"backoff"}:{next:{...Z,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(F!=="ok")return F;try{let Z=await c(S,C.clientKey,q,E,{machineUuid:R}),X=await n().catch(()=>C);return X.clientKey!==C.clientKey||X.enrolledCert?.sig!==q.sig?"failed":(await r({...X,clientKeyExpiresAt:Z.expiresAt}),await xd(({lastError:Ye,...We})=>({...We,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Rd(C)??We.keyTtlMs}),{now:t,readState:a,writeState:s}),g?await b(await JH(C,S,C.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Z){let X=aI(Z);return await xd(Ye=>({...Ye,lastAttemptAt:t(),failureCount:(Ye.failureCount??0)+1,lastError:{name:Z instanceof Error?Z.name:"Error",...X!==void 0?{code:X}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),Z instanceof fa&&Z.policyCode==="managed_device_required"&&console.error(Z.message),Z instanceof fa?Z.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!m&&C.clientKey&&!ge){let F=await uI(C,e,n),Z=await k();return F||Z?"repaired":W?"cert-renewed":"not-due"}let me=await dt(F=>{let Z=t()-(F.lastAttemptAt??0);if(m)return Z<DH(F.failureCount)?{result:"throttled"}:{next:{...F,lastAttemptAt:t()},result:"ok"};let X=F.lastError?.code!==void 0&&OH.has(F.lastError.code)?TH:oI;return Z<X?{result:"throttled"}:F.failureCount&&Z<lI(F.failureCount,F.keyTtlMs)?{result:"backoff"}:{next:{...F,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(me!=="ok")return me;try{let F=await i(S,q,E,{machineUuid:R}),Z=await l().catch(()=>{}),X=xe({origin:S,clientKey:F.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Z,user:C.name,team:C.team});if(await d(X,X.origin)===!1)throw new Error("one or more configured tools rejected the refreshed key");let We=await n().catch(()=>C),T=null;We.enrolledCert&&await gI(We,q.sig,E,o)&&(T={...We,clientKey:F.key,clientKeyExpiresAt:F.expiresAt??We.clientKeyExpiresAt},await r(T));let L=F.expiresAt?Date.parse(F.expiresAt):NaN,J=Rd(C)??(Number.isFinite(L)&&L-t()>0?L-t():void 0);return await xd(({lastError:pe,...ut})=>({...ut,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:J??ut.keyTtlMs}),{now:t,readState:a,writeState:s}),T&&await uI(T,e,n),await b(T?"repaired":"repair_failed"),await k(),"refreshed"}catch(F){let Z=aI(F);return await xd(X=>({...X,lastAttemptAt:t(),failureCount:(X.failureCount??0)+1,lastError:{name:F instanceof Error?F.name:"Error",...Z!==void 0?{code:Z}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),F instanceof lt&&F.policyCode==="managed_device_required"&&console.error(F.message),F instanceof lt?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await k()}catch{}}};var QH=`anyray-connect print-key [--json | --passthrough-headers]
|
|
376
376
|
|
|
377
377
|
Print the current short-lived Anyray client key for a consuming app.
|
|
378
378
|
|
|
@@ -384,10 +384,10 @@ Options:
|
|
|
384
384
|
"x-anyray-provider":"anthropic","x-anyray-metadata":"..."}).
|
|
385
385
|
Carries the client key, never the seat OAuth token.
|
|
386
386
|
--help Show this help.
|
|
387
|
-
`,
|
|
388
|
-
`);let s=o.passthroughHeaders?
|
|
387
|
+
`,eU=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}},tU=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=Sh(e):!0},kI=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},vI=(e,t)=>{if(!Ee(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},Eh=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,nU=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${Eh(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 \`${Eh(t)}\`.`:"Your enrollment certificate is no longer valid. Reconnect with `npx anyray-connect@latest --enroll <link>`, or for an SSO-managed organization run `npx anyray-connect@latest --sso <link>`.";case"gateway-incompatible":return"The gateway key-renewal route is unavailable (HTTP 404). Check the deployment version and routing; your enrollment certificate was not rejected.";case"failed":return"Could not refresh the Anyray client key.";case"not-enrolled":return t.ssoLink?`Not enrolled. Reconnect with \`${Eh(t)}\`.`:"Not enrolled. Run `npx anyray-connect@latest --enroll <link>` first.";case"disabled":return"Automatic key refresh is disabled.";case"backoff":case"throttled":return"Key refresh is temporarily unavailable; retry shortly.";case"not-due":case"repaired":case"cert-renewed":case"heartbeat-refreshed":case"refreshed":return""}},hi=async(e={})=>{let t=e.loadProfile??D,n=e.refreshIfDue??zt,r=e.now??Date.now,o=await t();if(kI(o),!o.enrolledCert){if(!vI(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||tU(o,r)){let i=nU(await n(),o);if(i){if(!vI(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(kI(s),!Ee(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},SI=e=>ue({user:e.name,team:e.team}),_d=({profile:e,token:t})=>{let n={},r=SI(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},xh=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=SI(e);return r&&(n["x-anyray-metadata"]=r),n},rU=e=>JSON.stringify(xh(e)),II=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=eU(e);if(o.help)return n.write(QH),0;let a=await hi(t);a.warning&&r.write(`${a.warning}
|
|
388
|
+
`);let s=o.passthroughHeaders?rU(a):o.json?_d(a):a.token;return n.write(`${s}
|
|
389
389
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
390
|
-
`),1}};var
|
|
390
|
+
`),1}};var EI=`anyray-connect models [<model-id>] [--json]
|
|
391
391
|
|
|
392
392
|
List the Copilot models your seat can run on the Anyray lane, or switch the
|
|
393
393
|
Copilot CLI's startup model. The CLI's own /models cannot list models on a
|
|
@@ -399,8 +399,8 @@ Options:
|
|
|
399
399
|
--json Emit {"origin","current","models":[{"id","wire",...caps}]} instead
|
|
400
400
|
of the table (listing only).
|
|
401
401
|
--help Show this help.
|
|
402
|
-
`,
|
|
403
|
-
`),0;A(V(`Copilot models your seat serves (via ${o.origin})`));for(let
|
|
402
|
+
`,oU=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},aU=e=>{let t=le.find(n=>n.id===Xr);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},sU=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(" / ")},iU=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Ns(t)}/${On(n)==="responses"?"responses":"chat/completions"}`,xI=async(e=[],t={})=>{let n=oU(e);if(n.help)return process.stdout.write(EI),0;if(n.error)return O(n.error),process.stdout.write(EI),1;let r=await(t.loadTarget??Be)();if(!r)return O("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??dl)({allowKeychainPrompt:!0});if(!a.token)return O("No Copilot sign-in Connect can read \u2014 run `copilot` once and `/login` (say YES to storing credentials locally), then retry."),1;let s=a.token.token,i=a.capiSegment??"default",c=await(t.fetchCatalog??Vo)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=gf(c);if(l.length===0)return O("Could not fetch your seat's model catalog from GitHub (offline, or the sign-in lost its Copilot seat)."),1;if(!n.modelId){let f=process.env.COPILOT_MODEL?.trim();if(n.json)return process.stdout.write(`${JSON.stringify({origin:o.origin,current:f??null,models:l.map(m=>({id:m.id,wire:On(m.id),...m.maxPromptTokens?{maxPromptTokens:m.maxPromptTokens}:{},...m.maxOutputTokens?{maxOutputTokens:m.maxOutputTokens}:{}}))})}
|
|
403
|
+
`),0;A(V(`Copilot models your seat serves (via ${o.origin})`));for(let m of l){let h=m.id===f?"*":" ",w=sU(m);A(` ${h} ${m.id.padEnd(24)}${w?v(w):""}`)}return $("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),$("The CLI's own /models cannot list models on a custom provider \u2014 this list is the picker."),0}let d=l.find(f=>f.id===n.modelId);if(!d)return O(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??ll)(iU(o,i,d.id),{...yf(),authorization:`Bearer ${s}`,...o.clientKey?{"x-anyray-api-key":o.clientKey}:{}},d.id);if(u==="rejected")return O(`GitHub refuses chat as '${d.id}' for this sign-in (it is in the catalog, but chat entitlement is narrower). Pick another id from \`anyray-connect models\`.`),1;u==="unreachable"?_("Could not verify the model over the lane (offline?) \u2014 applying anyway."):M(`'${d.id}' answers on your lane.`);let p=process.env.ANYRAY_COPILOT_MODEL;process.env.ANYRAY_COPILOT_MODEL=d.id;try{let f=await(t.applyCopilotCli??aU)(o);if(f.status!=="configured"){for(let m of f.messages)A(m);return O("Apply did not complete \u2014 see above."),1}}finally{p===void 0?delete process.env.ANYRAY_COPILOT_MODEL:process.env.ANYRAY_COPILOT_MODEL=p}return M(`Copilot CLI startup model \u2192 ${d.id}`),$("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};var cU=`anyray-connect copilot-login
|
|
404
404
|
|
|
405
405
|
Sign Anyray in to GitHub Copilot (device flow) so the Copilot CLI seat lane
|
|
406
406
|
can run your plan's current models. Opens no browser for you: it prints a
|
|
@@ -408,23 +408,23 @@ code to type at github.com/login/device.
|
|
|
408
408
|
|
|
409
409
|
Options:
|
|
410
410
|
--help Show this help.
|
|
411
|
-
`,
|
|
412
|
-
`,{mode:384}),await
|
|
411
|
+
`,RI=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(cU),0;A(V("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??MA)();if(!n)return O("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;A(` 1. Open ${et(n.verificationUri)}`),A(` 2. Enter the code: ${V(n.userCode)}`),$(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??BA)(n);if(r.status!=="ok")return O(r.status==="denied"?"Sign-in was declined in the browser.":r.status==="expired"?"The code expired before sign-in completed \u2014 run the command again.":"GitHub refused the sign-in. Run the command again."),1;let o=(t.now??(()=>new Date))().toISOString(),a=await(t.save??FA)(r.token,o);M(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??lf)(r.token);if(s.verdict==="no-copilot")return O("That GitHub account holds no Copilot seat."),1;let i=await(t.loadTarget??Be)(),c=i?{laneOrigin:i.target.origin.replace(/\/+$/,""),...i.target.clientKey?{clientKey:i.target.clientKey}:{}}:void 0,l=await(t.fetchCatalog??Vo)(r.token,{},s.capiSegment,c);return l.length===0?_("Signed in, but no model list came back \u2014 that is usually this machine or its network, not the sign-in. Continue with `anyray-connect --tools copilot-cli`; it verifies the model with a live check of its own."):M(`${l.length} models available (e.g. ${l[0].id}).`),$("Now run: anyray-connect --tools copilot-cli"),0};import{randomBytes as lU}from"node:crypto";import{chmod as dU,readFile as uU,rm as TI,writeFile as pU}from"node:fs/promises";import{join as fU}from"node:path";var mU=/^[A-Za-z0-9_-]{43}$/,OI=3900,hU=1e4,Rh=()=>fU(Q(),"device-token.json"),yU=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&mU.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},_I=async()=>{try{let e=JSON.parse(await uU(Rh(),"utf-8"));return yU(e)?e:null}catch{return null}},gU=0,wU=async e=>{await tt();let t=Rh(),n=`${t}.${process.pid}.${gU++}.tmp`;try{await pU(n,`${JSON.stringify(e)}
|
|
412
|
+
`,{mode:384}),await dU(n,384),await he(n,t)}catch(r){throw await TI(n,{force:!0}).catch(()=>{}),r}},Pd=async()=>{await TI(Rh(),{force:!0}).catch(()=>{})},bU=()=>lU(32).toString("base64url"),AU=e=>e instanceof Error?e.name:"UnknownError",PI=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??D)(),o=r.gateway?.replace(/\/+$/,""),a=r.clientKey;if(!o||!a)return!1;let s=bU(),i=new AbortController,c=setTimeout(()=>i.abort(),hU),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:OI}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await wU({v:1,token:s,expiresAt:t()+OI*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${AU(r)}`),!1}};var DI=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??D)()}catch{o={}}let a=o.gateway?.replace(/\/+$/,"");if(!a||!o.clientKey)return n.write("Not enrolled on this machine \u2014 run `npx anyray-connect` first.\n"),1;let s=e.readState??_I,i=await s();return(!i||i.expiresAt<=r())&&(await(e.rotateToken??PI)(),i=await s()),!i||i.expiresAt<=r()?(n.write(`Could not register a device token \u2014 retry after checking gateway connectivity.
|
|
413
413
|
`),1):(t.write(`${a}/device?dt=${i.token}
|
|
414
|
-
`),0)};import{join as
|
|
415
|
-
A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),$(" 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(!
|
|
416
|
-
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
|
|
414
|
+
`),0)};import{join as UI,dirname as _U}from"node:path";import{mkdir as PU,readFile as Lh,rm as GI,writeFile as VI}from"node:fs/promises";import{fstatSync as SU,openSync as IU,statSync as EU}from"node:fs";import{createInterface as xU}from"node:readline/promises";import{ReadStream as RU}from"node:tty";import{execFileSync as LI}from"node:child_process";import CU from"node:os";var Oh=e=>{try{return LI("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},kU=e=>{try{return LI("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},vU=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"]),Th=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:vU.has(t):!0},Dd=()=>{try{return CU.userInfo().username||void 0}catch{return}},NI=()=>Oh("user.name")??Oh("user.email")??Dd()??"unknown",$I=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Oh),global:e.globalGitConfig??(t||kU)}},go=e=>{try{return e()?.trim()||void 0}catch{return}},_h=(e={})=>{let t=$I(e),n=go(e.osUsername??Dd),r=go(()=>t.global("user.email"))??go(()=>t.local("user.email"));return r||(go(()=>t.global("user.name"))??go(()=>t.local("user.name"))??n??"unknown")},MI=(e={})=>{let t=_h(e);if(Th(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=$I(e);return!!(go(()=>n.global("user.email"))??go(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var Ft=()=>!!process.stdin.isTTY,OU=()=>{try{let e=SU(0);return e.isCharacterDevice()&&e.rdev===EU("/dev/tty").rdev}catch{return!1}},Ph=()=>{if(OU()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new RU(IU(`/dev/fd/${e}`,"r"));return{stream:n,close:()=>n.destroy()}}catch{}}return{stream:process.stdin,close:()=>{}}},yt=class extends Error{constructor(){super("prompt cancelled"),this.name="PromptCancelledError"}},BI=async(e,t)=>{let n=t.input??Ph(),r=t.output??process.stdout,o=xU({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 yt))}),o.question(e).then(d=>l(()=>a(d)),d=>l(()=>s(c?d:new yt)))})}finally{o.close(),n.close()}},Ia=async(e,t={})=>{let n=(await BI(`${e} ${v("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},Ea=async(e,t,n={})=>{let r=t?` ${v(`[${t}]`)}`:"";return(await BI(`${e}${r}: `,n)).trim()||t},FI=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return $(`Your name: ${t} ${v("(cached \u2014 pass --user to change)")}`),t;let r=NI();return n||!Ft()?($(`Your name: ${r} ${v("(auto-detected \u2014 pass --user to change)")}`),r):Ea("? Your name",r)},WI=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return $(`Team: ${t} ${v("(cached \u2014 pass --team to change)")}`),t;if(!(n||!Ft()))return Ea("? Team (optional)")},kr=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return Qt(e??n)},HI=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,xa="claude-desktop",Ld=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await yr(e.runReg??Bn))return n("managed-policy")}catch{return n("policy-unreadable")}let s=Nt({home:e.home});return await x(s)?{authoritative:!0}:n("no-local-record")}if(t!=="darwin")return n("manual-platform");let r={home:e.home,managedPolicyPaths:e.managedPolicyPaths,readManagedPolicyKeys:e.readManagedPolicyKeys},o=jt(r);return await to(o,r)?n("managed-policy"):(await la({home:e.home,readClaudeAppVersion:e.readClaudeAppVersion,readClaudeAppBundle:e.readClaudeAppBundle})).supported?await x(o.journal)?{authoritative:!0}:n("no-local-record"):n("unverified-build")}catch{return n("no-local-record")}},Nd=e=>e.id!==xa||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",TU={"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"},$d=(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=TU[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 Dh=["claude-code","codex"],DU="anyray-connect print-key",Nh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),LU=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:Ka,authMode:"placeholder",metadata:{}}),$h=e=>UI(e,".claude","settings.json"),NU=async(e,t,n)=>{let r=$h(e),o=await B(r),{env:a}=tn(t,{includeAuthToken:!1,includeClientKey:!1}),s=Nh(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Mr(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=DU,n||await Y(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]}},KI=async(e=process.cwd())=>{let t=[],n=$h(e);try{if(await x(n)){let o=await B(n),a=Nh(o.env)?o.env:{};(Nr.some(s=>s in a)||Mr(o))&&t.push(n)}}catch{}let r=Mh(e);try{if(await x(r)){let o=await Lh(r,"utf-8");mp(o)&&t.push(r)}}catch{}return t},$U=async(e,t)=>{let n=$h(e);if(!await x(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await B(n),o=!1;if(Nh(r.env)){let s={...r.env};for(let i of Nr)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Mr(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 GI(n,{force:!0}):await Y(n,r,{backup:!1})),{messages:[`${t?"Would remove":"Removed"} the Anyray routing from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},Mh=e=>UI(e,".codex","config.toml"),MU=async(e,t,n)=>{let r=Mh(e),o=await Lh(r,"utf-8").catch(()=>""),a=xc(o,ds(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await PU(_U(r),{recursive:!0}),await VI(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]}},BU=async(e,t)=>{let n=Mh(e);if(!await x(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await Lh(n,"utf-8"),o=Rc(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await GI(n,{force:!0}):await VI(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},jI=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...Dh],r=n.filter(s=>!Dh.includes(s));if(r.length>0)return O(`--project supports ${Dh.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 D(),i=e.gateway??s.gateway;if(!i)return O("--project needs a gateway: pass --gateway <url>, or run `anyray-connect` once on this machine so it is cached."),1;try{let c=new URL(i.trim());if(c.protocol!=="http:"&&c.protocol!=="https:")throw new Error("not http(s)")}catch{return O(`invalid gateway URL: "${i}" \u2014 must start with http:// or https://`),1}o=LU(Ht(i))}if(A(V(e.revert?"Anyray connect \u2014 remove project config":"Anyray connect \u2014 project config")),U("Project"),A(` Directory: ${t}`),o&&A(` Gateway: ${o.origin}`),A(` Tools: ${n.join(", ")}`),e.revert||(_(`
|
|
415
|
+
A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),$(" 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(!Ft())return O(`
|
|
416
|
+
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 Ia(`
|
|
417
417
|
${s} ${n.length} tool(s)?`))return $("Aborted. Nothing changed."),0}e.dryRun&&$(`
|
|
418
|
-
Dry run \u2014 no files will be written.`);let a=[];for(let s of n){U(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await
|
|
419
|
-
`),1;let o;try{o=await
|
|
420
|
-
`),1}let a=o.profile.authMode??"auto",s;if(a==="placeholder")s=
|
|
421
|
-
`),1;s=
|
|
418
|
+
Dry run \u2014 no files will be written.`);let a=[];for(let s of n){U(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await NU(t,o,e.dryRun):await MU(t,o,e.dryRun):s==="claude-code"?await $U(t,e.dryRun):await BU(t,e.dryRun);for(let c of i.messages)A(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(U("Next"),e.revert)M(" Project config removed. Commit the change to propagate it.");else{M(" Commit these files to route every checkout of this repo:");for(let s of a)A(` ${s}`);A(v(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as FU}from"node:child_process";var WU="/usr/bin/security",HU=["find-generic-password","-s","Claude Code-credentials","-w"],UU=1e4,GU=64*1024,VU=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,Bh="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",KU=(e,t,n)=>new Promise((r,o)=>{FU(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),ZI=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),jU=e=>{let t=JSON.parse(e);if(!ZI(t)||!ZI(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!VU.test(n))throw new Error("unexpected keychain access token");return n},ZU=async(e,t)=>{let n=xh(e),r=await(t.execSecurity??KU)(WU,[...HU],{encoding:"utf8",timeout:UU,maxBuffer:GU,shell:!1});return JSON.stringify({token:jU(r.stdout),headers:n})},YI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${Bh}
|
|
419
|
+
`),1;let o;try{o=await hi(t)}catch(i){let c=i instanceof Error&&i.message?i.message:Bh;return r.write(`${c}
|
|
420
|
+
`),1}let a=o.profile.authMode??"auto",s;if(a==="placeholder")s=_d(o);else try{s=await ZU(o,t)}catch{if(a==="subscription")return r.write(`${Bh}
|
|
421
|
+
`),1;s=_d(o)}return o.warning&&r.write(`${o.warning}
|
|
422
422
|
`),n.write(`${s}
|
|
423
|
-
`),0};var
|
|
424
|
-
`),1;try{let o=await
|
|
423
|
+
`),0};var JI="Anyray: could not resolve the Anyray client key for the Claude Desktop bootstrap fetch. Run `anyray-connect` and try again.",XI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${JI}
|
|
424
|
+
`),1;try{let o=await hi(t);return o.warning&&r.write(`${o.warning}
|
|
425
425
|
`),n.write(`${JSON.stringify({Authorization:`Bearer ${o.token}`})}
|
|
426
|
-
`),0}catch{return r.write(`${
|
|
427
|
-
`),1}};import{mkdir as
|
|
426
|
+
`),0}catch{return r.write(`${JI}
|
|
427
|
+
`),1}};import{mkdir as wG,writeFile as bG}from"node:fs/promises";import{dirname as AG}from"node:path";import{Buffer as CG}from"node:buffer";import{constants as zI}from"node:fs";import{access as YU,chmod as JU,lstat as XU,mkdir as zU,open as qU,readFile as QU,realpath as eG,rm as tG,stat as QI,writeFile as nG}from"node:fs/promises";import{randomUUID as rG}from"node:crypto";import{platform as Wh}from"node:os";import{dirname as oG,join as aG,posix as sG,win32 as eE}from"node:path";var wi="/usr/local/bin/anyray-credential-helper",bi="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Md="/usr/local/bin/anyray-bootstrap-headers-helper",Bd="C:\\Program Files\\Anyray\\anyray-bootstrap-headers-helper.cmd",gi="Managed by anyray-connect desktop helper; do not edit.",Fd="__anyray-refresh-desktop-helpers",iG=`anyray-connect desktop helper <--write|--print> --bin <absolute> [options]
|
|
428
428
|
|
|
429
429
|
Create the helpers required by Claude Desktop and Codex fleet artifacts: the
|
|
430
430
|
credential helper (inferenceCredentialHelper, also used by Codex) and the
|
|
@@ -445,8 +445,8 @@ Options:
|
|
|
445
445
|
--platform <target> posix or windows (default: current host).
|
|
446
446
|
--wrapper <kind> credential or bootstrap-headers (--print only).
|
|
447
447
|
--path <absolute> Credential helper destination. Defaults by target:
|
|
448
|
-
${
|
|
449
|
-
${
|
|
448
|
+
${wi}
|
|
449
|
+
${bi}
|
|
450
450
|
--bootstrap-headers-path <absolute>
|
|
451
451
|
Bootstrap-headers helper destination. Defaults:
|
|
452
452
|
${Md}
|
|
@@ -466,15 +466,15 @@ Examples:
|
|
|
466
466
|
anyray-connect desktop helper --print --wrapper bootstrap-headers \\
|
|
467
467
|
--platform posix --bin /usr/local/bin/anyray-connect \\
|
|
468
468
|
> anyray-bootstrap-headers-helper
|
|
469
|
-
`,
|
|
470
|
-
`);let r=
|
|
471
|
-
`)},
|
|
472
|
-
`):["#!/bin/sh",`# ${
|
|
473
|
-
`)},Hd=(e,t)=>{if(!
|
|
474
|
-
`),0}if(s!==
|
|
469
|
+
`,Fh=(e=Wh())=>e==="win32"?"windows":"posix",tE=e=>e==="windows"?bi:wi,nE=e=>e==="windows"?Bd:Md,qI=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},cG=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":qI(t,"write");break;case"--print":qI(t,"print");break;case"--bin":t.binaryPath=o();break;case"--path":t.helperPath=o();break;case"--bootstrap-headers-path":t.bootstrapHeadersHelperPath=o();break;case"--wrapper":{let a=o();if(a!=="credential"&&a!=="bootstrap-headers")throw new Error("--wrapper must be credential or bootstrap-headers");t.wrapper=a;break}case"--platform":{let a=o();if(a!=="posix"&&a!=="windows")throw new Error("--platform must be posix or windows");t.targetPlatform=a;break}case"--help":case"-h":t.help=!0;break;default:throw new Error(r.startsWith("-")?`unknown option: ${r}`:`unexpected argument: ${r}`)}}return t},lG=e=>/[\0\r\n]/.test(e),dG=e=>/^[A-Za-z]:[\\/]/.test(e)&&eE.isAbsolute(e),Ai=(e,t)=>!lG(e)&&(t==="windows"?dG(e):sG.isAbsolute(e)),yi=e=>e.replace(/\\/g,"/").toLowerCase(),Wd=(e,t)=>{if(!Ai(e,t))return!1;let n=yi(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)))},Ci=(e,t)=>t==="windows"?eE.normalize(e):e,Hh=e=>`'${e.replace(/'/g,`'"'"'`)}'`,rE=(e,t)=>{if(!Wd(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Ci(t,e);if(e==="windows")return["@echo off",`REM ${gi}`,'if "%~1"=="" goto json','if not "%~2"=="" exit /b 64','if "%~1"=="--token" goto token',"exit /b 64",":json",`"${n}" ${mr}`,"exit /b %ERRORLEVEL%",":token",`"${n}" print-key`,"exit /b %ERRORLEVEL%",""].join(`\r
|
|
470
|
+
`);let r=Hh(n);return["#!/bin/sh",`# ${gi}`,'if [ "$#" -eq 0 ]; then',` exec ${r} ${mr}`,"fi",'if [ "$#" -eq 1 ] && [ "$1" = "--token" ]; then',` exec ${r} print-key`,"fi","exit 64",""].join(`
|
|
471
|
+
`)},oE=(e,t)=>{if(!Wd(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Ci(t,e);return e==="windows"?["@echo off",`REM ${gi}`,'if not "%~1"=="" exit /b 64',`"${n}" ${Vs}`,"exit /b %ERRORLEVEL%",""].join(`\r
|
|
472
|
+
`):["#!/bin/sh",`# ${gi}`,'if [ "$#" -eq 0 ]; then',` exec ${Hh(n)} ${Vs}`,"fi","exit 64",""].join(`
|
|
473
|
+
`)},Hd=(e,t)=>{if(!Ai(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=Ci(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"]}},aE=async e=>{try{return await QU(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},uG=async(e,t)=>{try{let n=await eG(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!Wd(r,t))throw new Error;if(!(await QI(n)).isFile())throw new Error;await YU(n,t==="posix"?zI.X_OK:zI.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},sE=e=>e.slice(0,300).includes(gi),iE=async(e,t,n)=>{let r=await aE(e);if(r!==void 0&&r!==t&&!sE(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 QI(e)).mode&511)===493)return"unchanged"}catch{}}let o=oG(e);try{await zU(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=aG(o,`.anyray-helper.${process.pid}.${rG()}.tmp`),s=!1;try{await nG(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await JU(a,493);let i=await qU(a,"r");try{await Tr(i)}finally{await i.close()}await he(a,e),s=!0}catch{throw new Error(`could not install helper at ${e}`)}finally{s||await tG(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},pG=(e,t,n)=>{let r=n==="windows"?`"${Ci(t,n)}" `:` exec ${Hh(t)} `;return e.split(/\r?\n/).some(o=>o.startsWith(r)&&o.length>r.length)},Ud=async(e,t={})=>{let n=Fh((t.platform??Wh)());if(!Wd(e,n))return;let r=[{path:t.helperPath??tE(n),content:rE(n,e)},{path:t.bootstrapHeadersHelperPath??nE(n),content:oE(n,e)}];for(let o of r)try{if((await XU(o.path).catch(()=>{}))?.isSymbolicLink())continue;let a=await aE(o.path);if(a===void 0||a===o.content||!sE(a)||!pG(a,e,n))continue;await iE(o.path,o.content,n)}catch{}},cE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=cG(e);if(o.help)return n.write(iG),0;if(!o.mode)throw new Error("pick exactly one helper mode: --write or --print");if(!o.binaryPath)throw new Error("--bin is required");if(o.wrapper&&o.mode!=="print")throw new Error("--wrapper applies to --print only; --write installs both helpers");let a=(t.platform??Wh)(),s=o.targetPlatform??Fh(a),i=o.binaryPath,c=(d,u,p)=>{let f=Ci(u??p,s);if(!Ai(f,s))throw new Error(`${d} must be an absolute ${s} path`);if(s==="windows"&&Hd("windows",f),yi(f)===yi(i))throw new Error(`${d} must differ from --bin (the helper cannot invoke itself)`);return f},l=[{kind:"credential",label:"credential helper",path:c("--path",o.helperPath,tE(s)),content:rE(s,i)},{kind:"bootstrap-headers",label:"bootstrap-headers helper",path:c("--bootstrap-headers-path",o.bootstrapHeadersHelperPath,nE(s)),content:oE(s,i)}];if(yi(l[0].path)===yi(l[1].path))throw new Error("--path and --bootstrap-headers-path must differ");if(o.mode==="print"){let d=o.wrapper??"credential",u=l.find(p=>p.kind===d);return n.write(u.content),r.write(`Deploy this wrapper at ${u.path} after deploying the binary at ${i}.
|
|
474
|
+
`),0}if(s!==Fh(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await uG(i,s);for(let d of l){let u=await iE(d.path,d.content,s),p=d.label[0].toUpperCase()+d.label.slice(1);r.write(u==="unchanged"?`${p} already current at ${d.path}.
|
|
475
475
|
`:`${u==="installed"?"Installed":"Updated"} ${d.label} at ${d.path}.
|
|
476
476
|
`)}return 0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
477
|
-
`),1}};var
|
|
477
|
+
`),1}};var fG=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),mG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,hG=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.")},yG=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Gd=(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!==""||hG(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Ra=(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()}},lE=e=>{if(!yG(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!fG.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Ra(e.clientId,"clientId",!0),r=Ra(e.scopes,"scopes",!0),o=Ra(e.issuer,"issuer",!1),a=Ra(e.authorizationUrl,"authorizationUrl",!1),s=Ra(e.tokenUrl,"tokenUrl",!1),i=Ra(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:Gd(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:Gd(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:Gd(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},dE=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return lE(t)},Uh=e=>e==="windows"?Bd:Md,gG=(e,t)=>{let n=new URL(e);return n.searchParams.set("os",t),n.toString()},Vd=(e,t)=>{let n=gG(Gd(e.url,"--bootstrap-url"),t),r=e.oidc?lE(e.oidc):void 0,o;if(e.deploymentOrganizationUuid!==void 0&&(o=e.deploymentOrganizationUuid.trim(),!mG.test(o)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:n,bootstrapHeadersHelper:Uh(t),...r?{bootstrapOidc:r}:{},...o?{deploymentOrganizationUuid:o}:{}}},uE=(e,t)=>hr(Vd(e,t));var kG=`anyray-connect desktop [disconnect] [options]
|
|
478
478
|
|
|
479
479
|
The minimum Claude Desktop workflow:
|
|
480
480
|
anyray-connect desktop Connect this machine
|
|
@@ -519,8 +519,8 @@ Options:
|
|
|
519
519
|
|
|
520
520
|
Older flag-based Claude artifacts and Codex fleet output remain accepted for
|
|
521
521
|
compatibility, but are not part of the recommended Claude Desktop workflow.
|
|
522
|
-
|
|
523
|
-
<string>${Gn(t)}</string>`,
|
|
522
|
+
`,vG=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",SG=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),IG=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[vG(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...SG(o)]},EG=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),Gh=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>EG.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"]},Gn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),pE=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),xG=(e,t)=>` <key>${Gn(e)}</key>
|
|
523
|
+
<string>${Gn(t)}</string>`,Vh=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>xG(i,c)).join(`
|
|
524
524
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
525
525
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
526
526
|
<plist version="1.0">
|
|
@@ -553,21 +553,21 @@ ${s}
|
|
|
553
553
|
<string>${Gn(n)}</string>
|
|
554
554
|
</dict>
|
|
555
555
|
</plist>
|
|
556
|
-
`},
|
|
557
|
-
`,
|
|
558
|
-
`,
|
|
559
|
-
`),
|
|
556
|
+
`},ki={disableDeploymentModeChooser:!0},mE=(e,t)=>Vh("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",hr({...eo(e,t),...ki})),RG=(e,t)=>`${JSON.stringify({...eo(e,t),...ki},null,2)}
|
|
557
|
+
`,OG=e=>Vh("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",hr({...Vd(e,"macos"),...ki})),TG=e=>`${JSON.stringify({...Vd(e,"linux"),...ki},null,2)}
|
|
558
|
+
`,hE=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries({...e,...hr(ki)}).map(([n,r])=>`"${pE(n)}"="${pE(r)}"`),""].join(`
|
|
559
|
+
`),yE=(e,t)=>{let n=Fl(e,t);return hE(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},_G=e=>hE(uE(e,"windows")),gE=(e,t,n)=>{if(t==="darwin"){let r=wi;return{path:`${n}/claude-desktop-anyray.mobileconfig`,content:mE(e,r),helperPath:r}}if(t==="win32"){let r=bi;return{path:`${n}\\claude-desktop-anyray.reg`,content:yE(e,r),helperPath:r}}},wE=(e,t)=>[`Generated the complete Claude Desktop profile your administrator can deploy: ${e.path}`,t==="darwin"?"Send it to IT to push through MDM (Jamf, Intune, Kandji). It carries the full Anyray connection \u2014 no hand-merging, and no Developer Mode on the target machines.":"Send it to IT to import into machine policy (HKLM\\SOFTWARE\\Policies\\Claude), or push it through your device-management system.",`It references the shared credential helper at ${e.helperPath}, which IT deploys once per machine with \`anyray-connect desktop helper --write\`. The profile contains no credential.`,"Nothing on this machine changed; the managed policy stays authoritative until IT deploys it."],PG=(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=Hd(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${ds(e,o).join(`
|
|
560
560
|
`)}
|
|
561
|
-
`},
|
|
561
|
+
`},DG=e=>Vh("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:CG.from(e,"utf-8").toString("base64")}),LG=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},NG=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=Qt(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:Ka,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},fE=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??wG,o=n.writeFile??bG;await r(AG(t),{recursive:!0}),await o(t,e)},$G=(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:
|
|
562
562
|
`),o.write(r==="windows"?` anyray-connect desktop helper --write --platform windows --bin "C:\\Program Files\\Anyray\\anyray-connect.exe" --path "${n}"
|
|
563
563
|
`:` sudo anyray-connect desktop helper --write --platform posix --bin /usr/local/bin/anyray-connect --path '${n.replace(/'/g,`'"'"'`)}'
|
|
564
564
|
`),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.
|
|
565
565
|
`):t==="json"&&o.write(`Deploy this file to /etc/claude-desktop/managed-settings.json.
|
|
566
|
-
`)},
|
|
567
|
-
`),t.write(`The bootstrap fetch is authenticated by the bootstrap-headers helper at ${
|
|
566
|
+
`)},MG=(e,t)=>{t.write(`This artifact is a stable MDM trust anchor; it contains no inference credential. Claude Desktop authenticates the user and fetches the effective configuration from the bootstrap service at launch.
|
|
567
|
+
`),t.write(`The bootstrap fetch is authenticated by the bootstrap-headers helper at ${Uh(e)}, and the response names the credential helper; install both on every managed machine first with \`anyray-connect desktop helper --write\` (deploy a stable anyray-connect binary through your software-distribution system before that).
|
|
568
568
|
`),t.write(`Update the bootstrap response instead of redeploying MDM. Claude polls every 30 minutes, then applies changed values on the next Claude Desktop launch; no managed action is required for each policy update.
|
|
569
569
|
`),t.write(`Each bootstrap response replaces the allowed managed configuration; omitted keys are unset.
|
|
570
|
-
`)},
|
|
570
|
+
`)},BG=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??oo)({account:e.account,allAccounts:e.allAccounts});if(!o.ok)return r.write(`Cannot migrate: ${o.reason}.
|
|
571
571
|
${o.remedy}
|
|
572
572
|
`),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("; ")})`:"")+`
|
|
573
573
|
`)}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)`:"")+`
|
|
@@ -578,10 +578,10 @@ Reopen Claude Desktop \u2014 migrated ${c} available in the Anyray profile.
|
|
|
578
578
|
Your previous profile is untouched, so \`desktop disconnect\` still works.
|
|
579
579
|
`)}else n.write(`
|
|
580
580
|
Nothing new to migrate \u2014 no local sessions or portable local data needed copying.
|
|
581
|
-
`);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},
|
|
582
|
-
`),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 ${
|
|
581
|
+
`);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},bE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=IG(e);if(o[0]==="helper")return cE(o.slice(1),t);let a=LG(o);if(a.help)return n.write(kG),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 BG(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:dE(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},p=a.artifact==="reg"?_G(u):a.artifact==="json"?TG(u):OG(u);return await fE(p,a.path,t),MG(a.artifact==="reg"?"windows":a.artifact==="json"?"linux":"macos",r),a.path&&n.write(`Wrote ${a.path}
|
|
582
|
+
`),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 ${wi} on macOS/Linux or ${bi} 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(!Ai(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"&&Hd("windows",i);let l=NG(a),d;if(a.target==="claude")d=a.artifact==="reg"?yE(l,i):a.artifact==="json"?RG(l,i):mE(l,i);else{let u=PG(l,i);d=a.artifact==="mobileconfig"?DG(u):u}return await fE(d,a.path,t),$G(a.target,a.artifact,i,c,r),a.path&&n.write(`Wrote ${a.path}
|
|
583
583
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
584
|
-
`),1}};var
|
|
584
|
+
`),1}};var FG=`anyray-connect retrieve <handle> [--source auto|claude|profile]
|
|
585
585
|
|
|
586
586
|
Print the original content Anyray externalized behind a "\xB7 retrieve ctx_\u2026"
|
|
587
587
|
marker. The content is written to stdout byte-for-byte (no trailing newline
|
|
@@ -591,7 +591,7 @@ Options:
|
|
|
591
591
|
--source <s> Which client config resolves the gateway: auto (default),
|
|
592
592
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
593
593
|
--help Show this help.
|
|
594
|
-
`,
|
|
594
|
+
`,WG=`anyray-connect recall <query> [--k N] [--source auto|claude|profile]
|
|
595
595
|
|
|
596
596
|
Semantic search over your externalized tool outputs. Prints one match per line
|
|
597
597
|
to stdout as: handle<TAB>score<TAB>preview. Fetch a full original with
|
|
@@ -602,36 +602,36 @@ Options:
|
|
|
602
602
|
--source <s> Which client config resolves the gateway: auto (default),
|
|
603
603
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
604
604
|
--help Show this help.
|
|
605
|
-
`,
|
|
605
|
+
`,AE=(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},HG=e=>e.replace(/[\t\r\n]+/g," ").trim(),CE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=AE(e,!1);if(o.help)return n.write(FG),0;let a=o.positional?.trim();if(!a)return r.write(`A handle is required: anyray-connect retrieve ctx_\u2026 (see --help)
|
|
606
606
|
`),1;let s=await(t.readTarget??nt)(o.source),i=await(t.retrieve??ka)(s,a,{probe:!0});return i.ok?(n.write(i.content),0):(r.write(`${i.message}
|
|
607
607
|
`),1)}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
608
|
-
`),1}},
|
|
609
|
-
`),1;let s=await(t.readTarget??nt)(o.source),i=await(t.recall??
|
|
608
|
+
`),1}},kE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=AE(e,!0);if(o.help)return n.write(WG),0;let a=o.positional?.trim();if(!a)return r.write(`A query is required: anyray-connect recall "what to find" (see --help)
|
|
609
|
+
`),1;let s=await(t.readTarget??nt)(o.source),i=await(t.recall??vd)(s,a,o.k,{probe:!0});if(!i.ok)return r.write(`${i.message}
|
|
610
610
|
`),1;if(i.matches.length===0)return r.write(`No matching externalized outputs found.
|
|
611
|
-
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${
|
|
611
|
+
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${HG(c.preview)}
|
|
612
612
|
`)}return r.write(`Fetch a full original: anyray-connect retrieve <handle>
|
|
613
613
|
`),0}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
614
|
-
`),1}};import{promises as
|
|
614
|
+
`),1}};import{promises as f1}from"node:fs";var Cn=e=>typeof e=="string"?e:"",UG=e=>{let t=Cn(e.text).trim();if(t)return t;let n=e.content;if(!Array.isArray(n))return"";let r=[];for(let o of n){if(!o||typeof o!="object")continue;let a=Cn(o.text).trim();a&&r.push(a)}return r.join(`
|
|
615
615
|
|
|
616
|
-
`).trim()},
|
|
616
|
+
`).trim()},GG=e=>{let t=Cn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},VG=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=UG(r);if(!o)continue;let a=Cn(r.created_at).trim();t.push({role:GG(r),text:o,...a?{createdAt:a}:{}})}return t},Kd=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=VG(s.chat_messages??s.messages);if(i.length===0){o+=1;continue}let c=(Cn(s.uuid)||Cn(s.id)).trim(),l=(Cn(s.name)||Cn(s.title)).trim()||"Untitled conversation",d=Cn(s.created_at).trim(),u=Cn(s.updated_at).trim();r.push({uuid:c,title:l,...d?{createdAt:d}:{},...u?{updatedAt:u}:{},messages:i})}return{ok:!0,conversations:r,skipped:o}};import{createHash as i1}from"node:crypto";import{promises as Ii}from"node:fs";import{homedir as OE}from"node:os";import{join as Zd}from"node:path";import{promises as vE}from"node:fs";import Kh from"node:path";var KG=4e4,jG=16*1024*1024,vi=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),Si=async(e,t={})=>{let n=(e??"").trim();if(!n)return vi("","path is required");let r=t.cwd??process.cwd(),o=Kh.resolve(r,n),a=Kh.relative(r,o);if(a.startsWith("..")||Kh.isAbsolute(a))return vi(n,"path is outside the workspace");let s=t.maxBytes??KG,i;try{let w=await vE.stat(o);if(!w.isFile())return vi(n,"not a regular file");let y=t.maxFileBytes??jG;if(w.size>y)return vi(n,`file too large to read (${w.size} bytes; limit ${y})`);i=await vE.readFile(o,"utf8")}catch(w){return vi(n,w instanceof Error?w.message:"read failed")}let c=i.split(`
|
|
617
617
|
`),l=Math.max(1,t.startLine??1),d=Math.min(c.length,t.endLine??c.length),u=l<=d?c.slice(l-1,d):[],p=u.join(`
|
|
618
|
-
`),f=l<=d?d:l,
|
|
619
|
-
`),f=l+y-1),
|
|
618
|
+
`),f=l<=d?d:l,m=!1,h=!1;if(Buffer.byteLength(p,"utf8")>s){let w=0,y=0;for(let g of u){let b=Buffer.byteLength(g,"utf8")+(y===0?0:1);if(w+b>s)break;w+=b,y+=1}y===0?(p=Buffer.from(u[0]??"","utf8").subarray(0,s).toString("utf8").replace(/\uFFFD$/,""),f=l,m=!0):(p=u.slice(0,y).join(`
|
|
619
|
+
`),f=l+y-1),h=!0}return{ok:!0,content:p,path:n,lines:c.length,truncated:h,span:{startLine:l,endLine:f,...m?{partialLine:!0}:{}}}},jh=e=>{if(!e.ok)return`Read failed: ${e.message??"unknown error"}`;if(!e.truncated)return`${e.path}:
|
|
620
620
|
${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}
|
|
621
|
-
${e.content}`};import{spawn as
|
|
622
|
-
`)){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:
|
|
623
|
-
`);for(let C=0;C<k.length;C+=1){let S=c(k[C]);if(l.some(
|
|
621
|
+
${e.content}`};import{spawn as ZG}from"node:child_process";import{promises as Zh}from"node:fs";import Yh from"node:path";var Jh=400,YG=240,JG=4e3,XG=4e3,zG=512*1024,qG=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),IE=(e,t)=>e.length>t?e.slice(0,t):e,QG=new Set(["a","about","an","and","are","as","at","be","been","but","by","can","could","did","do","does","for","from","had","has","have","here","how","if","in","is","it","me","my","of","on","or","our","should","so","that","the","their","there","this","to","us","was","we","were","what","when","where","which","who","why","with","would","you","your"]),e1=8,t1=2e3,n1=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],r1=e=>{let t=e.toLowerCase(),n=t.split(/[\\/]/).pop()??t;return/(^|[\\/])\.(ssh|aws|gnupg)([\\/]|$)/.test(t)||n.startsWith(".env")||n.startsWith("id_rsa")||n.startsWith("id_ed25519")||/\.(pem|key|p12|pfx)$/.test(n)?!0:n.includes("secret")||n.includes("credential")},EE=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!QG.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=e1))break}return n},xE=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},o1=(e,t,n)=>{if(t.length<2)return e;let r=n?t:t.map(a=>a.toLowerCase()),o=a=>{let s=n?a.text:a.text.toLowerCase(),i=0;for(let c of r)s.includes(c)&&(i+=1);return i};return e.map((a,s)=>({m:a,i:s,s:o(a)})).sort((a,s)=>s.s-a.s||a.i-s.i).map(a=>a.m)},SE=(e,t,n)=>{let r=[];for(let o of e.split(`
|
|
622
|
+
`)){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:IE(l,t)})}return r},a1=(e,t,n,r,o,a,s)=>new Promise(i=>{let c=["--line-number","--no-heading","--color","never","--max-columns",String(o),"--max-columns-preview","--smart-case","--max-count","20","--fixed-strings"];for(let m of n)c.push("-g",m);for(let m of n1)c.push("-g",m);if(s?.length){for(let m of s)c.push("-e",m);c.push("--",".")}else c.push("--",e,".");let l;try{l=ZG("rg",c,{cwd:t})}catch{i({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let d="",u=!1,p=m=>{u||(u=!0,clearTimeout(f),i(m))},f=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}let m=SE(d,o,r);p({ok:!0,matches:m,truncated:!0,engine:"ripgrep"})},a);l.stdout?.setEncoding("utf8"),l.stdout?.on("data",m=>{if(d+=m,d.length>r*(o+64))try{l.kill("SIGKILL")}catch{}}),l.on("error",()=>{p({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"})}),l.on("close",m=>{if(typeof m=="number"&&m>=2){p({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let h=SE(d,o,r+1),w=h.length>r;p({ok:!0,matches:w?h.slice(0,r):h,truncated:w,engine:"ripgrep"})})}),s1=async(e,t,n,r,o,a,s)=>{let i=xE(s?.length?s:e),c=h=>i?h:h.toLowerCase(),l=(s?.length?s:[e]).map(c),d=n.map(h=>h.replace(/^\*+/,"")).filter(h=>h.startsWith(".")),u=[],p=0,f=!1,m=async h=>{if(u.length>=r||Date.now()>a){f=!0;return}let w;try{w=await Zh.readdir(h,{withFileTypes:!0})}catch{return}for(let y of w){if(u.length>=r||Date.now()>a){f=!0;return}let g=Yh.join(h,y.name);if(y.isDirectory()){if(qG.has(y.name))continue;await m(g)}else if(y.isFile()){if(p>=XG){f=!0;return}if(d.length&&!d.some(C=>y.name.endsWith(C))||r1(Yh.relative(t,g)))continue;p+=1;let b;try{if((await Zh.stat(g)).size>zG)continue;b=await Zh.readFile(g,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let k=b.split(`
|
|
623
|
+
`);for(let C=0;C<k.length;C+=1){let S=c(k[C]);if(l.some(I=>S.includes(I))&&(u.push({file:Yh.relative(t,g),line:C+1,text:IE(k[C],o)}),u.length>=r)){f=!0;return}}}}};return await m(t),{ok:!0,matches:u,truncated:f,engine:"walk"}},jd=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??Jh,s=t.maxColumns??YG,i=t.timeoutMs??JG,c=Date.now()+i,l=EE(n),d=l.length>1,u=Math.min(a*4,t1),p=(y,g)=>s1(n,r,o,y,s,c,g),f=async y=>{let g=await y(u,l);if(!g.ok)return g;let b=o1(g.matches,l,xE(l)),k=b.length>a;return{...g,matches:k?b.slice(0,a):b,truncated:g.truncated||k,matched:"tokens",tokens:l}};if(t.engine==="walk"){let y=await p(a);return y.matches.length>0||!d?y:f((g,b)=>p(g,b))}let m=(y,g)=>a1(n,r,o,y,s,Math.max(0,c-Date.now()),g),h=await m(a);if(h.ok){if(h.matches.length>0||!d)return h;let y=await f((g,b)=>m(g,b));return y.ok?y:f((g,b)=>p(g,b))}let w=await p(a);return w.matches.length>0||!d?w:f((y,g)=>p(y,g))},RE=(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=EE(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.
|
|
624
624
|
`:"";if(n==="paths"){let d=new Map;for(let p of t.matches)d.set(p.file,(d.get(p.file)??0)+1);let u=[...d].map(([p,f])=>`${p} (${f} match${f===1?"":"es"})`);return[`${r}${d.size}${t.truncated?"+":""} file${d.size===1?"":"s"} match "${e}":`,...u].join(`
|
|
625
625
|
`)}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(`
|
|
626
626
|
`):[o,...a.slice(0,Math.max(1,l)),s(a.length-Math.max(1,l))].join(`
|
|
627
|
-
`)};var
|
|
627
|
+
`)};var TE=448,c1=384,l1=4e4,Sr=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=Zd(OE(),".anyray");try{if((await Ii.stat(t)).isDirectory())return Zd(t,"history")}catch{}return Zd(OE(),".anyray-history")},d1=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:u1(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},u1=e=>{let t=i1("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)},p1=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}
|
|
628
628
|
|
|
629
629
|
${r.text}
|
|
630
630
|
`});return[...t,...n].join(`
|
|
631
631
|
`).replace(/\n{3,}/g,`
|
|
632
632
|
|
|
633
633
|
`)+`
|
|
634
|
-
`},Yd=async e=>{let t=await Sr();await
|
|
634
|
+
`},Yd=async e=>{let t=await Sr();await Ii.mkdir(t,{recursive:!0,mode:TE});try{await Ii.chmod(t,TE)}catch{}let n=0,r=0;for(let o of e)try{await Ii.writeFile(Zd(t,d1(o)),p1(o),{mode:c1}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Oa=async()=>{try{let e=await Sr();return(await Ii.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},_E=async e=>{let t=await Sr();return jd(e,{cwd:t,globs:["*.md"]})},PE=async e=>{let t=await Sr();return Si(e,{cwd:t,maxBytes:l1})};var DE=`anyray-connect history <command>
|
|
635
635
|
|
|
636
636
|
Make past Claude conversations searchable from any Anyray-connected client.
|
|
637
637
|
|
|
@@ -652,7 +652,7 @@ Which one you want:
|
|
|
652
652
|
conversation into the chat when you ask for it. Recall, not a list.
|
|
653
653
|
|
|
654
654
|
Running both is fine, and gets you both.
|
|
655
|
-
`,
|
|
655
|
+
`,m1=async e=>{try{return{raw:await f1.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"})`}}},h1=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return O("Usage: anyray-connect history import <conversations.json>"),A(v("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await m1(t);if("error"in n)return O(n.error),1;let r=Kd(n.raw);if(!r.ok)return O(`Could not read that export: ${r.message??"unrecognized format"}`),A(v("Expected the conversations.json from a Claude data export (claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data).")),1;if(r.conversations.length===0)return O("That export contains no conversations with readable messages."),1;let o;try{o=await Yd(r.conversations)}catch(a){let s=a?.code;return O(`Could not create the history archive (${s??"write failed"}).`),A(v("Check that ~/.anyray is a writable directory, then try again.")),1}return M(`Imported ${o.written} conversation${o.written===1?"":"s"} into ${o.dir}`),r.skipped>0&&A(v(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&_(`${o.failed} conversation${o.failed===1?"":"s"} could not be written.`),A(""),A(V("Your history is now searchable from any Anyray-connected client.")),A(v(' Ask about a past conversation \u2014 e.g. "what did we decide about the pricing model?" \u2014')),A(v(" and the assistant can search this archive and pull it up.")),A(v(" This is recall, not the Claude Desktop sidebar: past chats come back when you ask")),A(v(" for them, they do not reappear as a clickable list in the app.")),0},y1=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return O("Usage: anyray-connect history restore <export.zip>"),A(v("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await Hl(t);return n.ok?(M(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&A(v(` ${n.skipped} already present, left untouched.`)),n.failed>0&&_(`${n.failed} conversation${n.failed===1?"":"s"} could not be written.`),A(""),A(V("Open Claude Desktop \u2014 they are in the sidebar again.")),A(v(" Anyray stays configured; this changed nothing about your routing.")),A(v(" Heads up: this writes into Claude Desktop\u2019s own session storage, which is")),A(v(" undocumented. A future Desktop release could stop reading it \u2014 your export")),A(v(" file still works, and `history import` remains a second copy.")),0):(O(`Could not restore into Claude Desktop: ${n.reason}`),A(v(` ${n.remedy}`)),1)},g1=async()=>{let e=await Sr(),t=await Oa();return t===0?(A(`No conversations imported yet. Archive would live at ${e}`),A(v(" Import one with: anyray-connect history import <conversations.json>")),0):(M(`${t} conversation${t===1?"":"s"} in ${e}`),0)},LE=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(DE),0):t==="import"?h1(e.slice(1)):t==="restore"?y1(e.slice(1)):t==="status"?g1():(O(`Unknown history command: ${t}`),console.log(DE),1)};import{promises as w1}from"node:fs";var b1=`anyray-connect migrate [options]
|
|
656
656
|
|
|
657
657
|
Bring what Claude Desktop was showing you onto Anyray. Quit Claude Desktop first.
|
|
658
658
|
|
|
@@ -681,60 +681,60 @@ Getting the export (you do this, not Anyray \u2014 it needs your Claude login):
|
|
|
681
681
|
Open claude.ai -> Settings -> Privacy -> Export data. Anthropic emails a link.
|
|
682
682
|
Pass the .zip to --export, and the conversations.json inside it to
|
|
683
683
|
--conversations. Both are safe to re-run; they skip what is already there.
|
|
684
|
-
`,
|
|
685
|
-
`).filter(Boolean))A(` ${s}`);return!1}for(let s of n.lanes)A(` ${L1(s)}`);for(let s of n.portableAssets){let i=s.migrated+s.alreadyPresent,c=s.conflicts+s.invalid+s.failed;if(i+c===0)continue;let l=s.kind==="skill"?"User-created skills":s.kind==="plugin"?"User-installed plugins":"Local MCP servers";A(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&_(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&_(` Claude Desktop has more than one target ${r.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run this again.`);let o=n.retryableAssets??[];o.length>0&&_(` ${o.length} portable configuration ${o.length===1?"type needs":"types need"} another local-copy attempt; no existing target entry was replaced.`);for(let s of n.blocked??[])_(` ${PI[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),A(` ${xh(s.reason,s.lane,"anyray-connect migrate")}`);return(n.blocked??[]).length===0&&n.lanes.every(s=>s.migrated+s.alreadyPresent+s.skippedNoTranscript+s.failed===0)&&A(v(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},$1=async(e,t)=>{if(A(""),A(V("2. Your claude.ai chats")),t){A(v(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){A(" These live on your Claude account, not this machine, so they need"),A(" an export. Anyray cannot fetch them: the only credential that could"),A(" is your claude.ai session, which Connect never holds."),A(v(" claude.ai -> Settings -> Privacy -> Export data, then:")),A(v(" anyray-connect migrate --export ~/Downloads/claude-export.zip"));return}let n=await Ul(e.exportZip);if(!n.ok){O(` ${n.reason}`),A(` ${n.remedy}`);return}M(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),A(v(" They are listed under Cowork \u2014 the Chat tab has no local store."));let r=n.projects;if(r.imported+r.alreadyPresent+r.skippedCollision+r.failed>0){let a=[r.alreadyPresent>0?`${r.alreadyPresent} already there`:"",r.skippedCollision>0?`${r.skippedCollision} skipped, a folder of that name already exists`:"",r.failed>0?`${r.failed} failed`:""].filter(Boolean);M(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&A(v(` Instructions and docs are in ${r.root}, listed under Projects.`))}},M1=async e=>{if(A(""),A(V("3. Searchable from every Anyray client")),!e.conversations){let o=await Oa();o>0?A(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(A(v(" Optional. Pass the conversations.json inside the export:")),A(v(" anyray-connect migrate --conversations <path>/conversations.json")));return}let t;try{t=await _1.readFile(e.conversations,"utf8")}catch{O(` could not read ${e.conversations}`);return}let n=Kd(t);if(!n.ok){O(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await Yd(n.conversations);M(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),A(v(` Ask any Anyray-connected client about a past chat. ${await Sr()}`))},B1=e=>{A(""),A(V("Next")),A(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||_(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),A(v(" No Chat tab? Configured before this Connect version: run `anyray-connect desktop`."))},DI=async(e,t={})=>{let n;try{n=D1(e)}catch(o){return O(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(P1),0;A(V("Migrating Claude Desktop onto Anyray")),A(v("Claude Desktop must be fully quit.")),A("");let r=await N1(n,t);return await $1(n,!r),await M1(n),r?(B1(n),0):(A(""),_("Fix the item above and re-run to finish the migration."),1)};var F1=3e3,Jd=async(e,t={})=>{let n=t.timeoutMs??F1,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`:ft(s).trim()||"connection failed"}}finally{clearTimeout(a)}};var W1="enl_",LI="enp_",NI=e=>e.startsWith(W1)||e.startsWith(LI),Xm=e=>e.startsWith(LI),H1=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],zm=e=>H1.find(t=>e.startsWith(t.prefix)),$I=/^\/enroll\/([^/]+)\/?$/,MI=/^\/i\/([^/]+)\/?$/,BI=e=>{let t=e.match($I);if(t)return zm(t[1])?void 0:t[1];let n=e.match(MI);return n&&NI(n[1])?n[1]:void 0},U1=1e4,Xd=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=BI(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!zm(t))return{cpOrigin:Hn(),token:t}},FI=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match($I)??o.pathname.match(MI);if(!a)return;n=a[1]}catch{}let r=zm(n);return r?{flag:r.flag,what:r.what}:void 0},Ei=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:BI(n.pathname)!==void 0}catch{return NI(t)}},Si=e=>typeof e=="string"&&e.trim()?e.trim():void 0,WI=async(e,t={})=>{let n=t.timeoutMs??U1,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 p=u instanceof Error&&u.name==="AbortError"?` no response within ${n}ms.`:ft(u);throw new Error(`could not reach the enrollment page at ${e.cpOrigin}.${p}`)}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"&&Si(u.url)!==void 0),d=Si(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:Si(l?.deploymentId),org:Si(i.org),email:Si(i.email),seatMode:i.seatMode===!0,...i.provisioningKind==="manual"||i.provisioningKind==="mdm"?{provisioningKind:i.provisioningKind}:{},...i.provisioningProofMode==="macos-bootstrap"?{provisioningProofMode:i.provisioningProofMode}:{}}};import{execFileSync as GI}from"node:child_process";import G1 from"node:os";var VI="ai.anyray.connect",zd="EnrollmentEmail",HI="EnrollmentUrl",V1="HKLM\\SOFTWARE\\Policies\\Anyray\\Connect",K1=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,j1=254,Z1=2048,Y1=()=>`/Library/Managed Preferences/${VI}.plist`,J1=e=>`/Library/Managed Preferences/${e}/${VI}.plist`;var UI=e=>{try{let t=JSON.parse(e);return{...typeof t[zd]=="string"?{email:t[zd]}:{},...typeof t[HI]=="string"?{enrollmentUrl:t[HI]}:{}}}catch{return{}}},X1=e=>new RegExp(`${zd}\\s+REG_SZ\\s+(.+)`).exec(e)?.[1]?.trim()||void 0,Ii=e=>{if(!e)return;let t=e.trim().toLowerCase();if(!(!t||t.length>j1))return K1.test(t)?t:void 0},z1=e=>{if(!e)return;let t=e.trim();if(!(!t||t.length>Z1))try{let n=new URL(t);return n.protocol==="https:"&&n.username===""&&n.password===""&&n.search===""&&n.hash===""&&/^\/enroll\/enp_[A-Za-z0-9_-]{43}$/.test(n.pathname)?n.toString():void 0}catch{return}},q1=e=>{try{return GI("plutil",["-convert","json","-o","-",e],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},Q1=()=>{try{return G1.userInfo().username||void 0}catch{return}},eV=()=>{try{return GI("reg",["query",V1,"/v",zd],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},KI={platform:process.platform,readMacPlistJson:q1,username:Q1,readWindowsRegQuery:eV},qm=(e=KI)=>{try{if(e.platform==="darwin"){let t=e.username(),n=t?UI(e.readMacPlistJson(J1(t))??""):{},r=UI(e.readMacPlistJson(Y1())??""),o=Ii(n.email)??Ii(r.email),a=z1(r.enrollmentUrl);return{...o?{email:o}:{},...a?{enrollmentUrl:a}:{}}}if(e.platform==="win32"){let t=e.readWindowsRegQuery(),n=t?Ii(X1(t)):void 0;return n?{email:n}:{}}return{}}catch{return{}}},jI=(e=KI)=>qm(e).email;var tV="anyray-device-enroll",nV=32e3,rV=2e4,oV=12e3,aV=512,sV=/^[A-Za-z0-9_-]+$/,iV=/^[A-Za-z0-9_-]{43}$/,Qm=(e,t)=>typeof e=="string"&&e.length>0&&e.length<=t&&sV.test(e),cV=e=>{try{let t=Buffer.from(e,"base64url");if(t.toString("base64url")!==e)return;let n=JSON.parse(t.toString("utf8"));return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}catch{return}},lV=e=>{if(typeof e!="string"||!iV.test(e))return!1;let t=Buffer.from(e,"base64url");return t.length===32&&t.toString("base64url")===e},dV=e=>{if(!(Buffer.byteLength(e,"utf8")>nV))try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t)||Object.keys(t).length!==6||Object.keys(t).some(o=>!["v","operation","devPublicKey","claims","certificate","signature"].includes(o))||t.v!==1||t.operation!=="enrollment-proof"||!fd(t.devPublicKey)||!Qm(t.claims,rV)||!Qm(t.certificate,oV)||!Qm(t.signature,aV))return;let n=cV(t.claims),r=Ii(typeof n?.email=="string"?n.email:void 0);return n?.v!==1||n.purpose!==tV||typeof n.tokenHash!="string"||!/^[0-9a-f]{64}$/.test(n.tokenHash)||n.devPublicKey!==t.devPublicKey||typeof n.issuedAt!="string"||!Number.isFinite(Date.parse(n.issuedAt))||!lV(n.nonce)||!r?void 0:{email:r,devPublicKey:t.devPublicKey,proof:{claims:t.claims,certificate:t.certificate,signature:t.signature}}}catch{return}},ZI=async(e={invokeHelper:Yh})=>{let t=await e.invokeHelper(JSON.stringify({v:1,operation:"enrollment-proof"})),n=dV(t);if(!n)throw new Error("device proof helper returned an invalid response");return n};import{spawn as uV}from"node:child_process";import{platform as pV}from"node:os";var Ta=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=pV(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=uV(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var YI=()=>Pm(),JI=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??YI)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},fV=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},XI=async(e,t={})=>{let n=(t.openInput??YI)(),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=ha(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],y=m===s?l("36","\u276F"):" ",g=e.single?a[m]?"(\u25CF)":"(\u25CB)":a[m]?"[x]":"[ ]",b=w.hint?` ${l("2",w.hint)}`:"";h.push(`${y} ${g} ${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(`
|
|
684
|
+
`,A1=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},NE={code:"Claude Code sessions",cowork:"Cowork tasks"},C1=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`${NE[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},k1=async(e,t)=>{A(V("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??oo)({account:e.account,allAccounts:e.allAccounts,command:"anyray-connect migrate"});if(!n.ok){O(` ${n.reason}`);for(let s of n.remedy.split(`
|
|
685
|
+
`).filter(Boolean))A(` ${s}`);return!1}for(let s of n.lanes)A(` ${C1(s)}`);for(let s of n.portableAssets){let i=s.migrated+s.alreadyPresent,c=s.conflicts+s.invalid+s.failed;if(i+c===0)continue;let l=s.kind==="skill"?"User-created skills":s.kind==="plugin"?"User-installed plugins":"Local MCP servers";A(` ${l}: ${s.migrated} migrated`+(s.alreadyPresent>0?` (${s.alreadyPresent} already there)`:"")),c>0&&_(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&_(` Claude Desktop has more than one target ${r.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run this again.`);let o=n.retryableAssets??[];o.length>0&&_(` ${o.length} portable configuration ${o.length===1?"type needs":"types need"} another local-copy attempt; no existing target entry was replaced.`);for(let s of n.blocked??[])_(` ${NE[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),A(` ${xm(s.reason,s.lane,"anyray-connect migrate")}`);return(n.blocked??[]).length===0&&n.lanes.every(s=>s.migrated+s.alreadyPresent+s.skippedNoTranscript+s.failed===0)&&A(v(" Nothing to copy \u2014 the previous profile held no sessions.")),r.length===0&&o.length===0},v1=async(e,t)=>{if(A(""),A(V("2. Your claude.ai chats")),t){A(v(" Waiting on step 1 \u2014 this writes into the same app store."));return}if(!e.exportZip){A(" These live on your Claude account, not this machine, so they need"),A(" an export. Anyray cannot fetch them: the only credential that could"),A(" is your claude.ai session, which Connect never holds."),A(v(" claude.ai -> Settings -> Privacy -> Export data, then:")),A(v(" anyray-connect migrate --export ~/Downloads/claude-export.zip"));return}let n=await Hl(e.exportZip);if(!n.ok){O(` ${n.reason}`),A(` ${n.remedy}`);return}M(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),A(v(" They are listed under Cowork \u2014 the Chat tab has no local store."));let r=n.projects;if(r.imported+r.alreadyPresent+r.skippedCollision+r.failed>0){let a=[r.alreadyPresent>0?`${r.alreadyPresent} already there`:"",r.skippedCollision>0?`${r.skippedCollision} skipped, a folder of that name already exists`:"",r.failed>0?`${r.failed} failed`:""].filter(Boolean);M(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&A(v(` Instructions and docs are in ${r.root}, listed under Projects.`))}},S1=async e=>{if(A(""),A(V("3. Searchable from every Anyray client")),!e.conversations){let o=await Oa();o>0?A(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(A(v(" Optional. Pass the conversations.json inside the export:")),A(v(" anyray-connect migrate --conversations <path>/conversations.json")));return}let t;try{t=await w1.readFile(e.conversations,"utf8")}catch{O(` could not read ${e.conversations}`);return}let n=Kd(t);if(!n.ok){O(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await Yd(n.conversations);M(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),A(v(` Ask any Anyray-connected client about a past chat. ${await Sr()}`))},I1=e=>{A(""),A(V("Next")),A(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||_(" Your claude.ai chats are still only on claude.ai \u2014 see step 2."),A(v(" No Chat tab? Configured before this Connect version: run `anyray-connect desktop`."))},$E=async(e,t={})=>{let n;try{n=A1(e)}catch(o){return O(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(b1),0;A(V("Migrating Claude Desktop onto Anyray")),A(v("Claude Desktop must be fully quit.")),A("");let r=await k1(n,t);return await v1(n,!r),await S1(n),r?(I1(n),0):(A(""),_("Fix the item above and re-run to finish the migration."),1)};var E1=3e3,Jd=async(e,t={})=>{let n=t.timeoutMs??E1,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`:ht(s).trim()||"connection failed"}}finally{clearTimeout(a)}};import{execFileSync as FE}from"node:child_process";import x1 from"node:os";var WE="ai.anyray.connect",zd="EnrollmentEmail",ME="EnrollmentUrl",R1="HKLM\\SOFTWARE\\Policies\\Anyray\\Connect",O1=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,T1=254,_1=2048,P1=()=>`/Library/Managed Preferences/${WE}.plist`,D1=e=>`/Library/Managed Preferences/${e}/${WE}.plist`;var BE=e=>{try{let t=JSON.parse(e);return{...typeof t[zd]=="string"?{email:t[zd]}:{},...typeof t[ME]=="string"?{enrollmentUrl:t[ME]}:{}}}catch{return{}}},L1=e=>new RegExp(`${zd}\\s+REG_SZ\\s+(.+)`).exec(e)?.[1]?.trim()||void 0,Xd=e=>{if(!e)return;let t=e.trim().toLowerCase();if(!(!t||t.length>T1))return O1.test(t)?t:void 0},N1=e=>{if(!e)return;let t=e.trim();if(!(!t||t.length>_1))try{let n=new URL(t);return n.protocol==="https:"&&n.username===""&&n.password===""&&n.search===""&&n.hash===""&&/^\/enroll\/enp_[A-Za-z0-9_-]{43}$/.test(n.pathname)?n.toString():void 0}catch{return}},$1=e=>{try{return FE("plutil",["-convert","json","-o","-",e],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},M1=()=>{try{return x1.userInfo().username||void 0}catch{return}},B1=()=>{try{return FE("reg",["query",R1,"/v",zd],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},HE={platform:process.platform,readMacPlistJson:$1,username:M1,readWindowsRegQuery:B1},Xh=(e=HE)=>{try{if(e.platform==="darwin"){let t=e.username(),n=t?BE(e.readMacPlistJson(D1(t))??""):{},r=BE(e.readMacPlistJson(P1())??""),o=Xd(n.email)??Xd(r.email),a=N1(r.enrollmentUrl);return{...o?{email:o}:{},...a?{enrollmentUrl:a}:{}}}if(e.platform==="win32"){let t=e.readWindowsRegQuery(),n=t?Xd(L1(t)):void 0;return n?{email:n}:{}}return{}}catch{return{}}},UE=(e,t)=>{if(!e?.length)return;let n=t?.trim().toLowerCase();if(n)return Xd(`${n}@${e[0]}`)},GE=(e=HE)=>Xh(e).email;import{spawn as F1}from"node:child_process";import{platform as W1}from"node:os";var Ta=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=W1(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=F1(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var VE=()=>Ph(),KE=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??VE)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},H1=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},jE=async(e,t={})=>{let n=(t.openInput??VE)(),r=n.stream,o=t.output??process.stderr;if(typeof r.setRawMode!="function")throw n.close(),new Error("raw terminal input is unavailable");let a=e.items.map(m=>m.selected===!0&&m.requiresExplicitChoice!==!0),s=0,i=0,c=ma(o,t.env??process.env),l=(m,h)=>c?`\x1B[${m}m${h}\x1B[0m`:h,d=()=>{let m=[l("1",e.title)];for(let h=0;h<e.items.length;h++){let w=e.items[h],y=h===s?l("36","\u276F"):" ",g=e.single?a[h]?"(\u25CF)":"(\u25CB)":a[h]?"[x]":"[ ]",b=w.hint?` ${l("2",w.hint)}`:"";m.push(`${y} ${g} ${w.label}${b}`)}m.push(l("2",e.single?"\u2191/\u2193 move \xB7 space choose \xB7 enter accept \xB7 q cancel":"\u2191/\u2193 move \xB7 space toggle \xB7 a toggle all \xB7 enter accept \xB7 q cancel")),i>0&&o.write(`\x1B[${i}A`),o.write(m.map(h=>`\r\x1B[2K${h}`).join(`
|
|
686
686
|
`)),o.write(`
|
|
687
|
-
`),i=
|
|
688
|
-
`).join("")),o.write(`\x1B[${i}A`))},p=!!r.isRaw,f=!1;try{return f=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((h
|
|
689
|
-
`)&&y({kind:"ok",values:[]});continue}if(
|
|
690
|
-
`){y({kind:"ok",values:e.items.filter((
|
|
691
|
-
`),t();let a=0,s=()=>{r.write(`\r${
|
|
692
|
-
`)){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()}},ox=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&&_a(e.current,e.minVersion)<0&&_a(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},xV=e=>_a(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}:{...ox(e),downgradeBlocked:!1},Pa=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",RV=(e=process.execPath)=>{let t=Hu(e);return t?Er(t):Er(Er(e))},OV=async(e=ut())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=Be(RV(e.execPath),"bin",Pa());try{if(await tu(t)!==await tu(e.execPath))return}catch{return}return t},ay=async(e=ut(),t=Q())=>{let n=await OV(e);if(n)return{kind:"managed",root:Er(Er(n)),link:n,entryPath:Kn(e)};let r=Kn(e);return Gu(r,t)?{kind:"durable",root:t,entryPath:r}:Fu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},ru=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=Ti)=>{let t=await ru(`${tx}/latest`,e,{redirect:"manual"});return IV(t.headers.get("location"))},TV=async e=>{try{let t=await ru(`${e}/connect-update.json`,Ti);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}},Oi=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},iy=async(e,t,n)=>{let r=await ru(e,vV);if(!r.ok||!r.body)throw new Oi(r.status);let o=wV("sha256"),a=0;if(await AV(bV.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>kV)throw new Error("asset exceeds size cap");o.update(c),yield c}},mV(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},_V=e=>Qd(e)===Pa()?Qd(Er(e)):Qd(e),PV=async e=>{let t=await nu(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Et(Be(e,n),{force:!0}).catch(()=>{})},ax=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Et(r,{force:!0}).catch(()=>{});let o=!1;try{await qd(e,r),o=!0}catch{}try{await ty(t,e),await gV(za(e),_V(t))}catch(a){throw o&&await qd(r,e).catch(()=>{}),a}await Et(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Et(n,{force:!0}),await yV(t,n),await qd(n,e)},DV=".anyray",cy=(e,t)=>e===t||Qd(e)===DV?448:493,Ri=async(e,t)=>{let n=(await ex(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await QI(e,n&4095|t).catch(()=>{})},eu=async(e,t)=>{await ry(e,{recursive:!0,mode:t}),await Ri(e,t)},LV=async(e,t,n)=>{let r=cy(e,Q());if(r!==448){let o=Be(e,"versions");await Ri(e,r),await Ri(Be(e,"bin"),r),await Ri(o,r);for(let a of await nu(o).catch(()=>[]))await Ri(Be(o,a),r)}await(n.refreshDesktopHelpers??Ud)(t)},NV=async(e,t={})=>{let n=Be(e.root,"bin"),r=Be(e.root,"versions"),o=Be(n,Pa()),a=cy(e.root,(t.privateRoot??Q)());await eu(n,a),await eu(r,a);let s=Be(r,e.version),c=(await ny(s).catch(()=>{}))?.isFile()?s:Be(s,Pa());if(!(await ny(c).catch(()=>{}))?.isFile()){let d=await(t.fetchResponse??ru)(`${e.tagUrl}/SHA256SUMS`,Ti),u=d.ok?oy(await d.text(),e.asset):void 0;if(!u)throw new Error("no published checksum");await eu(Er(c),a),await PV(Er(c));let p=`${c}.part-${process.pid}`;try{await(t.download??iy)(`${e.tagUrl}/${e.asset}`,p,u),await QI(p,493),await qd(p,c)}catch(f){throw await Et(p,{force:!0}).catch(()=>{}),f}}return await(t.activate??ax)(o,c),{link:o,target:c,versionsDir:r}},$V=async e=>{qI(e.target,[Fd,e.link],{stdio:"ignore",timeout:Ti})},MV=async e=>{let t=qI(e,["--version"],{stdio:"ignore",timeout:Ti});return!t.error&&t.status===0},BV=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??ho)(n);if(r.length>0){let o=await(t.resolveTarget??Me)(async()=>e);if(!o||!(await(t.repair??$t)(r,o.target)).every(fo))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??tr)()).ok)},FV=async e=>{let t=await e.install();if(!await(e.smoke??MV)(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},WV=async(e,t)=>{let n=await nu(e).catch(()=>[]);for(let r of n)t.includes(r)||await Et(Be(e,r),{force:!0,recursive:!0}).catch(()=>{})},HV=async e=>{let t=await nu(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Et(Be(e,n),{force:!0}).catch(()=>{})},UV=async(e,t)=>{let n=async()=>{await Et(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await ry(e,{recursive:!1}),n}catch{}let r=await ex(e).catch(()=>{});if(!(!r||t-r.mtimeMs<EV)){await n();try{return await ry(e,{recursive:!1}),n}catch{return}}},ey=e=>Be(e,"update-state.json"),GV=async e=>{let t=await B(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},Da=async(e={})=>{let t=e.now??Date.now,n=Ae;if(Sn(nn(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??ut(),o=e.root??Q(),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=e.force===!0,l=await(e.load??D)().catch(()=>({})),d=l.autoUpdate!==!1;!i&&s.link&&!e.checkOnly&&(d||c)&&await LV(o,s.link,e).catch(()=>{});let u=rx(e.platform??process.platform,e.arch??process.arch);if(!u)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??sy)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let p=a;if(!i&&p===n)return{outcome:"current",current:n,latest:p};if(i&&_a(p,n)<0)return{outcome:"migration-deferred",current:n,latest:p};let f=await GV(ey(o));if((e.respectFailureBackoff===!0||!c)&&f.failedVersion===p&&f.failedAt!==void 0&&t()-f.failedAt<SV)return{outcome:"failed",current:n,latest:p};let h=`${tx}/download/${nx}${p}`,m=d||c?void 0:await(e.minimumVersion??TV)(h),w={current:n,latest:p,autoUpdate:d,forced:c,minVersion:m},y=i?xV(w):{...ox(w),downgradeBlocked:!1};if(y.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:p};if(!y.apply)return{outcome:"disabled",current:n,latest:p};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:p,mandatory:y.mandatory};o===Q()?await tt():await eu(o,cy(o,Q()));let g=await UV(Be(o,"update.lock"),t());if(!g)return{outcome:i?"migration-available":"available",current:n,latest:p};let b,k;try{await HV(Be(o,"bin"));let C=await tu(Be(o,"versions")).catch(()=>{}),S=await tu(Be(o,"bin",Pa())).catch(()=>{}),E=S&&ec(S,C)?S:void 0,I=Be(o,"bin",Pa());i&&process.platform==="win32"&&(await ny(I).catch(()=>{}))?.isFile()&&(k=`${I}.rollback-${process.pid}`,await ty(I,k));let R=()=>(e.installBinary??NV)({root:o,version:p,asset:u,tagUrl:h});i?b=await FV({install:R,smoke:e.smoke,rollback:async({link:P,target:W})=>{k?(await ty(k,P),await Et(za(P),{force:!0}).catch(()=>{})):E&&E!==W?await ax(P,E):(await Et(P,{force:!0}),await Et(za(P),{force:!0}).catch(()=>{}))},repoint:async P=>e.repoint?e.repoint(l,P):BV(l),prune:async()=>{await(e.pruneDurable??(P=>tc(P)))(r)}}):b=await R(),await WV(b.versionsDir,[p,n]),await(e.refreshHelpersFromInstalled??$V)(b).catch(()=>{}),await Et(ey(o),{force:!0}).catch(()=>{})}finally{k&&await Et(k,{force:!0}).catch(()=>{}),await g()}return{outcome:i?"migrated":"updated",current:n,latest:p,managedPath:b.link,mandatory:y.mandatory}}catch{return a&&await Y(ey(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},sx=async(e={})=>{let t=e.context??ut(),n=await ay(t,e.root??Q()),r=Oo(e.root??Q());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:Ae,managedPath:n.link??r}:Da({...e,context:t,allowNpmMigration:!0})},bo=async(e={})=>{let t=e.context??ut(),n=e.root??Q(),r=await ay(t,n),o=r.kind==="npm"||r.kind==="durable"?Oo(n):void 0,a=await(e.load??D)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!rx(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=Sn(nn(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:Ae,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l}};import{z as ix}from"zod";var VV=5e3,KV=ix.object({lane:ix.enum(["subscription","org"]).optional().catch(void 0)}),cx=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??VV);try{let a=await(n.fetchResponse??fetch)(`${e.replace(/\/$/,"")}/connect/policy`,{headers:{"x-anyray-api-key":t.trim()},signal:r.signal});if(!a.ok)return;let s=KV.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},lx=(e,t)=>{if(!e||t.byoUpstream)return{overrodeFlag:!1};let n=t.subscription?"subscription":t.org?"org":void 0;return{lane:e,overrodeFlag:n!=null&&n!==e}};var jV=12e3,ZV="anyray-wiring-probe-not-a-real-token",YV={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"}]},Ao=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},ux=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}"`))},dx=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."],JV=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>"]}),_i=e=>({kind:"key-rejected",detail:`gateway rejected the client key (HTTP ${e}).`,remedy:["The gateway did not receive a usable personal key (missing, unknown, expired,","or revoked). Re-run `anyray-connect` to refresh an existing enrollment, or","use `--enroll` / `--sso` to enroll first."]}),XV=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:JV(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${Ao(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")?dx([" \u2022 add a provider key in the console \u2192 Providers (fixes it for everyone), or"]):["If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]]}:e===401||e===403?py(t)?fy(e):uy(t)?_i(e):ux(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${Ao(t)}`,remedy:["The org provider rejected the request \u2014 check the gateway\u2019s provider","key/config (e.g. the model is enabled for that account)."]}:{kind:"provider-rejected",detail:`gateway accepted your key but the model provider rejected the request (HTTP ${e}): ${Ao(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).",...dx([" \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}: ${Ao(t)}`,remedy:[]},zV=(e,t)=>{if(uy(t))return _i(e);if(py(t))return fy(e);if(ux(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}: ${Ao(t)}`,remedy:[]}},qV=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),QV=(e,t)=>{if(uy(t))return _i(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")||qV(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}: ${Ao(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)}},eK=async(e,t)=>{if(!e.clientKey)return _i(401);let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`${e.origin}/connect/savings`,{method:"GET",headers:{"x-anyray-api-key":e.clientKey},signal:n.signal}),a=await o.text();return o.ok?{kind:"ok",detail:"gateway accepted your personal key \u2014 Cursor hooks/MCP can report and retrieve.",remedy:[]}:o.status===401||o.status===403?_i(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${Ao(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},tK=(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."]}},Pi=async(e,t={})=>{let n=t.timeoutMs??jV,r=pe(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await eK(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 QV(d,u)}if(ee(e,"anthropic")){let l={Authorization:`Bearer ${ZV}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"};r&&(l["x-anyray-metadata"]=r),e.clientKey&&(l["x-anyray-api-key"]=e.clientKey);let{status:d,bodyText:u}=await ly(`${e.anthropicBaseUrl}/v1/messages`,l,dy,n);return zV(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,YV,n);return XV(i,c,t.tools??[])}catch(o){return tK(n,o)}};var px=async e=>{let t=await D(),n;try{n=kr(e.gateway,t)}catch(o){return A(V("Anyray connect \u2014 status")),$(`Gateway: ${o.message}`),0}A(V("Anyray connect \u2014 status")),U("Gateway"),A(` Origin: ${Qe(n)}`),t.gateway?$(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?$(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||$(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),U("Identity"),A(` Name: ${t.name??v("(not set)")}`),A(` Team: ${t.team??v("(not set)")}`);let r=nn();r&&(U("Environment"),A(` Remote dev context: ${_o(r)}`),Sn(r)&&$(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),$(" VS Code tools configure the remote server variant backing this window.")),t.enrolledCert&&t.clientKey&&(U("Credential renewal"),M(" Direct gateway routing with a proof-backed key heartbeat."),$(" Renewal extends the same key; tool configuration is not rewritten.")),U("Tools");for(let o of le){if(!(await o.detect()).installed){$(` ${o.title}: not installed`);continue}if(!o.pointsAt){$(` ${o.title}: installed ${v("(status not introspectable)")}`);continue}let s=await o.pointsAt(n);if(s){if(o.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){M(` ${o.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}M(` ${o.title}: pointed at Anyray`)}else{let i=null,c=null;if(o.id===xa&&o.mcpStatus)try{let l=(await o.mcpStatus()).registered,d=await Ld();i=Nd({id:o.id,installed:!0,pointedAt:s,mcpRegistered:l,introspectable:d.authoritative}),c={...d.authoritative?{}:{reason:d.reason},mcpRegistered:l}}catch{i=null,c=null}if((i==="not-routed"||i==="unverifiable")&&c){let l=$d(i,c);_(` ${o.title}: ${l.headline}`);for(let d of l.detail)A(v(` ${d}`))}else $(` ${o.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as gK}from"node:fs";import{isAbsolute as wK}from"node:path";import{access as nK}from"node:fs/promises";import{constants as rK}from"node:fs";import{platform as oK}from"node:os";var aK=async e=>{try{return await nK(e,rK.F_OK),!0}catch{return!1}},sK=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"]:[],Co=async(e={})=>{let t=e.os??oK(),n=e.exists??aK;for(let r of sK(t))if(await n(r))return!0;return!1};import{execFile as iK}from"node:child_process";import{readFile as cK}from"node:fs/promises";import{homedir as lK,platform as dK}from"node:os";import{promisify as uK}from"node:util";var pK=uK(iK),fK="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",fx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hK=async e=>{let t;try{t=await cK(e,"utf-8")}catch(n){return n?.code==="ENOENT"?{readable:!0}:{readable:!1}}try{if(t.trim()==="")return{readable:!0};let n=gt(t);if(!fx(n))return{readable:!1};let r=n[dn],o=n[un];return{readable:!0,supportsAnyray:fx(r)?r[z]===!0:void 0,bridgeEnabled:typeof o=="boolean"?o:void 0}}catch{return{readable:!1}}},mK=async(e=async()=>(await pK("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(dK()==="win32")return"unknown";let t;try{t=await e()}catch{return"unknown"}let n=!1;for(let r of t.split(`
|
|
693
|
-
`)){let o=new RegExp(`${fK}=(\\w*)`).exec(r);if(!o)continue;let a=r.replace(/\bVSCODE_[A-Z0-9_]*=\S*/g,"");if(/Code Helper|MacOS\/Code|VSCodium|Visual Studio Code|agentHost/i.test(a)&&(n=!0,o[1]==="true"))return"on"}return n?"off":"unknown"},yK=e=>e.mode!=="copilot-seat"?"not-applicable":e.settings.readable?e.settings.supportsAnyray!==!0||e.settings.bridgeEnabled!==!0?"not-configured":e.bridge==="off"?"awaiting-relaunch":"ready":"unknown",ou=(e,t)=>{switch(e){case"ready":return t==="on"?"Agents window: Anyray models available (agent host is running with the model bridge on).":"Agents window: configured. No running agent host was found to confirm it, so it applies from the next VS Code start.";case"awaiting-relaunch":return"Agents window: configured, but the agent host running right now started before it. Quit and relaunch VS Code once; a window reload will not do it, because that process outlives every window.";case"not-configured":return`Agents window: not enabled. Re-run anyray-connect --tools copilot, then quit and relaunch VS Code (it sets ${dn} and ${un}; if you switched either off yourself, that choice is left alone).`;case"unknown":return"Agents window: could not read VS Code settings.json, so its state is unknown. Nothing is reported as missing on that basis.";case"not-applicable":return"Agents window: not applicable on this machine."}},hx=async(e={})=>{let{installedVariant:t=Ho,receiptMode:n=rl,awaitingReload:r=nl,readSettings:o=hK,probeBridge:a=mK,home:s=lK()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:ou("not-applicable","unknown")};let c=await n(i,s);if(c!=="copilot-seat"){let p=c===void 0&&await r(i,s);return{state:p?"unknown":"not-applicable",bridge:"unknown",detail:p?"Agents window: VS Code has an Anyray configuration staged but not applied yet, so its state is unknown. Restart VS Code to finish.":ou("not-applicable","unknown")}}let l=await o(xs(i)),d=await a(),u=yK({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:ou(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:ou("not-applicable","unknown")}}};var zt="connect",hy=e=>e.replace(/-/g,"_"),mx=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:zt,checkId:"gateway_reachable",status:e.gateway.reachable?"ok":"unreachable"});let n=Date.parse(e.report.generatedAt),r=Date.parse(e.enrollment.expiresAt??""),o=e.enrollment.enrolled&&e.enrollment.expired===!1&&Number.isFinite(n)&&Number.isFinite(r)&&r-n<=336*60*60*1e3;if(t.push({tool:zt,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:zt,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.refreshScheduler.enabled){let i=e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy===!0:e.refreshScheduler.installed;t.push({tool:zt,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.identity.sharedIdentityRisk&&t.push({tool:zt,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:zt,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=hy(e.retrieval.kind);t.push({tool:zt,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":hy(e.verify.kind);t.push({tool:zt,checkId:"auth_verify",status:c,...i?{errorClass:"verify_not_applicable_subscription"}:c==="ok"?{}:{errorClass:`verify_${c}`}})}for(let i of e.tools)!i.installed||i.claudeCodeHookPolicy===void 0||t.push({tool:i.id,checkId:"hook_policy",status:i.claudeCodeHookPolicy==="fine"?"ok":i.claudeCodeHookPolicy});if(e.hookLane&&e.hookLane.verdict!=="indeterminate"){let i=e.hookLane.verdict==="dark";t.push({tool:zt,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:hy(e.hookLane.reason)}:{}})}t.push({tool:zt,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)i.installed&&(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp&&t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing"}),a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"}));return t.push({tool:zt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function bK(){return Ae}var AK="ctx_doctor-probe-synthetic",CK=(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 kK(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function vK(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 yx=e=>Nd({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&&yx(e)!=="unverifiable",gx=e=>e.registered&&e.command&&wK(e.command)?gK(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),SK=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,EK=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},wx=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},IK=(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(yo),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,y])=>({checkId:w,at:y})),p=n(l.flapping)?l.flapping:void 0,f=Array.isArray(p?.checks)?p.checks.filter(w=>typeof w=="string"&&a.has(w)):[],h=p?.reason==="rebroke_same_day"||p?.reason==="repeat_days"?p.reason:void 0,m=p&&r(p.since)&&h&&f.length>0?{since:p.since,reason:h,checks:f}:void 0;(u.length>0||m)&&s.push({tool:c,repaired:u,...m?{flapping:m}:{}})}return s},xK=async(e,t,n,r,o,a,s=n,i=Pi,c=!0,l=Do,d=bo,u=St,p=va)=>{let f=c?await Jd(e):null,h=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,m=K=>K&&Tm(K)?"machine_default":null,w=t.enrolledCert?.payload,y=w?.expiresAt??t.enrolledCertExpiry??null,b=(await a())?.sso??null,k=vK({ssoLink:b,enrolledViaToken:!!t.enrolledTokenHash}),C=yt(),S=await $w(C),E=S?[]:$c(Ie({origin:e})),I=[];for(let K of r){let De=await K.detect(),dt=null;if(De.installed&&K.mcpStatus)try{let Va=await K.mcpStatus();dt={...Va,commandOk:gx(Va)}}catch{}let Ye=De.installed&&K.id===xa?await o():void 0,et=De.installed&&K.pointsAt?await K.pointsAt(e):null,Or=await SK(et,K,t.managedTools??[]),Vi=et===!1&&Or===null,Wa=Or===!1&&K.routingPendingReload?await K.routingPendingReload().catch(()=>!1):!1,Ki=De.installed?K.runtimeDiagnostics?await K.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:K.routingOverrides?await K.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Ha,claudeCodeHookPolicy:Ua}=Ki,Ga=t.fleetToolPolicy,vo=Ga?.enabled.includes(K.id)?Ga.tiers?.[K.id]??ga:void 0;I.push({id:K.id,title:K.title,installed:De.installed,...De.detail?{detail:De.detail}:{},pointedAt:Or,...Vi?{routingHeld:!0}:{},...Wa?{routingPendingReload:!0}:{},...Ha.length?{routingOverrides:Ha}:{},...Ua===void 0?{}:{claudeCodeHookPolicy:Ua},mcp:dt,...vo?{policyTier:vo}:{},...t.revertedTools?.includes(K.id)?{tombstoned:!0}:{},...K.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...Ye===void 0?{}:{inferenceIntrospectable:Ye.authoritative,...Ye.authoritative?{}:{inferenceUnverifiableReason:Ye.reason}}})}let R=s?await(async()=>{let{kind:K,detail:De,remedy:dt}=await i(Ie({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:K,detail:De,remedy:dt}})():null,P=R?.kind==="provider-rejected"&&await EK(t.managedTools??[],r),W=R?{...R,...P?{notApplicableSubscription:!0}:{}}:null,q=n?CK(await ka({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:pe({user:t.name,team:t.team})},AK,{probe:!0}),{mode:k,ssoLink:b}):null,de=await u().catch(()=>({})),ie=An(de.hookLane),j=s?await wx(r):!1,ge=j?await(async()=>{let K=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...wm(K,{hookRegistered:j,neverInvoked:ym(ie,Date.now())}),lastInvokedAt:kd(ie)}})():null,he=(await rr()).map(K=>({adapter:K.adapter,op:K.op,requestedAt:K.requestedAt,watcherAlive:ar(K.watcherPid)})),F=he.find(K=>K.adapter==="cursor"),Z=F?{op:F.op,requestedAt:F.requestedAt,watcherAlive:F.watcherAlive}:null,X=!!t.refreshSchedulerEnabled,Ze=await Po(),Fe=await d(),T=t.persistenceOwner==="tray",N=T?await l(t)==="healthy":null,J=await vw({schedulerEnabled:X&&!T,schedulerInstalled:Ze,binaryDurable:!He(er())}),ue=0;f&&!f.reachable&&(ue+=1),T?X&&!N&&(ue+=1):X&&!Ze&&(ue+=1);for(let K of I)ue+=yy(K);W&&W.kind!=="ok"&&!W.notApplicableSubscription&&(ue+=1),q&&q.kind!=="ok"&&(ue+=1),ge?.verdict==="dark"&&(ue+=1),E.length>0&&(ue+=1),ue+=he.filter(K=>!K.watcherAlive).length;let qt=await hx();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:bK(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:nn(),selfUpdate:{managed:Fe.managed,available:Fe.available,autoUpdate:Fe.autoUpdate,state:Fe.state}},gateway:{origin:e,reachable:f?f.reachable:null,detail:f?f.detail:"not probed (--quick)"},refreshScheduler:{enabled:X,installed:Ze,owner:T?"tray":"os",...T?{trayHealthy:!!N}:{}},serviceRemoval:J,fleetdPresent:await Co(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:h,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:m(t.name)},enrollment:{enrolled:!!w,deploymentId:w?.deploymentId??null,issuedAt:w?.issuedAt??null,expiresAt:y,expired:y?Date.parse(y)<Date.now():null,orgMode:k,ssoLink:b},shell:{profilePath:C,blockPresent:S,staleExports:E},tools:I,...t.fleetToolPolicy?{fleetPlan:Ad(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Z,pendingOps:he,ambientRepairs:IK(de,r),verify:W,retrieval:q,hookLane:ge,agentsWindow:qt,problems:ue}},RK=e=>{if(e.serviceRemoval.suspected){U("Endpoint security"),_(" Anyray installed these background services, but their files are gone from disk \u2014"),_(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),_(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)A(v(` missing: ${t}`));A(v(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),A(v(" tools straight at the gateway (your key then needs a periodic re-run).")),A(v(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),A(v(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},OK=e=>{switch(A(V("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(U("Environment"),A(` Remote dev context: ${_o(e.connect.remoteContext)}`),Sn(e.connect.remoteContext)&&A(v(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."))),U("CLI updates"),e.connect.selfUpdate.state){case"managed":M(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||_(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":_(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),A(v(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":_(" Self-update is unavailable on this platform because no standalone binary is published."),A(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":A(v(" This copy is externally managed; update it with the method that installed it."));break;case"container":A(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(U("Gateway"),e.gateway.reachable===null?A(v(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?M(` Reachable: ${e.gateway.origin} ${v(`(${e.gateway.detail})`)}`):(O(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),A(v(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.refreshScheduler.enabled&&(U("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?M(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."):(O(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),A(v(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?M(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(O(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||A(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),RK(e),U("Personal key"),kK(e)){case"env":M(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":M(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":_(" Enrolled, but no personal key is cached locally right now."),A(v(" Fix: re-run `anyray-connect` to re-mint it from your enrollment \u2014 no need to re-enroll. Claude Code and Codex are still attributed to you by name."));break;default:_(" Enrollment required \u2014 no personal gateway key is available."),A(v(` Fix: ${gy(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?_(` Enrollment cert expired ${v(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):M(` Enrollment cert valid until ${e.enrollment.expiresAt} ${v(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(U("Shell"),O(" This terminal still exports Anyray, but the config is gone."),A(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),A(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),A(v(" Anything you start from this terminal keeps reaching the gateway with")),A(v(" no credential, and fails with 401.")),A(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),A(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),A(v(" reuses the environment it captured at launch, so a new terminal")),A(v(" (or Reload Window) keeps serving the old one.")));let t=e.tools.find(c=>c.installed&&c.claudeCodeHookPolicy!==void 0&&c.claudeCodeHookPolicy!=="fine");if(t?.claudeCodeHookPolicy){let c={state:t.claudeCodeHookPolicy};U("Claude Code hook policy"),O(` ${ic(c)}.`),A(v(` ${cc(c)}`))}U("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])O(` ${c.title}: ${l.problem}.`),A(v(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(O(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),A(v(" Fix: re-run `anyray-connect` to re-register the current binary."))):M(` ${c.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(_(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),A(v(" Fix: 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){A(v(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){A(v(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){M(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}M(` ${c.title}: pointed at ${e.gateway.origin}`),o(c),c.id==="claude-code"&&A(v(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===xa&&A(v(` ${NC}`)),c.id==="codex"&&A(v(" Note: Codex app, CLI, and IDE extension share config.toml; Codex cloud/web tasks cannot route through a local gateway.")),a(c)}else{o(c);let l=yx(c);if(l==="not-routed"||l==="unverifiable"){let d=$d(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});_(` ${c.title}: ${d.headline}`);for(let u of d.detail)A(v(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(_(` ${c.title}: reverted locally against admin policy (out of compliance)`),A(v(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?_(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):A(v(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(O(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),A(v(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(O(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),A(v(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(_(" No tools are pointed at this gateway yet."),A(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){U("Queued operations");for(let c of e.pendingOps){let l=pt(c.adapter)?.title??c.adapter;c.watcherAlive?_(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(O(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),A(v(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){U("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=pt(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:f,at:h})=>`${c(f)} ${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 p=` ${d}: ${u.join("; ")}`;l.flapping?_(p):A(p)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){U("Fleet policy");let c=l=>l.map(d=>pt(d)?.title??d).join(", ");i.freshIds.length>0&&A(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&_(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(U("Auth probe"),e.verify.notApplicableSubscription)M(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")M(` ${e.verify.detail}`);else{O(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)A(v(` ${c}`))}if(e.retrieval)if(U("Retrieval loop"),e.retrieval.kind==="ok")M(` ${e.retrieval.detail}`);else{O(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)A(v(` ${c}`))}if(e.hookLane){if(U("Hook lane"),e.hookLane.verdict==="live")M(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){O(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}else{_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}e.hookLane.lastInvokedAt!==null&&A(v(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(U("VS Code Agents window"),_(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(U("VS Code Agents window"),M(` ${e.agentsWindow.detail}`)),U("Summary"),e.problems===0?(e.verify?M(" No problems found."):M(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),A(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):O(` ${e.problems} problem(s) found \u2014 see fixes above.`)},TK=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}),_K=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!fm(n.code))return{hookLane:n,note:`Hook lane: the gateway rejected this machine\u2019s key as '${n.code??"unclassified"}', which an automatic re-mint must never answer \u2014 no key was minted. Re-enroll (see the Hook lane fixes above).`};let r=t.probeHookLane??va,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??Xt)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=An((await(t.readRefreshState??St)().catch(()=>({}))).hookLane),l=wm(i,{hookRegistered:await wx(t.adapters??le).catch(()=>!1),neverInvoked:ym(c,Date.now())}),d=s==="disabled"?"Hook lane: key refresh is disabled here (ANYRAY_REFRESH_DISABLE), so no key was minted and the finding stands.":l.verdict==="live"?"Hook lane: re-minted the personal key and rewrote the configured tools \u2014 the lane answers again.":l.verdict==="indeterminate"?`Hook lane: re-mint reported '${s}', but the confirming probe could not establish the lane's state \u2014 nothing is proven fixed and the finding stands.`:`Hook lane: re-mint reported '${s}' and the lane is still not live \u2014 re-enroll (see the Hook lane fixes above).`;return{hookLane:{...l,lastInvokedAt:kd(c)},note:d}},PK=async(e,t,n={})=>{let r=n.adapters??le,o=n.resolveTarget??Me,a=n.applyTools??$t,s=await _K(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(g=>g.installed&&(my(g)||g.mcp?.commandOk===!1||g.routingOverrides?.some(b=>b.repairable)));if(l.length===0)return{entries:[],remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,"Nothing to repair \u2014 no tool has drifted."]};let d=await o(async()=>t);if(!d)return{entries:l.map(g=>({id:g.id,title:g.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??[]),p=[],f=[...c.notes],h=[];for(let g of l){let b=r.find(k=>k.id===g.id);if(!u.has(g.id)||!b){p.push({id:g.id,title:g.title,status:"skipped-unmanaged"});continue}h.push(b)}p.length>0&&f.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,y=0;for(let g of m){if(p.push(g),!fo(g))continue;let b=e.tools.find(P=>P.id===g.id);if(!b)continue;let k=r.find(P=>P.id===g.id),C=b.mcp;if(k?.mcpStatus)try{let P=await k.mcpStatus();C={...P,commandOk:gx(P)}}catch{}let S=my(b)?!0:b.pointedAt;if(k?.pointsAt&&b.pointedAt!==null)try{S=await k.pointsAt(e.gateway.origin)}catch{}let E=b.routingOverrides,I=b.claudeCodeHookPolicy;if(k?.runtimeDiagnostics)try{let P=await k.runtimeDiagnostics();E=P.routingOverrides.length?P.routingOverrides:void 0,I=P.claudeCodeHookPolicy}catch{}else if(k?.routingOverrides)try{let P=await k.routingOverrides();E=P.length?P:void 0}catch{}let R={...b,pointedAt:S,mcp:C,...E?{routingOverrides:E}:{},...I===void 0?{}:{claudeCodeHookPolicy:I}};E||delete R.routingOverrides,I===void 0&&delete R.claudeCodeHookPolicy,w.set(g.id,R),y+=yy(b)-yy(R)}return{entries:p,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:f}},DK=e=>{U("Repair"),e.entries.length===0&&M(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?M(` ${t.title}: re-applied`):t.status==="queued"?M(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?A(v(` ${t.title}: ${t.status}`)):O(` ${t.title}: ${t.status}`);for(let t of e.notes)A(v(` ${t}`))},au=async(e,t={})=>{let n=await D();if(e.securityReview){if(!e.silent){A(V("Anyray connect \u2014 security review"));for(let c of Sw())A(c?` ${c}`:"")}return 0}let r;try{r=kr(e.gateway,n)}catch(c){return e.silent?1:e.json?(console.log(JSON.stringify({error:c.message})),1):(A(V("Anyray connect \u2014 doctor")),O(` Gateway URL: ${c.message}`),A(v(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.silent||(e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(A(V("Anyray connect \u2014 doctor")),O(" --quick skips the network probes; it cannot be combined with --verify."))),1;let o=!e.noVerify&&!e.quick,a=await xK(r,n,!!e.verify&&!e.quick,t.adapters??le,t.inferenceIntrospection??Ld,t.fleetBootstrap??br,o,t.verifyAuth??Pi,!e.quick,t.checkTray??Do,t.updateStatus??bo,t.readRefreshState??St,t.probeHookLane??va),s=e.repair?await PK(a,n,t):void 0,i=s?{...a,tools:a.tools.map(c=>s.refreshedTools.get(c.id)??c),...s.hookLane!==void 0?{hookLane:s.hookLane}:{},repairs:s.entries,problems:s.remainingProblems}:a;t.captureReport?.(i),e.silent||(e.json?console.log(JSON.stringify(TK(i),null,2)):(OK(i),s&&DK(s)));try{e.quick||await(t.reportHealth??GS)(mx(i),i.connect.version)}catch{}return i.problems===0?0:1};var LK=()=>{let e=[];for(let t of le){let n=t.skillsDir?.();n&&e.push(n)}return e},bx=async e=>{let t=await D();A(V("Anyray connect \u2014 sync"));let n;try{n=kr(e.gateway,t)}catch(s){return O(s.message),1}$(`Gateway: ${n}`);let r=BE(t.clientKey,"anyray-placeholder"),o;try{o=await ba(n,r)}catch(s){return O(`Team policy sync failed: ${dm(s)}`),1}let a=LK();if(a.length===0)NK();else if(o.skills.length===0)$("No team skills published yet \u2014 nothing to sync.");else{let s=await OS(o,a,t.syncedSkills??{});U("Skills");for(let i of s.results)i.written?M(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):$(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await oe({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){$(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}U("Summary"),A(` ${Qe(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Aa(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(A(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&$(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){$(`Fleet policy reconcile skipped: ${dm(s)}`)}return 0},NK=()=>{$("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as F2}from"node:zlib";import{promisify as W2}from"node:util";var Ir={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},wy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),Ax=e=>`
|
|
687
|
+
`),i=m.length},u=()=>{i!==0&&(o.write(`\x1B[${i}A`),o.write(Array.from({length:i},()=>`\r\x1B[2K
|
|
688
|
+
`).join("")),o.write(`\x1B[${i}A`))},p=!!r.isRaw,f=!1;try{return f=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((m,h)=>{let w=()=>{r.off("data",C),r.off("end",b),r.off("close",b),r.off("error",k)},y=S=>{w(),m(S)},g=S=>{w(),h(S)},b=()=>y({kind:"cancelled"}),k=S=>g(S),C=S=>{try{for(let I of H1(S)){if(I===""||I==="\x1B"||I==="q"){y({kind:"cancelled"});return}if(e.items.length===0){(I==="\r"||I===`
|
|
689
|
+
`)&&y({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 E=!a[s];a.fill(!1),a[s]=E}else a[s]=!a[s];d()}else if(I==="a"&&!e.single){let E=e.items.map((P,W)=>({item:P,index:W})).filter(({item:P})=>P.requiresExplicitChoice!==!0),R=!E.every(({index:P})=>a[P]);for(let{index:P}of E)a[P]=R;d()}else if(I==="\r"||I===`
|
|
690
|
+
`){y({kind:"ok",values:e.items.filter((E,R)=>a[R]).map(E=>E.value)});return}}}catch(I){g(I)}};r.on("data",C),r.on("end",b),r.on("close",b),r.on("error",k)})}finally{try{u(),o.write("\x1B[?25h")}catch{}try{r.pause?.(),f&&r.setRawMode(p)}catch{}n.close()}};var ZE=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],U1=80,Ei=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&ma(r,n.env??process.env)))return r.write(`${e}
|
|
691
|
+
`),t();let a=0,s=()=>{r.write(`\r${ZE[a++%ZE.length]} ${e}`)};s();let i=setInterval(s,U1);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as G1}from"node:fs";import{spawnSync as YE}from"node:child_process";import{chmod as JE,copyFile as qh,lstat as Qh,mkdir as ey,readdir as nu,realpath as tu,rename as qd,rm as Et,stat as XE,symlink as V1,writeFile as K1}from"node:fs/promises";import{createHash as j1}from"node:crypto";import{basename as Qd,dirname as Ir,join as Fe}from"node:path";import{Readable as Z1}from"node:stream";import{pipeline as Y1}from"node:stream/promises";var zE="https://github.com/anyrayHQ/install/releases",qE="connect-v",J1=new RegExp(`/releases/tag/${qE}([0-9][0-9A-Za-z.-]*)$`),X1=300*1024*1024,Oi=1e4,z1=5*6e4,q1=360*6e4,Q1=30*6e4,_a=(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)},QE=(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"}},eV=e=>{if(e)return J1.exec(e.trim())?.[1]},ty=(e,t)=>{for(let n of e.split(`
|
|
692
|
+
`)){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()}},ex=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&&_a(e.current,e.minVersion)<0&&_a(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},tV=e=>_a(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}:{...ex(e),downgradeBlocked:!1},Pa=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",nV=(e=process.execPath)=>{let t=Hu(e);return t?Ir(t):Ir(Ir(e))},rV=async(e=ft())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=Fe(nV(e.execPath),"bin",Pa());try{if(await tu(t)!==await tu(e.execPath))return}catch{return}return t},ny=async(e=ft(),t=Q())=>{let n=await rV(e);if(n)return{kind:"managed",root:Ir(Ir(n)),link:n,entryPath:Kn(e)};let r=Kn(e);return Gu(r,t)?{kind:"durable",root:t,entryPath:r}:Fu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},ru=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)}},ry=async(e=Oi)=>{let t=await ru(`${zE}/latest`,e,{redirect:"manual"});return eV(t.headers.get("location"))},oV=async e=>{try{let t=await ru(`${e}/connect-update.json`,Oi);if(!t.ok)return;let n=await t.json();if(!n||typeof n!="object")return;let r=n.minVersion;return typeof r=="string"&&/^\d+\.\d+\.\d+/.test(r)?r:void 0}catch{return}},Ri=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},oy=async(e,t,n)=>{let r=await ru(e,z1);if(!r.ok||!r.body)throw new Ri(r.status);let o=j1("sha256"),a=0;if(await Y1(Z1.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>X1)throw new Error("asset exceeds size cap");o.update(c),yield c}},G1(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},aV=e=>Qd(e)===Pa()?Qd(Ir(e)):Qd(e),sV=async e=>{let t=await nu(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Et(Fe(e,n),{force:!0}).catch(()=>{})},tx=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Et(r,{force:!0}).catch(()=>{});let o=!1;try{await qd(e,r),o=!0}catch{}try{await qh(t,e),await K1(za(e),aV(t))}catch(a){throw o&&await qd(r,e).catch(()=>{}),a}await Et(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Et(n,{force:!0}),await V1(t,n),await qd(n,e)},iV=".anyray",ay=(e,t)=>e===t||Qd(e)===iV?448:493,xi=async(e,t)=>{let n=(await XE(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await JE(e,n&4095|t).catch(()=>{})},eu=async(e,t)=>{await ey(e,{recursive:!0,mode:t}),await xi(e,t)},cV=async(e,t,n)=>{let r=ay(e,Q());if(r!==448){let o=Fe(e,"versions");await xi(e,r),await xi(Fe(e,"bin"),r),await xi(o,r);for(let a of await nu(o).catch(()=>[]))await xi(Fe(o,a),r)}await(n.refreshDesktopHelpers??Ud)(t)},lV=async(e,t={})=>{let n=Fe(e.root,"bin"),r=Fe(e.root,"versions"),o=Fe(n,Pa()),a=ay(e.root,(t.privateRoot??Q)());await eu(n,a),await eu(r,a);let s=Fe(r,e.version),c=(await Qh(s).catch(()=>{}))?.isFile()?s:Fe(s,Pa());if(!(await Qh(c).catch(()=>{}))?.isFile()){let d=await(t.fetchResponse??ru)(`${e.tagUrl}/SHA256SUMS`,Oi),u=d.ok?ty(await d.text(),e.asset):void 0;if(!u)throw new Error("no published checksum");await eu(Ir(c),a),await sV(Ir(c));let p=`${c}.part-${process.pid}`;try{await(t.download??oy)(`${e.tagUrl}/${e.asset}`,p,u),await JE(p,493),await qd(p,c)}catch(f){throw await Et(p,{force:!0}).catch(()=>{}),f}}return await(t.activate??tx)(o,c),{link:o,target:c,versionsDir:r}},dV=async e=>{YE(e.target,[Fd,e.link],{stdio:"ignore",timeout:Oi})},uV=async e=>{let t=YE(e,["--version"],{stdio:"ignore",timeout:Oi});return!t.error&&t.status===0},pV=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??fo)(n);if(r.length>0){let o=await(t.resolveTarget??Be)(async()=>e);if(!o||!(await(t.repair??Mt)(r,o.target)).every(po))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??tr)()).ok)},fV=async e=>{let t=await e.install();if(!await(e.smoke??uV)(t.target))throw await e.rollback?.(t),new Error("managed binary smoke test failed");if(!await e.repoint(t.link))throw new Error("persistent config repoint failed");return await e.prune(),t},mV=async(e,t)=>{let n=await nu(e).catch(()=>[]);for(let r of n)t.includes(r)||await Et(Fe(e,r),{force:!0,recursive:!0}).catch(()=>{})},hV=async e=>{let t=await nu(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Et(Fe(e,n),{force:!0}).catch(()=>{})},yV=async(e,t)=>{let n=async()=>{await Et(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await ey(e,{recursive:!1}),n}catch{}let r=await XE(e).catch(()=>{});if(!(!r||t-r.mtimeMs<Q1)){await n();try{return await ey(e,{recursive:!1}),n}catch{return}}},zh=e=>Fe(e,"update-state.json"),gV=async e=>{let t=await B(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},Da=async(e={})=>{let t=e.now??Date.now,n=Ae;if(Sn(nn(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??ft(),o=e.root??Q(),a;try{let s=await ny(r,o);if(o=s.root,s.kind==="unmanaged")return{outcome:"unmanaged",current:n};if(s.kind==="npm"&&!e.allowNpmMigration)return{outcome:"unmanaged",current:n};let i=s.kind!=="managed",c=e.force===!0,l=await(e.load??D)().catch(()=>({})),d=l.autoUpdate!==!1;!i&&s.link&&!e.checkOnly&&(d||c)&&await cV(o,s.link,e).catch(()=>{});let u=QE(e.platform??process.platform,e.arch??process.arch);if(!u)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??ry)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let p=a;if(!i&&p===n)return{outcome:"current",current:n,latest:p};if(i&&_a(p,n)<0)return{outcome:"migration-deferred",current:n,latest:p};let f=await gV(zh(o));if((e.respectFailureBackoff===!0||!c)&&f.failedVersion===p&&f.failedAt!==void 0&&t()-f.failedAt<q1)return{outcome:"failed",current:n,latest:p};let m=`${zE}/download/${qE}${p}`,h=d||c?void 0:await(e.minimumVersion??oV)(m),w={current:n,latest:p,autoUpdate:d,forced:c,minVersion:h},y=i?tV(w):{...ex(w),downgradeBlocked:!1};if(y.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:p};if(!y.apply)return{outcome:"disabled",current:n,latest:p};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:p,mandatory:y.mandatory};o===Q()?await tt():await eu(o,ay(o,Q()));let g=await yV(Fe(o,"update.lock"),t());if(!g)return{outcome:i?"migration-available":"available",current:n,latest:p};let b,k;try{await hV(Fe(o,"bin"));let C=await tu(Fe(o,"versions")).catch(()=>{}),S=await tu(Fe(o,"bin",Pa())).catch(()=>{}),I=S&&Qi(S,C)?S:void 0,E=Fe(o,"bin",Pa());i&&process.platform==="win32"&&(await Qh(E).catch(()=>{}))?.isFile()&&(k=`${E}.rollback-${process.pid}`,await qh(E,k));let R=()=>(e.installBinary??lV)({root:o,version:p,asset:u,tagUrl:m});i?b=await fV({install:R,smoke:e.smoke,rollback:async({link:P,target:W})=>{k?(await qh(k,P),await Et(za(P),{force:!0}).catch(()=>{})):I&&I!==W?await tx(P,I):(await Et(P,{force:!0}),await Et(za(P),{force:!0}).catch(()=>{}))},repoint:async P=>e.repoint?e.repoint(l,P):pV(l),prune:async()=>{await(e.pruneDurable??(P=>ec(P)))(r)}}):b=await R(),await mV(b.versionsDir,[p,n]),await(e.refreshHelpersFromInstalled??dV)(b).catch(()=>{}),await Et(zh(o),{force:!0}).catch(()=>{})}finally{k&&await Et(k,{force:!0}).catch(()=>{}),await g()}return{outcome:i?"migrated":"updated",current:n,latest:p,managedPath:b.link,mandatory:y.mandatory}}catch{return a&&await Y(zh(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},nx=async(e={})=>{let t=e.context??ft(),n=await ny(t,e.root??Q()),r=Ro(e.root??Q());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:Ae,managedPath:n.link??r}:Da({...e,context:t,allowNpmMigration:!0})},wo=async(e={})=>{let t=e.context??ft(),n=e.root??Q(),r=await ny(t,n),o=r.kind==="npm"||r.kind==="durable"?Ro(n):void 0,a=await(e.load??D)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!QE(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=Sn(nn(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:Ae,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l}};import{z as rx}from"zod";var wV=5e3,bV=rx.object({lane:rx.enum(["subscription","org"]).optional().catch(void 0)}),ox=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??wV);try{let a=await(n.fetchResponse??fetch)(`${e.replace(/\/$/,"")}/connect/policy`,{headers:{"x-anyray-api-key":t.trim()},signal:r.signal});if(!a.ok)return;let s=bV.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},ax=(e,t)=>{if(!e||t.byoUpstream)return{overrodeFlag:!1};let n=t.subscription?"subscription":t.org?"org":void 0;return{lane:e,overrodeFlag:n!=null&&n!==e}};var AV=12e3,CV="anyray-wiring-probe-not-a-real-token",kV={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},iy={model:"claude-3-5-haiku-20241022",max_tokens:1,messages:[{role:"user",content:"ping"}]},bo=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},ix=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},cy=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},sx=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."],vV=e=>e.includes("no provider key configured for"),ly=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},dy=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>"]}),Ti=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."]}),SV=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:vV(t)?{kind:"provider-rejected",detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${bo(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")?sx([" \u2022 add a provider key in the console \u2192 Providers (fixes it for everyone), or"]):["If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]]}:e===401||e===403?ly(t)?dy(e):cy(t)?Ti(e):ix(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${bo(t)}`,remedy:["The org provider rejected the request \u2014 check the gateway\u2019s provider","key/config (e.g. the model is enabled for that account)."]}:{kind:"provider-rejected",detail:`gateway accepted your key but the model provider rejected the request (HTTP ${e}): ${bo(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).",...sx([" \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}: ${bo(t)}`,remedy:[]},IV=(e,t)=>{if(cy(t))return Ti(e);if(ly(t))return dy(e);if(ix(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}: ${bo(t)}`,remedy:[]}},EV=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),xV=(e,t)=>{if(cy(t))return Ti(e);if(ly(t))return dy(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")||EV(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}: ${bo(t)}`,remedy:[`The probe asks for a fixed model (${iy.model}) your upstream`,"is not required to serve, so a model rejection here does not mean your","tools are broken. Check that the upstream serves it before chasing this."]}},sy=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),r);try{let s=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...t},body:JSON.stringify(n),signal:o.signal});return{status:s.status,bodyText:await s.text()}}finally{clearTimeout(a)}},RV=async(e,t)=>{if(!e.clientKey)return Ti(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?Ti(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${bo(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},OV=(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."]}},_i=async(e,t={})=>{let n=t.timeoutMs??AV,r=ue(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await RV(e,n);if(e.byoUpstream){let l={Authorization:`Bearer ${e.byoUpstream.key}`,"anthropic-version":"2023-06-01","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic","x-anyray-custom-host":e.byoUpstream.url};e.clientKey&&(l["x-anyray-api-key"]=e.clientKey),r&&(l["x-anyray-metadata"]=r);let{status:d,bodyText:u}=await sy(`${e.anthropicBaseUrl}/v1/messages`,l,iy,n);return xV(d,u)}if(ee(e,"anthropic")){let l={Authorization:`Bearer ${CV}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"};r&&(l["x-anyray-metadata"]=r),e.clientKey&&(l["x-anyray-api-key"]=e.clientKey);let{status:d,bodyText:u}=await sy(`${e.anthropicBaseUrl}/v1/messages`,l,iy,n);return IV(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await sy(`${e.openaiBaseUrl}/chat/completions`,s,kV,n);return SV(i,c,t.tools??[])}catch(o){return OV(n,o)}};var cx=async e=>{let t=await D(),n;try{n=kr(e.gateway,t)}catch(o){return A(V("Anyray connect \u2014 status")),$(`Gateway: ${o.message}`),0}A(V("Anyray connect \u2014 status")),U("Gateway"),A(` Origin: ${et(n)}`),t.gateway?$(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?$(" (from $ANYRAY_GATEWAY_URL)"):e.gateway||$(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),U("Identity"),A(` Name: ${t.name??v("(not set)")}`),A(` Team: ${t.team??v("(not set)")}`);let r=nn();r&&(U("Environment"),A(` Remote dev context: ${To(r)}`),Sn(r)&&$(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),$(" VS Code tools configure the remote server variant backing this window.")),t.enrolledCert&&t.clientKey&&(U("Credential renewal"),M(" Direct gateway routing with a proof-backed key heartbeat."),$(" Renewal extends the same key; tool configuration is not rewritten.")),U("Tools");for(let o of le){if(!(await o.detect()).installed){$(` ${o.title}: not installed`);continue}if(!o.pointsAt){$(` ${o.title}: installed ${v("(status not introspectable)")}`);continue}let s=await o.pointsAt(n);if(s){if(o.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")){M(` ${o.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}M(` ${o.title}: pointed at Anyray`)}else{let i=null,c=null;if(o.id===xa&&o.mcpStatus)try{let l=(await o.mcpStatus()).registered,d=await Ld();i=Nd({id:o.id,installed:!0,pointedAt:s,mcpRegistered:l,introspectable:d.authoritative}),c={...d.authoritative?{}:{reason:d.reason},mcpRegistered:l}}catch{i=null,c=null}if((i==="not-routed"||i==="unverifiable")&&c){let l=$d(i,c);_(` ${o.title}: ${l.headline}`);for(let d of l.detail)A(v(` ${d}`))}else $(` ${o.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as KV}from"node:fs";import{isAbsolute as jV}from"node:path";import{access as TV}from"node:fs/promises";import{constants as _V}from"node:fs";import{platform as PV}from"node:os";var DV=async e=>{try{return await TV(e,_V.F_OK),!0}catch{return!1}},LV=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"]:[],Ao=async(e={})=>{let t=e.os??PV(),n=e.exists??DV;for(let r of LV(t))if(await n(r))return!0;return!1};import{execFile as NV}from"node:child_process";import{readFile as $V}from"node:fs/promises";import{homedir as MV,platform as BV}from"node:os";import{promisify as FV}from"node:util";var WV=FV(NV),HV="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",lx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),UV=async e=>{let t;try{t=await $V(e,"utf-8")}catch(n){return n?.code==="ENOENT"?{readable:!0}:{readable:!1}}try{if(t.trim()==="")return{readable:!0};let n=wt(t);if(!lx(n))return{readable:!1};let r=n[dn],o=n[un];return{readable:!0,supportsAnyray:lx(r)?r[z]===!0:void 0,bridgeEnabled:typeof o=="boolean"?o:void 0}}catch{return{readable:!1}}},GV=async(e=async()=>(await WV("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(BV()==="win32")return"unknown";let t;try{t=await e()}catch{return"unknown"}let n=!1;for(let r of t.split(`
|
|
693
|
+
`)){let o=new RegExp(`${HV}=(\\w*)`).exec(r);if(!o)continue;let a=r.replace(/\bVSCODE_[A-Z0-9_]*=\S*/g,"");if(/Code Helper|MacOS\/Code|VSCodium|Visual Studio Code|agentHost/i.test(a)&&(n=!0,o[1]==="true"))return"on"}return n?"off":"unknown"},VV=e=>e.mode!=="copilot-seat"?"not-applicable":e.settings.readable?e.settings.supportsAnyray!==!0||e.settings.bridgeEnabled!==!0?"not-configured":e.bridge==="off"?"awaiting-relaunch":"ready":"unknown",ou=(e,t)=>{switch(e){case"ready":return t==="on"?"Agents window: Anyray models available (agent host is running with the model bridge on).":"Agents window: configured. No running agent host was found to confirm it, so it applies from the next VS Code start.";case"awaiting-relaunch":return"Agents window: configured, but the agent host running right now started before it. Quit and relaunch VS Code once; a window reload will not do it, because that process outlives every window.";case"not-configured":return`Agents window: not enabled. Re-run anyray-connect --tools copilot, then quit and relaunch VS Code (it sets ${dn} and ${un}; if you switched either off yourself, that choice is left alone).`;case"unknown":return"Agents window: could not read VS Code settings.json, so its state is unknown. Nothing is reported as missing on that basis.";case"not-applicable":return"Agents window: not applicable on this machine."}},dx=async(e={})=>{let{installedVariant:t=Wo,receiptMode:n=nl,awaitingReload:r=tl,readSettings:o=UV,probeBridge:a=GV,home:s=MV()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:ou("not-applicable","unknown")};let c=await n(i,s);if(c!=="copilot-seat"){let p=c===void 0&&await r(i,s);return{state:p?"unknown":"not-applicable",bridge:"unknown",detail:p?"Agents window: VS Code has an Anyray configuration staged but not applied yet, so its state is unknown. Restart VS Code to finish.":ou("not-applicable","unknown")}}let l=await o(xs(i)),d=await a(),u=VV({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:ou(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:ou("not-applicable","unknown")}}};var qt="connect",uy=e=>e.replace(/-/g,"_"),ux=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:qt,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:qt,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:qt,checkId:"shell_exports",status:e.shell.staleExports.length?"stale":"ok"}),e.refreshScheduler.enabled){let i=e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy===!0:e.refreshScheduler.installed;t.push({tool:qt,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:qt,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:qt,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=uy(e.retrieval.kind);t.push({tool:qt,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":uy(e.verify.kind);t.push({tool:qt,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:qt,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:uy(e.hookLane.reason)}:{}})}t.push({tool:qt,checkId:"overall",status:e.problems===0?"ok":"problems"});let a=new Set(e.fleetPlan?.tombstonedIds),s=new Set(e.fleetPlan?.candidateIds);for(let i of e.tools)i.installed&&(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp&&t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing"}),a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"}));return t.push({tool:qt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function ZV(){return Ae}var YV="ctx_doctor-probe-synthetic",JV=(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: ${my(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 XV(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function zV(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function my(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 px=e=>Nd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),py=e=>e.pointedAt===!1&&e.tombstoned!==!0&&px(e)!=="unverifiable",fx=e=>e.registered&&e.command&&jV(e.command)?KV(e.command):null,fy=e=>(py(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),qV=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,QV=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},mx=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},eK=(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(ho),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,y])=>({checkId:w,at:y})),p=n(l.flapping)?l.flapping:void 0,f=Array.isArray(p?.checks)?p.checks.filter(w=>typeof w=="string"&&a.has(w)):[],m=p?.reason==="rebroke_same_day"||p?.reason==="repeat_days"?p.reason:void 0,h=p&&r(p.since)&&m&&f.length>0?{since:p.since,reason:m,checks:f}:void 0;(u.length>0||h)&&s.push({tool:c,repaired:u,...h?{flapping:h}:{}})}return s},tK=async(e,t,n,r,o,a,s=n,i=_i,c=!0,l=Po,d=wo,u=It,p=va)=>{let f=c?await Jd(e):null,m=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,h=j=>j&&Th(j)?"machine_default":null,w=t.enrolledCert?.payload,y=w?.expiresAt??t.enrolledCertExpiry??null,b=(await a())?.sso??null,k=zV({ssoLink:b,enrolledViaToken:!!t.enrolledTokenHash}),C=gt(),S=await Dw(C),I=S?[]:Nc(xe({origin:e})),E=[];for(let j of r){let _e=await j.detect(),Ce=null;if(_e.installed&&j.mcpStatus)try{let Va=await j.mcpStatus();Ce={...Va,commandOk:fx(Va)}}catch{}let Je=_e.installed&&j.id===xa?await o():void 0,pt=_e.installed&&j.pointsAt?await j.pointsAt(e):null,Or=await qV(pt,j,t.managedTools??[]),Gi=pt===!1&&Or===null,Wa=Or===!1&&j.routingPendingReload?await j.routingPendingReload().catch(()=>!1):!1,Vi=_e.installed?j.runtimeDiagnostics?await j.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:j.routingOverrides?await j.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Ha,claudeCodeHookPolicy:Ua}=Vi,Ga=t.fleetToolPolicy,ko=Ga?.enabled.includes(j.id)?Ga.tiers?.[j.id]??ga:void 0;E.push({id:j.id,title:j.title,installed:_e.installed,..._e.detail?{detail:_e.detail}:{},pointedAt:Or,...Gi?{routingHeld:!0}:{},...Wa?{routingPendingReload:!0}:{},...Ha.length?{routingOverrides:Ha}:{},...Ua===void 0?{}:{claudeCodeHookPolicy:Ua},mcp:Ce,...ko?{policyTier:ko}:{},...t.revertedTools?.includes(j.id)?{tombstoned:!0}:{},...j.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...Je===void 0?{}:{inferenceIntrospectable:Je.authoritative,...Je.authoritative?{}:{inferenceUnverifiableReason:Je.reason}}})}let R=s?await(async()=>{let{kind:j,detail:_e,remedy:Ce}=await i(xe({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:j,detail:_e,remedy:Ce}})():null,P=R?.kind==="provider-rejected"&&await QV(t.managedTools??[],r),W=R?{...R,...P?{notApplicableSubscription:!0}:{}}:null,q=n?JV(await ka({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:ue({user:t.name,team:t.team})},YV,{probe:!0}),{mode:k,ssoLink:b}):null,de=await u().catch(()=>({})),ie=An(de.hookLane),K=s?await mx(r):!1,ge=K?await(async()=>{let j=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...wh(j,{hookRegistered:K,neverInvoked:yh(ie,Date.now())}),lastInvokedAt:Cd(ie)}})():null,me=(await rr()).map(j=>({adapter:j.adapter,op:j.op,requestedAt:j.requestedAt,watcherAlive:ar(j.watcherPid)})),F=me.find(j=>j.adapter==="cursor"),Z=F?{op:F.op,requestedAt:F.requestedAt,watcherAlive:F.watcherAlive}:null,X=!!t.refreshSchedulerEnabled,Ye=await _o(),We=await d(),T=t.persistenceOwner==="tray",L=T?await l(t)==="healthy":null,J=await Aw({schedulerEnabled:X&&!T,schedulerInstalled:Ye,binaryDurable:!Ue(er())}),pe=0;f&&!f.reachable&&(pe+=1),T?X&&!L&&(pe+=1):X&&!Ye&&(pe+=1);for(let j of E)pe+=fy(j);W&&W.kind!=="ok"&&!W.notApplicableSubscription&&(pe+=1),q&&q.kind!=="ok"&&(pe+=1),ge?.verdict==="dark"&&(pe+=1),I.length>0&&(pe+=1),pe+=me.filter(j=>!j.watcherAlive).length;let ut=await dx();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:ZV(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:nn(),selfUpdate:{managed:We.managed,available:We.available,autoUpdate:We.autoUpdate,state:We.state}},gateway:{origin:e,reachable:f?f.reachable:null,detail:f?f.detail:"not probed (--quick)"},refreshScheduler:{enabled:X,installed:Ye,owner:T?"tray":"os",...T?{trayHealthy:!!L}:{}},serviceRemoval:J,fleetdPresent:await Ao(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:m,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:h(t.name)},enrollment:{enrolled:!!w,deploymentId:w?.deploymentId??null,issuedAt:w?.issuedAt??null,expiresAt:y,expired:y?Date.parse(y)<Date.now():null,orgMode:k,ssoLink:b},shell:{profilePath:C,blockPresent:S,staleExports:I},tools:E,...t.fleetToolPolicy?{fleetPlan:bd(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Z,pendingOps:me,ambientRepairs:eK(de,r),verify:W,retrieval:q,hookLane:ge,agentsWindow:ut,problems:pe}},nK=e=>{if(e.serviceRemoval.suspected){U("Endpoint security"),_(" Anyray installed these background services, but their files are gone from disk \u2014"),_(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),_(" as suspected persistence. Re-running connect just rewrites them.");for(let t of e.serviceRemoval.missingPaths)A(v(` missing: ${t}`));A(v(" Fix now: `anyray-connect --no-key-refresh` \u2014 installs no background service, points")),A(v(" tools straight at the gateway (your key then needs a periodic re-run).")),A(v(" Fix properly: `anyray-connect doctor --security-review` prints the allow-list your")),A(v(" security team needs; once approved, `anyray-connect --yes` restores auto-refresh."))}},rK=e=>{switch(A(V("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(U("Environment"),A(` Remote dev context: ${To(e.connect.remoteContext)}`),Sn(e.connect.remoteContext)&&A(v(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."))),U("CLI updates"),e.connect.selfUpdate.state){case"managed":M(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||_(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":_(" This npm runtime will migrate to the managed standalone binary on the next persistent setup change."),A(v(" Run `anyray-connect update` to migrate now."));break;case"platform-unsupported":_(" Self-update is unavailable on this platform because no standalone binary is published."),A(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":A(v(" This copy is externally managed; update it with the method that installed it."));break;case"container":A(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(U("Gateway"),e.gateway.reachable===null?A(v(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?M(` Reachable: ${e.gateway.origin} ${v(`(${e.gateway.detail})`)}`):(O(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),A(v(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.refreshScheduler.enabled&&(U("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?M(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."):(O(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),A(v(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?M(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(O(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||A(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),nK(e),U("Personal key"),XV(e)){case"env":M(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":M(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":_(" Enrolled, but no personal key is cached locally right now."),A(v(" Fix: re-run `anyray-connect` to re-mint it from your enrollment \u2014 no need to re-enroll. Claude Code and Codex are still attributed to you by name."));break;default:_(" Enrollment required \u2014 no personal gateway key is available."),A(v(` Fix: ${my(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?_(` Enrollment cert expired ${v(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):M(` Enrollment cert valid until ${e.enrollment.expiresAt} ${v(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(U("Shell"),O(" This terminal still exports Anyray, but the config is gone."),A(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),A(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),A(v(" Anything you start from this terminal keeps reaching the gateway with")),A(v(" no credential, and fails with 401.")),A(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),A(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),A(v(" reuses the environment it captured at launch, so a new terminal")),A(v(" (or Reload Window) keeps serving the old one.")));let t=e.tools.find(c=>c.installed&&c.claudeCodeHookPolicy!==void 0&&c.claudeCodeHookPolicy!=="fine");if(t?.claudeCodeHookPolicy){let c={state:t.claudeCodeHookPolicy};U("Claude Code hook policy"),O(` ${sc(c)}.`),A(v(` ${ic(c)}`))}U("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])O(` ${c.title}: ${l.problem}.`),A(v(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(O(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),A(v(" Fix: re-run `anyray-connect` to re-register the current binary."))):M(` ${c.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(_(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),A(v(" Fix: 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){A(v(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){A(v(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){M(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}M(` ${c.title}: pointed at ${e.gateway.origin}`),o(c),c.id==="claude-code"&&A(v(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===xa&&A(v(` ${PC}`)),c.id==="codex"&&A(v(" Note: Codex app, CLI, and IDE extension share config.toml; Codex cloud/web tasks cannot route through a local gateway.")),a(c)}else{o(c);let l=px(c);if(l==="not-routed"||l==="unverifiable"){let d=$d(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});_(` ${c.title}: ${d.headline}`);for(let u of d.detail)A(v(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(_(` ${c.title}: reverted locally against admin policy (out of compliance)`),A(v(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?_(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):A(v(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(O(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),A(v(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(O(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),A(v(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(_(" No tools are pointed at this gateway yet."),A(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){U("Queued operations");for(let c of e.pendingOps){let l=mt(c.adapter)?.title??c.adapter;c.watcherAlive?_(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(O(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),A(v(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){U("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=mt(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:f,at:m})=>`${c(f)} ${new Date(m).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let p=` ${d}: ${u.join("; ")}`;l.flapping?_(p):A(p)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){U("Fleet policy");let c=l=>l.map(d=>mt(d)?.title??d).join(", ");i.freshIds.length>0&&A(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&_(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(U("Auth probe"),e.verify.notApplicableSubscription)M(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")M(` ${e.verify.detail}`);else{O(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)A(v(` ${c}`))}if(e.retrieval)if(U("Retrieval loop"),e.retrieval.kind==="ok")M(` ${e.retrieval.detail}`);else{O(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)A(v(` ${c}`))}if(e.hookLane){if(U("Hook lane"),e.hookLane.verdict==="live")M(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){O(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}else{_(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}e.hookLane.lastInvokedAt!==null&&A(v(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(U("VS Code Agents window"),_(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(U("VS Code Agents window"),M(` ${e.agentsWindow.detail}`)),U("Summary"),e.problems===0?(e.verify?M(" No problems found."):M(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),A(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):O(` ${e.problems} problem(s) found \u2014 see fixes above.`)},oK=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}),aK=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!fh(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??va,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??zt)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=An((await(t.readRefreshState??It)().catch(()=>({}))).hookLane),l=wh(i,{hookRegistered:await mx(t.adapters??le).catch(()=>!1),neverInvoked:yh(c,Date.now())}),d=s==="disabled"?"Hook lane: key refresh is disabled here (ANYRAY_REFRESH_DISABLE), so no key was minted and the finding stands.":l.verdict==="live"?"Hook lane: re-minted the personal key and rewrote the configured tools \u2014 the lane answers again.":l.verdict==="indeterminate"?`Hook lane: re-mint reported '${s}', but the confirming probe could not establish the lane's state \u2014 nothing is proven fixed and the finding stands.`:`Hook lane: re-mint reported '${s}' and the lane is still not live \u2014 re-enroll (see the Hook lane fixes above).`;return{hookLane:{...l,lastInvokedAt:Cd(c)},note:d}},sK=async(e,t,n={})=>{let r=n.adapters??le,o=n.resolveTarget??Be,a=n.applyTools??Mt,s=await aK(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(g=>g.installed&&(py(g)||g.mcp?.commandOk===!1||g.routingOverrides?.some(b=>b.repairable)));if(l.length===0)return{entries:[],remainingProblems:Math.max(0,e.problems-i),refreshedTools:new Map,...c,notes:[...c.notes,"Nothing to repair \u2014 no tool has drifted."]};let d=await o(async()=>t);if(!d)return{entries:l.map(g=>({id:g.id,title:g.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 ${my(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),p=[],f=[...c.notes],m=[];for(let g of l){let b=r.find(k=>k.id===g.id);if(!u.has(g.id)||!b){p.push({id:g.id,title:g.title,status:"skipped-unmanaged"});continue}m.push(b)}p.length>0&&f.push("Drifted tools outside the managed record are never auto-repaired \u2014 run `anyray-connect` once to (re)configure and record them.");let h=await a(m,d.target),w=new Map,y=0;for(let g of h){if(p.push(g),!po(g))continue;let b=e.tools.find(P=>P.id===g.id);if(!b)continue;let k=r.find(P=>P.id===g.id),C=b.mcp;if(k?.mcpStatus)try{let P=await k.mcpStatus();C={...P,commandOk:fx(P)}}catch{}let S=py(b)?!0:b.pointedAt;if(k?.pointsAt&&b.pointedAt!==null)try{S=await k.pointsAt(e.gateway.origin)}catch{}let I=b.routingOverrides,E=b.claudeCodeHookPolicy;if(k?.runtimeDiagnostics)try{let P=await k.runtimeDiagnostics();I=P.routingOverrides.length?P.routingOverrides:void 0,E=P.claudeCodeHookPolicy}catch{}else if(k?.routingOverrides)try{let P=await k.routingOverrides();I=P.length?P:void 0}catch{}let R={...b,pointedAt:S,mcp:C,...I?{routingOverrides:I}:{},...E===void 0?{}:{claudeCodeHookPolicy:E}};I||delete R.routingOverrides,E===void 0&&delete R.claudeCodeHookPolicy,w.set(g.id,R),y+=fy(b)-fy(R)}return{entries:p,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:f}},iK=e=>{U("Repair"),e.entries.length===0&&M(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?M(` ${t.title}: re-applied`):t.status==="queued"?M(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?A(v(` ${t.title}: ${t.status}`)):O(` ${t.title}: ${t.status}`);for(let t of e.notes)A(v(` ${t}`))},au=async(e,t={})=>{let n=await D();if(e.securityReview){if(!e.silent){A(V("Anyray connect \u2014 security review"));for(let c of Cw())A(c?` ${c}`:"")}return 0}let r;try{r=kr(e.gateway,n)}catch(c){return e.silent?1:e.json?(console.log(JSON.stringify({error:c.message})),1):(A(V("Anyray connect \u2014 doctor")),O(` Gateway URL: ${c.message}`),A(v(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.silent||(e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(A(V("Anyray connect \u2014 doctor")),O(" --quick skips the network probes; it cannot be combined with --verify."))),1;let o=!e.noVerify&&!e.quick,a=await tK(r,n,!!e.verify&&!e.quick,t.adapters??le,t.inferenceIntrospection??Ld,t.fleetBootstrap??br,o,t.verifyAuth??_i,!e.quick,t.checkTray??Po,t.updateStatus??wo,t.readRefreshState??It,t.probeHookLane??va),s=e.repair?await sK(a,n,t):void 0,i=s?{...a,tools:a.tools.map(c=>s.refreshedTools.get(c.id)??c),...s.hookLane!==void 0?{hookLane:s.hookLane}:{},repairs:s.entries,problems:s.remainingProblems}:a;t.captureReport?.(i),e.silent||(e.json?console.log(JSON.stringify(oK(i),null,2)):(rK(i),s&&iK(s)));try{e.quick||await(t.reportHealth??ZS)(ux(i),i.connect.version)}catch{}return i.problems===0?0:1};var cK=()=>{let e=[];for(let t of le){let n=t.skillsDir?.();n&&e.push(n)}return e},hx=async e=>{let t=await D();A(V("Anyray connect \u2014 sync"));let n;try{n=kr(e.gateway,t)}catch(s){return O(s.message),1}$(`Gateway: ${n}`);let r=HI(t.clientKey,"anyray-placeholder"),o;try{o=await ba(n,r)}catch(s){return O(`Team policy sync failed: ${dh(s)}`),1}let a=cK();if(a.length===0)lK();else if(o.skills.length===0)$("No team skills published yet \u2014 nothing to sync.");else{let s=await DS(o,a,t.syncedSkills??{});U("Skills");for(let i of s.results)i.written?M(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):$(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await oe({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){$(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}U("Summary"),A(` ${et(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Aa(o);(s.routingUpdated||s.teamUpdated||s.toolsRequested>0||s.toolsTombstoned.length>0)&&(A(`Fleet policy: routing ${s.routingUpdated?"updated":"unchanged"}, team ${s.teamUpdated?"updated":"unchanged"}, ${s.toolsApplied}/${s.toolsRequested} tool(s) reconciled${s.toolsEnrolled>0?` (${s.toolsEnrolled} newly enrolled)`:""}.`),s.toolsTombstoned.length>0&&$(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){$(`Fleet policy reconcile skipped: ${dh(s)}`)}return 0},lK=()=>{$("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as fj}from"node:zlib";import{promisify as mj}from"node:util";var Er={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},hy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),yx=e=>`
|
|
694
694
|
|
|
695
695
|
\u2026[anyray-hook trimmed ${e} chars (~${Math.round(e/3.3)} tokens) \u2014 elided locally, cache-safe]\u2026
|
|
696
696
|
|
|
697
|
-
`,su=(e,t={})=>{if(typeof e!="string")return
|
|
698
|
-
`,S);
|
|
699
|
-
`,C);
|
|
697
|
+
`,su=(e,t={})=>{if(typeof e!="string")return hy(String(e??""));let n=Math.max(1,t.maxChars??Er.maxChars);if(e.length<=n)return hy(e);let r=e.length,o=Math.max(0,t.headChars??Er.headChars),a=Math.max(0,t.tailChars??Er.tailChars),s=Math.max(0,t.middleWindows??Er.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 p=c-o-a;if(s>0&&p>0&&d>l){let y=d-l,g=Math.max(1,Math.floor(p/s));for(let b=0;b<s;b++){let k=l+Math.round((b+.5)/s*y),C=Math.min(d,Math.max(l,k)+Math.ceil(g/2)),S=Math.max(l,C-g),I=e.lastIndexOf(`
|
|
698
|
+
`,S);I>=l&&(S=I+1);let E=e.indexOf(`
|
|
699
|
+
`,C);E!==-1&&E<d&&(C=E),C>S&&u.push([S,C])}}a>0&&u.push([d,r]),u.sort((y,g)=>y[0]-g[0]);let f=[];for(let[y,g]of u){let b=f[f.length-1];b&&y<=b[1]?b[1]=Math.max(b[1],g):f.push([y,g])}let m="",h=0;for(let[y,g]of f)y>h&&(m+=yx(y-h)),m+=e.slice(y,g),h=g;if(r>h&&(m+=yx(r-h)),m.length>=r)return hy(e);let w=r-m.length;return{text:m,trimmed:!0,originalChars:r,trimmedChars:m.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},dK=["stdout","content","output","text","result"],gx=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} ---
|
|
700
700
|
${d}`);s&&i.push(`--- MCP structuredContent ---
|
|
701
701
|
${JSON.stringify(t.structuredContent)}`);let c=a[0],l=new Set(a.map(({index:d})=>d));return{body:i.join(`
|
|
702
702
|
|
|
703
|
-
`),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((p,f)=>l.has(f)?f!==c?.index?[]:[{...c.part,text:d}]:[p]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n
|
|
704
|
-
`),s=0,i=0;for(let c of a)c.trim()&&(s++,
|
|
705
|
-
${e.slice(-
|
|
706
|
-
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},
|
|
707
|
-
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},
|
|
708
|
-
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},
|
|
709
|
-
`).filter(s=>s.trim()!==""),r=
|
|
710
|
-
|
|
711
|
-
\u2026[anyray-hook digest \u2014 ${e}; ${
|
|
712
|
-
|
|
713
|
-
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,
|
|
714
|
-
|
|
715
|
-
\u2026[anyray-hook \u2014 ${
|
|
716
|
-
`):"",
|
|
717
|
-
`).slice(0,
|
|
718
|
-
`);i=l>=0?i.slice(l+1):""}let c=
|
|
719
|
-
`));return
|
|
720
|
-
`:"",
|
|
721
|
-
${
|
|
722
|
-
`,{mode:384}),await
|
|
703
|
+
`),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((p,f)=>l.has(f)?f!==c?.index?[]:[{...c.part,text:d}]:[p]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n=dK.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 uK=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},Pi={minChars:8e3,minDataLineRatio:.6,minDataLines:20},iu=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??Pi.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??Pi.minDataLineRatio,o=t.minDataLines??Pi.minDataLines,a=e.split(`
|
|
704
|
+
`),s=0,i=0;for(let c of a)c.trim()&&(s++,uK(c)&&i++);return s===0||i<o?!1:i/s>=r};var Di=(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"},Ax=new Set(["npm","pnpm","yarn","bun"]),lu=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},pK=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")||Ax.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},gy=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=pK(t);if(n)return n}return null},fK={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},mK=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,hK=(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},Cx=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(Ax.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&mK.test(i)}let a=r[1]?lu(r[1]):void 0;if(hK(o,a,r))return!1;let s=fK[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},yK=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==="]"},gK=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},wK=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=gK(t);return r>0&&t[r+1]===":"},bK=80,AK=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/bK),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,wK(e[o])&&r++;return n>0&&r/n>.3},CK=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,kK=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();(CK.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},vK=[/\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],yy=8192,SK=e=>{let t=e.length>2*yy?`${e.slice(0,yy)}
|
|
705
|
+
${e.slice(-yy)}`:e;return vK.some(n=>n.test(t))},IK=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),EK=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),xK=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},RK=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),wx=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(EK(i)){t.push(Di(i));continue}let c=xK(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(Di(c)),o=12;continue}IK(i)||RK(i)||o>0&&(t.push(Di(s)),o--)}if(t.length===0)return null;let a=r>0?` (+${r} more)`:"";return{text:t.join(`
|
|
706
|
+
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},OK=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,kx=e=>{let t=OK.exec(e);return t&&/[/.]/.test(t[1])?t:null},TK=/^([^\s:]+)-(\d+)-/,_K=e=>{if(e==="--")return!0;let t=TK.exec(e);return t!=null&&/[/.]/.test(t[1])},PK=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>kx(r)!=null).length;return n>=3&&n/t.length>=.7},bx=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=kx(c);if(!l){if(_K(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(Di(` ${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(`
|
|
707
|
+
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},DK=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(),LK=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=DK(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=Di(a.trim());return s>1?`[\xD7${s}] ${i}`:i}).join(`
|
|
708
|
+
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},vx=(e,t)=>{if(typeof t!="string"||t.length===0||yK(t))return null;let n=t.split(`
|
|
709
|
+
`).filter(s=>s.trim()!==""),r=gy(e),o=SK(t),a=null;return r==="test-run"&&o?a=wx(n):r==="grep"&&(a=bx(n,.5)),a||(o?a=wx(n):PK(n)?a=bx(n,.7):!kK(n)&&!AK(n)&&(a=LK(n))),!a||a.text.length>=t.length?null:a},Sx=e=>`full output: Read ${e}`,wy=(e,t)=>t?`
|
|
710
|
+
|
|
711
|
+
\u2026[anyray-hook digest \u2014 ${e}; ${Sx(t)}]\u2026`:`
|
|
712
|
+
|
|
713
|
+
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,Ix=e=>`
|
|
714
|
+
|
|
715
|
+
\u2026[anyray-hook \u2014 ${Sx(e)}]\u2026`;import{createHash as NK}from"node:crypto";import{homedir as $K}from"node:os";import{join as xr}from"node:path";import{chmod as MK,mkdir as BK,readdir as Ox,stat as Ni,unlink as Li,utimes as FK,writeFile as Ay}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},Tx=".swept",WK=".sweeping",Ex=64,xx=448,Cy=384,ky=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",_x=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,vy=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=Q();try{if((await Ni(t)).isDirectory())return xr(t,"hook-tee")}catch{}return xr($K(),".anyray-hook-tee")},HK=/^(?:ctx_)?([0-9a-f]{16})$/,Sy=e=>e.trim().match(HK)?.[1]??null,Iy=async e=>{let t=Sy(e);return t?xr(await vy(),`${t}.txt`):null},UK=async(e,t={})=>{let n=t.limits??du;try{let r=Date.now(),o=(await Ox(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=Ex)await Promise.all(o.slice(c,c+Ex).map(async l=>{let d=xr(e,l);try{let u=await Ni(d);if(!u.isFile())return;let p=r-u.mtimeMs>n.ttlMs||r-_x(u)>n.maxAgeMs;if(d!==t.protect&&p){await Li(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 Li(c.path).catch(()=>{})}}catch{}},Px=async e=>{try{return Date.now()-(await Ni(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},Rx=async e=>{try{return await Ay(e,"",{mode:Cy,flag:"wx"}),!0}catch{return!1}},GK=async(e,t)=>{let n=du,r=xr(e,WK),o=xr(e,Tx);if(!await Rx(r)){let a=0;try{a=Date.now()-(await Ni(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await Li(r).catch(()=>{}),!await Rx(r)))return!1}try{return await Px(o)<n.sweepIntervalMs?!1:(await Ay(o,"",{mode:Cy}).catch(()=>{}),await UK(e,{protect:t}),!0)}finally{await Li(r).catch(()=>{})}},by=async(e,t)=>await Px(xr(e,Tx))<du.sweepIntervalMs?!1:GK(e,t),VK=async()=>{try{let e=await vy();if(!(await Ox(e)).some(t=>t.endsWith(".txt")))return;await by(e)}catch{}},Dx=async e=>{if(ky())return await VK(),null;try{let t=await vy();await BK(t,{recursive:!0,mode:xx}),await MK(t,xx).catch(()=>{});let n=`${NK("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=xr(t,n),o=Date.now();try{let a=await Ni(r);if(a.isFile()){if(o-_x(a)<=du.maxAgeMs){let s=new Date(o);return await FK(r,s,s).catch(()=>{}),await by(t,r),r}await Li(r).catch(()=>{})}}catch{}return await Ay(r,e,{mode:Cy}),await by(t,r),r}catch{return null}};import{createHash as KK}from"node:crypto";import{homedir as Lx}from"node:os";import{join as Ey}from"node:path";import{readFile as jK,writeFile as ZK,chmod as YK,stat as JK,unlink as XK}from"node:fs/promises";var zK=200,qK=1440*60*1e3,QK=4e6,Nx=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",$x=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},ej=()=>$x("ANYRAY_HOOK_CACHE_MAX_ENTRIES",zK),Mx=()=>$x("ANYRAY_HOOK_CACHE_TTL_MS",qK),Bx=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=Ey(Lx(),".anyray");try{if((await JK(t)).isDirectory())return Ey(t,"hook-cache.json")}catch{}return Ey(Lx(),".anyray-hook-cache.json")},Fx=(e,t,n)=>KK("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),Wx=async e=>{try{let t=JSON.parse(await jK(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},Hx=async e=>{if(Nx())return null;try{let n=(await Wx(await Bx())).entries[e];return!n||Date.now()-n.at>Mx()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},tj=e=>{let t=Date.now(),n=Mx(),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=ej();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>QK&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},Ux=async(e,t)=>{if(Nx())return;let n;try{let r=await Bx(),o=await Wx(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=tj(o.entries),n=`${r}.${process.pid}.tmp`,await ZK(n,JSON.stringify(o),{mode:384}),await YK(n,384),await he(n,r)}catch{if(n)try{await XK(n)}catch{}}};import{open as nj,stat as rj}from"node:fs/promises";var Gx=600,oj=3,aj=256e3,sj=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(`
|
|
716
|
+
`):"",ij=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),cj=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},lj=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=sj(o.message?.content).trim();if(!(!a||ij(a))&&(t.unshift(a),n+=a.length,t.length>=oj||n>=Gx))break}return t.join(`
|
|
717
|
+
`).slice(0,Gx)};var dj=e=>/(^|[\\/])subagents[\\/]/i.test(e),uj=e=>/\.jsonl$/i.test(e),pj=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),Vx=async e=>{let t={intent:"",kind:"unknown"};if(!e||!uj(e))return t;let n;try{let{size:r}=await rj(e),o=Math.max(0,r-aj),a=r-o;if(a<=0)return t;n=await nj(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(`
|
|
718
|
+
`);i=l>=0?i.slice(l+1):""}let c=cj(i.split(`
|
|
719
|
+
`));return pj(c)?{intent:lj(c),kind:dj(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var hj=3e3,yj=1500,gj=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:hj},wj={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},bj=new Set(["claude","opencode"]),Aj=(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:wj[t]})},Cj={cacheGet:async()=>null,cachePut:async()=>{}},kj=(e,t={cacheGet:Hx,cachePut:Ux,tee:Dx})=>e==="claude"?t:Cj,vj=1e3,Sj=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),uu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ij=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}},Ej=e=>{try{let t=JSON.parse(e);return uu(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},xj=e=>uu(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
|
|
720
|
+
`:"",xy=e=>Math.round(Math.max(0,e)/4),Kx=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",Rj=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),Oj=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),Tj=["tool_output","tool_response","tool_result"],_j=e=>{for(let t of Tj)if(t in e)return e[t]},Pj=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},Dj=120,Lj=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??vj))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=wy(r.stat,null).length+Dj;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=wy(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}}},Nj=async(e,t)=>{let n={stdout:""};if(!e.trim())return n;let r;try{let S=JSON.parse(e);if(!S||typeof S!="object")return n;r=S}catch{return n}let o=typeof r.tool_name=="string"?r.tool_name:"unknown";if(Rj.has(o)||Oj(o))return n;let a=gx(_j(r));if(!a)return n;let s=async S=>{try{await t.beacon(o,S)}catch{}},i=a.body,c=typeof r.transcript_path=="string"?r.transcript_path:"",l={intent:"",retrievalContext:t.defaultRetrievalContext??"unknown"};if(t.readContext&&c)try{l=await t.readContext(c)}catch{l={intent:"",retrievalContext:"unknown"}}if(jx(o)&&l.retrievalContext!=="available")return n;let d=await Lj(t,Pj(o,r.tool_input),i),u=d?.body??i,p=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!iu(i,{minChars:yj})))return n;let f=i.length-u.length-p.length,m=async(S,I,E=S.length+p.length)=>{let R=d?.teePath??null;if(!R&&t.tee)try{R=await t.tee(i)}catch{R=null}let P=R?S.replaceAll("; not retrievable in this context]","]"):S,W=R&&!p?Ix(R):"",q=P+p+W,de=W.length,ie=q;if(t.finalizeOutput)try{let F=t.finalizeOutput(q);F.length<=q.length&&(ie=F)}catch{ie=q}let K=q.length-ie.length,ge=xy(Math.max(0,f-de))+I+xy(K);ge>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,E+de-K),estTokensSaved:ge,...d&&{digest:d.decision}});let me=a.rebuild(ie);return{stdout:Sj(me),replacement:me}},h=async()=>d?m(u,0):n;if(d&&u.length<=t.sizeGate)return m(u,0);let w=l.intent?`${l.intent}
|
|
721
|
+
${Kx(r.tool_input)}`:Kx(r.tool_input),y=Fx(o,w,u),g=async S=>{try{await t.cachePut(y,S)}catch{}},b=null;try{b=await t.cacheGet(y)}catch{b=null}if(b)return b.optimized&&b.output.length<u.length?m(b.output,b.tokensSaved):h();let k=null;try{k=Hj(o)?null:await t.optimize(o,r.tool_input,u,l.intent,l.retrievalContext)}catch{k=null}if(k&&!k.handled&&(k=null),k)return k.optimized&&k.output.length<u.length?(await g({optimized:!0,output:k.output,tokensSaved:xy(u.length-k.output.length)}),m(k.output,0,u.length+p.length)):(await g({optimized:!1}),h());let C;try{C=t.localTrim(u)}catch{return h()}return C.trimmed?m(C.text,C.estTokensSaved):h()},$i=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},$j=()=>{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")}},Mj=mj(fj),Bj=async e=>{try{let t=await Mj(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},jx=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),Fj=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},Wj=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),Hj=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),Uj=2048,Gj=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,Uj),n=Ad(t);if(!n)return;await bI({at:Date.now(),status:e.status,code:n})}catch{}},Vj=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),gj());try{let c=await Bj(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...jx(t)||Fj(t)&&a==="available"?{reversible:!0}:{},...Wj(t)?{semanticRerank:!0}:{},output:r})),l=Vt(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 Gj(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)}},Zx=async(e="claude")=>{let t=await $i();if(e!=="cursor"&&Ej(t))return 0;let n=e==="cursor"?Ij(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await Ry(n,e);if(e==="cursor"){let a=xj(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},Ry=async(e,t="claude",n)=>{await Cr(),await wI(t);let r=$j(),o=await nt(),a=o&&{...o,metadata:Aj(o.metadata,t)},s=kj(t);return Nj(e,{optimize:(i,c,l,d,u)=>Vj(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await Vx(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)=>lc(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??Er.maxChars,digestCommand:vx,tee:s.tee,mediumBand:bj.has(t),finalizeOutput:n})};var Yx=async()=>0;import{spawn as zj}from"node:child_process";import{homedir as qj}from"node:os";import{join as Qj}from"node:path";import{chmod as Kj,readFile as jj,rm as Jx,writeFile as Zj}from"node:fs/promises";import{join as Yj}from"node:path";var Oy=()=>Yj(Q(),"sso-gate.json"),Jj=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))},La=async()=>{try{let e=JSON.parse(await jj(Oy(),"utf-8"));return Jj(e)?e:null}catch{return null}},Xj=0,pu=async e=>{await tt();let t=Oy(),n=`${t}.${process.pid}.${Xj++}.tmp`;try{await Zj(n,`${JSON.stringify(e)}
|
|
722
|
+
`,{mode:384}),await Kj(n,384),await he(n,t)}catch(r){throw await Jx(n,{force:!0}).catch(()=>{}),r}},Xx=async()=>{await Jx(Oy(),{force:!0}).catch(()=>{})},zx=e=>{if(!e||!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}};var e2=3e4,t2=5*6e4,n2=30*6e4,r2=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},o2=()=>Qj(qj(),".claude","settings.json"),a2=async e=>{try{let n=(await B(o2())).env;if(!n)return!1;let r=tn(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}},s2=async e=>{await qn.apply(e,{dryRun:!1})},i2=()=>{let{command:e,args:t}=Qn("__anyray-sso-poll");return{exe:e,args:t}},c2=()=>{let{exe:e,args:t}=i2(),n=zj(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))}}},l2=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},qx=(e,t,n,r)=>xe({origin:e,clientKey:r,subscription:!0,user:t.name??t.enrolledCert?.payload.user,team:n??t.team??t.enrolledCert?.payload.team}),Na=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},Qx=e=>`Anyray: one-time sign-in required to use AI tools on this device.
|
|
723
723
|
1. Open ${e.verificationUriComplete}
|
|
724
724
|
2. Confirm code ${e.userCode}
|
|
725
725
|
Your prompt was not sent \u2014 complete sign-in, then resubmit it.
|
|
726
|
-
`,
|
|
726
|
+
`,Ty=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
|
|
727
727
|
`:e==="gateway-unreachable"?`Anyray: can't reach the gateway \u2014 check your network/VPN, then resubmit your prompt.
|
|
728
728
|
`:`Anyray: can't reach ${t} \u2014 check your network/VPN, then resubmit your prompt.
|
|
729
|
-
|
|
730
|
-
`))}let
|
|
731
|
-
`}catch{return}},
|
|
729
|
+
`,d2=e=>Math.min(t2,e2*2**Math.max(0,e-1)),u2=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?n2:d2(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Co=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??D,o=t.saveProfile??oe,a=t.loadDevKey??$e,s=t.readGateState??La,i=t.writeGateState??pu,c=t.isProcessAlive??zx,l=t.startGrant??md,d=t.verify??Xt,u=t.routingIntact??a2,p=t.applyClaudeCode??s2,f=t.maybeSpawnRefresh??Cr,m=t.recordMint??Sa,h=t.reserveMint??yo,w=t.spawnPoller??c2,y=t.openBrowser??Ta;try{let g=St(e.sso);if(!g)return{exitCode:0};let b=await r(),k=await s(),C=b.enrolledCert?await a():void 0,S=l2(b),I=!!(b.enrolledCert&&C)&&Number.isFinite(S)&&S>n(),E=e.gateway??b.gateway;if(I&&b.enrolledCert&&C&&E){let de=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(de)&&de>n()&&b.clientKey){let me=qx(E,b,e.team,b.clientKey);return await u(me)?(de-n()<=vh()&&await f(),{exitCode:0}):(await p(me),Na(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
|
|
730
|
+
`))}let K;await h();let ge=(t.resolveMachineUuid??Bt)()||void 0;try{K=await d(E,b.enrolledCert,C,{timeoutMs:1e4,machineUuid:ge})}catch(me){if(!(me instanceof lt))return Na(e,Ty("gateway-unreachable",g.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(K){let me={...b,gateway:E,name:K.user,team:e.team??K.team??b.team,clientKey:K.key,clientKeyExpiresAt:K.expiresAt,authMode:"subscription"};return await o(me),await m({expiresAt:K.expiresAt}),await p(qx(E,me,e.team,K.key)),{exitCode:0}}}if(k?.status==="pending"&&(k.userCode&&k.verificationUriComplete)&&(k.grantExpiresAt??0)>n()&&c(k.pollerPid)){if(e.sessionStart&&k.verificationUriComplete)try{y(k.verificationUriComplete)}catch{}return Na(e,Qx(k))}if(k){let de=u2(k,n());if(de)return Na(e,Ty(de,g.cpOrigin))}let R;try{R=await l({cpOrigin:g.cpOrigin,tenantId:g.tenantId,gatewayUrl:e.gateway,now:n})}catch(de){let ie=de instanceof uo?de.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:k?.lastFailure===ie?(k.failureCount??0)+1:1,lastFailure:ie}),Na(e,Ty(ie,g.cpOrigin))}let P={v:1,status:"pending",userCode:R.userCode,verificationUriComplete:R.verificationUriComplete,grantExpiresAt:R.grantExpiresAt,startedAt:R.startedAt,lastAttemptAt:n(),failureCount:0};await i(P);let W=w(),q={...P,pollerPid:W.pid};if(await i(q),W.handoff({deviceCode:R.deviceCode,privateKeyPem:R.privateKeyPem,publicKeyPem:R.publicKeyPem,cpOrigin:R.cpOrigin,tenantId:R.tenantId,intervalMs:R.intervalMs,grantExpiresAt:R.grantExpiresAt,startedAt:R.startedAt,gatewayUrl:R.gatewayUrl,gatewayOverride:e.gateway,team:e.team}),e.sessionStart)try{y(R.verificationUriComplete)}catch{}return Na(e,Qx(q))}catch{return{exitCode:0}}},p2=async()=>{try{for await(let e of process.stdin);}catch{}},e0=async e=>{await p2();try{let t=await Co(r2(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var f2=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},m2=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??br)();if(!r)return;let o=await(t.ssoGate??Co)({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})}
|
|
731
|
+
`}catch{return}},h2=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},y2=()=>{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")}},g2=(e,t)=>{let n=t.minChars??Pi.minChars,r={maxChars:Math.min(Er.maxChars,n)},o=su(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},t0=async()=>{let e=await h2(),t=await m2(e);t&&process.stdout.write(t);let n=y2(),r=await nt();return await f2(e,{isPaste:o=>iu(o,n),measure:o=>g2(o,n),beacon:o=>lc(r,"prompt",o)}),0};import{spawn as w2}from"node:child_process";var n0=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),b2=/[|&;<>`$()\n]/,r0=e=>{if(b2.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},A2=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!n0(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!n0(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(ju)||!t.isRecognized(o)||r0(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},C2=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?r0(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
|
|
732
732
|
`),1;let o;try{o=await t.exec(r)}catch{return t.writeErr(`anyray: failed to run wrapped command
|
|
733
|
-
`),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},Yj=16*1024*1024,Jj=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=Vj(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>Yj){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)}}),Xj=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await _y(n,"cursor");return typeof r=="string"?r:t},c0=e=>{let t=e[0]==="--b64"?e[1]:void 0;return Zj(t,{exec:Jj,trim:Xj,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},l0=async()=>{let e=await Mi();if(process.platform==="win32")return 0;let t=jj(e,{isRecognized:n=>Ay(n)!==null||Ex(n),wrap:n=>xt(ju,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as zj}from"node:crypto";import{homedir as d0}from"node:os";import{extname as qj,isAbsolute as Qj,join as Ly,resolve as Bi,sep as u0}from"node:path";import{chmod as eZ,readFile as tZ,stat as y0,unlink as nZ,writeFile as rZ}from"node:fs/promises";var $y=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),oZ=16*1024,p0=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],aZ=["pattern","query","regex","search"],sZ=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"]),iZ=720*60*1e3,cZ=512,Ny=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},lZ=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],f0=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(u0)?n:n+u0)),dZ=(e,t,n)=>Qj(e)?[Bi(e)]:[...new Set([Bi(t,e),...n.map(r=>Bi(r,e))])],h0=(e,t,n)=>zj("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),m0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),uZ=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=lZ(n.workspace_roots).map(d=>Bi(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=Ny(o,aZ);if(!d)return"";let u=Ny(o,p0);return u&&!f0(Bi(s,u),a)||!await t.remember(h0(i,"Grep",d))?"":m0(`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=Ny(o,p0);if(!c||sZ.has(qj(c).toLowerCase()))return"";let l=await t.resolveFile(dZ(c,s,a));return!l||l.bytes<oZ||!f0(l.path,a)||!await t.remember(h0(i,"Read",l.path))?"":m0(`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.`)},pZ=async e=>{for(let t of e)try{let n=await y0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},fZ=async()=>{let e=Ly(d0(),".anyray");try{if((await y0(e)).isDirectory())return Ly(e,"cursor-redirects.json")}catch{}return Ly(d0(),".anyray-cursor-redirects.json")},hZ=async e=>{let t;try{let n=await fZ(),r=Date.now(),o={};try{let s=JSON.parse(await tZ(n,"utf-8"));if(s?.v===1&&$y(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=iZ&&(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,cZ);return t=`${n}.${process.pid}.tmp`,await rZ(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await eZ(t,384),await me(t,n),!0}catch{if(t)try{await nZ(t)}catch{}return!1}},g0=async()=>{let e=await Mi(),t="";try{t=await uZ(e,{resolveFile:pZ,remember:hZ})}catch{t=""}return t&&process.stdout.write(t),0};var w0=(e,t)=>{let n=new Set(t);return e.filter(r=>!n.has(r.id))},b0=async e=>{try{if(e.platform!=="darwin")return 0;let t=await e.loadProfile();if(t.managedEnrollmentDisabled===!0)return 0;let n=e.readManagedEnrollment().enrollmentUrl;return n?await e.runApply(["--enroll",n,"--yes"],t.revertedTools??[]):0}catch{return 1}},A0=e=>({platform:process.platform,readManagedEnrollment:qm,loadProfile:D,runApply:e});var Fi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},My=e=>typeof e=="string"&&e.trim()?e.trim():void 0,mZ=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Fi(n,"deviceCode"),o=Fi(n,"privateKeyPem"),a=Fi(n,"publicKeyPem"),s=Fi(n,"cpOrigin"),i=Fi(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=My(n.gatewayUrl),p=My(n.gatewayOverride),f=My(n.team);return{deviceCode:r,privateKeyPem:o,publicKeyPem:a,cpOrigin:s,tenantId:i,intervalMs:c,grantExpiresAt:l,startedAt:d,...u?{gatewayUrl:u}:{},...p?{gatewayOverride:p}:{},...f?{team:f}:{}}}catch{return null}},yZ=e=>new Promise(t=>setTimeout(t,e)),gZ=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})},wZ=async(e,t={})=>{let n=t.poll??yd,r=t.verify??Jt,o=t.loadProfile??D,a=t.saveProfile??oe,s=t.saveDevKey??Xi,i=t.readGateState??La,c=t.writeGateState??pu,l=t.clearGateState??e0,d=t.sleep??yZ,u=t.now??Date.now,p=t.recordMint??Sa,f=t.reserveMint??go,h=t.applyClaudeCode??(async I=>{await qn.apply(I,{dryRun:!1})}),m=I=>gZ(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},y;try{y=await n(w,{gatewayUrl:e.gatewayOverride})}catch(I){let R=I instanceof Nt?I.kind:"cp-unreachable";return await m(R),R}let g=e.gatewayOverride??y.gatewayUrl,b=await o(),k={...b,gateway:g??b.gateway,name:y.cert.payload.user||b.name,team:e.team??y.cert.payload.team??b.team,enrolledCert:y.cert,enrolledCertExpiry:y.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(y.privateKeyPem),await a(k)}catch{return"failed"}if(!g)return await m("gateway-unreachable"),"gateway-unreachable";let C;await f();let S=(t.resolveMachineUuid??Mt)()||void 0;for(let I=0;I<3;I++)try{C=await r(g,y.cert,y.privateKeyPem,{timeoutMs:1e4,machineUuid:S});break}catch(R){if(R instanceof ht||I===2)break;await d(1e3)}if(!C)return await m("gateway-unreachable"),"gateway-unreachable";let E={...k,gateway:g,name:C.user,team:e.team??C.team??k.team,clientKey:C.key,clientKeyExpiresAt:C.expiresAt,authMode:"subscription"};try{await a(E),await p({expiresAt:C.expiresAt});let I=Ie({origin:g,clientKey:C.key,subscription:!0,user:E.name,team:E.team});return await h(I),await l(),"enrolled"}catch{return await m("gateway-unreachable"),"failed"}},bZ=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},C0=async()=>{let e=mZ(await bZ());if(e)try{await wZ(e)}catch{}return 0};var AZ=1e4,By=/^[\w.:-]{1,64}$/,Ft=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},Fy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,k0=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),AZ);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 Ft("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},CZ=e=>{let t=Fy(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}},kZ=e=>{let t=Fy(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&By.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&By.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},vZ=e=>{let t=Fy(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ee(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!By.test(t.team)))return{status:"complete",key:t.key,user:t.user,team:t.team,...typeof t.expires_at=="string"&&{expires_at:t.expires_at}}},SZ=e=>new Promise(t=>setTimeout(t,e)),EZ=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Ft("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}A("Available teams:"),e.forEach((i,c)=>A(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await Ia("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 Ft("invalid-team","Choose one of the teams shown above.");return s},IZ=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??SZ,a=t.loadProfile??D,s=t.saveProfile??oe,i=t.clearDevKey??Ya,c=t.chooseTeam??EZ,l=t.apply??(async y=>{await qn.apply(y,{dryRun:!1})}),d=t.log??$,u=await a(),p=kr(e.gateway,u),f=await k0(`${p}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),h=CZ(f.body);if(f.status!==200||!h)throw new Ft("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??Ta)(h.browser_url);let m=r()+h.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<m;){let y=await k0(`${p}/sso/cli/poll/${encodeURIComponent(h.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":h.poll_secret,...w?{"x-anyray-team":w}:{}}},n);if(y.status===202){await o(h.interval*1e3);continue}if(y.status===401)throw new Ft("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(y.status===410)throw new Ft("expired","SSO login expired before it completed. Run anyray-connect login again.");let g=kZ(y.body);if(y.status===200&&g){if(w&&!g.teams.includes(w))throw new Ft("invalid-team",`Team ${w} is not available for this account.`);w=await c(g.teams,g.default_team,e.interactive??Bt());continue}let b=vZ(y.body);if(y.status!==200||!b)throw new Ft("login-failed","SSO login could not be completed.");let k={...u,gateway:p,name:b.user,team:b.team,clientKey:b.key,clientKeyExpiresAt:b.expires_at,enrolledCert:void 0,enrolledCertExpiry:void 0,enrolledTokenHash:void 0,ssoLink:void 0,authMode:"subscription"};return await i(),await s(k),await l(Ie({origin:p,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Ft("expired","SSO login expired before it completed. Run anyray-connect login again.")},xZ=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
733
|
+
`),1}if(o.alreadyWritten)return o.code;let a=o.output;try{a=await t.trim(n,o.output)}catch{a=o.output}return t.write(a),o.code},k2=16*1024*1024,v2=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=w2(e[0],e.slice(1),{stdio:["inherit","pipe","pipe"]});for(let d of["SIGINT","SIGTERM","SIGHUP"]){let u=()=>{if(c.exitCode===null&&c.signalCode===null)try{c.kill(d)}catch{}};s.set(d,u),process.on(d,u)}let l=d=>{if(o){process.stdout.write(d);return}if(r+d.byteLength>k2){for(let u of n)process.stdout.write(u);n.length=0,process.stdout.write(d),o=!0;return}n.push(d),r+=d.byteLength};c.stdout?.on("data",l),c.stderr?.on("data",l),c.on("error",()=>i(1)),c.on("close",(d,u)=>i(typeof d=="number"?d:u?1:0))}catch{i(1)}}),S2=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await Ry(n,"cursor");return typeof r=="string"?r:t},o0=e=>{let t=e[0]==="--b64"?e[1]:void 0;return C2(t,{exec:v2,trim:S2,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},a0=async()=>{let e=await $i();if(process.platform==="win32")return 0;let t=A2(e,{isRecognized:n=>gy(n)!==null||Cx(n),wrap:n=>Rt(ju,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as I2}from"node:crypto";import{homedir as s0}from"node:os";import{extname as E2,isAbsolute as x2,join as _y,resolve as Mi,sep as i0}from"node:path";import{chmod as R2,readFile as O2,stat as p0,unlink as T2,writeFile as _2}from"node:fs/promises";var Dy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),P2=16*1024,c0=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],D2=["pattern","query","regex","search"],L2=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"]),N2=720*60*1e3,$2=512,Py=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},M2=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],l0=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(i0)?n:n+i0)),B2=(e,t,n)=>x2(e)?[Mi(e)]:[...new Set([Mi(t,e),...n.map(r=>Mi(r,e))])],d0=(e,t,n)=>I2("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),u0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),F2=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=M2(n.workspace_roots).map(d=>Mi(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=Py(o,D2);if(!d)return"";let u=Py(o,c0);return u&&!l0(Mi(s,u),a)||!await t.remember(d0(i,"Grep",d))?"":u0(`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=Py(o,c0);if(!c||L2.has(E2(c).toLowerCase()))return"";let l=await t.resolveFile(B2(c,s,a));return!l||l.bytes<P2||!l0(l.path,a)||!await t.remember(d0(i,"Read",l.path))?"":u0(`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.`)},W2=async e=>{for(let t of e)try{let n=await p0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},H2=async()=>{let e=_y(s0(),".anyray");try{if((await p0(e)).isDirectory())return _y(e,"cursor-redirects.json")}catch{}return _y(s0(),".anyray-cursor-redirects.json")},U2=async e=>{let t;try{let n=await H2(),r=Date.now(),o={};try{let s=JSON.parse(await O2(n,"utf-8"));if(s?.v===1&&Dy(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=N2&&(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,$2);return t=`${n}.${process.pid}.tmp`,await _2(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await R2(t,384),await he(t,n),!0}catch{if(t)try{await T2(t)}catch{}return!1}},f0=async()=>{let e=await $i(),t="";try{t=await F2(e,{resolveFile:W2,remember:U2})}catch{t=""}return t&&process.stdout.write(t),0};var m0=(e,t)=>{let n=new Set(t);return e.filter(r=>!n.has(r.id))},h0=async e=>{try{if(e.platform!=="darwin")return 0;let t=await e.loadProfile();if(t.managedEnrollmentDisabled===!0)return 0;let n=e.readManagedEnrollment().enrollmentUrl;return n?await e.runApply(["--enroll",n,"--yes"],t.revertedTools??[]):0}catch{return 1}},y0=e=>({platform:process.platform,readManagedEnrollment:Xh,loadProfile:D,runApply:e});var Bi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},Ly=e=>typeof e=="string"&&e.trim()?e.trim():void 0,G2=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Bi(n,"deviceCode"),o=Bi(n,"privateKeyPem"),a=Bi(n,"publicKeyPem"),s=Bi(n,"cpOrigin"),i=Bi(n,"tenantId"),c=n.intervalMs,l=n.grantExpiresAt,d=n.startedAt;if(!r||!o||!a||!s||!i||typeof c!="number"||!Number.isFinite(c)||typeof l!="number"||!Number.isFinite(l)||typeof d!="number"||!Number.isFinite(d))return null;let u=Ly(n.gatewayUrl),p=Ly(n.gatewayOverride),f=Ly(n.team);return{deviceCode:r,privateKeyPem:o,publicKeyPem:a,cpOrigin:s,tenantId:i,intervalMs:c,grantExpiresAt:l,startedAt:d,...u?{gatewayUrl:u}:{},...p?{gatewayOverride:p}:{},...f?{team:f}:{}}}catch{return null}},V2=e=>new Promise(t=>setTimeout(t,e)),K2=async(e,t)=>{let n=await t.readGateState()??{v:1};await t.writeGateState({v:1,lastAttemptAt:t.now(),failureCount:(n.failureCount??0)+1,lastFailure:e})},j2=async(e,t={})=>{let n=t.poll??hd,r=t.verify??Xt,o=t.loadProfile??D,a=t.saveProfile??oe,s=t.saveDevKey??Ji,i=t.readGateState??La,c=t.writeGateState??pu,l=t.clearGateState??Xx,d=t.sleep??V2,u=t.now??Date.now,p=t.recordMint??Sa,f=t.reserveMint??yo,m=t.applyClaudeCode??(async E=>{await qn.apply(E,{dryRun:!1})}),h=E=>K2(E,{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},y;try{y=await n(w,{gatewayUrl:e.gatewayOverride})}catch(E){let R=E instanceof $t?E.kind:"cp-unreachable";return await h(R),R}let g=e.gatewayOverride??y.gatewayUrl,b=await o(),k={...b,gateway:g??b.gateway,name:y.cert.payload.user||b.name,team:e.team??y.cert.payload.team??b.team,enrolledCert:y.cert,enrolledCertExpiry:y.cert.payload.expiresAt,ssoLink:`${e.cpOrigin}/sso/${e.tenantId}`,clientKey:void 0,clientKeyExpiresAt:void 0,authMode:"subscription"};try{await s(y.privateKeyPem),await a(k)}catch{return"failed"}if(!g)return await h("gateway-unreachable"),"gateway-unreachable";let C;await f();let S=(t.resolveMachineUuid??Bt)()||void 0;for(let E=0;E<3;E++)try{C=await r(g,y.cert,y.privateKeyPem,{timeoutMs:1e4,machineUuid:S});break}catch(R){if(R instanceof lt||E===2)break;await d(1e3)}if(!C)return await h("gateway-unreachable"),"gateway-unreachable";let I={...k,gateway:g,name:C.user,team:e.team??C.team??k.team,clientKey:C.key,clientKeyExpiresAt:C.expiresAt,authMode:"subscription"};try{await a(I),await p({expiresAt:C.expiresAt});let E=xe({origin:g,clientKey:C.key,subscription:!0,user:I.name,team:I.team});return await m(E),await l(),"enrolled"}catch{return await h("gateway-unreachable"),"failed"}},Z2=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},g0=async()=>{let e=G2(await Z2());if(e)try{await j2(e)}catch{}return 0};var Y2=1e4,Ny=/^[\w.:-]{1,64}$/,Wt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},$y=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,w0=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),Y2);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 Wt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},J2=e=>{let t=$y(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}},X2=e=>{let t=$y(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&Ny.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&Ny.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},z2=e=>{let t=$y(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ee(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!Ny.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}}},q2=e=>new Promise(t=>setTimeout(t,e)),Q2=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Wt("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}A("Available teams:"),e.forEach((i,c)=>A(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await Ea("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 Wt("invalid-team","Choose one of the teams shown above.");return s},eZ=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??q2,a=t.loadProfile??D,s=t.saveProfile??oe,i=t.clearDevKey??Ya,c=t.chooseTeam??Q2,l=t.apply??(async y=>{await qn.apply(y,{dryRun:!1})}),d=t.log??$,u=await a(),p=kr(e.gateway,u),f=await w0(`${p}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),m=J2(f.body);if(f.status!==200||!m)throw new Wt("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${m.browser_url}`),d(`Enter this code in the browser: ${m.user_code}`),(t.openBrowser??Ta)(m.browser_url);let h=r()+m.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<h;){let y=await w0(`${p}/sso/cli/poll/${encodeURIComponent(m.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":m.poll_secret,...w?{"x-anyray-team":w}:{}}},n);if(y.status===202){await o(m.interval*1e3);continue}if(y.status===401)throw new Wt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(y.status===410)throw new Wt("expired","SSO login expired before it completed. Run anyray-connect login again.");let g=X2(y.body);if(y.status===200&&g){if(w&&!g.teams.includes(w))throw new Wt("invalid-team",`Team ${w} is not available for this account.`);w=await c(g.teams,g.default_team,e.interactive??Ft());continue}let b=z2(y.body);if(y.status!==200||!b)throw new Wt("login-failed","SSO login could not be completed.");let k={...u,gateway:p,name:b.user,team:b.team,clientKey:b.key,clientKeyExpiresAt:b.expires_at,enrolledCert:void 0,enrolledCertExpiry:void 0,enrolledTokenHash:void 0,ssoLink:void 0,authMode:"subscription"};return await i(),await s(k),await l(xe({origin:p,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Wt("expired","SSO login expired before it completed. Run anyray-connect login again.")},tZ=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
734
734
|
|
|
735
735
|
Start browser SSO, choose a team, mint a personal gateway key, and configure
|
|
736
736
|
the subscription-backed Connect lane. In a non-interactive shell, --team may be
|
|
737
|
-
omitted only when the identity authority supplies a default or sole team.`,
|
|
737
|
+
omitted only when the identity authority supplies a default or sole team.`,b0=async(e,t={})=>{let n,r;for(let o=0;o<e.length;o++){let a=e[o];if(a==="--help"||a==="-h")return A(tZ),0;if(a==="--gateway"||a==="--team"){let s=e[++o];if(!s)return O(`${a} requires a value.`),1;a==="--gateway"?n=s:r=s;continue}return O(`unknown login option: ${a}`),1}try{let o=await eZ({gateway:n,team:r},t);return M(`Signed in as ${o.user} for team ${o.team}. Your personal key was saved and configured.`),0}catch(o){if(o instanceof yt)throw o;return O(o instanceof Wt?o.message:"SSO login failed."),1}};var A0=`anyray-connect update [--check] [--auto on|off] [--json]
|
|
738
738
|
|
|
739
739
|
Keep this machine's anyray-connect binary on the published release. Runs
|
|
740
740
|
automatically about every 30 minutes; this command forces it now.
|
|
@@ -745,34 +745,34 @@ Options:
|
|
|
745
745
|
Off still accepts a release the Anyray team marks mandatory.
|
|
746
746
|
--json Emit the result as JSON.
|
|
747
747
|
--help Show this help.
|
|
748
|
-
`,
|
|
749
|
-
`),0}let n=await Da({checkOnly:t.check,force:!t.check,allowNpmMigration:!0});if(t.json){let o=await
|
|
750
|
-
`),n.outcome==="failed"?1:0}let r=
|
|
748
|
+
`,nZ=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},rZ=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}.`}},C0=async e=>{let t;try{t=nZ(e)}catch(o){return O(o.message),process.stderr.write(A0),1}if(t.help)return process.stdout.write(A0),0;if(t.auto!==void 0){let o=await D();if(o.autoUpdate!==!1!==t.auto&&await oe({...o,autoUpdate:t.auto}),t.json||(M(`Automatic updates ${t.auto?"enabled":"disabled"}.`),t.auto||A("A release the Anyray team marks mandatory still installs \u2014 that lever is for security fixes.")),!t.auto)return t.json&&process.stdout.write(`${JSON.stringify({autoUpdate:!1},null,2)}
|
|
749
|
+
`),0}let n=await Da({checkOnly:t.check,force:!t.check,allowNpmMigration:!0});if(t.json){let o=await wo();return process.stdout.write(`${JSON.stringify({...n,autoUpdate:o.autoUpdate,path:o.path,selfUpdateAvailable:o.available,selfUpdateState:o.state},null,2)}
|
|
750
|
+
`),n.outcome==="failed"?1:0}let r=rZ(n);switch(n.outcome){case"updated":case"migrated":M(r);break;case"current":M(r);break;case"available":case"migration-available":A(r),t.check&&A(`Run ${V("anyray-connect update")} to install it.`);break;case"migration-deferred":_(r),A(v("Use the newer npm runtime until that standalone release is published."));break;case"disabled":_(r),A(`Run ${V("anyray-connect update")} to install it now, or ${V("--auto on")} to resume.`);break;case"unmanaged":A(r),A(v("A copy your IT team placed is theirs to roll."));break;case"container":A(r);break;case"platform-unsupported":_(r),A(v("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":_(r);break;case"failed":return O(r),1}return 0};var oZ=3e3,k0=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>ry(oZ)),o=e.updateStatus??wo;t(`anyray-connect ${Ae}
|
|
751
751
|
`);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&_a(a,Ae)>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: ${Ae} \u2192 ${a}
|
|
752
752
|
${i}
|
|
753
|
-
`)}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
|
|
754
|
-
`),0};import
|
|
755
|
-
`)},
|
|
756
|
-
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,
|
|
753
|
+
`)}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 aZ=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},sZ=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),iZ=async(e={})=>{try{let t=await(e.readBootstrap??br)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??zt)().catch(()=>{});let n=await(e.loadProfile??D)();if(Ee(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??Co)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??D)(),Ee(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??La)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!aZ(a)||!sZ(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"}}},v0=async(e={})=>{let t=await iZ(e);return process.stdout.write(`${JSON.stringify(t)}
|
|
754
|
+
`),0};import cZ from"node:path";var lZ="2025-06-18",dZ={name:"anyray",version:"1"},S0={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}},uZ=20,I0={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}},T0=Jh,pZ=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,T0)},fZ=e=>e==="paths"||e==="lines"||e==="full"?e:"full",E0={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-${T0}). 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}},x0={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}},mZ=8,hZ=3,R0={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}},yZ=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(`
|
|
755
|
+
`)},gZ=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
|
|
756
|
+
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,mZ).map(([a,s])=>{let i=s.slice(0,hZ).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
|
|
757
757
|
`)});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(`
|
|
758
|
-
`)},be=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),
|
|
758
|
+
`)},be=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),My=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}}),O0=e=>e?.name??"error",ye=(e,t=!1)=>{let n=e;if(n.length>4e4){let r=t?`
|
|
759
759
|
|
|
760
760
|
[anyray: error output cut to fit the tool-result limit \u2014 ${n.length} chars total.]`:`
|
|
761
761
|
|
|
762
762
|
[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(`
|
|
763
|
-
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},
|
|
764
|
-
`+y.content))}let g=y!==null;return be(n??null,ye(`${i} is a hook-tee file id, not a stash handle`+(g&&w?`, and ${w} is not readable`+(y?.message?` (${y.message})`:"")+". The hook writes these files when it trims a tool output; this one has been swept, or the tee is off. Re-run the command to regenerate its output.":`. Read ${w??"the path in its footer"} directly.`),!0))}let
|
|
765
|
-
${
|
|
766
|
-
`)}catch{}},l=async p=>{let f=p.trim();if(!f)return;let
|
|
767
|
-
`))>=0;){let
|
|
768
|
-
`);
|
|
769
|
-
`),!0)}catch{return!1}},
|
|
770
|
-
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!
|
|
771
|
-
`),1;await(n.refreshIfDue??
|
|
772
|
-
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??fn)():void 0,d=
|
|
773
|
-
`),1;w=n.comSpec??a.ComSpec??"cmd.exe",y=["/d","/s","/c",`"${
|
|
774
|
-
`),g(1)}),k.once("exit",(C,S)=>{g(typeof C=="number"?C:S?1:0)})})};import{randomUUID as
|
|
775
|
-
`,"utf8"),await a.chmod(384),await Tr(a),await a.close(),a=void 0,await(t.publish??
|
|
763
|
+
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},wZ=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 be(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:lZ,capabilities:{tools:{}},serverInfo:dZ});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return be(n??null,{});case"tools/list":{let a=[S0,I0];t.advertiseContextTools!==!1&&a.push(E0,x0);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(R0),be(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===S0.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return be(n??null,ye("handle is required",!0));let c=w=>{if(w!==void 0)return typeof w!="number"||!Number.isFinite(w)?null:Math.max(Math.round(w),1)},l=c(s.startLine),d=c(s.endLine);if(l===null||d===null)return be(n??null,ye("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return be(n??null,ye("grep must be non-empty",!0));if(s.grep.length>256)return be(n??null,ye("grep is limited to 256 characters",!0));u=s.grep}let p=l!==void 0||d!==void 0||u!==void 0,f=Sy(i);if(f){let w=await Iy(f);if(u!==void 0)return be(n??null,ye(`${i} is a local hook-tee file, not a stash handle, and grep is not supported on these \u2014 re-call with startLine/endLine, or Read ${w??"the path in the footer"} directly.`,!0));let y=t.readTee?await t.readTee(f,{startLine:l,endLine:d}).catch(b=>({ok:!1,content:"",path:w??f,lines:0,truncated:!1,message:b instanceof Error?b.message:"tee read failed"})):null;if(y?.ok){let b=y.span?`lines ${y.span.startLine}-${y.span.endLine} of ${y.lines}`:`${y.lines} line(s)`,k=y.truncated&&!y.span?.partialLine&&y.span?` Continue with anyray_retrieve(handle="${i}", startLine=${y.span.endLine+1}).`:"";return be(n??null,ye(`[anyray: ${i} is a local hook-tee file, not a stash handle \u2014 served ${b} from ${y.teePath??w}.${k} Read that path directly next time.]
|
|
764
|
+
`+y.content))}let g=y!==null;return be(n??null,ye(`${i} is a hook-tee file id, not a stash handle`+(g&&w?`, and ${w} is not readable`+(y?.message?` (${y.message})`:"")+". The hook writes these files when it trims a tool output; this one has been swept, or the tee is off. Re-run the command to regenerate its output.":`. Read ${w??"the path in its footer"} directly.`),!0))}let m;try{m=await t.retrieve(i,p?{startLine:l,endLine:d,grep:u}:void 0)}catch(w){m={ok:!1,message:w instanceof Error?w.message:"retrieve failed"}}let h="this gateway does not support partial retrieval yet \u2014 call again without startLine/endLine/grep for the full content";if(!m.ok)return be(n??null,ye(m.kind==="slice-unsupported"?h:m.message,!0));if(p&&(m.partial===void 0||typeof m.totalLines!="number"))return be(n??null,ye(h,!0));if(m.partial===!0&&typeof m.totalLines=="number"){let w=m.grepMatches!==void 0?`[anyray: partial \u2014 ${m.grepMatches} matching line(s) in lines ${m.startLine}-${m.endLine} of ${m.totalLines}`+(m.grepTruncated?`, windows around the first ${uZ} matches shown \u2014 narrow the range or grep`:"")+` \xB7 retrieve ${i} again with startLine/endLine, another grep, or no params for full]`:`[anyray: partial \u2014 lines ${m.startLine}-${m.endLine} of ${m.totalLines} \xB7 retrieve ${i} again with other lines, grep, or no params for full]`;return be(n??null,ye(`${w}
|
|
765
|
+
${m.content}`))}return be(n??null,ye(m.content))}if(a.name===I0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return be(n??null,ye("query is required",!0));let c=typeof s.k=="number"?s.k:void 0,l;try{l=await t.recall(i,c)}catch(d){l={ok:!1,message:d instanceof Error?d.message:"recall failed"}}return be(n??null,l.ok?ye(yZ(l.matches)):ye(l.message,!0))}if(a.name===E0.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return be(n??null,ye("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(p=>typeof p=="string"):void 0,l=pZ(s.maxResults),d=fZ(s.resultShape),u;try{u=await t.search(i,c,l)}catch(p){u={ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:p instanceof Error?p.message:"search failed"}}return be(n??null,u.ok?ye(RE(i,u,d)):ye(u.message??"search failed",!0))}if(a.name===R0.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 be(n??null,d.ok?ye(jh(d)):ye(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return be(n??null,ye("query (or open) is required",!0));let l;try{l=await t.historySearch(c)}catch(d){l={ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:d instanceof Error?d.message:"history search failed"}}return be(n??null,l.ok?ye(gZ(c,l)):ye(l.message??"history search failed",!0))}if(a.name===x0.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return be(n??null,ye("path is required",!0));let c={startLine:typeof s.startLine=="number"?s.startLine:void 0,endLine:typeof s.endLine=="number"?s.endLine:void 0},l;try{l=await t.read(i,c)}catch(d){l={ok:!1,content:"",path:i,lines:0,truncated:!1,message:d instanceof Error?d.message:"read failed"}}return be(n??null,l.ok?ye(jh(l)):ye(l.message??"read failed",!0))}return My(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:My(n??null,-32601,`method not found: ${o}`)}},bZ=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),kd);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:Vt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},AZ=(e,t=!0)=>({retrieve:async(n,r)=>ka(await e(),n,r),recall:async(n,r)=>vd(await e(),n,r),search:(n,r,o)=>jd(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>Si(n,r),readTee:async(n,r)=>{if(ky())return{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"the hook tee is off (ANYRAY_HOOK_TEE=off)"};let o=await Iy(n);return o?{...await Si(o,{cwd:cZ.dirname(o),...r}),teePath:o}:{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"not a tee id"}},historySearch:n=>_E(n),historyOpen:n=>PE(n),historyAvailable:async()=>await Oa()>0,advertiseContextTools:t,heartbeat:()=>{e().then(bZ).catch(()=>{})}}),_0=async(e="auto",t={})=>{let n=AZ(()=>nt(e),e!=="claude"),r=t.stdin??process.stdin,o=t.stdout??process.stdout,a=0,s=t.refreshTick??(()=>{let p=Date.now();p<a||(a=p+6e4,Cr().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=p=>{try{o.write(JSON.stringify(p)+`
|
|
766
|
+
`)}catch{}},l=async p=>{let f=p.trim();if(!f)return;let m;try{m=JSON.parse(f)}catch{console.error("anyray mcp: dropping unparseable frame");return}let h;try{h=await wZ(m,n)}catch(w){console.error("anyray mcp: dispatch error",O0(w)),h=m?.id===void 0?null:My(m.id,-32603,"internal error")}h&&c(h),i()};i();let d=setInterval(i,30*6e4);d.unref?.();let u="";try{for await(let p of r){u+=p.toString("utf-8");let f;for(;(f=u.indexOf(`
|
|
767
|
+
`))>=0;){let m=u.slice(0,f);u=u.slice(f+1),await l(m)}}u.trim()&&await l(u)}catch(p){console.error("anyray mcp: stdin error",O0(p))}finally{clearInterval(d)}return 0};import{spawn as CZ}from"node:child_process";var kZ=e=>e==="jetbrains"||e==="windsurf"?e:void 0,vZ=async(e,t,n,r=1e4)=>{let o=await new Promise(a=>{let s="",i=!1,c=f=>{i||(i=!0,clearTimeout(l),t.off("data",d),t.off("error",u),t.off("end",p),a(f))},l=setTimeout(()=>c(void 0),r),d=f=>{s+=f.toString();let m=s.indexOf(`
|
|
768
|
+
`);m!==-1?c(s.slice(0,m)):s.length>65536&&c(void 0)},u=()=>c(void 0),p=()=>c(s.length>0?s:void 0);t.on("data",d),t.once("error",u),t.once("end",p)});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}})}
|
|
769
|
+
`),!0)}catch{return!1}},SZ={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},IZ=(e,t,n)=>{let r=new Set(SZ[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}},P0=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
|
|
770
|
+
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!nd(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
|
|
771
|
+
`),1;await(n.refreshIfDue??zt)().catch(()=>{});let s=await(n.loadProfile??D)(),i=await(n.readBootstrap??br)().catch(()=>{});if(i){let g=await(n.ssoGate??Co)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(g.exitCode===2&&g.stderr)return await vZ(g.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(g.stderr),1;s=await(n.loadProfile??D)()}if(!s.gateway)return r.write(`Anyray ACP agent is not configured; run anyray-connect first.
|
|
772
|
+
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??fn)():void 0,d=xe({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=kZ(n.clientTool);u&&(d.metadata.tool=u);let p=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",f=(n.hookBinaryIsDurable??ce)(),m=Ov(d,t,{mcpServer:f?Ge("profile"):void 0})[p],h=n.spawn??CZ,w=m.command,y=m.args;if(o==="win32"){if(!m.args.every(g=>g==="--yes"||/^@agentclientprotocol\/(claude-agent-acp|codex-acp)@[0-9]+(?:\.[0-9]+){2}$/.test(g)))return r.write(`Anyray ACP adapter arguments are invalid.
|
|
773
|
+
`),1;w=n.comSpec??a.ComSpec??"cmd.exe",y=["/d","/s","/c",`"${m.command}" ${m.args.join(" ")}`]}return await new Promise(g=>{let b=IZ(e,a,m.env),k=h(w,y,{env:b,stdio:"inherit",windowsHide:!0});k.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
|
|
774
|
+
`),g(1)}),k.once("exit",(C,S)=>{g(typeof C=="number"?C:S?1:0)})})};import{randomUUID as EZ}from"node:crypto";import{open as xZ,rm as RZ}from"node:fs/promises";import{join as OZ}from"node:path";import{z as Se}from"zod";var fu=Se.string().min(1).refine(e=>Number.isFinite(Date.parse(e)),"expected an ISO-8601 timestamp"),TZ=Se.enum(["reconcile","refresh","repair","status","offboard"]),By=Se.union([Se.literal(0),Se.literal(1),Se.literal(2),Se.literal(3),Se.literal(4)]),_Z=Se.enum(["locked","required","recommended","optional"]),mu=Se.object({schemaVersion:Se.literal(1),generatedAt:fu,connectVersion:Se.string().min(1),fleetManaged:Se.boolean(),enrollment:Se.object({state:Se.enum(["enrolled","degraded","broken","none"]),lastRefreshAt:fu.optional(),lastRefreshOutcome:Se.enum(["ok","failed"]).optional()}).strict(),keyExpiresAt:fu.optional(),tools:Se.array(Se.object({id:Se.string().min(1),tier:_Z,routed:Se.boolean()}).strict()),lastVerb:Se.object({verb:TZ,exitCode:By,at:fu}).strict()}).strict(),D0=(e,t)=>{if(!e)return!1;let n=Date.parse(e);return Number.isFinite(n)&&n>t},PZ=(e,t,n=Date.now())=>{if(!!!(e.clientKey||e.enrolledCert||t))return"none";let o=e.enrolledCertExpiry??e.enrolledCert?.payload.expiresAt;return!e.gateway||!e.enrolledCert||!t||!D0(o,n)?"broken":!e.clientKey||e.clientKeyExpiresAt&&!D0(e.clientKeyExpiresAt,n)?"degraded":"enrolled"},DZ=e=>{let t=e.lastSuccessAt,n=e.lastAttemptAt;if(t===void 0&&n===void 0)return{};let r=Math.max(t??0,n??0);return!Number.isFinite(r)||r<=0?{}:{lastRefreshAt:new Date(r).toISOString(),lastRefreshOutcome:t!==void 0&&t>=(n??0)?"ok":"failed"}},L0=(e,t)=>e.fleetToolPolicy?.tiers?.[t]??"required",LZ=async(e,t)=>{let n=new Set(e.managedTools??[]),r=new Set(e.revertedTools??[]),o=(e.fleetToolPolicy?.enabled??[]).filter(c=>{let l=L0(e,c);return l==="locked"||l==="required"||l==="recommended"&&!r.has(c)}),a=[...new Set([...n,...o])].sort();if(a.length===0)return[];let s=e.gateway,i=[];for(let c of a){let l=t(c),d=!1;if(l&&s&&l.pointsAt)try{let u=await l.detect();if(!u.installed&&!n.has(c))continue;u.installed&&(d=await l.pointsAt(s))}catch{d=!1}i.push({id:c,tier:L0(e,c),routed:d})}return i},N0=async(e,t={})=>{let n=t.now??Date.now,r=await(t.loadProfile??D)(),o=await(t.loadDevKey??$e)().catch(()=>{}),a=await(t.readRefreshState??It)().catch(()=>({})),s={schemaVersion:1,generatedAt:new Date(n()).toISOString(),connectVersion:Ae,fleetManaged:r.anyrayFleetManaged===!0,enrollment:{state:PZ(r,!!o,n()),...DZ(a)},...r.clientKeyExpiresAt&&Number.isFinite(Date.parse(r.clientKeyExpiresAt))?{keyExpiresAt:r.clientKeyExpiresAt}:{},tools:await LZ(r,t.toolById??mt),lastVerb:e};return mu.parse(s)},NZ=()=>OZ(Q(),"status.json"),$0=async(e,t={})=>{let n=mu.parse(e);await(t.ensureStateDir??tt)();let r=NZ(),o=`${r}.${process.pid}.${EZ()}.tmp`,a;try{a=await xZ(o,"wx",384),await a.writeFile(`${JSON.stringify(n,null,2)}
|
|
775
|
+
`,"utf8"),await a.chmod(384),await Tr(a),await a.close(),a=void 0,await(t.publish??he)(o,r)}catch(s){throw a&&await a.close().catch(()=>{}),await RZ(o,{force:!0}).catch(()=>{}),s}},Fy=e=>e.enrollment.state==="none"||e.enrollment.state==="broken"?3:e.enrollment.state==="degraded"?4:e.tools.every(t=>t.routed)?0:4;var $Z=1e4,$a=e=>e?.name??"Error",Wy=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($Z)})}catch(o){console.error(`anyray seat offboard report: ${$a(o)}`)}},MZ=e=>e==="reverted"||e==="queued",hu=async(e={})=>{let t=e.loadProfile??D,n=e.clearDeviceTokenState??Pd,r=e.reportSeatOffboarded??Wy,o=e.clearEnrollment??Xi,a=e.recordManagedTools??Vn,s=e.markSeatOffboarded??zi,i=e.adapterById??mt,c=e.uninstallScheduler??nr,l=e.unitsPresent??kc,d=e.saveProfile??oe,u=await t(),p=u.managedTools??[];await r(u).catch(()=>{}),await n().catch(()=>{});let f=!1,m=!1;try{f=await o()}catch(C){m=!0,console.error(`anyray offboard: clearing enrollment: ${$a(C)}`)}let h=[],w=[],y=[];for(let C of p){let S=i(C);if(!S){y.push(C);continue}try{let I=await S.revert({dryRun:!1,fullRevert:!0});h.push({id:C,status:I.status}),MZ(I.status)?w.push(C):y.push(C)}catch(I){console.error(`anyray offboard: reverting ${C}: ${$a(I)}`),y.push(C)}}let g=!0;try{await a(h,!0,!0)}catch(C){g=!1,console.error(`anyray offboard: recording managed tools: ${$a(C)}`)}let b=y.length===0&&g,k=!1;if(b)try{await s(),k=!0}catch(C){console.error(`anyray offboard: stamping offboard: ${$a(C)}`)}try{((await t()).refreshSchedulerEnabled||await l())&&await c(),await d({...await t(),refreshSchedulerEnabled:!1})}catch(C){console.error(`anyray offboard: unit teardown: ${$a(C)}`)}return{reverted:w,unresolved:y,enrollmentCleared:f,credentialHeld:m,recordPersisted:g,offboardMarked:k,ok:y.length===0&&!m&&g&&k}};var ae={success:0,unexpected:1,usage:2,authBroken:3,partial:4},BZ=`Stable non-interactive runtime commands:
|
|
776
776
|
anyray-connect reconcile
|
|
777
777
|
anyray-connect refresh
|
|
778
778
|
anyray-connect repair
|
|
@@ -788,7 +788,7 @@ Exit codes:
|
|
|
788
788
|
1 unexpected error
|
|
789
789
|
2 usage error (unknown flag or argument)
|
|
790
790
|
3 authentication broken; re-enrollment required
|
|
791
|
-
4 partial; the command ran but drift remains`,
|
|
791
|
+
4 partial; the command ran but drift remains`,FZ={reconcile:"reconcile",__anyray_reconcile:"reconcile",refresh:"refresh",__anyray_refresh:"refresh",repair:"repair",__anyray_repair:"repair",status:"status",__anyray_status:"status",offboard:"offboard",__anyray_offboard:"offboard"},WZ=e=>e.replaceAll("-","_"),F0=e=>{let t=e[0];if(!t)return;let n=FZ[WZ(t)];if(!n)return;let r=e.slice(1);if(n==="status"&&t==="status"&&!r.includes("--json"))return;if(r.length===1&&(r[0]==="--help"||r[0]==="-h"))return{verb:n,help:!0,usageError:!1};let a=n==="status"?t==="status"?r.length===1&&r[0]==="--json":r.length===0||r.length===1&&r[0]==="--json":r.length===0;return{verb:n,help:!1,usageError:!a}},Hy=e=>{let t=e?.name;return typeof t=="string"&&/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(t)?t:"Error"},HZ=async(e=D,t=Date.now())=>{let n=await e(),r=Date.parse(n.enrolledCertExpiry??n.enrolledCert?.payload.expiresAt??""),o=!!n.enrolledCert&&Number.isFinite(r)&&r>t,a=Date.parse(n.clientKeyExpiresAt??""),s=n.clientKeyExpiresAt!==void 0&&(!Number.isFinite(a)||a<=t);if(!n.gateway)return"auth-broken";if(!n.clientKey||s)return o?"credential-degraded":"auth-broken";try{let i=await ba(n.gateway,n.clientKey);return await Aa(i)}catch(i){if(lh(i))return o?"credential-degraded":"auth-broken";throw i}},UZ=e=>e==="auth-broken"?ae.authBroken:e==="credential-degraded"||e.toolsApplied<e.toolsRequested||e.toolsTombstoned.length>0?ae.partial:ae.success,GZ=e=>e.refresh==="not-enrolled"||e.refresh==="cert-expired"||e.refresh==="cert-rejected"?ae.authBroken:e.refresh==="failed"?ae.unexpected:e.partial||e.refresh==="disabled"||e.refresh==="backoff"||e.refresh==="throttled"||e.refresh==="gateway-incompatible"?ae.partial:ae.success,VZ=e=>!e.enrollment.enrolled||e.enrollment.expired===!0||e.verify?.kind==="enrollment-required",M0=async e=>{let t;return{code:await au({repair:e,quick:!e,silent:!0},{captureReport:r=>t=r}),authBroken:t?VZ(t):!1}},B0=e=>typeof e!="number"&&e.authBroken?ae.authBroken:(typeof e=="number"?e:e.code)===0?ae.success:ae.partial,KZ=(e,t)=>{let n=Fy(t);return n===ae.authBroken?n:e!==0||n===ae.partial?ae.partial:ae.success},jZ=async(e,t)=>{if(e==="reconcile")return UZ(await(t.reconcile??(()=>HZ(t.loadProfile)))());if(e==="refresh"){if(!t.refresh)throw new Error("refresh runtime is unavailable");return GZ(await t.refresh())}return e==="repair"?B0(await(t.repair??(()=>M0(!0)))()):e==="status"?B0(await(t.status??(()=>M0(!1)))()):(await(t.offboard??hu)()).ok?ae.success:ae.partial},Uy=(e,t)=>mu.parse({...e,lastVerb:{...e.lastVerb,exitCode:t}}),W0=async(e,t={})=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.help)return n(BZ),ae.success;let o=t.now??Date.now,a=new Date(o()).toISOString(),s=t.withProfileLock??Ja,i=t.buildStatus??N0,c=t.writeStatus??$0,l,d=e.usageError?ae.usage:ae.unexpected;e.usageError&&r(`anyray-connect ${e.verb}: UsageError`);try{await s(async()=>{if(!e.usageError)try{d=By.parse(await jZ(e.verb,t))}catch(u){d=lh(u)?ae.authBroken:ae.unexpected,r(`anyray-connect ${e.verb}: ${Hy(u)}`)}if(l=await i({verb:e.verb,exitCode:d,at:a},{now:o}),(e.verb==="repair"||e.verb==="status")&&d!==ae.unexpected&&d!==ae.usage&&d!==ae.authBroken)d=KZ(d===0?0:1,l);else if(e.verb!=="offboard"&&d!==ae.unexpected&&d!==ae.usage){let u=Fy(l);(u===ae.authBroken||d===ae.success)&&(d=u)}l=Uy(l,d);try{await c(l)}catch(u){d=ae.unexpected,l=Uy(l,d),r(`anyray-connect ${e.verb}: ${Hy(u)}`)}})}catch(u){d=ae.unexpected,r(`anyray-connect ${e.verb}: ${Hy(u)}`);try{l=Uy(await i({verb:e.verb,exitCode:d,at:a},{now:o}),d)}catch{l=void 0}}return n(JSON.stringify(l||{schemaVersion:1,generatedAt:a,connectVersion:"unknown",fleetManaged:!1,enrollment:{state:"broken"},tools:[],lastVerb:{verb:e.verb,exitCode:d,at:a}})),d};import{createReadStream as ZZ}from"node:fs";import{spawnSync as q0}from"node:child_process";import{createHash as YZ}from"node:crypto";import{access as Q0,chmod as Ky,copyFile as JZ,lstat as XZ,mkdir as zZ,mkdtemp as eR,readFile as Au,rename as qZ,rm as Rr,stat as QZ,writeFile as eY}from"node:fs/promises";import{constants as tR}from"node:fs";import{platform as Fa,tmpdir as tY}from"node:os";import{dirname as nY,isAbsolute as rY,join as gu}from"node:path";import{z as Le}from"zod";var oY="fleetd-installer-v4.89.2",H0=`https://github.com/anyrayHQ/install/releases/download/${oY}`,aY=1e4,sY=1e4,U0=31,iY=1500,nR=20*1024,Gy=20,cY="0.25",lY="/var/tmp",Ba="/Library/LaunchDaemons/com.fleetdm.orbit.plist",wu="/etc/default/orbit",Wi="/opt/orbit/anyray-enroll-secret.txt",rR="/opt/orbit/secret-orbit-node-key.txt",dY="/opt/orbit/bin/orbit/orbit",Hi="C:\\Program Files\\Orbit",uY=`${Hi}\\bin\\orbit`,oR=`${Hi}\\secret-orbit-node-key.txt`,Fi=`${Hi}\\secret.txt`,pY=`${Hi}\\fleet_url.txt`,aR=`${Hi}\\anyray-managed.txt`,bu="Fleet osquery",jy="C:\\Windows\\System32\\sc.exe",fY="C:\\Windows\\System32\\whoami.exe",yu="C:\\Windows\\System32\\icacls.exe",mY="C:\\Windows\\System32\\msiexec.exe",Zy="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",G0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],hY=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],yY=`anyray-connect endpoint install
|
|
792
792
|
|
|
793
793
|
Install Fleet's signed endpoint agent and enroll this machine in Anyray.
|
|
794
794
|
|
|
@@ -796,11 +796,11 @@ Supported on macOS, Linux and Windows.
|
|
|
796
796
|
|
|
797
797
|
The command uses the current seat's stored gateway key. Administrator access is
|
|
798
798
|
required: on macOS and Linux Connect asks through sudo once when /dev/tty is
|
|
799
|
-
available; on Windows, run it from a shell started as Administrator.`,
|
|
800
|
-
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",
|
|
801
|
-
`&&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},
|
|
799
|
+
available; on Windows, run it from a shell started as Administrator.`,Xy=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),sR=(e,t=Fa())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),iR=(e,t=Fa(),n=!1)=>(Xy(e)||n)&&t!=="win32",se=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},gY=Le.object({kind:Le.enum(["pkg","deb","rpm","msi"]),path:Le.string().min(1).refine(rY),sha256:Le.string().regex(/^[0-9a-f]{64}$/)}).strict(),wY=Le.object({action:Le.literal("restart"),os:Le.enum(["darwin","linux","win32"])}).strict(),bY=Le.object({action:Le.literal("configure"),os:Le.enum(["darwin","linux","win32"]),fleetUrl:Le.string().min(1).max(2048),enrollSecret:Le.string().min(1).max(4096),package:gY.optional()}).strict(),AY=Le.discriminatedUnion("action",[wY,bY]),Ui=(e,t)=>{let n=q0(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},zy=async e=>{try{return await Q0(e,tR.F_OK),!0}catch{return!1}},CY=async e=>{try{let t=await QZ(e);return t.isFile()&&t.size>0}catch{return!1}},qy=(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}},Vy=(e,t)=>qy(e,t)!==null,V0=e=>e==="win32"?Fi:Wi,kY=e=>e==="win32"?oR:rR,vY=e=>Vy(e,"ORBIT_FLEET_URL")&&Vy(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${Wi}</string>`)&&!Vy(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),SY=e=>{let t=(n,r)=>e.split(`
|
|
800
|
+
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",Wi)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},Yy=(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()},cR=e=>{let t=e(jy,["qc",bu,"8192"]);return t.status===0?t.stdout:""},Jy=e=>{let t=e(Zy,hY(bu)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},IY=async e=>{try{return e==="win32"?Yy(e,cR(Ui)):Yy(e,await Au(e==="darwin"?Ba:wu,"utf8"))}catch{return}},EY=async e=>{try{if(e==="win32")return await zy(aR)&&Yy(e,cR(Ui))!==void 0;let n=await Au(e==="darwin"?Ba:wu,"utf8");return e==="darwin"?vY(n):SY(n)}catch{return!1}},lR=async(e,t={})=>{let n=t.exists??zy,r=t.command??Ui,o,a="absent";if(e==="win32")a=Jy(r),o=await n(uY)&&a!=="absent";else{let l=e==="darwin"?await n(Ba):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(dY)&&l}let s=await(t.configured??EY)(e),i=await(t.hasNodeKey??(()=>CY(kY(e))))(),c=!1;if(o)if(e==="darwin"){let l=r("/bin/launchctl",["print","system/com.fleetdm.orbit"]);c=l.status===0&&/\bstate\s*=\s*running\b/.test(l.stdout)}else e==="linux"?c=r("systemctl",["is-active","--quiet","orbit"]).status===0:c=a==="Running";return{installed:o,configured:s,running:c,checkedIn:i}},xY=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),dR=(e,t)=>{let n=qy(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]===`
|
|
801
|
+
`&&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},RY=(e,t)=>{let n=dR(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},K0=(e,t,n)=>{let r=`
|
|
802
802
|
<key>${t}</key>
|
|
803
|
-
<string>${
|
|
803
|
+
<string>${xY(n)}</string>`,o=dR(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=qy(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new se("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)},OY=(e,t,n=Wi)=>{let r=RY(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=K0(r,"ORBIT_FLEET_URL",t),K0(r,"ORBIT_ENROLL_SECRET_PATH",n)},TY=(e,t,n=Wi)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
|
|
804
804
|
`).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(`
|
|
805
805
|
`).trimEnd()}
|
|
806
806
|
|
|
@@ -810,13 +810,13 @@ available; on Windows, run it from a shell started as Administrator.`,Qy=e=>!!(e
|
|
|
810
810
|
# file, never in this world-readable one.
|
|
811
811
|
ORBIT_FLEET_URL=${t}
|
|
812
812
|
ORBIT_ENROLL_SECRET_PATH=${n}
|
|
813
|
-
`},
|
|
814
|
-
`,384);e.os!=="win32"&&await
|
|
815
|
-
`,384),e.os==="win32"&&
|
|
816
|
-
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??
|
|
817
|
-
sudo anyray-connect endpoint install`),"deferred"},
|
|
818
|
-
`;if(Buffer.byteLength(t)>
|
|
819
|
-
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Fa()==="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 D()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},
|
|
813
|
+
`},uR=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}},_Y=Le.object({code:Le.string().min(1).optional(),message:Le.string().min(1).optional()}).passthrough(),j0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},PY=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=_Y.safeParse(t);if(!r.success)return n;let o=j0(r.data.message??""),a=j0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},Z0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??sY),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":Ae},body:"{}",signal:r.signal})}catch{throw new se("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new se("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new se(PY(a.status,c))}let s;try{s=await a.json()}catch{throw new se("The gateway returned malformed endpoint enrollment data.")}let i=Le.object({fleetUrl:Le.string().min(1).max(2048),enrollSecret:Le.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!uR(i.data.fleetUrl))throw new se("The gateway returned invalid endpoint enrollment data.");return i.data},DY=async(e={})=>{let t=e.exists??zy;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 se("Linux endpoint installation requires either dpkg or rpm.")},LY=async e=>e==="darwin"?"pkg":e==="win32"?"msi":DY(),Qy=e=>`fleetd.${e}`,NY=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",$Y=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),aY);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},MY=async(e,t={})=>{let n=Qy(e),r=t.fetchResponse??fetch,o;try{o=await $Y(`${H0}/SHA256SUMS`,r)}catch{throw new se("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new se(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=ty(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await eR(gu(tY(),"anyray-endpoint-")),i=gu(s,n);try{await Ky(s,448),await(t.download??oy)(`${H0}/${n}`,i,a)}catch(c){if(await Rr(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Ri&&c.status===404)return;throw new se("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>Rr(s,{recursive:!0,force:!0})}},BY=async(e,t,n)=>{await zZ(nY(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Rr(r,{force:!0});try{await eY(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await qZ(r,e)}catch(o){throw await Rr(r,{force:!0}).catch(()=>{}),o}},Y0=async e=>{let t=YZ("sha256");for await(let n of ZZ(e))t.update(n);return t.digest("hex")},FY=async(e,t={})=>{let n=await XZ(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new se("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await Y0(e.path)!==e.sha256)throw new se("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await eR(gu(lY,"anyray-endpoint-root-")),o=gu(r,Qy(e.kind));try{if(await Ky(r,448),await JZ(e.path,o),await Ky(o,384),await Y0(o)!==e.sha256)throw new se("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>Rr(r,{recursive:!0,force:!0})}}catch(a){throw await Rr(r,{recursive:!0,force:!0}).catch(()=>{}),a}},Ma=(e,t)=>{if(e.status!==0)throw new se(t)},J0="com.fleetdm.fleetd.config",WY="com.fleetdm.fleetd.enroll.secret",HY=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",rR],UY=[pY,oR],GY=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(J0))throw new se(`This machine already receives its endpoint configuration from an MDM profile (${J0}), 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=>Rr(o,{force:!0}));for(let o of e==="win32"?UY:HY)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",WY,"/Library/Keychains/System.keychain"])},VY=e=>{e(yu,[Fi,"/inheritance:r"]),e(yu,[Fi,"/grant:r","*S-1-5-18:(F)"]),e(yu,[Fi,"/grant:r","*S-1-5-32-544:(F)"]),e(yu,[Fi,"/remove:g","*S-1-5-32-545"])},KY=(e,t,n)=>{if(e.kind==="pkg"){Ma(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){Ma(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){Ma(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}Ma(t(mY,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},jY=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<Gy;r++){if(n=t("/bin/launchctl",["bootstrap","system",Ba]),n.status===0)return;t("/bin/sleep",[cY])}throw new se(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(jy,["stop",bu]);for(let n=0;n<Gy;n++){let r=Jy(t);if(r==="Stopped"||r==="absent")break;t(Zy,G0)}for(let n=0;n<Gy;n++){if(t(jy,["start",bu]).status===0||Jy(t)==="Running")return;t(Zy,G0)}throw new se("Orbit was configured, but the Windows service could not be started.")}Ma(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),Ma(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},ZY=e=>new Promise(t=>setTimeout(t,e)),pR=async(e,t={})=>{let n=t.command??Ui,r=t.readText??(c=>Au(c,"utf8")),o=t.writeText??BY,a=t.removeSecret??(()=>Rr(V0(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&GY(n),e.package&&!NY(e.os,e.package.kind))throw new se("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new se("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??FY)(e.package);i=d.cleanup,KY(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Ba);await o(Ba,OY(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(wu);await o(wu,TY(d,e.fleetUrl),420)}else await o(aR,`anyray
|
|
814
|
+
`,384);e.os!=="win32"&&await X0(e.os,n,t),await o(V0(e.os),`${e.enrollSecret}
|
|
815
|
+
`,384),e.os==="win32"&&VY(n),s=e.os!=="win32"}jY(e.os,n);let c=t.checkIn??(async d=>{let u=await lR(d);return u.running&&u.checkedIn}),l=t.wait??ZY;for(let d=0;d<(t.attempts??U0);d++){if(await c(e.os))return;d+1<(t.attempts??U0)&&await l(iY)}throw new se("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(()=>{})}},YY=async()=>{try{return await Q0("/dev/tty",tR.R_OK),!0}catch{return!1}},JY=12288,XY=e=>{let t=e(fY,["/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>=JY},zY=async(e,t={})=>{if((t.os??Fa())==="win32")return(t.elevated??(()=>XY(t.command??Ui)))()?(await e(),"direct"):((t.print??A)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
|
|
816
|
+
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??YY)()){if(await(t.reexec??(async()=>1))()!==0)throw new se("Administrator access did not complete; the endpoint agent was not enrolled.");return"sudo"}return(t.print??A)(`Administrator access is required. Run:
|
|
817
|
+
sudo anyray-connect endpoint install`),"deferred"},qY=async e=>{let t=`${JSON.stringify(e)}
|
|
818
|
+
`;if(Buffer.byteLength(t)>nR)throw new se("The privileged endpoint plan is unexpectedly large.");let n=en(["__anyray-endpoint-install"]);return q0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},QY=async(e,t={})=>(t.withRoot??zY)(()=>(t.apply??pR)(e),{...t.root,reexec:()=>(t.sudo??qY)(e)}),z0=async()=>{if((process.getuid?.()??-1)!==0||!process.env.SUDO_USER)return D();let e=process.env.SUDO_USER;if(!/^[A-Za-z0-9._-]{1,64}$/.test(e))return D();let t;try{let s=(await Au("/etc/passwd","utf8")).split(`
|
|
819
|
+
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Fa()==="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 D()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},fR=async(e={},t={})=>{let n=t.os??Fa();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new se("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??lR)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??z0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??IY)(r);if(!l||!d||u===void 0)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};let p=await(t.fetchEnrollment??Z0)(l,d);if(u===p.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};$("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new se("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??z0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new se("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??Z0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let p=await(t.packageKind??(()=>LY(r)))();if(i=await(t.stagePackage??MY)(p),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${Qy(p)} 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??QY)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},eg=e=>e instanceof se?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",mR=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return A(yY),0;if(e.length!==1||e[0]!=="install")return O("Usage: anyray-connect endpoint install"),1;try{let t=await fR();return t.message&&(t.outcome==="installed"?M(t.message):$(t.message)),0}catch(t){return O(eg(t)),1}},eJ=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>nR)throw new se("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new se("The privileged endpoint plan is malformed.")}let r=AY.safeParse(n);if(!r.success||r.data.os!==Fa()||r.data.action==="configure"&&!uR(r.data.fleetUrl))throw new se("The privileged endpoint plan is invalid.");return r.data},hR=async e=>{if((process.getuid?.()??-1)!==0)return O("The privileged endpoint step must run as root."),1;if(e.length!==0)return O("The privileged endpoint step does not accept arguments."),1;try{return await pR(await eJ()),0}catch(t){return O(eg(t)),1}},yR=async(e,t=fR)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?M(n.message):$(n.message)),n.outcome}catch(n){$(`Endpoint agent: ${eg(n)} Tool routing remains configured.`);return}};var tJ=new Set(["not-due","repaired","cert-renewed","heartbeat-refreshed","refreshed"]),gR=async(e,t={})=>await(t.fleetdPresent??Ao)()?tJ.has(e)?{retired:!0,messages:(await(t.uninstallScheduler??nr)()).messages}:{retired:!1,reason:"refresh-unhealthy",messages:[]}:{retired:!1,reason:"no-fleetd",messages:[]};var wR=["reapply_config","remint","revert","revert_tool","update"],nJ=/^[a-z0-9][a-z0-9-]{0,31}$/;var rJ=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id!="string"||t.id.length===0||typeof t.kind!="string"||!wR.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&nJ.test(t.tool):t.tool===void 0},tg=e=>e?.name??"error",bR=async(e,t,n)=>{let r=n.fetchImpl??fetch,o=e.replace(/\/$/,""),a;try{let i=await r(`${o}/connect/directive`,{method:"GET",headers:{"x-anyray-api-key":t,"x-anyray-directive-kinds":wR.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!rJ(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",tg(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",tg(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:",tg(i))}return a.kind};var AR=e=>e?.name??"Error",CR=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??D,r=t.recordManagedTools??Vn,o=t.adapterById??mt,a=t.isLocked??di,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}: ${AR(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${AR(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{platform as vR}from"node:os";var SR=`${V("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
820
820
|
|
|
821
821
|
${V("Usage")}
|
|
822
822
|
npx anyray-connect [options]
|
|
@@ -861,7 +861,7 @@ ${V("What it does")}
|
|
|
861
861
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
862
862
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
863
863
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
864
|
-
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,
|
|
864
|
+
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,IR=`${V("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
865
865
|
|
|
866
866
|
${V("Usage")}
|
|
867
867
|
npx anyray-connect <gateway-url> [options]
|
|
@@ -956,9 +956,8 @@ ${V("Options")}
|
|
|
956
956
|
public key at the control plane for a
|
|
957
957
|
signed cert, then mints a short-lived personal gateway key
|
|
958
958
|
from it \u2014 no SSO, no need to also pass --gateway. The cert +
|
|
959
|
-
local key
|
|
960
|
-
|
|
961
|
-
Keychain reference, mode 600); a re-run re-mints a fresh key from the stored cert
|
|
959
|
+
local private key are saved (~/.anyray/dev-key.pem, mode
|
|
960
|
+
600); a re-run re-mints a fresh key from the stored cert
|
|
962
961
|
without re-enrolling until the cert expires. Defaults
|
|
963
962
|
--user/--team from the cert. --dry-run skips enrollment (no
|
|
964
963
|
key minted). Set $ANYRAY_CP_ORIGIN (https, or a
|
|
@@ -1064,22 +1063,22 @@ ${V("What it does")}
|
|
|
1064
1063
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
1065
1064
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
1066
1065
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
1067
|
-
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,
|
|
1068
|
-
${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?`}`,
|
|
1069
|
-
${o} ${n} tool target(s)?`;return await(r.confirm??Ea)(a)?"proceed":"declined"},e5=async(e=Da)=>{let t=await e({force:!0,respectFailureBackoff:!0,allowNpmMigration:!0});switch(t.outcome){case"current":case"updated":case"migrated":case"container":case"unmanaged":return"ok";case"available":case"migration-available":case"migration-deferred":case"disabled":case"platform-unsupported":case"unavailable":case"failed":return"failed";default:return t.outcome}},t5=async()=>{let e=!1,t=await Xt({runAmbientSelfcheck:!0});await cp(),await yE(),await gE()==="retry"&&(e=!0);let n=await D().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await oe(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await Co().catch(()=>!1);if(n&&(await CR(t,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey)){let o=n.gateway,a=n.clientKey,s=Mt(),i=n.enrolledCert;if(s&&i){let l=await Ne().catch(()=>{});l&&await rS(o,a,i,l,s).catch(()=>{})}await vR(o,a,{execute:async(l,d)=>{let u;return l==="remint"||l==="reapply_config"?u=await Xt({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?u=await ER(d):l==="update"?u=await e5():u=(await mu()).ok?"ok":"failed",u==="failed"&&(e=!0),u}}).catch(()=>{})}return r||await Da(),{refresh:t,...e?{partial:!0}:{}}},n5=async e=>{if(e[0]==="__anyray-hook"){let r=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return zx(r)}if(e[0]==="__anyray-codex-hook")return qx();if(e[0]==="__anyray-prompt-hook")return a0();if(e[0]==="__anyray-shell-pretool")return l0();if(e[0]==="__anyray-shell-run")return c0(e.slice(1));if(e[0]==="__anyray-read-pretool")return g0();if(e[0]==="__anyray-sso-gate")return o0(e.slice(1));if(e[0]==="__anyray-sso-poll")return C0();if(e[0]==="__anyray-managed-enroll")try{return await Ja(()=>b0(A0((r,o)=>NR(r,!1,{managedEnrollmentRevertedTools:o}))),{waitMs:DR})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return x0();if(e[0]==="__anyray-spawn-refresh")return await Cr(),0;if(e[0]==="__anyray-mcp-server"){let r=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return N0(r)}if(e[0]==="__anyray-acp-agent")return $0(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return bR(e.slice(1));let t=G0(e);if(t)return V0(t,{refresh:t5});if(e[0]==="__anyray-persistence")return Aw(e.slice(1));if(e[0]==="__anyray-quit-watch")return Kv(e.slice(1));if(e[0]===hr)return KE(e.slice(1));if(e[0]===Vs)return ZE(e.slice(1));if(e[0]===Fd){let r=e[1];return r&&await Ud(r),0}if(e[0]==="--version"||e[0]==="-V")return I0();try{let r=await $g(e);if(r!==void 0)return r}catch(r){return O(`Could not persist anyray-connect for long-lived integrations: ${r instanceof Error?r.message:String(r)}`),1}if(zJ(e)){let r=XJ(await sx());r?.level==="warn"?_(r.message):r&&console.error(r.message)}if(e[0]==="managed")return vS(e.slice(1));if(e[0]==="endpoint")return wR(e.slice(1));if(e[0]==="print-key")return CE(e.slice(1));if(e[0]==="models")return vE(e.slice(1));if(e[0]==="copilot-login")return SE(e.slice(1));if(e[0]==="desktop"){let r=e.slice(1),o=Gm(r);return o?sg(o,!1):yI(r)}if(e[0]==="retrieve")return wI(e.slice(1));if(e[0]==="recall")return bI(e.slice(1));if(e[0]==="history")return _I(e.slice(1));if(e[0]==="migrate")return DI(e.slice(1));if(e[0]==="login")return v0(e.slice(1));if(e[0]==="update")return E0(e.slice(1));let n=e[0];if(n&&YJ.has(n)){let r=e.slice(1),o;try{o=TR(r)}catch(a){return O(a.message),A("\nRun `npx anyray-connect --help` for usage."),1}return o.help?(A(o.helpAll?OR:RR),0):n==="status"?px({gateway:o.gateway}):n==="doctor"?au({gateway:o.gateway,json:o.json,verify:o.verify,noVerify:o.noVerify,quick:o.quick,repair:o.repair,securityReview:o.securityReview}):n==="sync"?bx({gateway:o.gateway}):n==="device-url"?OE():sg(r,!0)}return sg(e,!1)},LR=async e=>{try{return await n5(e)}catch(t){if(t instanceof mt)return console.error(v("Cancelled.")),130;throw t}},NR=async(e,t,n={})=>{let r=n.isInteractive??Bt,o;try{o=TR(e)}catch(T){return O(T.message),A("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return A(o.helpAll?OR:RR),0;if(o.revert&&(o.sso||o.enroll||o.claim))return O("--revert cannot be combined with --sso, --enroll or --claim. It removes Anyray configuration; re-run with --sso <link> --yes (without --revert) to configure a new CLI."),1;if(o.project)return o.sso||o.enroll||o.subscription||o.upstream?(O("--project cannot be combined with --sso/--enroll (per-machine enrollment) or --subscription/--upstream (per-dev credential lanes). It writes an org-lane, credential-free repo config."),1):GE({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return O("--upstream and --upstream-key go together: the URL says where your personal key is valid, the key is what the gateway forwards there."),1;if(o.upstream&&(o.subscription||o.placeholder))return O("--upstream cannot be combined with --subscription or --org: BYO passthrough sends your personal upstream key \u2014 not a seat OAuth token, and never the org's server-held key."),1;let a;if(o.upstream){let T;try{T=new URL(o.upstream.trim())}catch{return O(`invalid --upstream URL: "${o.upstream}"`),1}if(T.protocol!=="http:"&&T.protocol!=="https:")return O(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let N=o.upstreamKey.trim();if(!N)return O("--upstream-key must not be empty."),1;a={url:Wt(o.upstream),key:N}}let s=await D();!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream);let i=!t&&Bt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??KJ)(o,s),c=!0);let l;try{if(l=_J(o.tools),n.managedEnrollmentRevertedTools){let T=[...n.managedEnrollmentRevertedTools,...s.revertedTools??[]];l=w0(l,T)}}catch(T){return O(T.message),1}A(V(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&Ei(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,A("That looks like an enrollment link \u2014 treating it as --enroll."));let d,u,p,f,h=!1;if(o.enroll){let T=Xd(o.enroll);if(T&&(!o.gateway||s.enrolledCert||Xm(T.token)))try{let N=await xi("Resolving enrollment link\u2026",()=>WI(T)),J=!o.gateway;J&&(o.gateway=N.gatewayUrl),d=N.deploymentId,u=N.email,p=N.provisioningKind,f=N.provisioningProofMode,h=!0,J&&$(`Enrollment link${N.org?` for ${N.org}`:""}: gateway ${N.gatewayUrl}`),N.seatMode&&!o.subscription&&(o.subscription=!0,$("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(N){if(Xm(T.token))return O(N instanceof Error?N.message:String(N)),1;let J=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(J)$(`Could not resolve the gateway from the enrollment link \u2014 using ${J}.`);else return O(N instanceof Error?N.message:String(N)),1}}let m,w;if(o.claim&&!o.revert)if(o.dryRun)$("dry run: not enrolled (skipped redeeming the enrollment link).");else{let T=cS(o.claim);if(!T)return O("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let N=await xi("Connecting this machine\u2026",()=>lS({cpOrigin:T.cpOrigin,claim:T.claim,gatewayUrl:o.gateway}));m={cert:N.cert,privateKeyPem:N.privateKeyPem},N.deploymentId&&(d=N.deploymentId),!o.gateway&&N.gatewayUrl&&(o.gateway=N.gatewayUrl),w=N.ssoLink}catch(N){return O(N instanceof Error?N.message:String(N)),1}}if(o.sso&&!m&&!o.revert)if(o.dryRun)$("dry run: not enrolled via SSO (skipped minting a personal key).");else{let T=vt(o.sso);if(!T)return O(Ei(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 N=await md({cpOrigin:T.cpOrigin,tenantId:T.tenantId,gatewayUrl:o.gateway,log:ue=>$(ue),open:r()?Ta:void 0}),J=await xi("Waiting for SSO sign-in\u2026",()=>yd(N,{gatewayUrl:o.gateway}));m={cert:J.cert,privateKeyPem:J.privateKeyPem},J.deploymentId&&(d=J.deploymentId),!o.gateway&&J.gatewayUrl&&(o.gateway=J.gatewayUrl)}catch(N){return O(N instanceof Error?N.message:String(N)),1}}let y=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;y&&(o.gateway=y);let g;try{g=Qt(o.gateway)}catch(T){return O(T.message),1}let b,k;y&&!o.revert&&$(`Gateway: ${g} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&cg(g)&&_(`${g} 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 C=process.env.ANYRAY_CLIENT_KEY?.trim(),S=C||DJ(s),E,I,R,P,W,q,de=async T=>{await go();let N=eS(T.token),J=oS(s.enrolledCert,s.enrolledCertExpiry,T.deploymentId,Date.now(),N,s.enrolledTokenHash,T.expectedUser),ue=J?await Ne():void 0,qt=Mt()||void 0,K=J&&ue&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:ue,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,De=et=>aS({cpOrigin:T.cpOrigin,token:T.token,gatewayOrigin:g,email:T.email,team:T.team,machineId:T.machineId,deploymentId:T.deploymentId,machineUuid:qt,deviceProofFor:f==="macos-bootstrap"?ZI:void 0,reuse:et?K:void 0}),dt=!!K,Ye=await(async()=>{try{return await De(dt)}catch(et){if(K&&f==="macos-bootstrap"&&et instanceof lo)return $("the saved device certificate no longer matches this Mac's Keychain key \u2014 re-enrolling from scratch\u2026"),dt=!1,await De(!1);if(K&&et instanceof ht&&et.policyCode!=="managed_device_required")return $("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),dt=!1,await De(!1);throw et}})();S=Ye.clientKey,o.user=Cu(o.user,Ye.user),o.team=Cu(o.team,Ye.team),E=Ye.cert,I=Ye.cert.payload.expiresAt,q=Ye.expiresAt,W=void 0,dt||(R=Ye.privateKeyPem),dt||(P=N),M(`Enrolled${Ye.user?` as ${Ye.user}`:""}${dt?" (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)$("dry run: not enrolled (skipped minting a personal key).");else{let T=Xd(o.enroll);if(!T){let N=FI(o.enroll);return O(N?`that is ${N.what}, not an enrollment link \u2014 re-run with ${N.flag} instead of --enroll.`:vt(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 N=o.machine?Ed():void 0,J=p==="mdm"&&!u?jI():void 0;J&&A(o.user?.trim()&&o.user.trim()!==J?"Ignoring --user: enrolling as the email your MDM assigned to this machine.":"Enrolling as the email your MDM assigned to this machine.");let ue=u??J??TJ(o.user);if(!o.machine&&!o.user&&!u&&!J){let K=LE();K.distinct||(_(` Enrolling as "${K.identity}" \u2014 this may not be unique to you.`),_(K.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"),_(K.reason==="machine_default"?" this image would enroll as the same person and their spend would merge.":" enroll under the same name and their spend would merge."),_(" Re-run with `--user you@company.com` (or set `git config --global"),_(" user.email`) so your usage is attributed to you."))}let qt=o.machine?`machine:${N}`:h?ue:void 0;await de({cpOrigin:T.cpOrigin,token:T.token,email:ue,team:o.team,machineId:N,deploymentId:d,expectedUser:qt})}catch(N){return O(N instanceof Error?N.message:String(N)),N instanceof ht&&N.policyCode!=="managed_device_required"&&$("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(m){await go();try{let T=Mt()||void 0,N=await Jt(g,m.cert,m.privateKeyPem,{machineUuid:T});S=N.key,o.user=Cu(o.user,N.user),o.team=Cu(o.team,N.team),E=m.cert,I=m.cert.payload.expiresAt,R=m.privateKeyPem,q=N.expiresAt;let J=o.sso?vt(o.sso):void 0;W=J?`${J.cpOrigin}/sso/${J.tenantId}`:w,M(`Enrolled${N.user?` as ${N.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(T){return O(T instanceof Error?T.message:String(T)),T instanceof ht&&T.policyCode!=="managed_device_required"&&$("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 T=o.yes;b=await $E(o.user,s.name,T),k=await ME(o.team,s.team,T)}if(!o.revert&&!o.dryRun){let T=lx(await cx(g,S),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if(T.lane){let N=T.lane==="subscription";o.subscription=N,o.placeholder=!N;let J=N?"your own subscription seat":"the organization's provider account";T.overrodeFlag?$(`Your administrator assigns this machine to ${J}, so that is what was applied (it overrides the lane flag you passed).`):$(`Billing lane set by your administrator: ${J}.`)}}let ie;!o.revert&&!o.subscription&&!o.placeholder&&(ie=await fn(),U("Detecting your sign-ins"),A(` Claude (Anthropic): ${a?Qe("BYO upstream key (passthrough)"):ie.anthropic?Qe("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),A(` Codex (ChatGPT): ${ie.openai?Qe("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),!ie.anthropic&&!ie.openai&&!ie.copilot&&Br()&&(_(" No subscription sign-ins found on this host. Sign-ins do not cross the"),_(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),_(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),_(" and re-run, or everything below routes on the org key instead.")));let j=Ie({origin:g,placeholderKey:o.key,clientKey:S,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:ie,user:b,team:k,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),ge=o.revert===!0&&(o.tools?.length??0)===0,he={dryRun:o.dryRun,fullRevert:ge};if(!o.revert&&j.clientKey&&!Ee(j.clientKey))return O("Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key."),1;if(!o.revert&&!j.clientKey){U("Enrollment required");let T="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(_(` ${T}`),$(" Dry run only \u2014 no placeholder configuration will be written."),await IR(l,"after-enrollment"),$(`
|
|
1070
|
-
Dry run complete \u2014 no files were written.`),0):(O(` ${T}`),1)}o.revert||
|
|
1071
|
-
Dry run \u2014 no files will be written.`);let F=await
|
|
1072
|
-
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(F==="declined")return $(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 T=await Jd(
|
|
1073
|
-
Gateway ${
|
|
1066
|
+
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,oJ=e=>{let t=e?.trim();return t||_h()},Cu=(e,t)=>t||e,ER=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"--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},aJ=e=>!e||e.length===0?le:e.map(t=>{let n=mt(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${le.map(r=>r.id).join(", ")}`);return n}),sJ=(e,t)=>{if(U("Gateway target"),A(` Origin: ${et(e.origin)}`),e.byoUpstream)A(` Auth: BYO upstream key ${v(`(passthrough to ${e.byoUpstream.url}; Claude Code, OpenCode)`)}`),e.clientKey&&A(` Client key: personal gateway key (${Tt(e.clientKey)}) ${v("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=ee(e,"anthropic")?et("your subscription"):"org key",r=ee(e,"openai")?et("your subscription"):"org key";A(` Auth: auto ${v("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&A(` Client key: personal gateway key (${Tt(e.clientKey)})`)}else e.authMode==="subscription"?(A(` Auth: subscription pass-through ${v("(seat OAuth token; Claude Code + Codex + verified macOS Claude Desktop)")}`),e.clientKey&&A(` Client key: personal gateway key (${Tt(e.clientKey)}) ${v("rides x-anyray-api-key")}`)):e.clientKey?A(` Auth: personal gateway key (${Tt(e.clientKey)}) ${v("(replaces the placeholder)")}`):A(` Enrollment: ${v("required before a real apply (no configuration will be written)")}`);e.authMode!=="placeholder"&&t.some(n=>n.id==="cursor")&&A(` Cursor: ${et("native Team subscription")} ${v("(Claude/Opus inference remains Cursor-hosted; Anyray hooks/MCP optimize supported local context)")}`),t.some(n=>n.id==="claude-desktop")&&(ee(e,"anthropic")?(A(` Claude Desktop: ${et("subscription-backed Gateway lane")} ${v("(verified macOS builds; Windows fails closed)")}`),A(` ${v("Uses the Claude Code Keychain credential on demand; the first-party Desktop lane remains direct.")}`)):(A(` Claude Desktop: ${et("third-party API lane")} ${v("(API-billed; switches the active local inference profile)")}`),A(` ${v("The first-party Claude subscription remains untouched.")}`))),A(` Attribution: ${ue(e.metadata)??v("(none \u2014 pass --user)")}`)},kR=async(e,t)=>{U("Selected tools");for(let n of e){let r=await n.detect();r.installed?A(` ${n.title} ${v(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):$(` ${n.title} ${v(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},iJ=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!Ee(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},cJ={loadDevKey:$e,saveDevKey:Ji,clearDevKey:Ya,saveProfile:oe},lJ=async(e,t,n,r=cJ,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}},dJ=async(e,t,n,r,o)=>{let a=0,s=[],i=[],c=[],l=[],d=[];for(let u of e){if(!(await u.detect()).installed&&!r){d.push(u.title);continue}U(`${u.title} ${v(`(${u.id})`)}`);try{let f=r?await u.revert(n):await u.apply(t,{...n,explicit:o?.has(u.id)===!0,reportsToUser:!0});for(let m of f.messages)A(` ${m}`);a+=f.changedFiles?.length??0,l.push({id:u.id,status:f.status}),f.status==="configured"||f.status==="reverted"?M(` ${f.status}`):f.status==="manual"?(s.push(u.title),f.manualAudience==="admin"?(i.push(u.title),c.push(u.id),_(" blocked by machine policy \u2014 your IT team owns this one")):_(" manual step required (see above)")):f.status==="held"?$(" left on its own plan (no change)"):$(` ${f.status}`)}catch(f){l.push({id:u.id,status:"failed"}),O(` failed: ${f instanceof Error?f.message:String(f)}`)}}if(d.length>0&&$(`Skipped ${d.length} not installed (${d.join(", ")})`),!n.dryRun){let u=await ec().catch(()=>[]);u.length&&$(` Removed ${u.length} unused Anyray runtime copies.`)}return{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l}},uJ=(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},pJ=(e,t,n)=>{if(t.revert)return[];if((t.tools?.length??0)>0)return[];let r=new Set(n??[]);return e.filter(o=>xR(o)&&!r.has(o.id))},fJ=async e=>{let t=gE(e,process.platform,Q());if(t){await we(t.path,t.content);for(let n of wE(t,process.platform))A(` ${n}`)}},mJ=async(e,t,n=vR())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!sb(i,n)||!ab(i,n))continue;let c=rb(i,n);if(!o.has(c)){try{if(!(await a.detect()).installed||!s.isRunning()||await a.pointsAt?.(t)===!0)continue}catch{continue}o.add(c),r.push({id:a.id,title:ob(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},hJ=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,yJ=e=>`
|
|
1067
|
+
${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?`}`,gJ=async(e,t={})=>{let n=t.requestQuit??(a=>cb(a)),r=t.waitFor??(a=>lb(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),M(` Closed ${a.title}.`);continue}_(` ${a.title} is still open \u2014 leaving it alone.`),$(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},wJ=(e,t={})=>{let n=t.relaunch??(o=>db(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),M(` Reopened ${o.title}.`)):_(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},xR=e=>e.changesBilling===!0||e.changesOrgManagement===!0,RR=e=>e.changesBilling===!0?"moves inference spend from your subscription to the org API bill":e.changesOrgManagement===!0?"switches the app to third-party mode; claude.ai Enterprise org settings stop applying":void 0,ng=e=>!xR(e),bJ=async(e,t,n={})=>{let r=n.hasEnrollment??Nu,o=n.canMultiSelect??KE,a=n.multiSelect??jE,s=n.prompt??Ea,i=n.registry??le;if(A(V("Anyray connect \u2014 guided setup")),A(v("Point your local coding tools at the Anyray gateway. Ctrl-C to abort.")),await r())A("Stored enrollment will be reused. Run with --revert to clear it.");else if(!e.enroll&&!e.sso&&!e.gateway){U("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 yt;c=d.values[0]}else{A(" 1. Paste an enrollment link"),A(" 2. Sign in with SSO"),A(" 3. I already have a gateway URL");let d=await s("? Connection method (1-3)","1");c=d==="1"?"enroll":d==="2"?"sso":d==="3"?"gateway":void 0}c||_("Choose one of the three connection methods.")}if(!c)throw new yt;for(let l=0;l<3;l++)if(c==="enroll"){let d=await s("? Enrollment link or token");if(d&&ci(d)&&pd(d)){e.enroll=d;break}_("That is not a valid enrollment link or token. Try again.")}else if(c==="sso"){let d=await s("? SSO link or tenant id");if(d&&St(d)){e.sso=d;break}_("That is not a valid SSO link or tenant id. Try again.")}else{let d=await s("? Gateway URL",t.gateway||process.env.ANYRAY_GATEWAY_URL);if(d&&ci(d)){e.enroll=d,A("That looks like an enrollment link \u2014 using passwordless enrollment.");break}try{if(!d)throw new Error("missing gateway");e.gateway=Qt(d);break}catch{_("That is not a valid http(s) gateway URL. Try again.")}}if(!e.enroll&&!e.sso&&!e.gateway)throw new yt}if(!e.tools||e.tools.length===0){U("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=>ng(u)).map(u=>u.id);if(c.length>0){for(let u=0;u<3&&!e.tools;u++){let p;if(o()){let f=await a({title:"Tools to configure",items:c.map(m=>({value:m.id,label:`${m.title} (${m.id})`,hint:RR(m),selected:ng(m),requiresExplicitChoice:!ng(m)}))});if(f.kind==="cancelled")throw new yt;p=f.values}else{p=(await s("? Tools to configure (comma-separated, blank = all suggested)",d.join(",")||void 0)??"").split(",").map(w=>w.trim()).filter(Boolean);let m=new Set(c.map(w=>w.id)),h=p.filter(w=>!m.has(w));if(h.length>0){_(`Unknown or unavailable tool id${h.length===1?"":"s"}. Choose from: ${c.map(w=>w.id).join(", ")}.`);continue}}if(p.length===0){_("Choose at least one installed tool.");continue}e.tools=p}if(!e.tools)throw new yt}l.length>0&&$(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},AJ=async(e,t)=>{U("Verifying the connection");let n=await Ei("Checking the gateway\u2026",()=>_i(e,{tools:t}));n.kind==="ok"?M(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?_(` ${n.detail}`):O(` ${n.detail}`);for(let r of n.remedy)A(v(` ${r}`))},CJ=async(e,t={})=>{if(e.dryRun)return;let n=t.install??tr,r=t.uninstall??nr;if(e.want&&e.trayManaged){U("Automatic key refresh"),M(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh.");return}if(e.want){let o=await n();U("Automatic key refresh");for(let a of o.messages)A(` ${a}`);o.ok&&M(" Your gateway key now renews every ~30 min \u2014 no tool will 401 on a stale key mid-session."),o.ok||await oe({...await D(),refreshSchedulerEnabled:!1});return}if(!e.scopedRevert&&e.wasEnabled){U("Automatic key refresh");let o=await r();for(let a of o.messages)A(` ${a}`);await oe({...await D(),refreshSchedulerEnabled:!1}),M(" Removed the automatic key-refresh schedule.")}},kJ=new Set(["login","wizard","status","doctor","sync","device-url"]),vJ=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint"]),SJ=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."}},IJ=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=Gh(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]||!vJ.has(e[0])},rg=async(e,t)=>{try{return await _R(e,t)}catch(n){if(n instanceof yt)return console.error(v("Cancelled \u2014 nothing was written.")),130;if(n instanceof Error&&n.message==="connect profile is busy; retry the command")return O("Another Connect update is in progress. Try again."),1;throw n}},OR=12e4,EJ=async(e,t,n,r=Ja)=>e&&!t?r(n,{waitMs:OR}):n(),xJ=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??Ft)())return"non-interactive";let o=e.revert?"remove Anyray config from":"configure",a=t?"Apply this configuration?":`
|
|
1068
|
+
${o} ${n} tool target(s)?`;return await(r.confirm??Ia)(a)?"proceed":"declined"},RJ=async(e=Da)=>{let t=await e({force:!0,respectFailureBackoff:!0,allowNpmMigration:!0});switch(t.outcome){case"current":case"updated":case"migrated":case"container":case"unmanaged":return"ok";case"available":case"migration-available":case"migration-deferred":case"disabled":case"platform-unsupported":case"unavailable":case"failed":return"failed";default:return t.outcome}},OJ=async()=>{let e=!1,t=await zt({runAmbientSelfcheck:!0});await cp(),await AI(),await CI()==="retry"&&(e=!0);let n=await D().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await oe(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await Ao().catch(()=>!1);if(n&&(await gR(t,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey)){let o=n.gateway,a=n.clientKey,s=Bt(),i=n.enrolledCert;if(s&&i){let l=await $e().catch(()=>{});l&&await iS(o,a,i,l,s).catch(()=>{})}await bR(o,a,{execute:async(l,d)=>{let u;return l==="remint"||l==="reapply_config"?u=await zt({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?u=await CR(d):l==="update"?u=await RJ():u=(await hu()).ok?"ok":"failed",u==="failed"&&(e=!0),u}}).catch(()=>{})}return r||await Da(),{refresh:t,...e?{partial:!0}:{}}},TJ=async e=>{if(e[0]==="__anyray-hook"){let r=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return Zx(r)}if(e[0]==="__anyray-codex-hook")return Yx();if(e[0]==="__anyray-prompt-hook")return t0();if(e[0]==="__anyray-shell-pretool")return a0();if(e[0]==="__anyray-shell-run")return o0(e.slice(1));if(e[0]==="__anyray-read-pretool")return f0();if(e[0]==="__anyray-sso-gate")return e0(e.slice(1));if(e[0]==="__anyray-sso-poll")return g0();if(e[0]==="__anyray-managed-enroll")try{return await Ja(()=>h0(y0((r,o)=>_R(r,!1,{managedEnrollmentRevertedTools:o}))),{waitMs:OR})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return v0();if(e[0]==="__anyray-spawn-refresh")return await Cr(),0;if(e[0]==="__anyray-mcp-server"){let r=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return _0(r)}if(e[0]==="__anyray-acp-agent")return P0(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return hR(e.slice(1));let t=F0(e);if(t)return W0(t,{refresh:OJ});if(e[0]==="__anyray-persistence")return gw(e.slice(1));if(e[0]==="__anyray-quit-watch")return Uv(e.slice(1));if(e[0]===mr)return YI(e.slice(1));if(e[0]===Vs)return XI(e.slice(1));if(e[0]===Fd){let r=e[1];return r&&await Ud(r),0}if(e[0]==="--version"||e[0]==="-V")return k0();try{let r=await Dg(e);if(r!==void 0)return r}catch(r){return O(`Could not persist anyray-connect for long-lived integrations: ${r instanceof Error?r.message:String(r)}`),1}if(IJ(e)){let r=SJ(await nx());r?.level==="warn"?_(r.message):r&&console.error(r.message)}if(e[0]==="managed")return xS(e.slice(1));if(e[0]==="endpoint")return mR(e.slice(1));if(e[0]==="print-key")return II(e.slice(1));if(e[0]==="models")return xI(e.slice(1));if(e[0]==="copilot-login")return RI(e.slice(1));if(e[0]==="desktop"){let r=e.slice(1),o=Gh(r);return o?rg(o,!1):bE(r)}if(e[0]==="retrieve")return CE(e.slice(1));if(e[0]==="recall")return kE(e.slice(1));if(e[0]==="history")return LE(e.slice(1));if(e[0]==="migrate")return $E(e.slice(1));if(e[0]==="login")return b0(e.slice(1));if(e[0]==="update")return C0(e.slice(1));let n=e[0];if(n&&kJ.has(n)){let r=e.slice(1),o;try{o=ER(r)}catch(a){return O(a.message),A("\nRun `npx anyray-connect --help` for usage."),1}return o.help?(A(o.helpAll?IR:SR),0):n==="status"?cx({gateway:o.gateway}):n==="doctor"?au({gateway:o.gateway,json:o.json,verify:o.verify,noVerify:o.noVerify,quick:o.quick,repair:o.repair,securityReview:o.securityReview}):n==="sync"?hx({gateway:o.gateway}):n==="device-url"?DI():rg(r,!0)}return rg(e,!1)},TR=async e=>{try{return await TJ(e)}catch(t){if(t instanceof yt)return console.error(v("Cancelled.")),130;throw t}},_R=async(e,t,n={})=>{let r=n.isInteractive??Ft,o;try{o=ER(e)}catch(T){return O(T.message),A("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return A(o.helpAll?IR:SR),0;if(o.revert&&(o.sso||o.enroll||o.claim))return O("--revert cannot be combined with --sso, --enroll or --claim. It removes Anyray configuration; re-run with --sso <link> --yes (without --revert) to configure a new CLI."),1;if(o.project)return o.sso||o.enroll||o.subscription||o.upstream?(O("--project cannot be combined with --sso/--enroll (per-machine enrollment) or --subscription/--upstream (per-dev credential lanes). It writes an org-lane, credential-free repo config."),1):jI({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return O("--upstream and --upstream-key go together: the URL says where your personal key is valid, the key is what the gateway forwards there."),1;if(o.upstream&&(o.subscription||o.placeholder))return O("--upstream cannot be combined with --subscription or --org: BYO passthrough sends your personal upstream key \u2014 not a seat OAuth token, and never the org's server-held key."),1;let a;if(o.upstream){let T;try{T=new URL(o.upstream.trim())}catch{return O(`invalid --upstream URL: "${o.upstream}"`),1}if(T.protocol!=="http:"&&T.protocol!=="https:")return O(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let L=o.upstreamKey.trim();if(!L)return O("--upstream-key must not be empty."),1;a={url:Ht(o.upstream),key:L}}let s=await D();!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream);let i=!t&&Ft()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??bJ)(o,s),c=!0);let l;try{if(l=aJ(o.tools),n.managedEnrollmentRevertedTools){let T=[...n.managedEnrollmentRevertedTools,...s.revertedTools??[]];l=m0(l,T)}}catch(T){return O(T.message),1}A(V(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&ci(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,A("That looks like an enrollment link \u2014 treating it as --enroll."));let d,u,p,f,m=!1;if(o.enroll){let T=pd(o.enroll);if(T&&(!o.gateway||s.enrolledCert||Zm(T.token)))try{let L=await Ei("Resolving enrollment link\u2026",()=>eS(T)),J=!o.gateway;J&&(o.gateway=L.gatewayUrl),d=L.deploymentId,u=L.email,p=L.provisioningKind,f=L.allowedDomains,m=!0,J&&$(`Enrollment link${L.org?` for ${L.org}`:""}: gateway ${L.gatewayUrl}`),L.seatMode&&!o.subscription&&(o.subscription=!0,$("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(L){if(Zm(T.token))return O(L instanceof Error?L.message:String(L)),1;let J=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(J)$(`Could not resolve the gateway from the enrollment link \u2014 using ${J}.`);else return O(L instanceof Error?L.message:String(L)),1}}let h,w;if(o.claim&&!o.revert)if(o.dryRun)$("dry run: not enrolled (skipped redeeming the enrollment link).");else{let T=pS(o.claim);if(!T)return O("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let L=await Ei("Connecting this machine\u2026",()=>fS({cpOrigin:T.cpOrigin,claim:T.claim,gatewayUrl:o.gateway}));h={cert:L.cert,privateKeyPem:L.privateKeyPem},L.deploymentId&&(d=L.deploymentId),!o.gateway&&L.gatewayUrl&&(o.gateway=L.gatewayUrl),w=L.ssoLink}catch(L){return O(L instanceof Error?L.message:String(L)),1}}if(o.sso&&!h&&!o.revert)if(o.dryRun)$("dry run: not enrolled via SSO (skipped minting a personal key).");else{let T=St(o.sso);if(!T)return O(ci(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 md({cpOrigin:T.cpOrigin,tenantId:T.tenantId,gatewayUrl:o.gateway,log:pe=>$(pe),open:r()?Ta:void 0}),J=await Ei("Waiting for SSO sign-in\u2026",()=>hd(L,{gatewayUrl:o.gateway}));h={cert:J.cert,privateKeyPem:J.privateKeyPem},J.deploymentId&&(d=J.deploymentId),!o.gateway&&J.gatewayUrl&&(o.gateway=J.gatewayUrl)}catch(L){return O(L instanceof Error?L.message:String(L)),1}}let y=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;y&&(o.gateway=y);let g;try{g=Qt(o.gateway)}catch(T){return O(T.message),1}let b,k;y&&!o.revert&&$(`Gateway: ${g} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&ag(g)&&_(`${g} 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 C=process.env.ANYRAY_CLIENT_KEY?.trim(),S=C||iJ(s),I,E,R,P,W,q,de=async T=>{await yo();let L=rS(T.token),J=cS(s.enrolledCert,s.enrolledCertExpiry,T.deploymentId,Date.now(),L,s.enrolledTokenHash,T.expectedUser),pe=J?await $e():void 0,ut=Bt()||void 0,j=J&&pe&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:pe,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,_e=pt=>lS({cpOrigin:T.cpOrigin,token:T.token,gatewayOrigin:g,email:T.email,team:T.team,machineId:T.machineId,deploymentId:T.deploymentId,machineUuid:ut,reuse:pt?j:void 0}),Ce=!!j,Je=await(async()=>{try{return await _e(Ce)}catch(pt){if(j&&pt instanceof lt&&pt.policyCode!=="managed_device_required")return $("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),Ce=!1,await _e(!1);throw pt}})();S=Je.clientKey,o.user=Cu(o.user,Je.user),o.team=Cu(o.team,Je.team),I=Je.cert,E=Je.cert.payload.expiresAt,q=Je.expiresAt,W=void 0,Ce||(R=Je.privateKeyPem),Ce||(P=L),M(`Enrolled${Je.user?` as ${Je.user}`:""}${Ce?" (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)$("dry run: not enrolled (skipped minting a personal key).");else{let T=pd(o.enroll);if(!T){let L=Qv(o.enroll);return O(L?`that is ${L.what}, not an enrollment link \u2014 re-run with ${L.flag} instead of --enroll.`:St(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?Sd():void 0,J=p==="mdm"&&!u?GE():void 0,pe=p==="mdm"&&!u&&!J?UE(f,Dd()):void 0,ut=J??pe;if(ut){let Ce=J?"the email your MDM assigned to this machine":`${ut} (this Mac's login name at the first allowed domain)`;A(o.user?.trim()&&o.user.trim()!==ut?`Ignoring --user: enrolling as ${Ce}.`:`Enrolling as ${Ce}.`)}let j=u??ut??oJ(o.user);if(!o.machine&&!o.user&&!u&&!ut){let Ce=MI();Ce.distinct||(_(` Enrolling as "${Ce.identity}" \u2014 this may not be unique to you.`),_(Ce.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"),_(Ce.reason==="machine_default"?" this image would enroll as the same person and their spend would merge.":" enroll under the same name and their spend would merge."),_(" Re-run with `--user you@company.com` (or set `git config --global"),_(" user.email`) so your usage is attributed to you."))}let _e=o.machine?`machine:${L}`:m?j:void 0;await de({cpOrigin:T.cpOrigin,token:T.token,email:j,team:o.team,machineId:L,deploymentId:d,expectedUser:_e})}catch(L){return O(L instanceof Error?L.message:String(L)),L instanceof lt&&L.policyCode!=="managed_device_required"&&$("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."),aS(L)?3:1}}if(h){await yo();try{let T=Bt()||void 0,L=await Xt(g,h.cert,h.privateKeyPem,{machineUuid:T});S=L.key,o.user=Cu(o.user,L.user),o.team=Cu(o.team,L.team),I=h.cert,E=h.cert.payload.expiresAt,R=h.privateKeyPem,q=L.expiresAt;let J=o.sso?St(o.sso):void 0;W=J?`${J.cpOrigin}/sso/${J.tenantId}`:w,M(`Enrolled${L.user?` as ${L.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(T){return O(T instanceof Error?T.message:String(T)),T instanceof lt&&T.policyCode!=="managed_device_required"&&$("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 T=o.yes;b=await FI(o.user,s.name,T),k=await WI(o.team,s.team,T)}if(!o.revert&&!o.dryRun){let T=ax(await ox(g,S),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if(T.lane){let L=T.lane==="subscription";o.subscription=L,o.placeholder=!L;let J=L?"your own subscription seat":"the organization's provider account";T.overrodeFlag?$(`Your administrator assigns this machine to ${J}, so that is what was applied (it overrides the lane flag you passed).`):$(`Billing lane set by your administrator: ${J}.`)}}let ie;!o.revert&&!o.subscription&&!o.placeholder&&(ie=await fn(),U("Detecting your sign-ins"),A(` Claude (Anthropic): ${a?et("BYO upstream key (passthrough)"):ie.anthropic?et("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),A(` Codex (ChatGPT): ${ie.openai?et("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),!ie.anthropic&&!ie.openai&&!ie.copilot&&Br()&&(_(" No subscription sign-ins found on this host. Sign-ins do not cross the"),_(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),_(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),_(" and re-run, or everything below routes on the org key instead.")));let K=xe({origin:g,placeholderKey:o.key,clientKey:S,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:ie,user:b,team:k,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),ge=o.revert===!0&&(o.tools?.length??0)===0,me={dryRun:o.dryRun,fullRevert:ge};if(!o.revert&&K.clientKey&&!Ee(K.clientKey))return O("Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key."),1;if(!o.revert&&!K.clientKey){U("Enrollment required");let T="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(_(` ${T}`),$(" Dry run only \u2014 no placeholder configuration will be written."),await kR(l,"after-enrollment"),$(`
|
|
1069
|
+
Dry run complete \u2014 no files were written.`),0):(O(` ${T}`),1)}o.revert||sJ(K,l),c&&!o.revert&&await kR(l,"plan"),o.dryRun&&$(`
|
|
1070
|
+
Dry run \u2014 no files will be written.`);let F=await xJ(o,c,l.length,{isInteractive:r,confirm:n.confirm});if(F==="non-interactive")return O(`
|
|
1071
|
+
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(F==="declined")return $(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 T=await Jd(K.origin);if(!T.reachable)return O(`
|
|
1072
|
+
Gateway ${K.origin} is not reachable (${T.detail}).`),A(v(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
|
|
1074
1073
|
that would break them until you re-run with --revert.`)),A(`
|
|
1075
|
-
Start the gateway and try again, or pass --force to configure anyway.`),1;M(`Gateway reachable (${T.detail}).`)}let Z=o.revert?[]:await
|
|
1076
|
-
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),A("Run --revert with no --tools to remove it."));let
|
|
1077
|
-
Remove them from the repo (then commit):`),A(v(" anyray-connect --project --revert")));let
|
|
1078
|
-
Fix this terminal:`),A(v(` unset ${
|
|
1079
|
-
Every other open terminal needs the same \u2014 or just open a new one.`),A(" VS Code injects a copy it captured when IT launched, so its"),A(" terminals stay stale even if you open a new one: quit the app"),A(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(M(`Done (${
|
|
1080
|
-
Skipped the connection smoke test (--skip-verify).`):await
|
|
1081
|
-
Re-test by hand any time:`),
|
|
1082
|
-
-H "x-anyray-api-key: $(anyray-connect print-key)"`)),A(v(" Validate Opus itself inside Cursor: keep the Team login, select a native Claude Opus model, and run an Agent prompt."))):A(v(` curl -sS ${
|
|
1074
|
+
Start the gateway and try again, or pass --force to configure anyway.`),1;M(`Gateway reachable (${T.detail}).`)}let Z=o.revert?[]:await mJ(l,K.origin),X=[],Ye=()=>{X.length!==0&&(U("Reopening"),wJ(X),X=[])};if(Z.length>0){let T=Z.map(J=>J.title),L=T.length===1?"it":"them";if(U("Open apps"),hJ(o,Ft()))o.quitApps===!0||await Ia(yJ(T))?X=await gJ(Z):$(` Leaving ${L} open \u2014 restart when convenient.`);else{let J=o.noQuitApps===!0?"":" (or pass --quit-apps)";$(o.dryRun?` Would offer to quit ${T.join(", ")} \u2014 dry run, nothing was closed.`:` ${T.join(", ")} ${T.length===1?"is":"are"} open; restart ${L} to pick this up${J}.`)}}let We=async()=>{if(!o.dryRun)try{await tt()}catch{return O("Could not prepare the owner-only Anyray state directory."),1}let T=yI(s,q),L=s.anyrayFleetManaged===!0&&await Ao().catch(()=>!1),J=iR(o,vR(),L),pe=!!(C&&K.clientKey===C&&!I),ut=!pe&&!!(I??s.enrolledCert),j=l.some(Ne=>hI.has(Ne.id)),_e=!o.revert&&o.noKeyRefresh!==!0&&ut&&(T||!j),Ce=o.dryRun?await Po(s):await cp(),Je=Ce==="healthy";if(Ce==="healed"&&(delete s.persistenceOwner,delete s.trayAppPath),!o.revert&&!o.dryRun){let Ne={...s,managedEnrollmentDisabled:void 0,gateway:K.origin,name:b,team:k,clientKey:K.clientKey??s.clientKey,enrolledCert:pe?void 0:I??s.enrolledCert,enrolledCertExpiry:pe?void 0:E??s.enrolledCertExpiry,enrolledTokenHash:pe?void 0:P??s.enrolledTokenHash,ssoLink:pe?void 0:h?W:I?void 0:s.ssoLink,clientKeyExpiresAt:pe?void 0:q??(K.clientKey===s.clientKey?.trim()?s.clientKeyExpiresAt:void 0),authMode:K.authMode,byoUpstream:K.byoUpstream,refreshSchedulerEnabled:_e};try{await lJ(s,Ne,R,void 0,pe)}catch{return O("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}q&&!pe&&await Sa({expiresAt:q})}if(ge)if(o.dryRun)await Nu()&&(U("Enrollment"),A(" would remove the stored gateway credential"));else{await Wy(s),await Pd().catch(()=>{});try{await Xi()&&(U("Enrollment"),M(" Removed the stored gateway credential."),$(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(Ne){U("Enrollment"),_(" Could not remove the stored gateway credential."),_(` Delete ${Q()} by hand, or a credential refresh may restore your tool config.`)}}else o.revert&&!o.dryRun&&(A(`
|
|
1075
|
+
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),A("Run --revert with no --tools to remove it."));let pt=l,Or=pJ(pt,o,s.managedTools);if(Or.length>0){U("Not configured \u2014 needs your say-so");for(let Ie of Or)_(` ${Ie.id}: ${RR(Ie)??"changes where inference is billed"}.`),A(` Configure it deliberately with \`npx anyray-connect --tools ${Ie.id}\`.`);let Ne=new Set(Or.map(Ie=>Ie.id));pt=pt.filter(Ie=>!Ne.has(Ie.id))}if(o.revert&&!ge){let Ne=l.filter(Ie=>di(s,Ie.id));if(Ne.length>0){U("Fleet policy");for(let Ie of Ne)_(` ${Ie.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);pt=l.filter(Ie=>!di(s,Ie.id))}}let{changes:Gi,manual:Wa,manualAdminOnly:Vi,manualAdminOnlyIds:Ha,results:Ua}=await dJ(pt,K,me,o.revert,new Set(o.tools??[])),Ga;if(Xy(o)){U("Endpoint agent");try{Ga=await(n.installEndpointAfterEnrollment??yR)({gateway:g,clientKey:K.clientKey})}catch{$("Endpoint agent setup did not complete. Tool routing remains configured.")}}let ko=J&&sR(Ga),Va=_e&&!ko;if(J&&!ko&&_e&&!o.dryRun&&$(" The machine is not under endpoint policy, so automatic key refresh stays on this seat."),ko&&!o.dryRun&&await oe({...await D(),refreshSchedulerEnabled:!1}).catch(()=>{}),o.dryRun||(await Vn(Ua,o.revert,ge).catch(()=>{}),ge&&await zi().catch(()=>{})),await CJ({want:Va,scopedRevert:!!o.revert&&!ge,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!Va&&await kc(),trayManaged:Je}),!o.revert&&!o.dryRun&&!pe){let Ne=R??await $e();Ne&&await Ih(await D(),Ne).catch(()=>{})}if(Ye(),U("Summary"),o.dryRun)$("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){M(`Reverted (${Gi} file(s) touched).`),$("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let Ne=await KI();Ne.length>0&&(U("This repo carries its own Anyray routing"),_(` Committed here: ${Ne.join(", ")}`),_(" Those are tracked files, so they route every checkout of this"),_(" repo \u2014 this machine included, and your teammates' too. This"),_(" revert only removed THIS machine's own configuration."),A(`
|
|
1076
|
+
Remove them from the repo (then commit):`),A(v(" anyray-connect --project --revert")));let Ie=Nc(K);Ie.length>0&&(U("This terminal still points at the gateway"),_(` Still exported here: ${Ie.join(", ")}`),_(" Removing the block from your shell profile cannot reach a shell"),_(" that already ran it. Until these are gone, your tools keep"),_(" reaching the gateway and now fail with 401."),A(`
|
|
1077
|
+
Fix this terminal:`),A(v(` unset ${Ie.join(" ")}`)),A(`
|
|
1078
|
+
Every other open terminal needs the same \u2014 or just open a new one.`),A(" VS Code injects a copy it captured when IT launched, so its"),A(" terminals stay stale even if you open a new one: quit the app"),A(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(M(`Done (${Gi} file(s) written).`),Wa.length>0){let xt=Vi.length===Wa.length;U(xt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let og of uJ(Wa,Vi,Ha.includes("claude-desktop")?process.platform:void 0))_(og);if(Ha.includes("claude-desktop")&&!o.dryRun)try{await fJ(K)}catch{_(" Could not write the administrator profile locally. Your admin can generate it with `anyray-connect desktop fleet static macos <helper-path> --gateway <url>`.")}Ft()&&!o.yes&&!xt&&(await Ia("Have you applied the manual settings shown above?")?M("Acknowledged."):_("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}o.skipVerify?$(`
|
|
1079
|
+
Skipped the connection smoke test (--skip-verify).`):await AJ(K,l.map(xt=>xt.id)),U("What's next");let Ne=new Set(Ua.filter(xt=>xt.status==="configured").map(xt=>xt.id)),Ie=l.filter(xt=>Ne.has(xt.id)).map(xt=>xt.title);if(A(Ie.length>0?` Connected: ${Ie.join(", ")}`:" Connected: no tools completed automatic configuration."),A(" Restart any editor that was already running \u2014 it loaded our config at startup."),A(" If something looks wrong: npx anyray-connect doctor"),!o.verbose)return 0;A(`
|
|
1080
|
+
Re-test by hand any time:`),K.authMode!=="placeholder"&&l.length===1&&l[0]?.id==="cursor"?(A(v(` curl -sS ${K.origin}/connect/savings \\
|
|
1081
|
+
-H "x-anyray-api-key: $(anyray-connect print-key)"`)),A(v(" Validate Opus itself inside Cursor: keep the Team login, select a native Claude Opus model, and run an Agent prompt."))):A(v(` curl -sS ${K.openaiBaseUrl}/chat/completions \\
|
|
1083
1082
|
-H "Content-Type: application/json" \\
|
|
1084
|
-
-H "Authorization: Bearer ${
|
|
1085
|
-
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),A(v(" Revert: npx anyray-connect --revert"))}return 0};try{return await
|
|
1083
|
+
-H "Authorization: Bearer ${K.clientKey?`<your personal key (${Tt(K.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
|
|
1084
|
+
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),A(v(" Revert: npx anyray-connect --revert"))}return 0};try{return await EJ(o.revert,o.dryRun,We,n.withProfileLock)}catch(T){if(T instanceof Error&&T.message==="connect profile is busy; retry the command")return O("Another Connect update is in progress. Try again."),1;throw T}finally{Ye()}};TR(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});
|