anyray-connect 0.11.173 → 0.11.174
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 +207 -207
- package/package.json +1 -1
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 he(o,e),await
|
|
5
|
-
`,{mode:384})}catch(s){throw await Io(t,{recursive:!0,force:!0}).catch(()=>{}),s}return async()=>{try{JSON.parse(await Ya(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
|
|
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=
|
|
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}},ow=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"?ow():e==="claude"?rw():await rw()??await ow(),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(),GO);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 zn=()=>pc(uc(),".claude","settings.json"),dc=()=>pc(uc(),".claude.json"),VO=oc,Sn="anyray",KO=()=>({type:"stdio",...Ge("claude"),alwaysLoad:!0}),qn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),jO=e=>e instanceof Error?e.name:"UnknownError",ZO={unreadable:"mcp_unreadable",unwritable:"mcp_not_writable",foreign:"mcp_foreign","not-persisted":"mcp_not_persisted"},YO=(e,t)=>{switch(e){case"foreign":return`MCP name conflict in ${t}: mcpServers.${Sn} is not owned by Anyray Connect, so it was left untouched. Rename or remove that entry, then re-run anyray-connect.`;case"unreadable":return`Could not read ${t}, so the Anyray retrieval MCP server was not registered; anyray_retrieve is unavailable until that file is readable.`;case"unwritable":return`Could not write ${t}, so the Anyray retrieval MCP server was not registered; anyray_retrieve is unavailable until that file is writable.`;case"not-persisted":return`Registered the Anyray retrieval MCP server in ${t}, but the entry was gone when re-read \u2014 Claude Code rewrites that file wholesale while it runs. Fully quit Claude Code, then re-run anyray-connect.`}},JO={readJson:M,writeJson:(e,t)=>Y(e,t)},XO=async(e,t=JO)=>{for(let n=0;n<2;n+=1){let r;try{r=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}if(zO(r)==="conflict")return{outcome:"failed",failure:"foreign"};try{await t.writeJson(e,r)}catch{return{outcome:"failed",failure:"unwritable"}}let o;try{o=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}let a=o.mcpServers,s=qn(a)?a[Sn]:void 0;if(s&&Ot(s,"claude"))return{outcome:"registered"}}return{outcome:"failed",failure:"not-persisted"}},zO=e=>{if("mcpServers"in e&&!qn(e.mcpServers))return"conflict";let t=qn(e.mcpServers)?{...e.mcpServers}:{},n=t[Sn];return n!==void 0&&!Ot(n,"claude")?"conflict":(t[Sn]=KO(),e.mcpServers=t,"installed")},aw=e=>{let t=e.mcpServers;return!t||!(Sn in t)||!Ot(t[Sn],"claude")?!1:(delete t[Sn],Object.keys(t).length===0&&delete e.mcpServers,!0)},qO=e=>{tc(e,"PostToolUse",ze,kn(Rt(ze),{matcher:"*"})),tc(e,"UserPromptSubmit",Yn,kn(Rt(Yn)))},QO=e=>{tc(e,"SessionStart",Jn,kn(Rt(Jn),{async:!0}))},cw=e=>Oo(e,"SessionStart",Jn),sw=e=>{let t=Oo(e,"PostToolUse",ze),n=Oo(e,"UserPromptSubmit",Yn),r=cw(e);return t||n||r},eT="print-key",tT=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Oe()),Br=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===eT&&tT(t)},nT=async(e,t)=>{let n=(await Dr(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},rT=e=>typeof e.apiKeyHelper=="string"&&!Br(e),lw=async e=>{let t=await Xu(),n=async()=>t,[r,o,a]=await Promise.all([Yg({userSettings:e,readManaged:n}),ew({userSettings:e,readManaged:n}).catch(()=>[]),Qg({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},iw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await lw(e),o=Ju(t),a=nw(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:tw(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?zn():"no ~/.claude directory"}},async apply(e,t){let n=zn(),r=await M(n),o=Gg(r),a=await Vg(e.origin,e.clientKey,o),s=Kg(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=tn(e,{contextWindowTokens:s.envTokens}),{directOverrides:p,hookPolicy:f}=await lw(r),m=p.filter(O=>!O.repairable),h=p.filter(O=>O.repairable),w=[...m.map(O=>`WARNING: ${Yu(O)}.`),...m.length?[Ju(m)]:[],...f.state==="fine"?[]:[`WARNING: ${sc(f)}.`,ic(f)],...h.map(O=>Jg(O)),`${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:O}of vn)h.some(F=>F.name===O)?g[O]="":g[O]===""&&(process.env[O]??"").trim()===""&&delete g[O];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 O of Hg)delete g[O];let b=!!e.clientKey,k=te(),C=rT(r);!c&&!l&&b&&k&&!C?(r.apiKeyHelper=Ug(),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).")):Br(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?(QO(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):cw(r),te()?(qO(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.")):(sw(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(),T;if(te()){let O=await XO(E);O.outcome==="registered"?(I.push(E),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.")):(w.push(YO(O.failure,E)),T=ZO[O.failure])}else try{let O=await M(E);aw(O)&&(await Y(E,O),I.push(E))}catch(O){w.push(`Could not clean up a stale Anyray MCP registration in ${E} (${jO(O)}).`)}return{status:"configured",messages:w,changedFiles:I,...T?{errorClass:T}:{}}},skillsDir(){return pc(uc(),".claude","skills")},async pointsAt(e){let t=zn();if(!await x(t))return!1;try{let o=(await M(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await M(zn()).catch(()=>({}));return iw(e)},async routingOverrides(){let e=await M(zn()).catch(()=>({}));return(await iw(e)).routingOverrides},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=dc();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let r=(await M(e)).mcpServers?.[Sn];return r?Ot(r,"claude")?{registered:!0,command:typeof r.command=="string"?r.command:null}:{registered:!1,command:null,reason:"foreign"}:{registered:!1,command:null,reason:"absent"}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async integrationStatus(){let e,t=!0,n=zn();if(!await x(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!qn(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>Zn(c,ze))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>Zn(c,ze)&&qn(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>qn(l)&&nc(l.command,ze))))}}catch{e="unreadable"}let r,o=!0,a=dc();if(!await x(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!qn(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Sn];r=i===void 0?"missing":Ot(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 $r()?"owned":"missing",beacon_target:await cc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await M(zn()),t=qn(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=zn();if(!await x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await M(t),r=n.env,o=sw(n),a=Br(n);a&&delete n.apiKeyHelper;let s=r?await nT(t,r):[],i=jg(typeof n.model=="string"?n.model:void 0,(await Dr(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 M(l);aw(d)&&(await Y(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await oe(t),{status:"reverted",messages:c,changedFiles:[t]}}};var er=e=>{let{command:t,args:n}=en([e]);return{command:t,args:n}},tr=()=>Nr();import{homedir as qu,platform as uw}from"node:os";import{join as fc}from"node:path";import{mkdir as aT,rm as pw,writeFile as sT,link as iT,copyFile as cT,readFile as fX}from"node:fs/promises";import{spawnSync as lT}from"node:child_process";import{homedir as dw,userInfo as oT}from"node:os";var rs=()=>{try{return dw()!==oT().homedir}catch{return!1}},zu=e=>[`Skipped ${e} \u2014 HOME (${dw()}) 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",os="Anyray",fw=(e=qu())=>fc(e,"Applications",`${os}.app`),mw="anyray-connect",dT=e=>`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
var BR="http://localhost:8787",ja="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,FR=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),dg=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!FR.has(n)}catch{return!1}},Qt=e=>{let t=Ht(e||process.env.ANYRAY_GATEWAY_URL||BR),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()||ja,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 rp}from"node:os";import{join as Ur}from"node:path";import{mkdir as tp,readFile as wT,rename as bT,writeFile as mc,rm as Wr}from"node:fs/promises";import{spawnSync as AT}from"node:child_process";import{homedir as uc}from"node:os";import{join as pc}from"node:path";import{access as ZR,chmod as YR,mkdir as Su,open as Ou,readFile as wg,rm as Gt,stat as fg,utimes as JR}from"node:fs/promises";import{createHash as XR,randomUUID as bg}from"node:crypto";import{dirname as Tu,join as zR}from"node:path";import{isDeepStrictEqual as vo}from"node:util";import{randomUUID as WR}from"node:crypto";import{lstat as UR,open as HR,readFile as vu,rename as Ki,rm as GR,writeFile as VR}from"node:fs/promises";import{platform as ug}from"node:os";var pg=e=>e?.code==="ENOENT",KR=new Set(["EBUSY","EXDEV","ETXTBSY"]),Kn=async(e,t=ug())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},jR=async(e,t,n={})=>{let r=await vu(e),o;try{o=await vu(t)}catch(s){if(!pg(s))throw s;await VR(t,r);return}let a=async s=>{let i=await HR(t,"r+");try{await i.write(s,0,s.length,0),await i.truncate(s.length),await Kn(i)}finally{await i.close()}};try{if(await a(r),await n.corruptAfterWrite?.(t),!(await vu(t)).equals(r))throw Object.assign(new Error("in-place publication did not persist"),{code:"EIO"})}catch(s){throw await a(o).catch(()=>{}),s}},he=async(e,t,n=ug(),r={})=>{let o=r.rename??Ki;if(n!=="win32"){try{await o(e,t)}catch(i){if(!KR.has(i?.code??""))throw i;await jR(e,t,r)}return}let a=`${t}.anyray-old-${process.pid}-${WR()}`,s=!1;try{let i=await UR(t);if(!i.isFile()&&!i.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await Ki(t,a),s=!0}catch(i){if(!pg(i))throw i}try{await Ki(e,t)}catch(i){if(s)try{await Ki(a,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${a}`)}throw i}s&&await GR(a,{force:!0})};var Za=e=>`${e}.anyray-bak`,Ag=async e=>{let t;try{t=await Ou(Tu(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},mg=async(e,t)=>{let n,r;try{n=await Ou(e,"wx",384),await n.writeFile(t,"utf-8"),await Kn(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Gt(e,{force:!0}).catch(()=>{}),r;await Ag(e)},qR=async e=>{let t;try{t=await Ou(e,"r"),await Kn(t)}finally{await t?.close().catch(()=>{})}await Ag(e)},x=async e=>{try{return await ZR(e),!0}catch{return!1}},M=async e=>{if(!await x(e))return{};let t=await wg(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 Su(Tu(e),{recursive:!0,mode:448});let r=Za(e);if(n.backup!==!1&&!await x(r)){let a=await x(e),s=a?await wg(e,"utf-8"):`{}
|
|
3
|
+
`;if(a||n.tombstoneAbsent!==!1)try{await mg(r,s)}catch(i){if(i.code!=="EEXIST")throw i}}let o=`${e}.anyray-tmp-${process.pid}-${bg()}`;try{await mg(o,`${JSON.stringify(t,null,2)}
|
|
4
|
+
`),await he(o,e),await YR(e,384),await qR(e)}finally{await Gt(o,{force:!0}).catch(()=>{})}},Cg=1,hg=3e4,QR=5e3,eO=/^[a-f0-9]{64}$/,kg=e=>`${e}.pending`,tO=e=>`${e}.lock`,Iu=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=>Iu(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Iu(t[n])}`).join(",")}}`},Eu=(e,t)=>({exists:e,sha256:XR("sha256").update(Iu(t)).digest("hex")}),xu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),yg=e=>xu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&eO.test(e.sha256),nO=e=>xu(e)&&e.transactionVersion===Cg&&yg(e.before)&&yg(e.after)&&xu(e.journal),Ru=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,So=async(e,t)=>{try{return await M(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},rO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},vg=async e=>{let t=tO(e),n=zR(t,"owner.json");await Su(Tu(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=bg();try{await Su(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 fg(n)).mtimeMs;i=!rO(c.pid)||l>hg}catch{try{i=Date.now()-(await fg(t)).mtimeMs>hg}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Gt(t,{recursive:!0,force:!0});continue}try{await Y(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Gt(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 JR(n,i,i)}catch{}})()},QR);return a.unref(),async()=>{clearInterval(a);try{(await So(n,"ownership journal")).nonce===o&&await Gt(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},Sg=async e=>{let t=await x(e),n={};if(t)try{n=await M(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:Eu(t,n)}},Ig=async(e,t)=>{let n=kg(t);if(!await x(n))return;let r=await So(n,"prepared ownership transaction");if(!nO(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await Sg(e),a=await x(t),s=await x(Za(e)),i=Ru(o.fingerprint,r.before),c=Ru(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 Gt(n,{force:!0});return}if(i){await Gt(n,{force:!0}),a||await oe(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},ji=async(e,t,n)=>{let r=await vg(t);try{return await Ig(e,t),await n()}finally{await r()}},gg=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 Gt(e,{force:!0})}},Zi=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await vg(a);try{await Ig(n,a);let l=await Sg(n),d=Eu(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(!Ru(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(Za(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=kg(a),w={transactionVersion:Cg,before:l.fingerprint,after:Eu(!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 Gt(h,{force:!0})}catch(y){try{await gg(n,l.value,l.exists,o)}catch(g){throw new AggregateError([y,g],"ownership journal publication failed and config rollback was incomplete")}try{await gg(a,p??{},u,f),await Gt(h,{force:!0}),!m&&!p&&await oe(n)}catch(g){throw new AggregateError([y,g],"ownership journal publication failed after config rollback")}throw y}}finally{await c()}},Dr=async e=>{try{return await M(Za(e))}catch{return{}}},oe=async e=>{await Gt(Za(e),{force:!0}).catch(()=>{})};import{access as RO}from"node:fs/promises";import{spawnSync as fO}from"node:child_process";import{readFileSync as mO,realpathSync as za,statSync as Lg}from"node:fs";import{access as hO,cp as Ng,mkdir as Pg,readdir as yO,readFile as Fu,realpath as gO,rename as wO,rm as Mu,writeFile as bO}from"node:fs/promises";import{tmpdir as AO}from"node:os";import{basename as Eo,dirname as Ue,join as Re,resolve as CO}from"node:path";import{writeFile as Yi,readFile as Ya,chmod as Du,stat as Lu,mkdir as Rg,rm as Io}from"node:fs/promises";import{AsyncLocalStorage as oO}from"node:async_hooks";import{randomUUID as aO}from"node:crypto";import{homedir as Og}from"node:os";import{join as Lr}from"node:path";var Q=()=>Lr(Og(),".anyray"),Tg=async()=>{let e=Q();try{if((await Lu(e)).isDirectory())return Lr(e,"connect.json")}catch{}return e},Nu=()=>Lr(Q(),"dev-key.pem"),tt=async()=>{let e=Q(),t;try{if(!(await Lu(e)).isDirectory())t=await Ya(e,"utf-8").catch(()=>{}),await Io(e,{force:!0});else return}catch{}if(await Rg(e,{recursive:!0,mode:448}),t!==void 0){let n=Lr(e,"connect.json");await Yi(n,t,{mode:384}),await Du(n,384)}},Ji=async e=>{await tt();let t=Nu();await Yi(t,e,{mode:384}),await Du(t,384)},$e=async()=>{try{let e=await Ya(Nu(),"utf-8");return e.trim()?e:void 0}catch{return}},Ja=async()=>{await Io(Nu(),{force:!0}).catch(()=>{})},D=async()=>{try{let e=await Ya(await Tg(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:t}catch{return{}}},sO=0,iO=3e4,cO=5e3,lO=25,dO=()=>Lr(Og(),".anyray-connect-profile.lock"),_u=new oO,uO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},pO=async e=>{try{let t=JSON.parse(await Ya(Lr(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!uO(t.pid)}catch{}return Date.now()-(await Lu(e)).mtimeMs>iO},_g=async(e=cO)=>{let t=dO(),n=Lr(t,"owner.json"),r=Date.now()+e;for(;;){let o=aO();try{await Rg(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 Ya(n,"utf-8")).nonce===o&&await Io(t,{recursive:!0,force:!0})}catch{}}}catch(s){if(s.code!=="EEXIST")throw s}if(!(await pO(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,lO))}}},Xa=async(e,t={})=>{if(_u.getStore()===!0)return e();let n=await _g(t.waitMs);try{return await _u.run(!0,e)}finally{await n()}},Eg=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await Tg(),r=`${n}.${process.pid}.${sO++}.tmp`;await Yi(r,`${JSON.stringify(t,null,2)}
|
|
6
|
+
`,{mode:384}),await Du(r,384);try{await he(r,n)}catch(o){throw await Io(r,{force:!0}).catch(()=>{}),o}},ae=async e=>{if(_u.getStore()===!0){await Eg(e);return}let t=await _g();try{await Eg(e)}finally{await t()}};var Pu=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],xg="ssoLink",$u=async()=>{let e=await D();return Pu.some(t=>e[t]!==void 0)?!0:await $e()!==void 0},Xi=async()=>{let e=await D(),t=Pu.some(a=>e[a]!==void 0),n=e[xg]!==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 Pu)delete a[s];delete a[xg],delete a.byoUpstream,a.managedEnrollmentDisabled=!0,delete a.anyrayFleetManaged,await ae(a)}if(await Ja(),await $e())throw new Error(`could not remove the dev key from ${Q()}`);return t||n||r||o},jn=async(e,t,n=!1)=>{let r=await 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 ae({...f,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},zi=async(e=new Date().toISOString())=>{await ae({...await D(),offboardedAt:e})};var xo=e=>CO(e).replace(/\\/g,"/").toLowerCase(),Bu=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",qa=e=>`${e}.source`,$g=e=>/(^|\/)_npx(\/|$)/.test(xo(e)),Wu=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(xo(e)),Uu=e=>{let t=xo(e),n=[AO(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(xo);return $g(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),Zn=(e=ft())=>Qa(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,Dg=e=>{try{let t=Lg(e);return t.isFile()?t.size:void 0}catch{return}},Hu=e=>{let t=Ue(e);if(Eo(t)==="versions")return t;let n=Ue(t);return Eo(n)==="versions"?n:void 0},Qi=(e,t)=>t!==void 0&&(Ue(e)===t||Ue(Ue(e))===t),kO=e=>{let t=Hu(e);if(!t)return;let n=Re(Ue(t),"bin",Bu());try{let r=za(n);return r===za(e)||Qi(r,za(t))?n:void 0}catch{return}},Ro=(e=Q(),t=process.platform)=>{let n=Re(e,"bin",Bu(t));try{let r=za(n),o=za(Re(e,"versions"));if(Qi(r,o))return n;if(t==="win32"){let a=mO(qa(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=Dg(Re(o,a,Bu(t)))??Dg(Re(o,a));if(s!==void 0&&s===Lg(n).size)return n}}catch{return}},Nr=(e=ft())=>{let t=Zn(e),n=Wu(t)||Vu(t)?Ro():void 0;return kO(e.execPath)??n??t},Mg=(e=ft())=>Nr(e)!==Zn(e),en=(e,t=ft())=>{let n=Nr(t);return Qa(t.execPath)&&t.scriptPath!==void 0&&n===Zn(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},Bg=(e=ft())=>{let t=Nr(e);return!Qa(e.execPath)&&!Uu(t)?Ue(t):Re(Q(),"bin")},qi=async e=>{try{return await hO(e),!0}catch{return!1}},vO=async e=>{let t=await gO(e),n=Ue(t),r=Ue(n),o=Re(r,"package.json"),a=await Fu(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}},SO=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=Ue(n);if(o===n)return;n=o}},IO=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await Fu(Re(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await SO(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await Ng(i,Re(t,s),{recursive:!0}),r.push(i)}}},EO=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 vO(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 Mu(a,{recursive:!0,force:!0}),await Pg(a,{recursive:!0,mode:448});try{await Ng(n.dist,Re(a,"dist"),{recursive:!0}),await bO(Re(a,"package.json"),await Fu(n.packageJson),{mode:384}),await IO(n.root,Re(a,"node_modules")),await Pg(Ue(r),{recursive:!0,mode:448});try{await wO(a,r)}catch(s){if(!await qi(o))throw s}}finally{await Mu(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},Gu=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,xO=e=>{let t=Eo(Ue(Ue(e)));return Gu.test(t)?t:void 0},Vu=(e,t=Q())=>{let n=Ue(Ue(e));return xo(Ue(n))===xo(Re(t,"bin"))&&Gu.test(Eo(n))&&Eo(Ue(e))==="dist"&&Eo(e)==="index.js"},ec=async(e=ft())=>{let t=Re(Q(),"bin"),n=xO(Zn(e)),r=[];for(let o of await yO(t).catch(()=>[])){if(!Gu.test(o)||o===n)continue;let a=Re(t,o);await Mu(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},Fg=async(e,t=ft())=>{let n=Zn(t);if(!Qa(t.execPath)||!$g(n)||Ro())return;let r=await EO(t),o=fO(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var Ku=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,es=(e,t)=>[e,...t].map(Ku).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}:{}}]}),Yn=(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=>!Yn(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=>!Yn(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)},ju=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=>!Yn(s,"__anyray-"));a.length!==o.length&&(n=!0,a.length?t[r]=a:delete t[r])}return n&&Object.keys(t).length===0&&delete e.hooks,n};var ze="__anyray-hook",Wg="__anyray-codex-hook",Jn="__anyray-prompt-hook",Ug="__anyray-shell-pretool",Zu="__anyray-shell-run",Hg="__anyray-read-pretool",Xn="__anyray-refresh",ts=(e,t=[])=>{let{command:n,args:r}=en([e,...t]);return{command:n,args:r}},Rt=(e,t=[])=>{let n=ts(e,t);return[n.command,...n.args].map(Ku).join(" ")},nc=(e,t,n=[])=>typeof e=="string"&&e.trim()===Rt(t,n),Gg=()=>Rt("print-key"),Oe=()=>Nr(),He=Uu,te=()=>!He(Oe()),$r=async()=>{if(!te())return!1;try{return await RO(Oe()),!0}catch{return!1}},zn="__anyray-mcp-server",Ge=e=>ts(zn,[e]),OO=(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&&OO(n.args,r.args)},Ot=(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)===zn&&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 Mr=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],Vg=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],oc=[...Mr,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],TO=(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=TO(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 Yu}from"zod";var _O=5e3,PO=1e3,DO=1e8,LO=Yu.object({modelContext:Yu.object({contextTokens:Yu.number().int().min(PO).max(DO)}).optional()}),Kg=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},jg=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??_O,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=LO.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var NO=1e6,ns="[1m]",$O=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},Zg=(e,t)=>!e||t===void 0?{}:$O(e)?{envTokens:t}:t<NO?{}:e.toLowerCase().endsWith(ns)?{}:{model:`${e}${ns}`},Yg=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(ns))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(ns))return e.slice(0,-ns.length)};import{platform as MO}from"node:os";var Tt=(e=MO())=>{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()!=="",BO=(e,t)=>typeof e[t]=="string"&&!ac(e[t]),Jg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},FO=()=>M(Tt()).catch(()=>({})),Xg=async(e={})=>{let t=e.env??process.env,n=Jg(e.userSettings??{}),r=Jg(await(e.readManaged??FO)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of vn)ac(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Tt()})`,repairable:!1}):ac(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!BO(n,a)&&ac(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},Ju=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`,Xu=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.",zg=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 WO=vn.map(e=>e.name),UO=oc.filter(e=>!WO.includes(e)),qg=e=>typeof e=="string"&&e.trim()!=="",Qg=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},HO=(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)},GO=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},zu=()=>M(Tt()).catch(()=>({})),ew=zu,VO=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=>Yn(r,ze))},tw=async(e={})=>{let t=await(e.readManaged??ew)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!VO(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},sc=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Tt()}) \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 (${Tt()}), 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.",nw=async(e={})=>{let t=Qg(e.userSettings??{}),n=Qg(await(e.readManaged??ew)().catch(()=>({}))),r=[];for(let o of UO){if(!qg(n[o])||!qg(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(HO(n[o],t[o],a))continue;let s=a?GO(n[o]):void 0;r.push({name:o,source:`managed settings (${Tt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},rw=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`,ow=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 KO}from"node:os";import{join as jO}from"node:path";import{readFile as ZO}from"node:fs/promises";var YO=400,aw=async()=>{try{let e=jO(KO(),".claude","settings.json"),n=JSON.parse(await ZO(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}},sw=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"?sw():e==="claude"?aw():await aw()??await sw(),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(),YO);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 qn=()=>pc(uc(),".claude","settings.json"),dc=()=>pc(uc(),".claude.json"),JO=oc,Sn="anyray",XO=()=>({type:"stdio",...Ge("claude"),alwaysLoad:!0}),Qn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zO=e=>e instanceof Error?e.name:"UnknownError",qO={unreadable:"mcp_unreadable",unwritable:"mcp_not_writable",foreign:"mcp_foreign","not-persisted":"mcp_not_persisted"},QO=(e,t)=>{switch(e){case"foreign":return`MCP name conflict in ${t}: mcpServers.${Sn} is not owned by Anyray Connect, so it was left untouched. Rename or remove that entry, then re-run anyray-connect.`;case"unreadable":return`Could not read ${t}, so the Anyray retrieval MCP server was not registered; anyray_retrieve is unavailable until that file is readable.`;case"unwritable":return`Could not write ${t}, so the Anyray retrieval MCP server was not registered; anyray_retrieve is unavailable until that file is writable.`;case"not-persisted":return`Registered the Anyray retrieval MCP server in ${t}, but the entry was gone when re-read \u2014 Claude Code rewrites that file wholesale while it runs. Fully quit Claude Code, then re-run anyray-connect.`}},eT={readJson:M,writeJson:(e,t)=>Y(e,t)},tT=async(e,t=eT)=>{for(let n=0;n<2;n+=1){let r;try{r=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}if(nT(r)==="conflict")return{outcome:"failed",failure:"foreign"};try{await t.writeJson(e,r)}catch{return{outcome:"failed",failure:"unwritable"}}let o;try{o=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}let a=o.mcpServers,s=Qn(a)?a[Sn]:void 0;if(s&&Ot(s,"claude"))return{outcome:"registered"}}return{outcome:"failed",failure:"not-persisted"}},nT=e=>{if("mcpServers"in e&&!Qn(e.mcpServers))return"conflict";let t=Qn(e.mcpServers)?{...e.mcpServers}:{},n=t[Sn];return n!==void 0&&!Ot(n,"claude")?"conflict":(t[Sn]=XO(),e.mcpServers=t,"installed")},iw=e=>{let t=e.mcpServers;return!t||!(Sn in t)||!Ot(t[Sn],"claude")?!1:(delete t[Sn],Object.keys(t).length===0&&delete e.mcpServers,!0)},rT=e=>{tc(e,"PostToolUse",ze,kn(Rt(ze),{matcher:"*"})),tc(e,"UserPromptSubmit",Jn,kn(Rt(Jn)))},oT=e=>{tc(e,"SessionStart",Xn,kn(Rt(Xn),{async:!0}))},dw=e=>Oo(e,"SessionStart",Xn),cw=e=>{let t=Oo(e,"PostToolUse",ze),n=Oo(e,"UserPromptSubmit",Jn),r=dw(e);return t||n||r},aT="print-key",sT=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(Oe()),Br=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===aT&&sT(t)},iT=async(e,t)=>{let n=(await Dr(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of JO){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},cT=e=>typeof e.apiKeyHelper=="string"&&!Br(e),uw=async e=>{let t=await zu(),n=async()=>t,[r,o,a]=await Promise.all([Xg({userSettings:e,readManaged:n}),nw({userSettings:e,readManaged:n}).catch(()=>[]),tw({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},lw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await uw(e),o=Xu(t),a=ow(n);return{routingOverrides:[...t.map(i=>({problem:Ju(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:rw(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},er={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=pc(uc(),".claude"),t=await x(e);return{installed:t,detail:t?qn():"no ~/.claude directory"}},async apply(e,t){let n=qn(),r=await M(n),o=Kg(r),a=await jg(e.origin,e.clientKey,o),s=Zg(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=tn(e,{contextWindowTokens:s.envTokens}),{directOverrides:p,hookPolicy:f}=await uw(r),m=p.filter(O=>!O.repairable),h=p.filter(O=>O.repairable),w=[...m.map(O=>`WARNING: ${Ju(O)}.`),...m.length?[Xu(m)]:[],...f.state==="fine"?[]:[`WARNING: ${sc(f)}.`,ic(f)],...h.map(O=>zg(O)),`${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:O}of vn)h.some(F=>F.name===O)?g[O]="":g[O]===""&&(process.env[O]??"").trim()===""&&delete g[O];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 O of Vg)delete g[O];let b=!!e.clientKey,k=te(),C=cT(r);!c&&!l&&b&&k&&!C?(r.apiKeyHelper=Gg(),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).")):Br(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?(oT(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):dw(r),te()?(rT(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.")):(cw(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(),T;if(te()){let O=await tT(E);O.outcome==="registered"?(I.push(E),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.")):(w.push(QO(O.failure,E)),T=qO[O.failure])}else try{let O=await M(E);iw(O)&&(await Y(E,O),I.push(E))}catch(O){w.push(`Could not clean up a stale Anyray MCP registration in ${E} (${zO(O)}).`)}return{status:"configured",messages:w,changedFiles:I,...T?{errorClass:T}:{}}},skillsDir(){return pc(uc(),".claude","skills")},async pointsAt(e){let t=qn();if(!await x(t))return!1;try{let o=(await M(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await M(qn()).catch(()=>({}));return lw(e)},async routingOverrides(){let e=await M(qn()).catch(()=>({}));return(await lw(e)).routingOverrides},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=dc();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let r=(await M(e)).mcpServers?.[Sn];return r?Ot(r,"claude")?{registered:!0,command:typeof r.command=="string"?r.command:null}:{registered:!1,command:null,reason:"foreign"}:{registered:!1,command:null,reason:"absent"}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async integrationStatus(){let e,t=!0,n=qn();if(!await x(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!Qn(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>Yn(c,ze))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>Yn(c,ze)&&Qn(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>Qn(l)&&nc(l.command,ze))))}}catch{e="unreadable"}let r,o=!0,a=dc();if(!await x(a))r="missing";else try{let s=await M(a);if(s.mcpServers===void 0)r="missing";else if(!Qn(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Sn];r=i===void 0?"missing":Ot(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 $r()?"owned":"missing",beacon_target:await cc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await M(qn()),t=Qn(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=qn();if(!await x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await M(t),r=n.env,o=cw(n),a=Br(n);a&&delete n.apiKeyHelper;let s=r?await iT(t,r):[],i=Yg(typeof n.model=="string"?n.model:void 0,(await Dr(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 M(l);iw(d)&&(await Y(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await oe(t),{status:"reverted",messages:c,changedFiles:[t]}}};var tr=e=>{let{command:t,args:n}=en([e]);return{command:t,args:n}},nr=()=>Nr();import{homedir as Qu,platform as fw}from"node:os";import{join as fc}from"node:path";import{mkdir as dT,rm as mw,writeFile as uT,link as pT,copyFile as fT,readFile as wX}from"node:fs/promises";import{spawnSync as mT}from"node:child_process";import{homedir as pw,userInfo as lT}from"node:os";var rs=()=>{try{return pw()!==lT().homedir}catch{return!1}},qu=e=>[`Skipped ${e} \u2014 HOME (${pw()}) 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 ep="ai.anyray.connect.app",os="Anyray",hw=(e=Qu())=>fc(e,"Applications",`${os}.app`),yw="anyray-connect",hT=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
|
-
<key>CFBundleIdentifier</key><string>${
|
|
12
|
+
<key>CFBundleIdentifier</key><string>${ep}</string>
|
|
13
13
|
<key>CFBundleName</key><string>${os}</string>
|
|
14
14
|
<key>CFBundleDisplayName</key><string>${os}</string>
|
|
15
|
-
<key>CFBundleExecutable</key><string>${
|
|
15
|
+
<key>CFBundleExecutable</key><string>${yw}</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,7 +22,7 @@ var $R="http://localhost:8787",ja="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
|
+
`,yT="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",gT=e=>{try{mT(yT,["-f",e],{stdio:"ignore",timeout:1e4})}catch{}},gw=async(e={})=>{if((e.os??fw())!=="darwin")return{ok:!0,messages:[]};let n=e.home??Qu(),r=e.binaryPath??nr();if(He(r))return{ok:!1,messages:[`Skipped the Login Items identity app \u2014 anyray-connect is running from a temporary path (${r}).`]};if(rs())return{ok:!1,messages:["Skipped the Login Items identity app \u2014 HOME is redirected away from the real account."]};let o=hw(n),a=fc(o,"Contents","MacOS"),s=fc(a,yw),i=e.version??"0.0.0";try{await mw(o,{recursive:!0,force:!0}),await dT(a,{recursive:!0}),await uT(fc(o,"Contents","Info.plist"),hT(i),"utf8");try{await pT(r,s)}catch{await fT(r,s)}return(e.register??gT)(o),{ok:!0,messages:[`Registered ${os} 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.`]}}},ww=async(e={})=>{if((e.os??fw())!=="darwin")return{ok:!0,messages:[]};if(rs())return{ok:!0,messages:[]};let n=hw(e.home??Qu());try{return await mw(n,{recursive:!0,force:!0}),{ok:!0,messages:[`Removed ${os}.app.`]}}catch(r){return{ok:!1,messages:[`Could not remove the Login Items identity app (${r?.name??"Error"}).`]}}};var Ae="0.11.174";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,Fr=(e=process.env)=>nn(e)!==null,In=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 bw=()=>Ur(wc(),".anyray","logs"),np=()=>Ur(bw(),"connect-refresh.log"),gc=1800,bc="ai.anyray.connect.refresh",is="anyray-refresh",op="\\AnyrayConnectKeyRefresh",Ac=bc,cs=is,ss=op,CT=String(gc/60),ap=(e,t)=>{let n=AT(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},sp=()=>Ur(wc(),"Library","LaunchAgents",`${Ac}.plist`),ip=()=>Ur(wc(),".config","systemd","user"),Aw=()=>Ur(ip(),`${cs}.service`),yc=()=>Ur(ip(),`${cs}.timer`),hc=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Cc=()=>tr(Xn),kT=(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">
|
|
@@ -30,7 +30,7 @@ var $R="http://localhost:8787",ja="anyray-placeholder",Ee=e=>{let t=e?.trim();re
|
|
|
30
30
|
<key>Label</key><string>${Ac}</string>
|
|
31
31
|
<key>AssociatedBundleIdentifiers</key>
|
|
32
32
|
<array>
|
|
33
|
-
<string>${hc(
|
|
33
|
+
<string>${hc(ep)}</string>
|
|
34
34
|
</array>
|
|
35
35
|
<key>ProgramArguments</key>
|
|
36
36
|
<array>
|
|
@@ -40,18 +40,18 @@ ${r}
|
|
|
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>${hc(
|
|
44
|
-
<key>StandardErrorPath</key><string>${hc(
|
|
43
|
+
<key>StandardOutPath</key><string>${hc(np())}</string>
|
|
44
|
+
<key>StandardErrorPath</key><string>${hc(np())}</string>
|
|
45
45
|
</dict>
|
|
46
46
|
</plist>
|
|
47
|
-
`},
|
|
47
|
+
`},vT=(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
|
-
`},
|
|
54
|
+
`},ST=()=>`[Unit]
|
|
55
55
|
Description=Anyray connect gateway key refresh (every ${gc/60}m)
|
|
56
56
|
|
|
57
57
|
[Timer]
|
|
@@ -61,65 +61,65 @@ 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=Sc(r),a=
|
|
68
|
-
`),s=Sc(a),i=
|
|
64
|
+
`,IT=(e=Cc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),as=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(" ")}`],Cw=e=>!e.run&&rs(),ET=async(e,t)=>await wT(sp(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Ac]).ok,rr=async(e={})=>{let t=e.os??rp(),n=e.invocation??Cc(),r=e.run??ap,o=e.binaryPath??nr();if(He(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(Cw(e))return{ok:!1,messages:qu("auto-refresh scheduling")};let a=nn(e.env??(e.run?{}:process.env));if(In(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=sp(),i=kT(n);if(await ET(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`]};await tp(bw(),{recursive:!0,mode:448}),await tp(Ur(wc(),"Library","LaunchAgents"),{recursive:!0});let c=String(process.getuid?.()??""),l=await gw({os:t,binaryPath:o,version:Ae}),d=`${s}.new-${process.pid}`;await Wr(d,{force:!0}).catch(()=>{}),await mc(d,i),r("launchctl",["bootout",`gui/${c}`,s]),await Wr(s,{force:!0}).catch(()=>{});try{await bT(d,s)}catch{await mc(s,i),await Wr(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.`,...as(n)]}}if(t==="linux")return await tp(ip(),{recursive:!0}),await mc(Aw(),vT(n)),await mc(yc(),ST()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${cs}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${yc()}).`]}:{ok:!1,messages:[`Wrote ${yc()} but \`systemctl --user enable --now\` failed.`,...as(n)]};if(t==="win32"){let s=IT(n);return r("schtasks",["/Create","/TN",ss,"/TR",s,"/SC","MINUTE","/MO",CT,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",ss]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${ss}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...as(n)]}}return{ok:!1,messages:as(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...as(n)]}}},or=async(e={})=>{await Wr(np(),{force:!0}).catch(()=>{});let t=e.os??rp(),n=e.run??ap,r=[];if(Cw(e))return{ok:!0,messages:qu("scheduler teardown")};try{if(t==="darwin"){let o=sp(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Wr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.");let s=await ww();s.ok||r.push(...s.messages)}else t==="linux"?(n("systemctl",["--user","disable","--now",`${cs}.timer`]),await Wr(yc(),{force:!0}),await Wr(Aw(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",ss,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},_o=async(e=rp(),t=ap)=>e==="win32"?t("schtasks",["/Query","/TN",ss]).ok:e==="darwin"?t("launchctl",["list",Ac]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${cs}.timer`]).ok:!1;import{platform as xT}from"node:os";import{stat as RT}from"node:fs/promises";import{spawnSync as OT}from"node:child_process";var kw="/Applications/Anyray Connect Tray.app",TT=new Set(["V53XMA78UF"]),_T="ai.anyray.connect-tray",PT=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,DT=e=>{let t=OT("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
|
|
65
|
+
${t.stderr??""}`}},LT=async e=>{try{return(await RT(e)).isDirectory()}catch{return!1}},NT=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},cp=async(e,t={})=>{if((t.os??xT())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??LT)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??DT;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?NT(a.output):void 0;return s?TT.has(s)?PT(a.output)!==_T?{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 cp(n,t)).ok?"healthy":"gone"},lp=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??rr;return n.refreshSchedulerEnabled&&await o().catch(()=>{}),await(e.save??ae)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var $T={"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."},MT=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},BT=async(e,t)=>{let n=t.stderr??console.error,r=MT(e,"--app-path")??kw,o=await cp(r,t);if(!o.ok)return n($T[o.reason]),1;let s=await(t.load??D)();return await(t.save??ae)({...s,persistenceOwner:"tray",trayAppPath:r}),await(t.uninstallScheduler??or)().catch(()=>{}),0},FT=async e=>{let t=e.load??D,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??rr;return n.refreshSchedulerEnabled&&await r().catch(()=>{}),await(e.save??ae)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},vw=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await BT(e,t):e.includes("--release-tray")?await FT(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 WT}from"node:fs/promises";import{homedir as Sw,platform as dp}from"node:os";import{join as ls}from"node:path";var up=(e=dp(),t=Sw())=>{if(e==="darwin")return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:bc,paths:[ls(t,"Library","LaunchAgents",`${bc}.plist`)],dataPaths:[ls(t,".anyray","logs","connect-refresh.log")]}];if(e==="linux"){let n=ls(t,".config","systemd","user");return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:`${is}.timer`,paths:[ls(n,`${is}.timer`),ls(n,`${is}.service`)]}]}return e==="win32"?[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:op,paths:[]}]:[]},Iw=async e=>{try{return await WT(e),!0}catch{return!1}},kc=async(e={})=>{let t=e.os??dp(),n=e.exists??Iw;for(let r of up(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},Ew=async e=>{let t={suspected:!1,missingPaths:[],kinds:[]};if(!e.binaryDurable||!e.schedulerEnabled||e.schedulerInstalled)return t;let n=e.exists??Iw;for(let r of up(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},xw=(e=dp(),t=Sw(),n=nr())=>{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 up(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 YT}from"node:os";import{join as Tc}from"node:path";import{chmod as JT,readFile as ds,rm as Dw,copyFile as XT}from"node:fs/promises";var Hr="# >>> anyray connect >>>",Ic="# <<< anyray connect <<<",pp="# restore: ",Rw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ec=e=>{let t=new RegExp(`\\n*${Rw(Hr)}[\\s\\S]*?${Rw(Ic)}\\n?`,"g");return e.replace(t,"")},fp=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,Ow=e=>vc(e,"[")-vc(e,"]"),UT=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+Ow(fp(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?UT(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=fp(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+Ow(l)))}return t},mp=e=>e.findIndex(t=>t.kind==="table"),hp=e=>e.includes(Hr),Tw=(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("#")})},yp=(e,t)=>Tw(Ec(e),t),gp=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)},_w=(e,t)=>{let n=e.indexOf(Hr);if(n<0)return!1;let r=e.indexOf(Ic,n+Hr.length);return r<0?!1:Tw(e.slice(n,r),t)},wp=(e,t)=>{let r=Ec(e).split(`
|
|
67
|
+
`),o=Sc(r),a=mp(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=fp(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=Pw(e),a=Ec(e).split(`
|
|
68
|
+
`),s=Sc(a),i=mp(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=mp(p),m=(f===-1?d:d.slice(0,f)).join(`
|
|
69
69
|
`),h=f===-1?"":d.slice(f).join(`
|
|
70
|
-
`),w=[...u.entries()].sort(([b],[k])=>b.localeCompare(k)).map(([,b])=>`${
|
|
70
|
+
`),w=[...u.entries()].sort(([b],[k])=>b.localeCompare(k)).map(([,b])=>`${pp}${b}`),y=[Hr,...w,...t,Ic].join(`
|
|
71
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(
|
|
74
|
+
`},Pw=e=>{let t=new Map,n=gp(e);if(n===void 0)return t;for(let r of n.split(`
|
|
75
|
+
`)){let o=r.trim();if(!o.startsWith(pp))continue;let a=o.slice(pp.length).trim(),[s]=Sc([a]);s.kind==="key"&&s.key.length>0&&t.set(s.key,a)}return t},Rc=e=>{if(!hp(e))return null;let t=[...Pw(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 HT}from"node:crypto";import{chmod as GT,mkdir as VT,rm as KT,writeFile as jT}from"node:fs/promises";import{dirname as ZT}from"node:path";var we=async(e,t)=>{await VT(ZT(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${HT()}`;try{await jT(n,t,{flag:"wx",mode:384}),await he(n,e),await GT(e,384)}finally{await KT(n,{force:!0}).catch(()=>{})}};var zT="codex",qT="Codex app / CLI / IDE",QT="https://chatgpt.com/backend-api/codex",e_="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",t_="x-anyray-client-context-window",n_="x-anyray-client-auto-compact-limit",_c=()=>process.env.CODEX_HOME?.trim()||Tc(YT(),".codex"),Gr=()=>Tc(_c(),"config.toml"),Oc=()=>`${Gr()}.anyray-bak`,bp=()=>Tc(_c(),"hooks.json"),En=()=>Tc(_c(),"anyray.config.toml"),Lw=e=>Oo(e,"PostToolUse",Wg),Nw=(e,t=!1)=>ue({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||zT,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||qT}),rt=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Ap=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,us=(e,t={})=>{let n=Nw(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:Ap(),i=e.clientKey,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${rt(QT)}`,`"x-anyray-forward-headers" = ${rt(e_)}`,...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(`"${t_}" = ${rt(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${n_}" = ${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(", ")}]`]:[]]},r_=()=>Ap()?["model_provider","model"]:["model_provider"],$w={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=_c(),t=await x(e);return{installed:t,detail:t?Gr():`no ${e} directory`}},async apply(e,t){let n=Gr(),r=bp(),o=Nw(e),a=ee(e,"openai"),s=Ap(),i=te(),c={},l=await x(r);try{l&&(c=await M(r))}catch(k){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${r} (${k instanceof Error?k.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run Connect so the retired Anyray PostToolUse entry can be removed safely.`]}}let d=Lw(c),u=await x(n),p=u?await ds(n,"utf-8"):"";if(yp(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=yp(p,"mcp_servers.anyray"),m=wp(p,"model_context_window"),h=wp(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 oe(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 XT(n,Oc()),await JT(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,us(e,{mcpServer:g,modelContextWindow:m,modelAutoCompactTokenLimit:h}),r_());return await we(n,b),y.push(n),await x(En())&&(await Dw(En(),{force:!0}),y.push(En()),w.push(`Removed the old opt-in profile ${En()} (the default route replaces it).`)),{status:"configured",messages:w,changedFiles:y}},async pointsAt(e){let t=Gr();if(!await x(t))return!1;try{let n=await ds(t,"utf-8"),r=`base_url = ${rt(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=Gr();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await ds(e,"utf-8");if(!_w(t,"mcp_servers.anyray"))return{registered:!1,command:null,reason:"absent"};let n=t.match(/\[mcp_servers\.anyray\]\r?\ncommand = ("(?:[^"\\]|\\.)*")/),r=null;if(n)try{r=JSON.parse(n[1])}catch{r=null}return{registered:!0,command:r}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async inferenceAuthLanes(){try{let e=await ds(Gr(),"utf-8"),t=gp(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=Gr(),n=await x(t),r=await x(En()),o=await x(bp());if(!n&&!r&&!o)return{status:"not-found",messages:["nothing to revert"]};let a=[],s=[];if(o){let i=bp(),c;try{c=await M(i)}catch(l){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${i} (${l instanceof Error?l.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run --revert.`]}}Lw(c)&&(e.dryRun||(await Y(i,c,{backup:!1}),await oe(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 ds(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 Dw(En(),{force:!0}),s.push(En()),a.push(e.dryRun?`would remove the old opt-in profile ${En()}`:`removed the old opt-in profile ${En()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await oe(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as l_}from"node:os";import{join as d_}from"node:path";import{readFile as Ww,rm as kp}from"node:fs/promises";import{readFile as o_,writeFile as Mw,access as a_}from"node:fs/promises";import{homedir as s_}from"node:os";import{join as Cp}from"node:path";var i_="# >>> anyray connect >>>",c_="# <<< anyray connect <<<",ps=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:i_,end:c_},gt=()=>{let e=s_(),t=process.env.SHELL||"";return t.includes("zsh")?Cp(e,".zshrc"):t.includes("bash")?Cp(e,".bashrc"):Cp(e,".profile")},Pc=async e=>{try{return await a_(e),await o_(e,"utf-8")}catch{return""}},Bw=(e,t)=>{let{begin:n,end:r}=ps(t),o=e.indexOf(n);if(o===-1)return e;let a=e.indexOf(r,o+n.length);if(a===-1)return e;let s=o;for(;s>0&&e[s-1]===`
|
|
80
80
|
`;)s-=1;let i=a+r.length;return e[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}=ps(n),s
|
|
81
|
+
`&&(i+=1),e.slice(0,s)+e.slice(i)},Dc=async(e,t,n)=>{let r=await Pc(e),{begin:o,end:a}=ps(n),s=Bw(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 _t=e=>{if(e.length<=4)return"\u2026";let t=/^([a-z0-9]{2,6}_)/i.exec(e)?.[1]??"";return e.length>t.length+4?`${t}\u2026${e.slice(-4)}`:`\u2026${e.slice(-4)}`};var ve=e=>`'${e.replace(/'/g,"'\\''")}'`,
|
|
89
|
-
`)):w&&g&&await
|
|
86
|
+
`;return await Mw(e,c),e},Lc=async(e,t)=>{let n=await Pc(e),{begin:r,end:o}=ps(t),a=n.indexOf(r);if(a===-1)return;let s=a+r.length,i=n.indexOf(o,s);if(i!==-1)return n.slice(s,i).split(`
|
|
87
|
+
`).filter(c=>c.trim().length>0)},Fw=async(e,t)=>(await Pc(e)).includes(ps(t).begin),fs=async(e,t)=>{let n=await Pc(e);return n.includes(ps(t).begin)?(await Mw(e,Bw(n,t).replace(/\s*$/,"")+`
|
|
88
|
+
`),!0):!1};var _t=e=>{if(e.length<=4)return"\u2026";let t=/^([a-z0-9]{2,6}_)/i.exec(e)?.[1]??"";return e.length>t.length+4?`${t}\u2026${e.slice(-4)}`:`\u2026${e.slice(-4)}`};var ve=e=>`'${e.replace(/'/g,"'\\''")}'`,u_=e=>{let t=ve(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},Uw=(e,t,n,r)=>[`export OPENAI_BASE_URL=${ve(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${ve(t)}`],`export ANTHROPIC_BASE_URL=${ve(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${ve(t)}`],...e.byoUpstream?[]:["export ENABLE_TOOL_SEARCH='true'"],...e.byoUpstream?[]:["export _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL='1'"]],p_=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],f_=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],vp=()=>d_(l_(),".anyray","shell-env.sh"),Gw="# Managed by anyray-connect. Do not source this file anywhere else.",Hw=e=>e.split(/\r?\n/,1)[0]===Gw,Sp=e=>f_.some(t=>e.startsWith(`export ${t}=`)),Nc=(e,t=process.env)=>t.ANTHROPIC_BASE_URL===e.anthropicBaseUrl||t.OPENAI_BASE_URL===e.openaiBaseUrl?p_.filter(r=>(t[r]??"")!==""):[],Vw={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=>Sp(n)||n.includes(vp()))?["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=Uw(e,s,r,o),c=i.filter(Sp),l=i.filter(b=>!Sp(b)),d=vp(),u=Bg(),p=[u_(u),...l,...c.length>0?[`[ -r ${ve(d)} ] && . ${ve(d)}`]:[]],f=e.clientKey?Uw(e,_t(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 Ww(d,"utf8"):void 0,g=y===void 0||Hw(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,[Gw,...c,""].join(`
|
|
89
|
+
`)):w&&g&&await kp(d,{force:!0}),await Dc(n,p)}catch(b){try{y!==void 0&&g?await we(d,y):g&&await kp(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=vp(),r=await x(n),o=r?Hw(await Ww(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 fs(t);o&&await kp(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 X_}from"node:child_process";import{closeSync as z_,copyFileSync as q_,existsSync as Ce,mkdirSync as Q_,openSync as eP,readFileSync as kb,readSync as tP,renameSync as nP,rmSync as rn,writeFileSync as Bp}from"node:fs";import{homedir as vb,platform as rP}from"node:os";import{dirname as Sb,join as Mo,resolve as oP}from"node:path";import{isIP as Pp}from"node:net";import{homedir as m_,platform as h_}from"node:os";import{join as $c}from"node:path";var Ve=e=>{let t=m_();switch(h_()){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 y_,rmSync as g_,writeFileSync as w_}from"node:fs";import{createRequire as b_}from"node:module";import{tmpdir as A_}from"node:os";import{join as Kw}from"node:path";var ms=class extends Error{},hs=e=>e instanceof ms?`: ${e.message}`:"",jw=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new ms("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new ms(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},Zw=()=>{try{return Fc("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Ep=64*1024*1024,C_=Ep*2+64,Bc=e=>`'${e.replace(/'/g,"''")}'`,k_=(e,t)=>Fc("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:C_,stdio:["ignore","pipe","pipe"]}),v_=(e,t)=>Fc("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Ep,stdio:["pipe","pipe","pipe"]}),Yw=(e,t,n=k_)=>{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")},Jw=(e,t=v_)=>{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
|
-
`);Fc("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:
|
|
96
|
-
`,{mode:384}),await he(n,t)},
|
|
97
|
-
`),
|
|
98
|
-
`,{encoding:"utf-8",flag:"wx",mode:384})},
|
|
99
|
-
`,{encoding:"utf-8",flag:"wx",mode:384});try{z_(n,e)}catch(r){throw rn(n,{force:!0}),r}},yP=(e,t)=>{let n=Lo(e);xb(e,{...n,lastWritten:t})},re=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),wb=e=>re(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=Ab(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(re(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||re(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(!re(n)||n.version!==1||!re(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Ke],o=n.rows[at];if(!wb(r)||!wb(o))throw new Error("Cursor value backup is missing an exact managed row");return{applicationUser:r.exists?r.value:null,openAIKey:o.exists?o.value:null}},bb=e=>{let t=Buffer.alloc(16),n=J_(e,"r");try{return X_(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{j_(n)}},gP=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return re(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Rb=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 Rb(`${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},Ob=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Rb(t.hostname)}catch{return!1}},wP=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${Sb}`}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."],Dp=()=>{let e=cr();if(!Ce(e))return"clear";let t=Do();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ke)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return re(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},bP=(e,t)=>{if(!Ob(e))return{routed:!1,problem:"gateway-not-public-https"};let n=cr();if(!Ce(n))return{routed:!1,problem:"state-db-missing"};let r=Do();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Ke),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(!re(s))return{routed:!1,problem:"settings-malformed"};let i=`${Ht(e)}/v1${Sb}`;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}},AP=()=>{let e=cr();if(!Ce(e))return"unverifiable";let t=Do();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ke)}catch{return"unverifiable"}if(n===void 0)return"unverifiable";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}if(!re(r))return"unverifiable";let o=r.availableAPIKeyModels;return Array.isArray(o)?o.length>0?"registered":"none":"unverifiable"},CP=(e,t=[])=>({command:Rt(e,[...t,Jc])}),Fp=(e,t,n)=>{if(!re(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} `)},kP=(e,t)=>re(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(Fp(a,t,n)){r=!0;continue}if(!re(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!kP(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}},Wp=(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)=>re(e.hooks)&&Wp(e.hooks,t).some(a=>re(a)&&a.matcher===o&&Fp(a,n,r)),vP=(e,t,n,r,o)=>re(e.hooks)&&Wp(e.hooks,t).some(a=>re(a)&&a.matcher===o&&Fp(a,n,r)&&nc(a.command,n,[...r,Jc])),Pb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!re(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=re(e.hooks)?{...e.hooks}:{},{entries:s}=Tb(Wp(a,t),n,r);return s.push({...CP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},SP=(e,t,n,r=[])=>{if(!re(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},IP=async()=>{let e=on();if(!te()){let t=await Lb();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 M(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}}},Yc=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,Eb]}},Lp=e=>re(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]),EP=e=>{if(!re(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)!==Xn||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))},Xc=e=>re(e)&&Array.isArray(e.args)&&e.args.at(-1)===Eb||EP(e),xP=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,RP=async()=>{if(!te())return Db();let e=an();try{let t=await M(e);if(t.mcpServers!==void 0&&!re(t.mcpServers))throw new Error("mcpServers is not an object");let n=re(t.mcpServers)?{...t.mcpServers}:{},r=n[Pt];return r!==void 0&&!Xc(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Pt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Pt]=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}}},Db=async()=>{let e=an();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e);if(!re(t.mcpServers)||!(Pt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!Xc(t.mcpServers[Pt]))return{changedFiles:[],messages:[`Preserved the foreign ${Pt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Pt];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 M(e),n=t;for(let r of Kr)n=SP(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}}},OP=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=rP(e);if(!n)return t;let r=Mo(n,bs),o=nP();try{if(Ce(r)){let a=Ab(r,"utf8");if(a===o)return t;if(!a.includes(Ib))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: "${Bp}"`]}}return Y_(kb(r),{recursive:!0}),Mp(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 IP(),t=await RP(),n=await OP();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},Np=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(!te()){let e=await Np();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 M(on());for(let r of Kr)e=Pb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await M(an());if(t.mcpServers!==void 0&&!re(t.mcpServers))throw new Error("mcpServers is not an object");let n=re(t.mcpServers)?t.mcpServers[Pt]:void 0;return n!==void 0&&!Xc(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${an()} already contains a foreign ${Pt} 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}}},TP=async()=>{if(!te())return!1;try{let e=await M(on());if(!re(e.hooks)||!Kr.every(r=>_b(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await M(an()),n=re(t.mcpServers)?t.mcpServers[Pt]:void 0;return Lp(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(!re(t))throw new Error("Cursor application-user settings are not an object");return t},_P=(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:Ke}:{key:Ke,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:Ke}:{key:Ke,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);re(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.",...No];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.",...No]},$p=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!te())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]}},PP=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 ar("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=Ce(As())||Ce($o());if(r&&Zc())return $p("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=Dp();if(c!=="clear")return{status:"manual",messages:[c==="active"?"Cursor still has an OpenAI BYOK override enabled, and Connect has no recovery journal proving it owns those values.":"Cursor's OpenAI override state could not be verified safely, and Connect has no recovery journal for it.","In Cursor \u2192 Settings \u2192 Models, disable the OpenAI API-key/base-URL override, keep your Cursor Team login, then re-run Connect. No app-state value or credential was guessed or overwritten."]}}if(t.dryRun)return{status:"configured",messages:[r?`Would restore Cursor's journaled OpenAI override from ${Ce($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 ar("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 -- "${Bp}" (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:eP,needsTarget:e=>e!=="revert",async complete(e,t,n){return tP(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=vb(),t=Ce(e);return{installed:t,detail:t?cr():"Cursor user dir not found"}},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=an();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await M(e),n=re(t.mcpServers)?t.mcpServers[Pt]:void 0;return Lp(n)?{registered:!0,command:xP(n)}:{registered:!1,command:null,reason:n===void 0?"absent":"foreign"}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async integrationStatus(){let e,t=!0,n=on();if(!await x(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!re(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=>vP(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 M(a);if(s.mcpServers===void 0)r="missing";else if(!re(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Pt];r=i===void 0?"missing":Xc(i)?"owned":"foreign",r==="owned"&&(o=Lp(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await $r()?"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(oP(e))return PP(e,t);let n=wP(e),r=cr(),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(!Ob(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=Do();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(!Ce(r))return i({status:"manual",messages:ot(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(Ce(a)){if(Ce(o))return i({status:"manual",messages: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{bb(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(Ce(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(Zc())return i(await $p("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}, ${Ce(o)?`retain the original value backup at ${o}`:`create a mode-0600 value backup at ${o}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${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=jc(l.readItem(a,Ke)??null,l.readItem(a,at)??null);else{let g=Lo(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,Ke),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,Ke)}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=gP(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(Ce(o))try{yP(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{hP(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:Ke,value:m.value},{key:at,value:e.clientKey}])}catch{let y=!0;if(p)try{xb(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 ar("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")?Ce(As())||Ce($o())||Dp()!=="clear"?!1:TP():bP(e,n).routed},async routingOverrides(){return Dp()!=="active"?[]:AP()!=="none"?[]:[{problem:"no custom model is registered against Cursor\u2019s API-key lane, so every model in the picker still runs on Cursor-hosted inference and no request reaches the gateway",fix:"Cursor \u2192 Settings \u2192 Models: add a custom model named `anyray-default` (or an admin-registered alias) and enable it, quit Cursor fully, reopen, then select it in Ask, Plan, or Agent.",repairable:!1}]},async revert(e){let t=cr(),n=As(),r=$o(),o=Ce(n),a=Ce(r);if(e.dryRun)return{status:"reverted",messages:[o||a?`Would restore Cursor from ${a?r:n}, remove its recovery sidecar(s), remove Anyray Cursor hooks from ${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 Np(),h=!0;try{await ar("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 $p("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=Do(),i=!1,c=!1,l,d=[];if(a)try{if(bb(r))if(Ce(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let m=jc(s.readItem(r,Ke)??null,s.readItem(r,at)??null);s.mutateRows(t,[Pp(s.readItem(t,Ke),m.applicationUser),m.openAIKey===null?{key:at}:{key:at,value:m.openAIKey}]),c=!0}else i=!0,Z_(r,t),rn(`${t}-wal`,{force:!0}),rn(`${t}-shm`,{force:!0});else{let m=Lo(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ce(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let h=jc(m.applicationUser,m.openAIKey);s.mutateRows(t,[Pp(s.readItem(t,Ke),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}${hs(m)}; 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(!Ce(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let m=_P(s.readItem(t,Ke),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}${hs(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 ar("cursor")}catch{p=!1,u.push("Could not clear Cursor's stale queue marker.")}let f=await Np();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 ND,mkdir as $D,readFile as kA,rm as MD,writeFile as BD}from"node:fs/promises";import{randomUUID as FD}from"node:crypto";import{dirname as WD,join as vA}from"node:path";import{constants as NP,chmod as $P,copyFile as MP,readFile as Bb}from"node:fs/promises";import{applyEdits as BP,modify as FP}from"jsonc-parser";var DP=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()?wt(n):{};if(!zc(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},
|
|
94
|
+
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");jw(o?.slice(1).map(Number))},S_=(e,t)=>{let n=y_(Kw(A_(),"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=Kw(n,`value-${s}`);return w_(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:Ep,stdio:["pipe","ignore","pipe"]})}finally{try{g_(n,{recursive:!0,force:!0})}catch{}}},I_={kind:"sqlite3-cli",readItem:(e,t)=>Yw(e,t),checkpointWal:e=>Jw(e),mutateRows:S_},E_=()=>{try{let t=b_(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},Ip=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},x_=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),R_=e=>({kind:"node-sqlite",readItem:(t,n)=>Ip(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:x_(o.value)}),checkpointWal:t=>Ip(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);jw(o)}),mutateRows:(t,n)=>Ip(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,Do=()=>{if(Mc!==void 0)return Mc;let e=E_();return Mc=e?R_(e):Zw()?I_:null,Mc};import{spawn as O_}from"node:child_process";import{randomUUID as Xw}from"node:crypto";import{constants as zw}from"node:fs";import{chmod as T_,copyFile as qw,mkdir as __,readdir as P_,readFile as D_,rename as L_,rm as ys,writeFile as N_}from"node:fs/promises";import{join as xp}from"node:path";var Rp=/^[a-z0-9][a-z0-9-]{0,31}$/,$_=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,Qw=/^[a-z0-9][a-z0-9-]{0,31}$/,M_=/^[0-9TZ:.+-]{1,40}$/,Op=()=>xp(Q(),"pending"),Uc=e=>{if(!Rp.test(e)||$_.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return xp(Op(),`${e}.json`)},eb=()=>xp(Q(),"cursor-pending.json"),B_=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),F_=(e,t)=>{if(!B_(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!Rp.test(n)||typeof e.op!="string"||!Qw.test(e.op)||typeof e.requestedAt!="string"||!M_.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}:{}}},Tp=async(e,t)=>{try{return F_(JSON.parse(await D_(e,"utf-8")),t)}catch{return}},tb=async()=>{let e=eb(),t=await Tp(e,"cursor");if(!t)return;let n=!1;try{await nb(),await qw(e,Uc("cursor"),zw.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await ys(e,{force:!0})}catch{}return t},Hc=async e=>{let t=await Tp(Uc(e),e);return t||(e==="cursor"?tb():void 0)},ar=async()=>{let e;try{e=await P_(Op())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!Rp.test(r))continue;let o=await Hc(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await tb();n&&t.push(n)}return t},nb=async()=>{await tt();let e=Op();await __(e,{recursive:!0,mode:448});try{await T_(e,448)}catch{}},Wc=async e=>{await nb();let t=Uc(e.adapter),n=`${t}.${process.pid}.tmp`;await N_(n,`${JSON.stringify(e)}
|
|
96
|
+
`,{mode:384}),await he(n,t)},W_=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,sr=async(e,t)=>await _p(e,t)==="claimed",_p=async(e,t)=>{let n=Uc(e);if(t){let o=`${n}.${process.pid}.${Xw()}.claimed`;try{await L_(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Tp(o,e);if(a&&W_(a,t))return await ys(o,{force:!0}),"claimed";let s=!1;try{await qw(o,n,zw.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(eb(),{force:!0})}catch{}return r?"claimed":"absent"},ir=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},U_=e=>{let{command:t,args:n}=tr("__anyray-quit-watch");return{exe:t,args:[...n,e]}},H_=e=>{let{exe:t,args:n}=U_(e),r=O_(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},rb=H_;var ob=async()=>{let e=[],t;try{t=await ar()}catch{return e}for(let n of t)if(!ir(n.watcherPid))try{let r=rb(n.adapter);if(!r)continue;await Wc({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},gs=async(e,t)=>{if(!Qw.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await Hc(e),r=new Date().toISOString(),o=Xw();if(n&&ir(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=rb(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 G_,spawnSync as sb}from"node:child_process";import{existsSync as Gc}from"node:fs";import{homedir as V_,platform as cr}from"node:os";import{join as ib,win32 as ab}from"node:path";var cb=(e,t={})=>{let n=t.env??process.env,r=t.exists??Gc,o=(t.home??V_)(),a={localAppData:n.LOCALAPPDATA??ab.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=ab.join(i,s.path);if(r(c))return c}},Vr=/^[A-Za-z0-9 ._-]{1,64}$/,K_=/^[A-Za-z0-9.-]{1,128}$/,Vc=e=>e.darwinBundleId&&K_.test(e.darwinBundleId)?e.darwinBundleId:void 0,lb=(e,t=cr())=>t==="darwin"?Vc(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",db=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",ub=(e,t=cr(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return cb(e,r)!==void 0;let o=e.linuxProcess;return!o||!Vr.test(o)?!1:n.split(":").filter(Boolean).some(a=>Gc(ib(a,o)))},pb=(e,t=cr())=>{if(t==="darwin"&&Vc(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&Vr.test(n))},fb=1e4,ws=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=ib(t,"System32",e);return Gc(n)?n:e},j_=e=>{let t=`/usr/bin/${e}`;return Gc(t)?t:e},Z_=(e,t)=>{try{let n=sb(e,t,{encoding:"utf-8",timeout:fb,windowsHide:!0,...cr()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:cr()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},Y_=e=>new Promise(t=>setTimeout(t,e)),mb=(e,t={})=>{let n=t.runtimePlatform??cr(),r=t.run??Z_;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||!Vr.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||!Vr.test(a)?!1:r(ws("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!Vr.test(o)?!1:r(j_("pkill"),["-TERM","-o","-x",o])},hb=async(e,t=2e4,n={})=>{let r=n.sleep??Y_,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},J_=(e,t,n={})=>{let r=cr();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=sb(e,t,{stdio:"ignore",timeout:fb,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=G_(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},yb=(e,t={})=>{let n=t.runtimePlatform??cr(),r=t.launch??J_;if(n==="darwin"){let a=Vc(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!Vr.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=cb(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!Vr.test(o)?!1:r(o,[])};var aP={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"}]},sP=e=>e==="apply"||e==="native"||e==="revert",Ib=()=>Ve("Cursor"),lr=()=>Mo(Ib(),"User","globalStorage","state.vscdb"),As=()=>`${lr()}.anyray-bak.json`,$o=()=>`${lr()}.anyray-bak`,Ke="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",at="cursorAuth/openAIKey";var Eb="/seat/cursor",Fp="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=Mo(".cursor","rules","anyray.mdc"),xb="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",iP=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",xb,"",Fp,""].join(`
|
|
97
|
+
`),cP=e=>{let t=oP(e);for(;;){if(Ce(Mo(t,".git")))return t;let n=Sb(t);if(n===t)return null;t=n}},lP=e=>e.authMode!=="placeholder",on=()=>Mo(vb(),".cursor","hooks.json"),an=()=>Mo(vb(),".cursor","mcp.json"),Pt="anyray",Rb="--anyray-owner=cursor-v1",dP="postToolUse",uP="beforeSubmitPrompt",gb="preToolUse",pP="^MCP:",fP="UserPromptSubmit",mP="Shell",hP="^(Read|Grep)$",Jc="--anyray-owner=cursor-hook-v1",Kr=[{event:dP,flag:ze,trailingArgs:["cursor"],matcher:pP},{event:uP,flag:Jn,trailingArgs:[],matcher:fP},{event:gb,flag:Ug,trailingArgs:[],matcher:mP},{event:gb,flag:Hg,trailingArgs:[],matcher:hP}];var wb={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},yP=(e,t,n)=>X_(e,t,n),bb=yP,gP,wP=()=>{let e=gP??rP();if(e==="win32"){let t=bb(ws("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],wb);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=bb("pgrep",["-x",t],wb);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},bP=wP,Zc=()=>bP();var AP=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,Ke)??null,openAIKey:e.readItem(n,at)??null,lastWritten:r};Bp(t,`${JSON.stringify(o,null,2)}
|
|
98
|
+
`,{encoding:"utf-8",flag:"wx",mode:384})},Ob=(e,t)=>{let n=`${e}.${process.pid}.tmp`;Bp(n,`${JSON.stringify(t,null,2)}
|
|
99
|
+
`,{encoding:"utf-8",flag:"wx",mode:384});try{nP(n,e)}catch(r){throw rn(n,{force:!0}),r}},CP=(e,t)=>{let n=Lo(e);Ob(e,{...n,lastWritten:t})},re=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ab=e=>re(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=kb(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(re(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||re(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(!re(n)||n.version!==1||!re(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Ke],o=n.rows[at];if(!Ab(r)||!Ab(o))throw new Error("Cursor value backup is missing an exact managed row");return{applicationUser:r.exists?r.value:null,openAIKey:o.exists?o.value:null}},Cb=e=>{let t=Buffer.alloc(16),n=eP(e,"r");try{return tP(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{z_(n)}},kP=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return re(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Tb=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(".")&&Pp(t)===0||t==="0.0.0.0")return!0;if(Pp(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(Pp(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 Tb(`${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},_b=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Tb(t.hostname)}catch{return!1}},vP=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${Eb}`}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."],Lp=()=>{let e=lr();if(!Ce(e))return"clear";let t=Do();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ke)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return re(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},SP=(e,t)=>{if(!_b(e))return{routed:!1,problem:"gateway-not-public-https"};let n=lr();if(!Ce(n))return{routed:!1,problem:"state-db-missing"};let r=Do();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Ke),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(!re(s))return{routed:!1,problem:"settings-malformed"};let i=`${Ht(e)}/v1${Eb}`;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}},IP=()=>{let e=lr();if(!Ce(e))return"unverifiable";let t=Do();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ke)}catch{return"unverifiable"}if(n===void 0)return"unverifiable";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}if(!re(r))return"unverifiable";let o=r.availableAPIKeyModels;return Array.isArray(o)?o.length>0?"registered":"none":"unverifiable"},EP=(e,t=[])=>({command:Rt(e,[...t,Jc])}),Wp=(e,t,n)=>{if(!re(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} `)},xP=(e,t)=>re(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),Pb=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(Wp(a,t,n)){r=!0;continue}if(!re(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!xP(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}},Up=(e,t)=>{let n=e[t];if(n===void 0)return[];if(!Array.isArray(n))throw new Error(`Cursor hook event ${t} is not an array`);return n},Db=(e,t,n,r,o)=>re(e.hooks)&&Up(e.hooks,t).some(a=>re(a)&&a.matcher===o&&Wp(a,n,r)),RP=(e,t,n,r,o)=>re(e.hooks)&&Up(e.hooks,t).some(a=>re(a)&&a.matcher===o&&Wp(a,n,r)&&nc(a.command,n,[...r,Jc])),Lb=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!re(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=re(e.hooks)?{...e.hooks}:{},{entries:s}=Pb(Up(a,t),n,r);return s.push({...EP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},OP=(e,t,n,r=[])=>{if(!re(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=Pb(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},TP=async()=>{let e=on();if(!te()){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 M(e);for(let n of Kr)t=Lb(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,Rb]}},Np=e=>re(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]),_P=e=>{if(!re(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)!==zn||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))},Xc=e=>re(e)&&Array.isArray(e.args)&&e.args.at(-1)===Rb||_P(e),PP=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,DP=async()=>{if(!te())return Nb();let e=an();try{let t=await M(e);if(t.mcpServers!==void 0&&!re(t.mcpServers))throw new Error("mcpServers is not an object");let n=re(t.mcpServers)?{...t.mcpServers}:{},r=n[Pt];return r!==void 0&&!Xc(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Pt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Pt]=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}}},Nb=async()=>{let e=an();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await M(e);if(!re(t.mcpServers)||!(Pt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!Xc(t.mcpServers[Pt]))return{changedFiles:[],messages:[`Preserved the foreign ${Pt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Pt];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 M(e),n=t;for(let r of Kr)n=OP(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}}},LP=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=cP(e);if(!n)return t;let r=Mo(n,bs),o=iP();try{if(Ce(r)){let a=kb(r,"utf8");if(a===o)return t;if(!a.includes(xb))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: "${Fp}"`]}}return Q_(Sb(r),{recursive:!0}),Bp(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.`]}}},Mb=async()=>{let e=await TP(),t=await DP(),n=await LP();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},$p=async()=>{let e=await $b(),t=await Nb();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},Bb=async()=>{if(!te()){let e=await $p();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 M(on());for(let r of Kr)e=Lb(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await M(an());if(t.mcpServers!==void 0&&!re(t.mcpServers))throw new Error("mcpServers is not an object");let n=re(t.mcpServers)?t.mcpServers[Pt]:void 0;return n!==void 0&&!Xc(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${an()} already contains a foreign ${Pt} 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}}},NP=async()=>{if(!te())return!1;try{let e=await M(on());if(!re(e.hooks)||!Kr.every(r=>Db(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await M(an()),n=re(t.mcpServers)?t.mcpServers[Pt]:void 0;return Np(n)}catch{return!1}},Fb=["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(!re(t))throw new Error("Cursor application-user settings are not an object");return t},$P=(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 Fb){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:Ke}:{key:Ke,value:JSON.stringify(s)},conflicts:i}},Dp=(e,t)=>{let n=Cs(e),r=Cs(t??void 0),o={...n};for(let a of Fb)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Ke}:{key:Ke,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);re(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.",...No];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.",...No]},Mp=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!te())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]}},MP=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 sr("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 Bb();if(!n.complete)return{status:"manual",messages:n.messages};let r=Ce(As())||Ce($o());if(r&&Zc())return Mp("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=Lp();if(c!=="clear")return{status:"manual",messages:[c==="active"?"Cursor still has an OpenAI BYOK override enabled, and Connect has no recovery journal proving it owns those values.":"Cursor's OpenAI override state could not be verified safely, and Connect has no recovery journal for it.","In Cursor \u2192 Settings \u2192 Models, disable the OpenAI API-key/base-URL override, keep your Cursor Team login, then re-run Connect. No app-state value or credential was guessed or overwritten."]}}if(t.dryRun)return{status:"configured",messages:[r?`Would restore Cursor's journaled OpenAI override from ${Ce($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 Mb(),s=[];if(!t.preservePendingOp)try{await sr("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 -- "${Fp}" (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:aP,needsTarget:e=>e!=="revert",async complete(e,t,n){return sP(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=Ib(),t=Ce(e);return{installed:t,detail:t?lr():"Cursor user dir not found"}},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=an();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await M(e),n=re(t.mcpServers)?t.mcpServers[Pt]:void 0;return Np(n)?{registered:!0,command:PP(n)}:{registered:!1,command:null,reason:n===void 0?"absent":"foreign"}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async integrationStatus(){let e,t=!0,n=on();if(!await x(n))e="missing";else try{let s=await M(n);if(s.hooks===void 0)e="missing";else if(!re(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=>Db(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=Kr.every(c=>RP(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 M(a);if(s.mcpServers===void 0)r="missing";else if(!re(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Pt];r=i===void 0?"missing":Xc(i)?"owned":"foreign",r==="owned"&&(o=Np(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await $r()?"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(lP(e))return MP(e,t);let n=vP(e),r=lr(),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(!_b(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 Bb();if(!c.complete)return{status:"manual",messages:c.messages};let l=Do();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(!Ce(r))return i({status:"manual",messages:ot(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(Ce(a)){if(Ce(o))return i({status:"manual",messages: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{Cb(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(Ce(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(Zc())return i(await Mp("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}, ${Ce(o)?`retain the original value backup at ${o}`:`create a mode-0600 value backup at ${o}`}, atomically upsert Cursor's exact OpenAI settings and credential rows, install global hooks in ${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=jc(l.readItem(a,Ke)??null,l.readItem(a,at)??null);else{let g=Lo(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,[Dp(l.readItem(r,Ke),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,Ke)}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=kP(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(Ce(o))try{CP(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{AP(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:Ke,value:m.value},{key:at,value:e.clientKey}])}catch{let y=!0;if(p)try{Ob(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 Mb();let w=[];if(!t.preservePendingOp)try{await sr("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")?Ce(As())||Ce($o())||Lp()!=="clear"?!1:NP():SP(e,n).routed},async routingOverrides(){return Lp()!=="active"?[]:IP()!=="none"?[]:[{problem:"no custom model is registered against Cursor\u2019s API-key lane, so every model in the picker still runs on Cursor-hosted inference and no request reaches the gateway",fix:"Cursor \u2192 Settings \u2192 Models: add a custom model named `anyray-default` (or an admin-registered alias) and enable it, quit Cursor fully, reopen, then select it in Ask, Plan, or Agent.",repairable:!1}]},async revert(e){let t=lr(),n=As(),r=$o(),o=Ce(n),a=Ce(r);if(e.dryRun)return{status:"reverted",messages:[o||a?`Would restore Cursor from ${a?r:n}, remove its recovery sidecar(s), remove Anyray Cursor hooks from ${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 $p(),h=!0;try{await sr("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 Mp("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=Do(),i=!1,c=!1,l,d=[];if(a)try{if(Cb(r))if(Ce(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let m=jc(s.readItem(r,Ke)??null,s.readItem(r,at)??null);s.mutateRows(t,[Dp(s.readItem(t,Ke),m.applicationUser),m.openAIKey===null?{key:at}:{key:at,value:m.openAIKey}]),c=!0}else i=!0,q_(r,t),rn(`${t}-wal`,{force:!0}),rn(`${t}-shm`,{force:!0});else{let m=Lo(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Ce(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let h=jc(m.applicationUser,m.openAIKey);s.mutateRows(t,[Dp(s.readItem(t,Ke),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}${hs(m)}; 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(!Ce(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let m=$P(s.readItem(t,Ke),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}${hs(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 sr("cursor")}catch{p=!1,u.push("Could not clear Cursor's stale queue marker.")}let f=await $p();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 WD,mkdir as UD,readFile as SA,rm as HD,writeFile as GD}from"node:fs/promises";import{randomUUID as VD}from"node:crypto";import{dirname as KD,join as IA}from"node:path";import{constants as WP,chmod as UP,copyFile as HP,readFile as Wb}from"node:fs/promises";import{applyEdits as GP,modify as VP}from"jsonc-parser";var BP=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},FP=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(FP(BP(e)));var zc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),je=async e=>{let t=await x(e),n=t?await Wb(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}},Ub=(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(...Ub(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=Ub(t.data,n);if(o.length===0)return!1;if(r&&!await x(`${e}.anyray-bak`))if(t.existed)try{await HP(e,`${e}.anyray-bak`,WP.COPYFILE_EXCL),await UP(`${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=GP(s,VP(s,i.path,i.value,{formattingOptions:a}));return await we(e,s.endsWith(`
|
|
106
106
|
`)?s:`${s}
|
|
107
|
-
`),!0},Bo=async e=>{try{let t=wt(await
|
|
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},Bo=async e=>{try{let t=wt(await Wb(`${e}.anyray-bak`,"utf8"));return zc(t)?t:void 0}catch{return}};import{readFile as RD,writeFile as OD}from"node:fs/promises";import{dirname as TD,join as _D}from"node:path";import{mkdir as PD}from"node:fs/promises";var Hb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),KP=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},jP=(e,t)=>{let n=/\n([ \t]+)"/.exec(e.slice(t));return n?n[1]:" "},ZP=(e,t)=>{let n=e.slice(t+1),r=n.indexOf("}");return r===-1?!1:n.slice(0,r).trim()===""},Hp=(e,t,n)=>{let r;try{r=wt(e)}catch{return{ok:!1,reason:"unsupported"}}if(!Hb(r))return{ok:!1,reason:"unsupported"};if(t in r)return{ok:!1,reason:"key-present"};let o=KP(e);if(o===-1)return{ok:!1,reason:"unsupported"};let a=jP(e,o),s=`${JSON.stringify(t)}: ${JSON.stringify(n)}`,i=e.slice(0,o+1),c=e.slice(o+1),l=ZP(e,o)?`
|
|
109
109
|
${a}${s}
|
|
110
110
|
`:`
|
|
111
|
-
${a}${s},`,d=`${i}${l}${c}`;try{let u=wt(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 JP}from"node:child_process";import{readdirSync as XP,statSync as zP}from"node:fs";import{createHash as nA,randomBytes as qP,randomUUID as rA}from"node:crypto";import{chmod as QP,lstat as Jp,mkdir as Xp,readdir as oA,readFile as ln,rm as aA,unlink as el,writeFile as zp}from"node:fs/promises";import{homedir as Ho,platform as qp}from"node:os";import{dirname as jp,join as bt,posix as Qb,win32 as eD}from"node:path";import{promisify as tD}from"node:util";var cn="0.1.29";var lr="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",qc="c341829c0dacfc512fa49fb951be4864ca3e7d6b46d6befbee84e663daa8e9a7",Ub="UEsDBBQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeItLyqXVXGwiynQiVAhVyfSwwIkcr1lyS4HBlKb++2F19WXGSSg5y2+XMvMf54COz96vSsiVGMt71eFdccYZOeW1c0eNVmnd+4+/zy4tsAuoJChyDM3OkxB63Idfiqg5aldZRjy9SCjdSklpgCSRKo6InP09C+VJqXKL1AaNc0qrT+sjrq253E36jzwDoaCRTuBYnv7y4yMaYQEOC+uciG2p0yaQ1G4ErKiiwx9F1/p5yNtQ9Dm4dYd1ZkvIa+T6rK9EV179zNqlm1tAC49aVM9ni3hoKFtafoMS835jY3Ef2OGUDrzGTh/Y2AElFE5Lxrk73hgIo7PEQkTAuked9rRmugjXKJLaBLCDhM6xZ6TVaYj5uDJ3nCCGgZgMfjPWJUTXbw2+80yL6qlhs9/QrBE9/EPPzuVEGLLObinQafxaiXxqNkfUnQ5HJg/22CTxAQfnLGMpks9rYB5Cw8NEg5f3huzGohXHIRgjRGVdk8sDe+H8AazGu722N0BRaZfLFYu3WuE5i3fW0Dd0trJsmjndD8mioAjtNlTZe1DmLO1cYV3cWbIU9/k9XdK+bKZcnI60Suno6bjGg0+iUQdoBvwWwPls/BOhP4/QO6NnHp2bG3lXmDNCRV2DNZ9Tbc/O2XB3MLOp+MHWIJ7CvwJ2cNqoqIQ3ao9uCpVjhGYBTjEujkMTIuCcSU19FtQetRYlupCxMWlSzRopaNfj4lyy98xGDF4VJpxXmiPMDJkoQE+qfzGvSx2r2czmnVQg+ppNIpSGq6il8A28jRiex/hIRdHk0Umfwt1W+t7D0EfUY4pP2z+71sT0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thZ2UuanNvblBLAQI/AxQACAgIAARaGF0wVq3AThEAACgTAAASAAAAAAAAAAAAAACkgVUHAABleHRlbnNpb24vaWNvbi5wbmdQSwECPwMUAAAICAAXWhhdC7fjr0sCAAB9BAAAEwAAAAAAAAAAAAAAtIHjGAAAZXh0ZW5zaW9uL3JlYWRtZS5tZFBLAQI/AxQACAgIAMtZGF2yhnqNeQIAACcEAAAVAAAAAAAAAAAAAACkgV8bAABleHRlbnNpb24vTElDRU5TRS50eHRQSwECPwMUAAgICAAXWhhdpzIc9AM5AAAjqQAAGwAAAAAAAAAAAAAApIEbHgAAZXh0ZW5zaW9uL2Rpc3QvZXh0ZW5zaW9uLmpzUEsFBgAAAAAHAAcA1gEAAGdXAAAAAA==";import{readFile as Vb}from"node:fs/promises";import{homedir as jr,platform as Fo}from"node:os";import{join as xn,posix as GP,win32 as VP}from"node:path";var vs=["Code","Code - Insiders","VSCodium"],Hp="1.121.0",Hb=1,KP=121,Kb="1.102.0",Gb=1,jP=102,ZP={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])}},Gp=e=>{let t=Qc(e);return t?t.major!==Hb?t.major>Hb:t.minor>=KP:!1},jb=e=>{let t=Qc(e);return t?t.major!==Gb?t.major>Gb:t.minor>=jP:!1},YP=async e=>{if(Fo()!=="darwin")return;let t=xn("/Applications",`${ZP[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 xn(n,"Library","Application Support",e);case"win32":return xn(r.APPDATA??xn(n,"AppData","Roaming"),e);default:return xn(n,".config",e)}},Vp=(e,t)=>e?t==="win32"?VP.join:GP.join:xn,Wo=(e,t=!1,n=Fo(),r=jr(),o=process.env)=>t?Vp(t,n)(r,Ss[e],"data","User"):xn(Zb(e,n,r,o),"User"),Yb=async(e,t=!1,n=Fo(),r=jr(),o=process.env)=>{try{let a=Vp(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=Vp(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"))]},Uo=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())=>xn(t,Ss[e],"extensions"),Kp=async(e=jr())=>{for(let t of vs)if(await x(xn(e,Ss[t])))return t},qb=async e=>{let t=e??await Uo();if(!t)return{status:"unknown"};let n=await YP(t);return n?{variant:t,version:n,status:Gp(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var z="anyray.anyray-vscode",Qp="vscode-handoffs",sA="vscode-receipts",Is=2,nD=tD(JP),Rn={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"]}},rD={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"}},oD=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:"&&oD(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Es=e=>{if(iA(e))try{return new URL(e.trim()).origin}catch{return}},aD=(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)},sD=e=>{try{return XP(e)}catch{return[]}},iD=e=>{try{return zP(e).mtimeMs}catch{return}},cD=(e,t,n,r,o)=>{if(!Fr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=Rn[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)},lD=(e,t,n)=>{let{macAppName:r,commands:o}=Rn[e],a=o[0],s=[];for(let i of["/Applications",Qb.join(t,"Applications")])for(let c of n(i))aD(c,r)&&s.push(Qb.join(i,c,"Contents/Resources/app/bin",a));return s},dD=(e,t=qp(),n=Ho(),r=process.env,o=sD,a=iD)=>{let s=cD(e,n,r,o,a);if(t==="darwin")return[...new Set([...Rn[e].commands,...lD(e,n,o),...s])];if(t!=="win32"){let u=Rn[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=rD[e],c=eD.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)),Rn[e].commands[0],...s])]},cA={run:async(e,t)=>({stdout:(await nD(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>qP(24).toString("base64url"),home:"",commandCandidates:e=>dD(e)},Zr=(e,t)=>bt(e,".anyray",sA,`${t}.json`),ef=(e,t)=>bt(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&&Qc(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},Zp=async(e,t,n)=>{try{let r=await t.run(e,[...n===void 0?[]:["--profile",n],"--list-extensions","--show-versions"]);if(typeof r?.stdout!="string")return;let o=r.stdout.split(/\r?\n/).map(a=>a.trim()).flatMap(a=>{let s=a.lastIndexOf("@");return s<=0?[]:a.slice(0,s).toLowerCase()===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 Zp(n.command,t)},uD=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 Jp(a)).isFile()||JSON.parse(await ln(a,"utf8")).variant!==t)continue;await el(a)}catch{}}},pD=async(e,t)=>{let n=bt(e,".anyray",Qp),r;try{r=await oA(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=bt(n,o);try{if(!(await Jp(a)).isFile()||JSON.parse(await ln(a,"utf8")).variant!==t)continue;await el(a)}catch{}}},fD=async(e,t)=>{try{let n=JSON.parse(await ln(Zr(e,t),"utf8"));return n.extensionVersion===cn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==lr}catch{return!1}},uA=250,mD=9e4,hD=mD/uA,yD=async(e,t,n,r)=>{for(let o=0;o<hD;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!==lr?"reload-required":a.version===Is&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(uA)}return"timeout"},gD=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,gD))}return r.join(": ")},wD=async e=>{try{let t=await Jp(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},tA=e=>nA("sha256").update(e).digest("hex"),bD=async(e=Ho())=>{let t=Buffer.from(Ub,"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=bt(e,".anyray","vscode-extension"),r=bt(n,`anyray-vscode-${cn}-${qc.slice(0,12)}.vsix`);try{if(tA(await ln(r))===qc)return r}catch{}await Xp(n,{recursive:!0,mode:448});let o=`${r}.${rA()}.tmp`;try{await zp(o,t,{mode:384}),await he(o,r),qp()!=="win32"&&await QP(r,384)}finally{await aA(o,{force:!0})}return r},Yp=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=>Yp(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Yp(t[n])}`).join(",")}}`},pA=(e,t,n)=>nA("sha256").update(Yp({gatewayUrl:Es(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:cn,extensionDistSha256:lr,profiles:[...n].sort()})).digest("hex"),AD=async(e,t,n,r,o,a)=>{let s=JSON.parse(await ln(ef(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===lr&&i.gatewayUrl===Es(t.origin)?await dA(e,a)===!0:!1},CD=async(e,t,n,r)=>{let o=ef(e,t),a=`${o}.${rA()}.tmp`;try{await Xp(jp(o),{recursive:!0,mode:448}),await zp(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
112
|
-
`,{mode:384}),await he(a,o)}catch{}finally{await
|
|
113
|
-
`,{mode:384}),await
|
|
114
|
-
`,{flag:"wx",mode:384}),await he(n,e),await ND(e,384)}finally{await MD(n,{force:!0}).catch(()=>{})}},nf=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!==dr||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!==EA(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}})},rf=e=>{let t=e.filter(n=>!nf(n));return{next:t,removed:t.length!==e.length}},GD=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 "${dr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=rf(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${dr}" Custom Endpoint from ${n}.`]};try{return await xA(n,o),await oe(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${dr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${dr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},VD=async e=>{try{let t=wt(await kA(e,"utf-8"));if(At(t))return IA(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.`]}},RA=async(e,t)=>{let n=UD(e),r;try{r=await M(n)}catch{return VD(n)}let{next:o,removed:a}=IA(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 oe(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.`]}}},KD=async(e,t)=>{let n=await GD(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]),jD=e=>Array.isArray(e.args)&&e.args.at(-1)===SA,PA=(e,t)=>{if(!t.hookBinaryIsDurable()||!At(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)},ZD=(e,t)=>{if(!At(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)===Xn&&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))},sl=(e,t)=>PA(e,t)?"exact":At(e)&&jD(e)||ZD(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.`,YD=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 je(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=OA(o),C=b[pn],S=C===void 0?void 0:sl(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:m,next:{...h,servers:b},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!At(h.servers)||!(pn in h.servers))continue;if(sl(h.servers[pn],o)==="foreign"){u=!0,l.push(bA(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 oe(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 (${Kb}+).`),{changedFiles:c,messages:l,manual:u}},JD=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 je(c),d=l.data;if(!At(d.servers)||!(pn in d.servers)||sl(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 oe(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=>YD(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):KD(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.`}},XD=(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.`}},zD=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 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.`,...AA(t),a?tf({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:[$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),tf(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."],qD=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),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.`,...CA(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:EA(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]}},QD=async(e,t,n)=>{if(!n.hookBinaryIsDurable())return{registered:!1,command:null,reason:"ephemeral-runtime"};let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null,reason:"no-config"};let o=[];for(let s of r){if(!await x(s))return{registered:!1,command:null,reason:"no-config"};try{let{data:i}=await je(s),c=At(i.servers)?i.servers[pn]:void 0;if(!PA(c,n))return{registered:!1,command:null,reason:c===void 0?"absent":sl(c,n)==="stale-owned"?"stale":"foreign"};o.push(c.command)}catch{return{registered:!1,command:null,reason:"unreadable"}}}let a=o[0]||null;return{registered:!0,command:o.every(s=>s===a)?a:null}};var eL=async(e={installedVariant:Uo,remoteServerVariant:Kp,isRemoteDevContext:Fr})=>{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}},tL={installedVariant:Uo,remoteServerVariant:Kp,detectVscodeLmProviderEligibility:qb,configureVscodeExtension:fA,vscodeExtensionPointsAt:mA,vscodeExtensionAwaitingReload:tl,vscodeExtensionReceiptMode:nl,hookBinaryIsDurable:te,hookBinaryPath:Oe,mcpServerCommand:Ge,vscodeUserMcpConfigPaths:Xb,isRemoteDevContext:Fr},nL=(e={})=>{let t={...tL,...e},n=()=>eL(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 ${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")?zD(a,r,o,t.configureVscodeExtension,c,s,t):qD(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?QD(r,o,t):{registered:!1,command:null,reason:"no-config"}},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(nf)?.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(nf))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 JD(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(XD(g.reason,o,a,g.detail)))}let p=Os(o),f=await ol(p),m=f.kind==="missing"||f.kind==="array"&&!rf(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 "${dr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=rf(f.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${dr} Custom Endpoint from ${p}`]};await xA(p,w);let y=[...u,`Removed the ${dr} Custom Endpoint from ${p}.`];return await oe(p),{status:l||i.manual?"manual":"reverted",changedFiles:[...h,p],messages:y}}}},MA=nL();import{accessSync as PL,constants as zA,statSync as DL}from"node:fs";import{readFile as qA,rm as Ls}from"node:fs/promises";import{homedir as mf,platform as sC}from"node:os";import{delimiter as LL,join as hf,resolve as NL}from"node:path";import{execFile as iL}from"node:child_process";import{readFile as cL}from"node:fs/promises";import{homedir as sf,platform as lL}from"node:os";import{join as Ds}from"node:path";import{join as rL}from"node:path";var of="Iv1.b507a08c87ecfe98",oL="https://github.com/login/device/code",aL="https://github.com/login/oauth/access_token",sL="read:user",BA=1e4,Go=()=>rL(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(oL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:of,scope:sL}),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}},UA=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(aL,{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"}},HA=async(e,t)=>{let n=Go();return await we(n,`${JSON.stringify({token:e,clientId:of,mintedAtIso:t},null,2)}
|
|
115
|
-
`),n},il=async()=>{try{let e=await M(Go());if(!
|
|
116
|
-
`))}`]:[],`export ${fl}=${ve(n)}`]},
|
|
117
|
-
`).map(
|
|
118
|
-
`)):de&&K&&await Ls(F,{force:!0}),await Dc(c,q,mn)}catch(X){try{ce!==void 0&&K?await we(F,ce):K&&await Ls(F,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw X}return{status:"configured",messages:W,changedFiles:[c,...T.length>0||de&&K?[F]:[],...Z?[On()]:[]]}},d=await r(),u=d!==void 0&&!
|
|
111
|
+
${a}${s},`,d=`${i}${l}${c}`;try{let u=wt(d);if(!Hb(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 eD}from"node:child_process";import{readdirSync as tD,statSync as nD}from"node:fs";import{createHash as oA,randomBytes as rD,randomUUID as aA}from"node:crypto";import{chmod as oD,lstat as Xp,mkdir as zp,readdir as sA,readFile as ln,rm as iA,unlink as el,writeFile as qp}from"node:fs/promises";import{homedir as Ho,platform as Qp}from"node:os";import{dirname as Zp,join as bt,posix as tA,win32 as aD}from"node:path";import{promisify as sD}from"node:util";var cn="0.1.29";var dr="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",qc="c341829c0dacfc512fa49fb951be4864ca3e7d6b46d6befbee84e663daa8e9a7",Gb="UEsDBBQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeItLyqXVXGwiynQiVAhVyfSwwIkcr1lyS4HBlKb++2F19WXGSSg5y2+XMvMf54COz96vSsiVGMt71eFdccYZOeW1c0eNVmnd+4+/zy4tsAuoJChyDM3OkxB63Idfiqg5aldZRjy9SCjdSklpgCSRKo6InP09C+VJqXKL1AaNc0qrT+sjrq253E36jzwDoaCRTuBYnv7y4yMaYQEOC+uciG2p0yaQ1G4ErKiiwx9F1/p5yNtQ9Dm4dYd1ZkvIa+T6rK9EV179zNqlm1tAC49aVM9ni3hoKFtafoMS835jY3Ef2OGUDrzGTh/Y2AElFE5Lxrk73hgIo7PEQkTAuked9rRmugjXKJLaBLCDhM6xZ6TVaYj5uDJ3nCCGgZgMfjPWJUTXbw2+80yL6qlhs9/QrBE9/EPPzuVEGLLObinQafxaiXxqNkfUnQ5HJg/22CTxAQfnLGMpks9rYB5Cw8NEg5f3huzGohXHIRgjRGVdk8sDe+H8AazGu722N0BRaZfLFYu3WuE5i3fW0Dd0trJsmjndD8mioAjtNlTZe1DmLO1cYV3cWbIU9/k9XdK+bKZcnI60Suno6bjGg0+iUQdoBvwWwPls/BOhP4/QO6NnHp2bG3lXmDNCRV2DNZ9Tbc/O2XB3MLOp+MHWIJ7CvwJ2cNqoqIQ3ao9uCpVjhGYBTjEujk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ABMAAAAAAAAAAAAAALSBaAMAAFtDb250ZW50X1R5cGVzXS54bWxQSwECPwMUAAgICAAKWhhdcQ3Z86YCAAC7BQAAFgAAAAAAAAAAAAAApIFrBAAAZXh0ZW5zaW9uL3BhY2thZ2UuanNvblBLAQI/AxQACAgIAARaGF0wVq3AThEAACgTAAASAAAAAAAAAAAAAACkgVUHAABleHRlbnNpb24vaWNvbi5wbmdQSwECPwMUAAAICAAXWhhdC7fjr0sCAAB9BAAAEwAAAAAAAAAAAAAAtIHjGAAAZXh0ZW5zaW9uL3JlYWRtZS5tZFBLAQI/AxQACAgIAMtZGF2yhnqNeQIAACcEAAAVAAAAAAAAAAAAAACkgV8bAABleHRlbnNpb24vTElDRU5TRS50eHRQSwECPwMUAAgICAAXWhhdpzIc9AM5AAAjqQAAGwAAAAAAAAAAAAAApIEbHgAAZXh0ZW5zaW9uL2Rpc3QvZXh0ZW5zaW9uLmpzUEsFBgAAAAAHAAcA1gEAAGdXAAAAAA==";import{readFile as jb}from"node:fs/promises";import{homedir as jr,platform as Fo}from"node:os";import{join as xn,posix as YP,win32 as JP}from"node:path";var vs=["Code","Code - Insiders","VSCodium"],Gp="1.121.0",Vb=1,XP=121,Zb="1.102.0",Kb=1,zP=102,qP={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])}},Vp=e=>{let t=Qc(e);return t?t.major!==Vb?t.major>Vb:t.minor>=XP:!1},Yb=e=>{let t=Qc(e);return t?t.major!==Kb?t.major>Kb:t.minor>=zP:!1},QP=async e=>{if(Fo()!=="darwin")return;let t=xn("/Applications",`${qP[e]}.app`,"Contents","Resources","app","package.json");if(await x(t))try{let n=JSON.parse(await jb(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},Jb=(e,t=Fo(),n=jr(),r=process.env)=>{switch(t){case"darwin":return xn(n,"Library","Application Support",e);case"win32":return xn(r.APPDATA??xn(n,"AppData","Roaming"),e);default:return xn(n,".config",e)}},Kp=(e,t)=>e?t==="win32"?JP.join:YP.join:xn,Wo=(e,t=!1,n=Fo(),r=jr(),o=process.env)=>t?Kp(t,n)(r,Ss[e],"data","User"):xn(Jb(e,n,r,o),"User"),Xb=async(e,t=!1,n=Fo(),r=jr(),o=process.env)=>{try{let a=Kp(t,n)(Wo(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await jb(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[]}},zb=async(e,t=Fo(),n=jr(),r=process.env)=>{let a=(await Xb(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},qb=async(e,t=!1,n=Fo(),r=jr(),o=process.env)=>{let a=Kp(t,n),s=Wo(e,t,n,r,o),i=await Xb(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},Uo=async()=>{for(let e of vs)if(await x(Jb(e)))return e},Ss={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},Qb=(e,t=jr())=>xn(t,Ss[e],"extensions"),jp=async(e=jr())=>{for(let t of vs)if(await x(xn(e,Ss[t])))return t},eA=async e=>{let t=e??await Uo();if(!t)return{status:"unknown"};let n=await QP(t);return n?{variant:t,version:n,status:Vp(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var z="anyray.anyray-vscode",ef="vscode-handoffs",cA="vscode-receipts",Is=2,iD=sD(eD),Rn={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"]}},cD={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"}},lD=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),lA=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&lD(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Es=e=>{if(lA(e))try{return new URL(e.trim()).origin}catch{return}},dD=(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)},uD=e=>{try{return tD(e)}catch{return[]}},pD=e=>{try{return nD(e).mtimeMs}catch{return}},fD=(e,t,n,r,o)=>{if(!Fr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=Rn[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)},mD=(e,t,n)=>{let{macAppName:r,commands:o}=Rn[e],a=o[0],s=[];for(let i of["/Applications",tA.join(t,"Applications")])for(let c of n(i))dD(c,r)&&s.push(tA.join(i,c,"Contents/Resources/app/bin",a));return s},hD=(e,t=Qp(),n=Ho(),r=process.env,o=uD,a=pD)=>{let s=fD(e,n,r,o,a);if(t==="darwin")return[...new Set([...Rn[e].commands,...mD(e,n,o),...s])];if(t!=="win32"){let u=Rn[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=cD[e],c=aD.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)),Rn[e].commands[0],...s])]},dA={run:async(e,t)=>({stdout:(await iD(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>rD(24).toString("base64url"),home:"",commandCandidates:e=>hD(e)},Zr=(e,t)=>bt(e,".anyray",cA,`${t}.json`),tf=(e,t)=>bt(e,".anyray",cA,`${t}.applied.json`),uA=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{}},Yp=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}},pA=async(e,t)=>{let n=await uA(e,t);if(n)return Yp(n.command,t)},yD=async(e,t,n)=>{let r=bt(e,".anyray",ef);for(let o of n){if(!o.endsWith(".json"))continue;let a=bt(r,o);try{if(!(await Xp(a)).isFile()||JSON.parse(await ln(a,"utf8")).variant!==t)continue;await el(a)}catch{}}},gD=async(e,t)=>{let n=bt(e,".anyray",ef),r;try{r=await sA(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=bt(n,o);try{if(!(await Xp(a)).isFile()||JSON.parse(await ln(a,"utf8")).variant!==t)continue;await el(a)}catch{}}},wD=async(e,t)=>{try{let n=JSON.parse(await ln(Zr(e,t),"utf8"));return n.extensionVersion===cn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==dr}catch{return!1}},fA=250,bD=9e4,AD=bD/fA,CD=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!==dr?"reload-required":a.version===Is&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(fA)}return"timeout"},kD=200,nA=(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,kD))}return r.join(": ")},vD=async e=>{try{let t=await Xp(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},rA=e=>oA("sha256").update(e).digest("hex"),SD=async(e=Ho())=>{let t=Buffer.from(Gb,"base64");if(t.length<4||t[0]!==80||t[1]!==75||rA(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(rA(await ln(r))===qc)return r}catch{}await zp(n,{recursive:!0,mode:448});let o=`${r}.${aA()}.tmp`;try{await qp(o,t,{mode:384}),await he(o,r),Qp()!=="win32"&&await oD(r,384)}finally{await iA(o,{force:!0})}return r},Jp=e=>{if(e===void 0)return"null";if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(n=>Jp(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Jp(t[n])}`).join(",")}}`},mA=(e,t,n)=>oA("sha256").update(Jp({gatewayUrl:Es(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:cn,extensionDistSha256:dr,profiles:[...n].sort()})).digest("hex"),ID=async(e,t,n,r,o,a)=>{let s=JSON.parse(await ln(tf(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==mA(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===dr&&i.gatewayUrl===Es(t.origin)?await pA(e,a)===!0:!1},ED=async(e,t,n,r)=>{let o=tf(e,t),a=`${o}.${aA()}.tmp`;try{await zp(Zp(o),{recursive:!0,mode:448}),await qp(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
112
|
+
`,{mode:384}),await he(a,o)}catch{}finally{await iA(a,{force:!0})}},xD=async(e,t)=>{await el(tf(e,t)).catch(()=>{})},hA=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...dA,...r,home:r.home??Ho()},s=Rn[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!lA(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 uA(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!Vp(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>zb(b,Qp(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await ID(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 SD(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await vD(p))return{ok:!1,reason:"extension-missing"}}let f=a.nonce(),m=bt(a.home,".anyray",ef,`${f}.json`),h=Zr(a.home,s.slug);await zp(Zp(m),{recursive:!0,mode:448});let w=await sA(Zp(m)).catch(()=>[]);await qp(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:dr})}
|
|
113
|
+
`,{mode:384}),await yD(a.home,s.slug,w).catch(()=>{});let y={installed:[],failed:[]},g=!1;try{if(n==="configure"){let k=await wD(a.home,s.slug);if(k||await Yp(l,a)!==!0)try{await a.run(l,["--install-extension",p,"--force"])}catch(C){return g=!0,{ok:!1,reason:"install-failed",detail:nA(C,f)}}for(let C of u)try{(k||await Yp(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:nA(k,f)}}let b=await CD(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 ED(a.home,s.slug,mA(t,o,u),f);else{await xD(a.home,s.slug),await gD(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,Rn[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==cn||n.extensionDistSha256!==dr)}catch{return!1}},nl=async(e,t=Ho())=>{try{let n=JSON.parse(await ln(Zr(t,Rn[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}},yA=async(e,t,n=Ho(),r={})=>{try{let o=Es(t);if(!o)return!1;let a=JSON.parse(await ln(Zr(n,Rn[e].slug),"utf8"));if(!(a.version===Is&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===cn&&a.extensionDistSha256===dr))return!1;let i={...dA,...r,home:n};return await pA(e,i)===!0}catch{return!1}};var dn="extensions.supportAgentsWindow",un="chat.agentHost.byokModels.enabled",xs=e=>_D(Ve(e),"User","settings.json"),gA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),DD=e=>gA(e)&&e[z]===!0,wA=async(e,t={})=>{let n=xs(e),r=t.read??(f=>RD(f,"utf-8")),o=t.exists??x,a=t.write??(async(f,m)=>{await PD(TD(f),{recursive:!0}),await OD(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(!gA(i))return{status:"manual",reason:`${n} is not a JSON object`};let c=s,l=!1;if(!(dn in i)){let f=Hp(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=Hp(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=DD(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}},nf=(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 LD}from"node:child_process";import{platform as ND}from"node:os";var bA={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},$D=(e,t,n)=>LD(e,t,n),AA=$D,MD,BD=()=>{let e=MD??ND();if(e==="win32"){let n=AA(ws("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],bA);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=AA("pgrep",[n,r],bA);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},FD=BD,Rs=()=>FD();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 ur="Anyray",pn="anyray",EA="--anyray-owner=vscode-profile-v1",Os=e=>IA(Ve(e),"User","chatLanguageModels.json"),jD=e=>IA(Ve(e),"User","settings.json"),Ts="github.copilot.advanced",al="debug.overrideCapiUrl",At=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ZD=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}},xA=e=>{let t=e[Ts];if(!At(t)||!ZD(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]},RA=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 SA(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"}}},OA=async(e,t)=>{await UD(KD(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${VD()}`;try{await GD(n,`${JSON.stringify(t,null,2)}
|
|
114
|
+
`,{flag:"wx",mode:384}),await he(n,e),await WD(e,384)}finally{await HD(n,{force:!0}).catch(()=>{})}},rf=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!==ur||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!==RA(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}})},of=e=>{let t=e.filter(n=>!rf(n));return{next:t,removed:t.length!==e.length}},YD=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 "${ur}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=of(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${ur}" Custom Endpoint from ${n}.`]};try{return await OA(n,o),await oe(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${ur}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${ur}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},JD=async e=>{try{let t=wt(await SA(e,"utf-8"));if(At(t))return xA(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.`]}},TA=async(e,t)=>{let n=jD(e),r;try{r=await M(n)}catch{return JD(n)}let{next:o,removed:a}=xA(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 oe(n),{changedFiles:[n],manual:!1,messages:[`Removed the retired Anyray Copilot debug override from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the retired Anyray Copilot debug override from ${n}; remove it manually.`]}}},XD=async(e,t)=>{let n=await YD(e,t),r=await TA(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},_A=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,EA]}},PA=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},DA=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),zD=e=>Array.isArray(e.args)&&e.args.at(-1)===EA,LA=(e,t)=>{if(!t.hookBinaryIsDurable()||!At(e)||!PA(e,["type","command","args"]))return!1;let n=_A(t);return e.type==="stdio"&&e.command===n.command&&DA(e.args,n.args)},qD=(e,t)=>{if(!At(e)||!PA(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&&DA(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)===zn&&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))},sl=(e,t)=>LA(e,t)?"exact":At(e)&&zD(e)||qD(e,t)?"stale-owned":"foreign",CA=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.`,QD=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 je(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=_A(o),C=b[pn],S=C===void 0?void 0:sl(C,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(CA(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(sl(h.servers[pn],o)==="foreign"){u=!0,l.push(CA(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 oe(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 (${Zb}+).`),{changedFiles:c,messages:l,manual:u}},eL=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 je(c),d=l.data;if(!At(d.servers)||!(pn in d.servers)||sl(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 oe(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}},NA=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.)`,kA=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."],MA=(e,t,n,r)=>({runMcp:o=>QD(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):XD(e,o)}),BA=(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 ${Gp} 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.`}},tL=(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.`}},nL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=MA(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.`,...kA(t),a?nf({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:[BA(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),p=await i(!1),f=a?void 0:await wA(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()]:[],...kA(t),nf(f??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:NA(d.profiles),...p.messages,...u.messages]}},vA=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."],rL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=MA(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.`,...vA(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:RA(f)}))});if(!d.ok)return{status:"manual",messages:[BA(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()]:[],...vA(t),...d.alreadyCurrent?[]:NA(d.profiles),...p.messages,...u.messages]}},oL=async(e,t,n)=>{if(!n.hookBinaryIsDurable())return{registered:!1,command:null,reason:"ephemeral-runtime"};let r=await n.vscodeUserMcpConfigPaths(e,t);if(r.length===0)return{registered:!1,command:null,reason:"no-config"};let o=[];for(let s of r){if(!await x(s))return{registered:!1,command:null,reason:"no-config"};try{let{data:i}=await je(s),c=At(i.servers)?i.servers[pn]:void 0;if(!LA(c,n))return{registered:!1,command:null,reason:c===void 0?"absent":sl(c,n)==="stale-owned"?"stale":"foreign"};o.push(c.command)}catch{return{registered:!1,command:null,reason:"unreadable"}}}let a=o[0]||null;return{registered:!0,command:o.every(s=>s===a)?a:null}};var aL=async(e={installedVariant:Uo,remoteServerVariant:jp,isRemoteDevContext:Fr})=>{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}},sL={installedVariant:Uo,remoteServerVariant:jp,detectVscodeLmProviderEligibility:eA,configureVscodeExtension:hA,vscodeExtensionPointsAt:yA,vscodeExtensionAwaitingReload:tl,vscodeExtensionReceiptMode:nl,hookBinaryIsDurable:te,hookBinaryPath:Oe,mcpServerCommand:Ge,vscodeUserMcpConfigPaths:qb,isRemoteDevContext:Fr},iL=(e={})=>{let t={...sL,...e},n=()=>aL(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 ${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 ${Gp} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||Yb(i.version);return ee(r,"copilot")?nL(a,r,o,t.configureVscodeExtension,c,s,t):rL(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?oL(r,o,t):{registered:!1,command:null,reason:"no-config"}},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(rf)?.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(rf))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 eL(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await TA(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(tL(g.reason,o,a,g.detail)))}let p=Os(o),f=await ol(p),m=f.kind==="missing"||f.kind==="array"&&!of(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 "${ur}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=of(f.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${ur} Custom Endpoint from ${p}`]};await OA(p,w);let y=[...u,`Removed the ${ur} Custom Endpoint from ${p}.`];return await oe(p),{status:l||i.manual?"manual":"reverted",changedFiles:[...h,p],messages:y}}}},FA=iL();import{accessSync as ML,constants as QA,statSync as BL}from"node:fs";import{readFile as eC,rm as Ls}from"node:fs/promises";import{homedir as hf,platform as cC}from"node:os";import{delimiter as FL,join as yf,resolve as WL}from"node:path";import{execFile as pL}from"node:child_process";import{readFile as fL}from"node:fs/promises";import{homedir as cf,platform as mL}from"node:os";import{join as Ds}from"node:path";import{join as cL}from"node:path";var af="Iv1.b507a08c87ecfe98",lL="https://github.com/login/device/code",dL="https://github.com/login/oauth/access_token",uL="read:user",WA=1e4,Go=()=>cL(Q(),"copilot-seat-login.json"),UA={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},sf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),HA=async(e={})=>{let t={...UA,...e};try{let n=await t.fetch(lL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:af,scope:uL}),signal:AbortSignal.timeout(WA)});if(!n.ok)return;let r=await n.json();if(!sf(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}},GA=async(e,t={})=>{let n={...UA,...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(dL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:af,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(WA)})).json();if(!sf(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"}},VA=async(e,t)=>{let n=Go();return await we(n,`${JSON.stringify({token:e,clientId:af,mintedAtIso:t},null,2)}
|
|
115
|
+
`),n},il=async()=>{try{let e=await M(Go());if(!sf(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var hL=5e3,lf=5e3,yL=["copilot-cli","CopilotCLI"],gL="https://api.github.com/copilot_internal/user",jA="~/.copilot/config.json",ZA="macOS Keychain (Copilot CLI)",YA=e=>e===jA||e===ZA,Vo=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),Kt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wL=()=>process.env.XDG_CONFIG_HOME?.trim()||Ds(cf(),".config"),bL=()=>process.env.XDG_DATA_HOME?.trim()||Ds(cf(),".local","share"),AL=async()=>{try{let e=await fL(Ds(cf(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return Vo(t)?t:void 0}catch{}},CL=async e=>{try{let t=await M(Ds(wL(),"github-copilot",e));if(!Kt(t))return;for(let n of Object.values(t))if(Kt(n)&&Vo(n.oauth_token))return n.oauth_token}catch{}},kL=async()=>{try{let e=await M(Ds(bL(),"opencode","auth.json")),t=Kt(e)?e["github-copilot"]:void 0;if(!Kt(t)||t.type!=="oauth")return;if(Vo(t.access))return t.access;if(Vo(t.refresh))return t.refresh}catch{}},vL=(e,t)=>new Promise((n,r)=>{try{pL(e,[...t],{timeout:hL},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),SL=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return Vo(r)?r:void 0}catch{return}},IL=async(e=vL)=>{for(let t of yL){let n=await SL(t,e);if(n)return n}};var cl={env:process.env,platform:mL,tokenFromDeviceLogin:il,tokenFromCopilotCliConfig:AL,tokenFromSharedConfig:CL,tokenFromOpenCode:kL,tokenFromKeychain:IL,fetch:(...e)=>fetch(...e)},EL=new Set([401,403,404]),ll=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,JA=e=>{let t=e?.trim().toLowerCase()??"";return t&&t!=="default"&&ll.test(t)?t:"default"},xL=e=>e!=="default"&&ll.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",RL=e=>{if(typeof e!="string")return"default";let t=e.trim().match(/^https:\/\/api\.([a-z0-9-]{1,63})\.githubcopilot\.com\/?$/)?.[1];return t&&ll.test(t)?t:"default"},df=async(e,t={})=>{let n={...cl,...t},r=new AbortController,o=setTimeout(()=>r.abort(),lf);try{let a=await n.fetch(gL,{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:RL(s)}}return{verdict:EL.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var Ko=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${ll.test(n)?n:"default"}/header/models`,a=await KA(o,e,r.clientKey,t);if(a.length>0)return a}return KA(`${xL(n)}/models`,e,void 0,t)},KA=async(e,t,n,r={})=>{let o={...cl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),lf);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)}},dl=async(e,t,n,r={})=>{let o={...cl,...r},a=new AbortController,s=setTimeout(()=>a.abort(),lf);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)}},ul=async(e={},t={})=>{let n={...cl,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return Vo(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:ZA,read:()=>n.tokenFromKeychain()}]:[],{source:jA,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await df(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 pl,platform as zA}from"node:os";import{join as st}from"node:path";import{execFile as OL}from"node:child_process";import{readFile as TL,readdir as _L}from"node:fs/promises";var PL=3e3,DL="Claude Code-credentials",LL=["copilot-cli","CopilotCLI"],qA=e=>new Promise(t=>{try{OL("security",["find-generic-password","-s",e],{timeout:PL},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),NL=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=st(pl(),".claude");return!!(await x(st(e,".oauth_token"))||await x(st(e,".credentials.json"))||zA()==="darwin"&&await qA(DL))},$L=async()=>{let e=st(process.env.CODEX_HOME?.trim()||st(pl(),".codex"),"auth.json");if(!await x(e))return!1;try{let t=JSON.parse(await TL(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},XA=async e=>{try{return(await _L(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},uf=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(pl(),".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 XA(st(pl(),t,"extensions")))return!0;for(let t of vs){if(await XA(Qb(t)))return!0;let n=st(Wo(t,!0),"globalStorage");if(await x(st(n,"github.copilot-chat"))||await x(st(n,"github.copilot")))return!0}if(zA()==="darwin"){for(let t of LL)if(await qA(t))return!0}return!1},fn=async()=>{let[e,t,n]=await Promise.all([NL(),$L(),uf()]);return{anthropic:e,openai:t,copilot:n}};var Xr="copilot-cli",mn="copilot-cli",UL=Rs,HL=()=>UL()?["VS Code is open \u2014 its Copilot CLI runs inside the extension host, which","captured your shell environment when the editor launched. Restart VS Code,","or its CLI chat and Autopilot sessions stay on native GitHub traffic and","never reach the gateway (no spend, no traces) even though this block is set."]:[],lC=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],gf=()=>Object.fromEntries(lC.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),tC=()=>yf(hf(),".anyray","copilot-cli.sh"),dC="# Managed by anyray-connect. Do not source this file anywhere else.",nC=e=>e.split(/\r?\n/,1)[0]===dC,GL=["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"],fl="COPILOT_PROVIDER_API_KEY",rC=e=>e.startsWith(`export ${fl}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Tn=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",VL=()=>Ps()[0],Ns=(e="default")=>`/copilot/${e}/header`,nq=Ns(),Yr=e=>e.replace(/\/+$/,""),KL=(e,t="default")=>`${Yr(e.openaiBaseUrl)}${Ns(t)}`,pf=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),mf="claude-sonnet-5",jL=()=>{let e=Ps()[0];return e===_s?mf:e},uC=e=>e.endpoints.includes(Tn(e.id)==="responses"?"/responses":"/chat/completions"),wf=e=>{let t=e.filter(uC),n=a=>{let s=/^claude-sonnet-(\d+(?:\.\d+)*)$/.exec(a);return s?s[1].split(".").map(Number):void 0},r=t.map(a=>({m:a,version:n(a.id)})).filter(a=>!!a.version).sort((a,s)=>oC(a.version,s.version)?-1:oC(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var oC=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n+=1){let r=(e[n]??0)-(t[n]??0);if(r!==0)return r>0}return!1},aC=(e,t,n,r,o,a="default")=>{let s=ue({...e.metadata,tool:Xr}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],...lC];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(KL(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${Tn(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...o?.maxPromptTokens?[`export COPILOT_PROVIDER_MAX_PROMPT_TOKENS='${o.maxPromptTokens}'`]:[],...o?.maxOutputTokens?[`export COPILOT_PROVIDER_MAX_OUTPUT_TOKENS='${o.maxOutputTokens}'`]:[],...i.length>0?[`export COPILOT_PROVIDER_HEADERS=${ve(i.join(`
|
|
116
|
+
`))}`]:[],`export ${fl}=${ve(n)}`]},ff=(e,t,n)=>{let r=ue({...e.metadata,tool:Xr});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${ve(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Tn(t)}'`,`export COPILOT_MODEL=${ve(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${ve(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${fl}=${ve(n)}`]:[]]},ZL=(e,t)=>t||!ee(e,"copilot"),sC=()=>{let e=GL.filter(t=>(process.env[t]??"")!=="");return e.length===0?[]:[`This shell still exports ${e.join(", ")} \u2014 Copilot CLI keeps using BYOK until you`,`run \`unset ${e.join(" ")}\` or open a new terminal (fully quit a long-lived parent app).`]},iC=(e,t=[])=>["Left on native GitHub Copilot inference \u2014 a Copilot seat was detected, but no","Copilot sign-in Connect can read. To route the CLI through Anyray with billing","KEPT on your Copilot plan, give Connect a seat token and re-run:",...e==="darwin"?[" - run `copilot` once and `/login` (macOS Keychain; read on",` \`anyray-connect --tools ${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`."],YL=(e=process.env.PATH,t=cC())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(FL)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=WL(o,n);try{if(!BL(a).isFile())continue;return ML(a,t==="win32"?QA.F_OK:QA.X_OK),a}catch{}}},JL=()=>yf(hf(),".copilot","config.json"),On=()=>yf(hf(),".copilot","mcp-config.json"),Jr="anyray",XL=()=>({type:"local",...Ge("profile"),tools:["*"]}),pr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zL=async()=>{let e=On(),t;try{t=await M(e)}catch{return{status:"skipped",message:`Skipped the Anyray retrieval MCP server because ${e} could not be parsed; it was left unchanged.`}}if("mcpServers"in t&&!pr(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=(pr(t.mcpServers)?t.mcpServers:{})[Jr];return r!==void 0&&!Ot(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}},qL=async e=>{let t=On(),n=e.json,r=pr(n.mcpServers)?n.mcpServers:{};r[Jr]=XL(),n.mcpServers=r,await Y(t,n)},QL=async()=>{let e=On(),t;try{let r=await M(e);if(!pr(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!pr(n)||!(Jr in n)||!Ot(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 oe(e),!0)},eN={resolveCopilotCommand:YL,platform:cC,detectCopilotSeat:uf,discoverSeatToken:ul,readDeviceLoginToken:il,fetchSeatModelCatalog:Ko,probeSeatChatModel:dl},tN=e=>`'${e.replace(/'/g,"''")}'`,nN=e=>e.split(`
|
|
117
|
+
`).map(tN).join(" + [Environment]::NewLine + "),rN=(e={})=>{let t={...eN,...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&&pf(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=JL();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 T=S.filter(rC),O=S.filter(X=>!rC(X)),F=tC(),q=[...O,...T.length>0?[`[ -r ${ve(F)} ] && . ${ve(F)}`]:[]],de=await x(F),ce=de?await eC(F,"utf8"):void 0,K=ce===void 0||nC(ce);if(T.length>0&&!K)return{status:"manual",messages:[`Refused to overwrite user-managed ${F}; move or rename that file, then run Connect again.`]};let ge=te(),me=ge?await zL():void 0,W=[`${c} \u2190 managed Anyray block (${mn})`,...I.map(X=>` ${X}`),...T.length>0?[`${F} \u2190 owner-only credential (mode 0600)`]:[],...E,me?.status==="skipped"?me.message:ge?`${On()} \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.`,...HL()];if(i.dryRun)return{status:"configured",messages:W};let Z=!1;me?.status==="installable"&&(await qL(me),Z=!0);try{T.length>0?await we(F,[dC,...T,""].join(`
|
|
118
|
+
`)):de&&K&&await Ls(F,{force:!0}),await Dc(c,q,mn)}catch(X){try{ce!==void 0&&K?await we(F,ce):K&&await Ls(F,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw X}return{status:"configured",messages:W,changedFiles:[c,...T.length>0||de&&K?[F]:[],...Z?[On()]:[]]}},d=await r(),u=d!==void 0&&!pf(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=jL(),E=I!==mf||!!process.env.ANYRAY_COPILOT_MODEL,T=await t.fetchSeatModelCatalog(y.token,{},S,{laneOrigin:Yr(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),O=T.find(W=>W.id===I);if(!E){let W=wf(T);if(O=W[0],!i.dryRun&&W.length>0){let Z=_=>`${Yr(s.origin)}/v1${Ns(S)}/${Tn(_)==="responses"?"responses":"chat/completions"}`,X={...gf(),authorization:`Bearer ${y.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},Je=new Set,We;for(let _ of W.slice(0,4)){let L=await t.probeSeatChatModel(Z(_.id),X,_.id);if(L==="ok"){We=_;break}if(L==="unreachable")break;Je.add(_.id)}O=We??W.find(_=>!Je.has(_.id))??W[0]}I=O?.id??mf}let F=s.clientKey??s.placeholderKey,q=F&&s.clientKey?_t(F):F,de=aC(s,I,y.token,F,O,S),ce=aC(s,I,_t(y.token),q,O,S),K=Tn(I),ge=T.filter(W=>uC(W)&&Tn(W.id)===K).map(W=>W.id).filter(W=>W!==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)":T.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,...T.length===0&&YA(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",...ce.map(W=>{let Z=W.indexOf("="),X=W.slice(7,Z),Je=W.slice(Z+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${X}', ${nN(Je)}, '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,ce,me)}if(!ZL(s,m)){if(f&&!i.dryRun){let S=gt();if(await fs(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:",...iC(t.platform(),g),...sC()]}}return{status:"held",messages:[...f&&i.dryRun?[`would remove a stale Anyray ${mn} block from ${gt()} (org lane, not chosen)`]:[],...iC(t.platform(),g)]}}let b=VL(),k=s.clientKey??s.placeholderKey,C=k&&s.clientKey?_t(k):k;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...ff(s,b,C).map(S=>{let[I,...E]=S.replace(/^export /,"").split("=");return` setx ${I} "${E.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${fl} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(ff(s,b,k),ff(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=tC(),l=await x(c),d=l?nC(await eC(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 ${On()} if registered`,...await x(Go())?[`would remove the Copilot sign-in Connect minted (${Go()})`]:[]]};let u=await fs(i,mn);d&&await Ls(c,{force:!0});let p=await QL(),f=Go(),m=await x(f);m&&await Ls(f,{force:!0});let h=[...u?[i]:[],...d?[c]:[],...p?[On()]:[],...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 ${On()}`]:[],...sC()],changedFiles:h.length>0?h:void 0}},async pointsAt(s){let i=await r();return o(i,s)||a(i,s)},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let s=On();if(!await x(s))return{registered:!1,command:null,reason:"no-config"};try{let i=await M(s),c=pr(i)?i.mcpServers:void 0,l=pr(c)?c[Jr]:void 0;return!pr(l)||!Ot(l,"profile")?{registered:!1,command:null,reason:l===void 0?"absent":"foreign"}:{registered:!0,command:typeof l.command=="string"?l.command:null}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async inferenceAuthLanes(){try{let s=await r();return s===void 0?["native"]:pf(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(Xr)?!0:!await t.detectCopilotSeat()}}},pC=rN();import{homedir as bC}from"node:os";import{join as mr}from"node:path";import{readFile as AC}from"node:fs/promises";import{readFile as fC,rm as oN}from"node:fs/promises";var mC="// Managed by anyray-connect: OpenCode trim carrier v1",aN=5e3,bf=e=>`${mC}
|
|
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 = ${aN}
|
|
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 QL(e,{force:!0}),"removed")};var Af="https://opencode.ai/config.json",Dn="x-anyray-metadata",Dt="x-anyray-api-key",Cf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],_n="Authorization",pr=["anthropic","openai"],Ln="github-copilot",tN="header",Pn="anyray",nN=()=>process.env.XDG_CONFIG_HOME?.trim()||fr(gC(),".config"),rN=()=>process.env.XDG_DATA_HOME?.trim()||fr(gC(),".local","share"),yl=()=>fr(nN(),"opencode"),ml=()=>fr(yl(),"plugins","anyrayTrim.js"),bC=()=>fr(rN(),"opencode"),AC=async()=>{try{let e=await wC(fr(bC(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return U(t)?{chatGptOAuth:U(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}}},mC=async()=>(await AC()).chatGptOAuth,oN=["opencode.jsonc","opencode.json","config.json"],jo=async()=>{let e=yl(),t=[];for(let n of oN){let r=fr(e,n);await x(r)&&t.push(r)}return t},hC=async()=>(await jo())[0]??fr(yl(),"opencode.json"),kf=()=>ZA(process.env.ANYRAY_COPILOT_PLAN),vf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${kf()}/${tN}`,U=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}/`)},aN=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===pr[0]||n===pr[1]||n===Ln?[]:U(r)&&U(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`${pr[0]}/${o}`},If=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)If(n,t);return t}if(!U(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},sN=(e,t,n)=>{if(!U(e)||!U(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(!U(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]=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(!U(e)||!U(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},iN=e=>{if(U(e))for(let t of pr){let n=e[t];if(U(n)&&U(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Ms=e=>{if(!U(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Ot({command:t,args:n},"profile")},hl=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),cN=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return U(t)&&t.tool==="opencode"}catch{return!1}},Tf=e=>ee(e,"copilot")&&!!e.clientKey,lN=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".`]:[],dN=(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.`]:[],uN=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."]:[],pN=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Af);let o=!1;if(n)if("mcp"in r&&!U(r.mcp))o=!0;else{let g=U(r.mcp)?{...r.mcp}:{},b=g[Pn];b!==void 0&&!Ms(b)?o=!0:(g[Pn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=g)}else if(U(r.mcp)&&Ms(r.mcp[Pn])){let g={...r.mcp};delete g[Pn],Object.keys(g).length===0?delete r.mcp:r.mcp=g}let a=U(r.provider)?{...r.provider}:{},s=aN(a,t.origin),i=s.every(g=>sN(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&&!U(k.headers)){u.push(g);continue}let C=U(k.headers)?{...k.headers}:{},S=!1;for(let[I,E]of[[Dt,f],...m?[[Dn,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?[]:pr.filter(g=>g!=="openai"||!ee(t,"openai")),w=t.byoUpstream;for(let g of h){let b=U(a[g])?{...a[g]}:{},k=U(b.options)?{...b.options}:{};k.baseURL=p;let C=U(k.headers)?{...k.headers}:{};if(g==="anthropic"&&w)k.apiKey=w.key,C[_n]=`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[_n];for(let S of Cf)delete C[S]}C[Dt]=f,m&&(C[Dn]=m),k.headers=C,b.options=k,a[g]=b}let y=c.length===0&&Tf(t);if(y){let g=U(a[Ln])?{...a[Ln]}:{},b=U(g.options)?{...g.options}:{};b.baseURL=vf(t);let k=U(b.headers)?{...b.headers}:{};k[Dt]=t.clientKey,m&&(k[Dn]=m),b.headers=k,g.options=b,a[Ln]=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}},fN=["baseURL","apiKey"],yC=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!U(s)||!U(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=U(c.headers)?{...c.headers}:void 0,p=u?.[Dt],f=hl(p);if(d&&(delete c.baseURL,l=!0),u&&(d||f)){let m=u,h=U(r)?r.options:void 0,w=U(h)&&U(h.headers)?h.headers:void 0;for(let y of[Dt,Dn])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=U(r)?r.options:void 0,u=U(d)?d:{},p=U(c.headers)?c.headers:{},f=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof p[Dt]=="string"||typeof p[Dn]=="string"||Cf.some(m=>m in p);if(!o&&!f)return!1;for(let m of fN)m in u?c[m]!==u[m]&&(c[m]=u[m],l=!0):m in c&&(delete c[m],l=!0);if(U(c.headers)){let m={...c.headers},h=U(u.headers)?u.headers:{};"x-anyray-custom-host"in m&&_n in m&&(_n in h?m[_n]!==h[_n]&&(m[_n]=h[_n],l=!0):(delete m[_n],l=!0));for(let w of[Dt,Dn,...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},mN=(e,t,n)=>{let r=e[t];if(!U(r)||!U(r.options)||!U(n)||!U(n.options))return!1;let o={...r.options};if(!U(o.headers)||"headers"in n.options&&!U(n.options.headers))return!1;let a={...o.headers},s=U(n.options.headers)?n.options.headers:{},i=!1;return!(Dt in s)&&hl(a[Dt])&&(delete a[Dt],i=!0),!(Dn in s)&&cN(a[Dn])&&(delete a[Dn],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},hN=(e,t)=>{let n={...e},r=!1,o=iN(e.provider);if(U(n.mcp)&&Ms(n.mcp[Pn])){let c={...n.mcp};delete c[Pn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!U(n.provider))return{next:n,removed:r};let a={...n.provider},s=U(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===Af&&pr.every(c=>{let l=a[c];return U(l)&&U(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of pr)yC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...pr,Ln]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;mN(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&U(u)&&U(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,Ln,!0,s[Ln])&&(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 mC();return{installed:n,detail:n?`${await hC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await hC(),r=e.openaiBaseUrl,o=ue({...e.metadata,tool:"opencode"}),a=Tf(e),s=ee(e,"openai"),i=await mC(),c;try{c=await je(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": { "${Dt}": "<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 $r()?Ge("profile"):void 0,{next:d,customProviders:u,migratedProviders:p,modelRefsRemapped:f,customHeadersAdded:m,customHeaderConflicts:h,mcpConflict:w}=pN(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)"}`,...lN(e),...dN(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).",...uN(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Pn} 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=ml();if(te())try{let E=await fC(I,ts(ze,["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 jo())try{let{data:n}=await je(t);if(!U(n.provider))continue;for(let r of Object.values(n.provider))if(!(!U(r)||!U(r.options))&&Rf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=await jo();if(e.length===0)return{registered:!1,command:null,reason:"no-config"};let t=!1,n=!1;for(let r of e)try{let{data:o}=await je(r);if(!U(o.mcp))continue;let a=o.mcp[Pn];if(!Ms(a)||!U(a)){a!==void 0&&(t=!0);continue}return{registered:!0,command:Array.isArray(a.command)&&typeof a.command[0]=="string"?a.command[0]:null}}catch{n=!0}return{registered:!1,command:null,reason:t?"foreign":n?"unreadable":"absent"}},async integrationStatus(){let e,t=!0;try{let i=await $s(ml());e=i==="absent"?"missing":i,e==="owned"&&(t=await wC(ml(),"utf-8")===wf(ts(ze,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await jo()){let c;try{c=await je(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!U(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Pn];if(l!==void 0)if(Ms(l))if(n=!0,!U(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 $r()?"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 je(r);if(U(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!U(s)||!U(s.options)){e.add("unknown");continue}let i=s.options,c=U(i.headers)?i.headers:{};if(a===Ln&&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===Ln&&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(hl(c[Dt])||hl(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=ml(),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 je(i)}catch{s.push(i);continue}let{next:l,removed:d}=hN(c.data,await Bo(i));d&&(await sn(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await oe(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 yN}from"node:os";import{dirname as gN,join as mr}from"node:path";import{mkdir as wN,readdir as bN,readFile as SC,rm as IC}from"node:fs/promises";var _f="48ff8bb9a7afde1d9e8468d632f84b46f199e6a28657833b113de93698d9ac63",vC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyNTYwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0KICAgICAgICBdCiAgICAgIH0KICAgIH0KICB9LAogICJjb25maWdTY2hlbWEiOiB7CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogZmFsc2UsCiAgICAicmVxdWlyZWQiOiBbImdhdGV3YXlVcmwiXSwKICAgICJwcm9wZXJ0aWVzIjogewogICAgICAiZ2F0ZXdheVVybCI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBbnlyYXkgZ2F0ZXdheSBvcmlnaW4sIGUuZy4gaHR0cHM6Ly9nYXRld2F5LmV4YW1wbGUuYW55cmF5LmFpIChubyAvdjEgc3VmZml4KS4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiUGVyc29uYWwgQW55cmF5IGNsaWVudCBrZXkgKGFya1/igKYpLiBTdXBwb3J0cyAke0VOVl9WQVJ9IHN1YnN0aXR1dGlvbjsgZGVmYXVsdHMgdG8gJHtBTllSQVlfQ0xJRU5UX0tFWX0uIgogICAgICB9LAogICAgICAidXNlciI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB1c2VyIChjb250ZW50LWZyZWU7IHVzdWFsbHkgYW4gZW1haWwpLiBPcHRpb25hbCDigJQgdGhlIGNsaWVudCBrZXkgYWxyZWFkeSBhdHRyaWJ1dGVzIHRoZSBlbnJvbGxlZCB1c2VyLiIKICAgICAgfSwKICAgICAgInRlYW0iOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiQXR0cmlidXRpb24gdGVhbSAoY29udGVudC1mcmVlKS4gT3B0aW9uYWwuIgogICAgICB9CiAgICB9LAogICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIjIwMjYuNy4xIgogICAgfQogIH0sCiAgInBlZXJEZXBlbmRlbmNpZXMiOiB7CiAgICAib3BlbmNsYXciOiAiPj0yM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3YXlQcm92aWRlciA9IHN0YW1wUHJvdmlkZXIKICAgICAgPyBnYXRld2F5UHJvdmlkZXJGb3JNb2RlbChtb2RlbC5pZCkKICAgICAgOiB1bmRlZmluZWQ7CiAgICBpZiAoZ2F0ZXdheVByb3ZpZGVyICYmIGhlYWRlcnNbJ3gtYW55cmF5LXByb3ZpZGVyJ10gPT09IHVuZGVmaW5lZCkgewogICAgICBoZWFkZXJzWyd4LWFueXJheS1wcm92aWRlciddID0gZ2F0ZXdheVByb3ZpZGVyOwogICAgfQogICAgb3B0cy5oZWFkZXJzID0gaGVhZGVyczsKICAgIGNvbnN0IHNlc3Npb25JZCA9CiAgICAgIHR5cGVvZiBvcHRzLnNlc3Npb25JZCA9PT0gJ3N0cmluZycgPyBvcHRzLnNlc3Npb25JZCA6IHVuZGVmaW5lZDsKICAgIGNvbnN0IGNhbGxlck9uUGF5bG9hZCA9IG9wdHMub25QYXlsb2FkOwogICAgb3B0cy5vblBheWxvYWQgPSBhc3luYyAocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA9PiB7CiAgICAgIGlmIChwYXlsb2FkICYmIHR5cGVvZiBwYXlsb2FkID09PSAnb2JqZWN0JyAmJiAhQXJyYXkuaXNBcnJheShwYXlsb2FkKSkgewogICAgICAgIHBhdGNoUGF5bG9hZFNlc3Npb25JZGVudGl0eSgKICAgICAgICAgIHBheWxvYWQgYXMgUmVjb3JkPHN0cmluZywgdW5rbm93bj4sCiAgICAgICAgICBzZXNzaW9uSWQKICAgICAgICApOwogICAgICB9CiAgICAgIHJldHVybiBjYWxsZXJPblBheWxvYWQgPyBjYWxsZXJPblBheWxvYWQocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA6IHBheWxvYWQ7CiAgICB9OwogICAgcmV0dXJuIGlubmVyKG1vZGVsLCBjb250ZXh0LCBvcHRzKTsKICB9OwogIHJldHVybiB3cmFwcGVkOwp9Owo="}];var Pf=".anyray-source-sha",hn=()=>mr(yN(),".anyray","openclaw-plugin"),EC=async(e=hn())=>{try{if((await SC(mr(e,Pf),"utf8")).trim()===_f)return"current"}catch{}for(let t of vC){let n=mr(e,t.path);await wN(gN(n),{recursive:!0,mode:448}),await we(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await we(mr(e,Pf),`${_f}
|
|
191
|
-
`),"installed"},Bs=async(e,t=[])=>{let n=[],r=async a=>{let s=mr(a,"plugins","anyray","catalog.json");try{await IC(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await bN(mr(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(mr(e,"agents",a,"agent"));return n},gl=async(e=hn())=>{try{await SC(mr(e,Pf),"utf8")}catch{return!1}return await IC(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"],Uf="anyray/claude-sonnet-4-5",Hf=["anyray/claude-haiku-4-5"],AN=[Cl,Uf],CN=[Wf,Hf],qe="anyray",hr="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"),N=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(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},kN=e=>e==="~"||e.startsWith("~/")?kl(Mf(),e.slice(1)):e,wl=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(kN(o))}return n},vN=(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]}:{},T=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 O=Array.isArray(S.paths)?[...S.paths]:[];O.includes(n)||O.push(n),S.paths=O,C.load=S,E.enabled=!0,T.gatewayUrl=t.anthropicBaseUrl,T.apiKey=r;let F=t.metadata.user,q=t.metadata.team;F&&(T.user=F),q&&(T.team=q),E.config=T,I[qe]=E,C.entries=I,l.plugins=C;let de=N(l.env)?{...l.env}:{};de[hr]=r,l.env=de,f=!0}}let m=Al.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[Jo]=r,o&&(I[Lf]=o),C==="anthropic"&&(qr in I?c=I[qr]!==bl:I[qr]=bl),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=RC,h=!0,S.params=I);let E=N(S.model)?{...S.model}:{},T=f?[...s,qe]:s,O=F=>typeof F=="string"&&T.some(q=>F.startsWith(`${q}/`));typeof E.primary!="string"||E.primary.trim()===""?(E.primary=f?Uf:Cl,w=!0,S.model=E,"fallbacks"in E||(E.fallbacks=f?[...Hf]:[...Wf],y=!0)):O(E.primary)||(g=E.primary),b=(Array.isArray(E.fallbacks)?E.fallbacks:[]).filter(F=>typeof F=="string"&&!O(F)),(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}},SN=["baseUrl","apiKey","api","maxTokens"],Df=(e,t,n=Al,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[Jo]=="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 SN)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 m?[zr]:[]];m[qr]===bl&&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[hr];if(typeof y=="string"&&y.startsWith("ark_")){let g=N(t?.env)?t.env:{};hr in g?w[hr]!==g[hr]&&(w[hr]=g[hr],l=!0):(delete w[hr],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===RC&&("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:{};AN.includes(y.primary)&&("primary"in g?y.primary!==g.primary&&(y.primary=g.primary,l=!0):(delete y.primary,l=!0)),CN.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."],I;try{I=await je(n)}catch{return{status:"held",messages:S}}let{next:E,removed:T}=Df(I.data,await Bo(n),Al,hn());return T?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 oe(n),await gl(),await Bs(Yo(),wl(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 gl(),await Bs(Yo(),wl(E))),{status:"held",messages:S})}let r=hn(),o=!1;if(!t.dryRun)try{await EC(r)}catch{r=void 0,o=!0}let a;try{a=await je(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:m,structureConflicts:h,pluginConfigured:w}=vN(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: ${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?Uf:Cl} (none was set; routing is inert until the primary resolves to a routed provider).`,...p?[`Seeded agents.defaults.model.fallbacks = [${(w?Hf: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(Yo(),wl(y)),{status:k,messages:b,changedFiles:C?[n]:[]}},async pointsAt(e){try{let{data:t}=await je(Zo());for(let a of Object.values($f(t)))if(N(a)&&xC(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)&&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 je(Zo());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[Jo]=="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=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 je(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,hn()),a=await gl();return await Bs(Yo(),wl(r)),o?(await sn(t,n,r,!1),await oe(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${hn()}`]:[]],changedFiles:[t]}):(await oe(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${hn()}`]:[]]})}};import{execFile as mB}from"node:child_process";import{readFile as hB}from"node:fs/promises";import{homedir as oi,platform as br}from"node:os";import{join as bn}from"node:path";import{isDeepStrictEqual as Rm,promisify as yB}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 _M}from"node:crypto";import{promises as Uk}from"node:fs";import{platform as PM,tmpdir as DM}from"node:os";import{join as Ul}from"node:path";import{execFile as IN}from"node:child_process";import{promises as Us}from"node:fs";import{homedir as EN,platform as xN}from"node:os";import{delimiter as RN,join as Sl}from"node:path";import{promisify as ON}from"node:util";var TN=ON(IN),_N=15*6e4,PN=64*1024*1024,DN=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],TC=async(e={})=>{let t=(e.home??EN)(),n=e.env??process.env,r=DN(e.runtimePlatform??xN()),o=[Sl(t,".local","bin"),Sl(t,".claude","local"),...(n.PATH??"").split(RN).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Sl(a,`claude${s}`);try{return await Us.access(i),i}catch{}}return null},LN=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},NN=async e=>{let t=Sl(e,"projects"),n;try{n=(await Us.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(!BN.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},$N=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:LN(n.projectList)}},MN=async e=>{let t,n;try{let r=await Us.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=$N(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 MN(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await NN(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as UN}from"node:crypto";import{promises as Nn}from"node:fs";import{homedir as HN,platform as GN}from"node:os";import{join as Ct}from"node:path";var PC=448,$n="local_",VN="local-agent-mode-sessions",Gf="-3p",KN="cowork_account_settings.json",Qr=(e={})=>{let t=(e.home??HN)(),n=e.runtimePlatform??GN(),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},Hs=(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)}`},Il=async e=>{let t=Ct(e,VN),n;try{n=(await Nn.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 Nn.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 Nn.access(Ct(i,KN)),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 Nn.readdir(e);return new Set(t.filter(n=>n.startsWith($n)&&n.endsWith(".json")).map(n=>n.slice($n.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),jN=async(e,t)=>{let n=`${$n}${t.sessionId}`,r=Ct(e,n),o=Ct(r,"outputs"),a=Ct(r,".claude"),s=Ct(a,"projects",Vf(o));await Nn.mkdir(o,{recursive:!0,mode:PC}),await Nn.mkdir(s,{recursive:!0,mode:PC});let i=Ct(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${UN()}`;await Nn.copyFile(t.transcriptPath,c),await Nn.chmod(c,384),await Nn.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})},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 jN(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 ZN}from"node:os";import{dirname as YN,join as Gs}from"node:path";var JN=448,XN=["Documents","Claude","Projects"],zN="spaces.json",qN=(e={})=>Gs((e.home??ZN)(),...XN),QN=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}}},e$=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}},t$=async(e,t,n)=>{let r=Gs(t,e$(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(YN(a),{recursive:!0}),await zo.cp(e,a,{recursive:!0}),a)},n$=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=qN({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,zN),{spaces:a,readable:s}=await QN(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 t$(d,t,l);if(!u){n.skippedCollision+=1;continue}let p=await n$(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:JN}),await Y(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as s$}from"node:crypto";import{execFile as i$,spawnSync as KC}from"node:child_process";import{constants as jC}from"node:fs";import{access as _l,chmod as c$,mkdir as l$,readdir as d$,readFile as Yf,rename as u$,rm as qo,stat as ZC,writeFile as p$}from"node:fs/promises";import{homedir as f$,platform as m$,userInfo as h$}from"node:os";import{basename as y$,dirname as YC,isAbsolute as Qo,join as Lt,resolve as FC}from"node:path";import{isDeepStrictEqual as Ks,promisify as g$}from"node:util";var yr="__anyray-claude-desktop-credential",Vs="__anyray-claude-desktop-bootstrap-headers";var El=["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"],r$=new Set($C),o$=new Set($C.map(e=>e.toLowerCase())),a$=new Set(Rl.map(e=>e.toLowerCase())),Ol=(e,t=!1)=>(t?o$:r$).has(t?e.toLowerCase():e),MC=(e,t=!1)=>t?a$.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]}),gr=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}},w$=async e=>{try{let t=await d$(YC(e)),n=y$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},b$=async e=>{try{return await _l(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":w$(e)}},jt=(e={})=>{let t=(e.home??f$)(),n=(e.username??(()=>h$().username))(),r=Lt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Lt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Lt(r,"configLibrary"),meta:Lt(r,"configLibrary","_meta.json"),appConfig:Lt(r,"claude_desktop_config.json"),helper:Lt(t,".anyray","bin","claude-desktop-credential-helper"),journal:Lt(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"],A$=(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:te()&&(!o||r!==n)}},C$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,zf=e=>[e.command,...e.args].map(C$).join(" "),k$=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)=>{k$(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
|
|
194
|
-
exec ${
|
|
195
|
-
`),
|
|
196
|
-
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,
|
|
197
|
-
`)},
|
|
189
|
+
`,$s=async e=>await x(e)?(await fC(e,"utf-8")).startsWith(`${mC}
|
|
190
|
+
`)?"owned":"foreign":"absent",hC=async(e,t)=>{let n=bf(t),r=await $s(e);return r==="foreign"?"foreign":r==="owned"&&await fC(e,"utf-8")===n?"unchanged":(await we(e,n),"installed")},Af=async e=>{let t=await $s(e);return t!=="owned"?t:(await oN(e,{force:!0}),"removed")};var Cf="https://opencode.ai/config.json",Dn="x-anyray-metadata",Dt="x-anyray-api-key",kf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],_n="Authorization",fr=["anthropic","openai"],Ln="github-copilot",sN="header",Pn="anyray",iN=()=>process.env.XDG_CONFIG_HOME?.trim()||mr(bC(),".config"),cN=()=>process.env.XDG_DATA_HOME?.trim()||mr(bC(),".local","share"),yl=()=>mr(iN(),"opencode"),ml=()=>mr(yl(),"plugins","anyrayTrim.js"),CC=()=>mr(cN(),"opencode"),kC=async()=>{try{let e=await AC(mr(CC(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return U(t)?{chatGptOAuth:U(t.openai)&&t.openai.type==="oauth",readable:!0}:{chatGptOAuth:!1,readable:!1}}catch(e){return e.code==="ENOENT"?{chatGptOAuth:!1,readable:!0}:{chatGptOAuth:!1,readable:!1}}},yC=async()=>(await kC()).chatGptOAuth,lN=["opencode.jsonc","opencode.json","config.json"],jo=async()=>{let e=yl(),t=[];for(let n of lN){let r=mr(e,n);await x(r)&&t.push(r)}return t},gC=async()=>(await jo())[0]??mr(yl(),"opencode.json"),vf=()=>JA(process.env.ANYRAY_COPILOT_PLAN),Sf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${vf()}/${sN}`,U=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Of=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},dN=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===fr[0]||n===fr[1]||n===Ln?[]:U(r)&&U(r.options)&&Of(r.options.baseURL,t)?[n]:[]),If=/claude/i,Tf=["model","small_model"],vC=(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)||!If.test(o)))return`${fr[0]}/${o}`},Ef=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Ef(n,t);return t}if(!U(e))return t;for(let[n,r]of Object.entries(e))Tf.includes(n)&&typeof r=="string"?t.push(r):Ef(r,t);return t},uN=(e,t,n)=>{if(!U(e)||!U(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>If.test(a)))return!1;let o=`${n}/`;return Ef(t).filter(a=>a.startsWith(o)).every(a=>If.test(a.slice(o.length)))},xf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>xf(o,t,n));if(!U(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Tf.includes(o)?vC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=xf(a,t,n)}return r},Rf=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Rf(o,t[a],n));if(!U(e)||!U(t))return e;let r={};for(let[o,a]of Object.entries(e))Tf.includes(o)&&typeof a=="string"&&vC(t[o],n)===a?r[o]=t[o]:r[o]=Rf(a,t[o],n);return r},pN=e=>{if(U(e))for(let t of fr){let n=e[t];if(U(n)&&U(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},Ms=e=>{if(!U(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&Ot({command:t,args:n},"profile")},hl=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),fN=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return U(t)&&t.tool==="opencode"}catch{return!1}},_f=e=>ee(e,"copilot")&&!!e.clientKey,mN=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".`]:[],hN=(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.`]:[],yN=e=>_f(e)?["Tip: to spend your Copilot subscription (incl. Claude & GPT), pick the github-copilot/* models in OpenCode \u2014 e.g. github-copilot/claude-sonnet-4.5. The anthropic/* and openai/* entries are the direct providers (api-key mode, separate billing) \u2014 not your Copilot plan."]:[],gN=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Cf);let o=!1;if(n)if("mcp"in r&&!U(r.mcp))o=!0;else{let g=U(r.mcp)?{...r.mcp}:{},b=g[Pn];b!==void 0&&!Ms(b)?o=!0:(g[Pn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=g)}else if(U(r.mcp)&&Ms(r.mcp[Pn])){let g={...r.mcp};delete g[Pn],Object.keys(g).length===0?delete r.mcp:r.mcp=g}let a=U(r.provider)?{...r.provider}:{},s=dN(a,t.origin),i=s.every(g=>uN(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=xf(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&&!U(k.headers)){u.push(g);continue}let C=U(k.headers)?{...k.headers}:{},S=!1;for(let[I,E]of[[Dt,f],...m?[[Dn,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?[]:fr.filter(g=>g!=="openai"||!ee(t,"openai")),w=t.byoUpstream;for(let g of h){let b=U(a[g])?{...a[g]}:{},k=U(b.options)?{...b.options}:{};k.baseURL=p;let C=U(k.headers)?{...k.headers}:{};if(g==="anthropic"&&w)k.apiKey=w.key,C[_n]=`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[_n];for(let S of kf)delete C[S]}C[Dt]=f,m&&(C[Dn]=m),k.headers=C,b.options=k,a[g]=b}let y=c.length===0&&_f(t);if(y){let g=U(a[Ln])?{...a[Ln]}:{},b=U(g.options)?{...g.options}:{};b.baseURL=Sf(t);let k=U(b.headers)?{...b.headers}:{};k[Dt]=t.clientKey,m&&(k[Dn]=m),b.headers=k,g.options=b,a[Ln]=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}},wN=["baseURL","apiKey"],wC=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!U(s)||!U(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=U(c.headers)?{...c.headers}:void 0,p=u?.[Dt],f=hl(p);if(d&&(delete c.baseURL,l=!0),u&&(d||f)){let m=u,h=U(r)?r.options:void 0,w=U(h)&&U(h.headers)?h.headers:void 0;for(let y of[Dt,Dn])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=U(r)?r.options:void 0,u=U(d)?d:{},p=U(c.headers)?c.headers:{},f=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof p[Dt]=="string"||typeof p[Dn]=="string"||kf.some(m=>m in p);if(!o&&!f)return!1;for(let m of wN)m in u?c[m]!==u[m]&&(c[m]=u[m],l=!0):m in c&&(delete c[m],l=!0);if(U(c.headers)){let m={...c.headers},h=U(u.headers)?u.headers:{};"x-anyray-custom-host"in m&&_n in m&&(_n in h?m[_n]!==h[_n]&&(m[_n]=h[_n],l=!0):(delete m[_n],l=!0));for(let w of[Dt,Dn,...kf])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},bN=(e,t,n)=>{let r=e[t];if(!U(r)||!U(r.options)||!U(n)||!U(n.options))return!1;let o={...r.options};if(!U(o.headers)||"headers"in n.options&&!U(n.options.headers))return!1;let a={...o.headers},s=U(n.options.headers)?n.options.headers:{},i=!1;return!(Dt in s)&&hl(a[Dt])&&(delete a[Dt],i=!0),!(Dn in s)&&fN(a[Dn])&&(delete a[Dn],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=pN(e.provider);if(U(n.mcp)&&Ms(n.mcp[Pn])){let c={...n.mcp};delete c[Pn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!U(n.provider))return{next:n,removed:r};let a={...n.provider},s=U(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===Cf&&fr.every(c=>{let l=a[c];return U(l)&&U(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of fr)wC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...fr,Ln]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;bN(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&U(u)&&U(u.options)&&Of(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Rf(n,t,l))}return wC(a,Ln,!0,s[Ln])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===Cf&&(delete n.$schema,r=!0),{next:n,removed:r}},SC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=yl(),t=CC(),n=await x(e)||await x(t),r=n&&await yC();return{installed:n,detail:n?`${await gC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await gC(),r=e.openaiBaseUrl,o=ue({...e.metadata,tool:"opencode"}),a=_f(e),s=ee(e,"openai"),i=await yC(),c;try{c=await je(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(Sf(e))}, "headers": { "${Dt}": "<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 $r()?Ge("profile"):void 0,{next:d,customProviders:u,migratedProviders:p,modelRefsRemapped:f,customHeadersAdded:m,customHeaderConflicts:h,mcpConflict:w}=gN(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)"}`,...mN(e),...hN(e,i),a?`provider.github-copilot options.baseURL \u2192 ${Sf(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. ${vf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${vf()} 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).",...yN(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Pn} 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=ml();if(te())try{let E=await hC(I,ts(ze,["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 Af(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 jo())try{let{data:n}=await je(t);if(!U(n.provider))continue;for(let r of Object.values(n.provider))if(!(!U(r)||!U(r.options))&&Of(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){if(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=await jo();if(e.length===0)return{registered:!1,command:null,reason:"no-config"};let t=!1,n=!1;for(let r of e)try{let{data:o}=await je(r);if(!U(o.mcp))continue;let a=o.mcp[Pn];if(!Ms(a)||!U(a)){a!==void 0&&(t=!0);continue}return{registered:!0,command:Array.isArray(a.command)&&typeof a.command[0]=="string"?a.command[0]:null}}catch{n=!0}return{registered:!1,command:null,reason:t?"foreign":n?"unreadable":"absent"}},async integrationStatus(){let e,t=!0;try{let i=await $s(ml());e=i==="absent"?"missing":i,e==="owned"&&(t=await AC(ml(),"utf-8")===bf(ts(ze,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await jo()){let c;try{c=await je(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!U(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Pn];if(l!==void 0)if(Ms(l))if(n=!0,!U(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 $r()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await kC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await jo()){let{data:o}=await je(r);if(U(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!U(s)||!U(s.options)){e.add("unknown");continue}let i=s.options,c=U(i.headers)?i.headers:{};if(a===Ln&&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===Ln&&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(hl(c[Dt])||hl(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=ml(),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 je(i)}catch{s.push(i);continue}let{next:l,removed:d}=AN(c.data,await Bo(i));d&&(await sn(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await oe(i)}for(let i of s)o.push(`Couldn't parse ${i} \u2014 if you added Anyray settings there by hand, remove the baseURL/apiKey from provider.anthropic, provider.openai, and provider.github-copilot yourself.`);if(r==="owned")try{await Af(n)==="removed"&&(a.push(n),o.push(`removed the Anyray OpenCode trim carrier from ${n}`))}catch{o.push(`Could not remove the Anyray OpenCode trim carrier from ${n}. Remove that file manually.`)}return a.length===0&&s.length===0&&o.push("no Anyray provider settings found"),{status:a.length===0&&s.length>0?"manual":"reverted",messages:o,changedFiles:a.length?a:void 0}}};import{homedir as Bf}from"node:os";import{join as kl}from"node:path";import{homedir as CN}from"node:os";import{dirname as kN,join as hr}from"node:path";import{mkdir as vN,readdir as SN,readFile as EC,rm as xC}from"node:fs/promises";var Pf="48ff8bb9a7afde1d9e8468d632f84b46f199e6a28657833b113de93698d9ac63",IC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyNTYwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0KICAgICAgICBdCiAgICAgIH0KICAgIH0KICB9LAogICJjb25maWdTY2hlbWEiOiB7CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogZmFsc2UsCiAgICAicmVxdWlyZWQiOiBbImdhdGV3YXlVcmwiXSwKICAgICJwcm9wZXJ0aWVzIjogewogICAgICAiZ2F0ZXdheVVybCI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBbnlyYXkgZ2F0ZXdheSBvcmlnaW4sIGUuZy4gaHR0cHM6Ly9nYXRld2F5LmV4YW1wbGUuYW55cmF5LmFpIChubyAvdjEgc3VmZml4KS4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiUGVyc29uYWwgQW55cmF5IGNsaWVudCBrZXkgKGFya1/igKYpLiBTdXBwb3J0cyAke0VOVl9WQVJ9IHN1YnN0aXR1dGlvbjsgZGVmYXVsdHMgdG8gJHtBTllSQVlfQ0xJRU5UX0tFWX0uIgogICAgICB9LAogICAgICAidXNlciI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB1c2VyIChjb250ZW50LWZyZWU7IHVzdWFsbHkgYW4gZW1haWwpLiBPcHRpb25hbCDigJQgdGhlIGNsaWVudCBrZXkgYWxyZWFkeSBhdHRyaWJ1dGVzIHRoZSBlbnJvbGxlZCB1c2VyLiIKICAgICAgfSwKICAgICAgInRlYW0iOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiQXR0cmlidXRpb24gdGVhbSAoY29udGVudC1mcmVlKS4gT3B0aW9uYWwuIgogICAgICB9CiAgICB9LAogICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb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ZW50cmllcy5hbnlyYXkuY29uZmlnLmdhdGV3YXlVcmwgaXMgcmVxdWlyZWQnCiAgICApOwogIH0KICBjb25zdCBhcGlLZXkgPSB0cmltbWVkU3RyaW5nKGNvbmZpZy5hcGlLZXkpID8/IGVudltLRVlfRU5WXTsKICBjb25zdCBhdHRyaWJ1dGlvbiA9IGF0dHJpYnV0aW9uSGVhZGVyVmFsdWUoY29uZmlnKTsKICByZXR1cm4gewogICAgLy8gQmFyZSBvcmlnaW46IHRoZSBhbnRocm9waWMtbWVzc2FnZXMgdHJhbnNwb3J0IGFwcGVuZHMgL3YxL21lc3NhZ2VzLgogICAgYmFzZVVybDogZ2F0ZXdheVVybC5yZXBsYWNlKC9cLyskLywgJycpLAogICAgYXBpOiAnYW50aHJvcGljLW1lc3NhZ2VzJywKICAgIC4uLihhcGlLZXkgPyB7IGFwaUtleSB9IDoge30pLAogICAgaGVhZGVyczogewogICAgICAnYW50aHJvcGljLWJldGEnOiBBTlRIUk9QSUNfQkVUQSwKICAgICAgLi4uKGFwaUtleSA/IHsgJ3gtYW55cmF5LWFwaS1rZXknOiBhcGlLZXkgfSA6IHt9KSwKICAgICAgLi4uKGF0dHJpYnV0aW9uID8geyAneC1hbnlyYXktbWV0YWRhdGEnOiBhdHRyaWJ1dGlvbiB9IDoge30pLAogICAgfSwKICAgIG1vZGVsczogTU9ERUxTLAogIH07Cn07Cg=="},{path:"src/sessionIdentity.ts",contentBase64:"LyoqCiAqIFBlci1zZXNzaW9uIGlkZW50aXR5IGZvciB0aGUgQW55cmF5IGdhdGV3YXksIGluamVjdGVkIGludG8gdGhlIEFudGhyb3BpYwogKiBNZXNzYWdlcyBib2R5IGFzIGBtZXRhZGF0YS51c2VyX2lkYC4KICoKICogVGhlIGdhdGV3YXkgZGVyaXZlcyBpdHMgb3B0aW1pemVyIHNlc3Npb24gZnJvbSBhIGBfc2Vzc2lvbl88dXVpZD5gIHN1ZmZpeCBvbgogKiBgbWV0YWRhdGEudXNlcl9pZGAg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ICAgICAgICBzZXNzaW9uSWQKICAgICAgICApOwogICAgICB9CiAgICAgIHJldHVybiBjYWxsZXJPblBheWxvYWQgPyBjYWxsZXJPblBheWxvYWQocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA6IHBheWxvYWQ7CiAgICB9OwogICAgcmV0dXJuIGlubmVyKG1vZGVsLCBjb250ZXh0LCBvcHRzKTsKICB9OwogIHJldHVybiB3cmFwcGVkOwp9Owo="}];var Df=".anyray-source-sha",hn=()=>hr(CN(),".anyray","openclaw-plugin"),RC=async(e=hn())=>{try{if((await EC(hr(e,Df),"utf8")).trim()===Pf)return"current"}catch{}for(let t of IC){let n=hr(e,t.path);await vN(kN(n),{recursive:!0,mode:448}),await we(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await we(hr(e,Df),`${Pf}
|
|
191
|
+
`),"installed"},Bs=async(e,t=[])=>{let n=[],r=async a=>{let s=hr(a,"plugins","anyray","catalog.json");try{await xC(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await SN(hr(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(hr(e,"agents",a,"agent"));return n},gl=async(e=hn())=>{try{await EC(hr(e,Df),"utf8")}catch{return!1}return await xC(e,{recursive:!0,force:!0}),!0};var Nf="x-anyray-metadata",Jo="x-anyray-api-key",$f=["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"],TC="short",Ff="anthropic-messages",Wf=32e3,Cl="anthropic/claude-sonnet-4-5",Uf=["anthropic/claude-haiku-4-5"],Hf="anyray/claude-sonnet-4-5",Gf=["anyray/claude-haiku-4-5"],IN=[Cl,Hf],EN=[Uf,Gf],qe="anyray",yr="ANYRAY_API_KEY",Fs="openclaw",Yo=()=>process.env.OPENCLAW_STATE_DIR?.trim()||kl(Bf(),".openclaw"),Zo=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||kl(Yo(),"openclaw.json"),N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),OC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Mf=e=>{if(!N(e))return{};let t=e.models;return!N(t)||!N(t.providers)?{}:t.providers},xN=e=>e==="~"||e.startsWith("~/")?kl(Bf(),e.slice(1)):e,wl=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(xN(o))}return n},RN=(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]}:{},T=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 O=Array.isArray(S.paths)?[...S.paths]:[];O.includes(n)||O.push(n),S.paths=O,C.load=S,E.enabled=!0,T.gatewayUrl=t.anthropicBaseUrl,T.apiKey=r;let F=t.metadata.user,q=t.metadata.team;F&&(T.user=F),q&&(T.team=q),E.config=T,I[qe]=E,C.entries=I,l.plugins=C;let de=N(l.env)?{...l.env}:{};de[yr]=r,l.env=de,f=!0}}let m=Al.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=Ff,(typeof S.maxTokens!="number"||S.maxTokens<=0)&&(S.maxTokens=Wf)),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 $f)delete I[E]}I[Jo]=r,o&&(I[Nf]=o),C==="anthropic"&&(qr in I?c=I[qr]!==bl:I[qr]=bl),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=TC,h=!0,S.params=I);let E=N(S.model)?{...S.model}:{},T=f?[...s,qe]:s,O=F=>typeof F=="string"&&T.some(q=>F.startsWith(`${q}/`));typeof E.primary!="string"||E.primary.trim()===""?(E.primary=f?Hf:Cl,w=!0,S.model=E,"fallbacks"in E||(E.fallbacks=f?[...Gf]:[...Uf],y=!0)):O(E.primary)||(g=E.primary),b=(Array.isArray(E.fallbacks)?E.fallbacks:[]).filter(F=>typeof F=="string"&&!O(F)),(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}},ON=["baseUrl","apiKey","api","maxTokens"],Lf=(e,t,n=Al,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=Mf(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[Jo]=="string"||typeof m[Nf]=="string"||typeof f.apiKey=="string"&&f.apiKey.startsWith("ark_")||$f.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===Ff:C==="maxTokens"?f.maxTokens===Wf:C==="apiKey"?g||typeof f.apiKey=="string"&&f.apiKey.startsWith("ark_"):!0;for(let C of ON)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,Nf,...$f,..."x-anyray-custom-host"in m?[zr]:[]];m[qr]===bl&&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[yr];if(typeof y=="string"&&y.startsWith("ark_")){let g=N(t?.env)?t.env:{};yr in g?w[yr]!==g[yr]&&(w[yr]=g[yr],l=!0):(delete w[yr],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===TC&&("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:{};IN.includes(y.primary)&&("primary"in g?y.primary!==g.primary&&(y.primary=g.primary,l=!0):(delete y.primary,l=!0)),EN.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}},_C={id:Fs,title:"OpenClaw",automatic:!0,async detect(){let e=await x(Zo())||await x(Yo());return{installed:e,detail:e?Zo():`no ${kl(Bf(),".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."],I;try{I=await je(n)}catch{return{status:"held",messages:S}}let{next:E,removed:T}=Lf(I.data,await Bo(n),Al,hn());return T?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 oe(n),await gl(),await Bs(Yo(),wl(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 gl(),await Bs(Yo(),wl(E))),{status:"held",messages:S})}let r=hn(),o=!1;if(!t.dryRun)try{await RC(r)}catch{r=void 0,o=!0}let a;try{a=await je(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${Ff}", "maxTokens": ${Wf}, "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:m,structureConflicts:h,pluginConfigured:w}=RN(a.data,e,r),y=s,g=!1;if(!i.includes("openai")){let S=Lf(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: ${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:Cl} (none was set; routing is inert until the primary resolves to a routed provider).`,...p?[`Seeded agents.defaults.model.fallbacks = [${(w?Gf:Uf).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(Yo(),wl(y)),{status:k,messages:b,changedFiles:C?[n]:[]}},async pointsAt(e){try{let{data:t}=await je(Zo());for(let a of Object.values(Mf(t)))if(N(a)&&OC(a.baseUrl,e))return!0;let n=N(t.plugins)?t.plugins:{},o=(N(n.entries)?n.entries:{})[qe];if(N(o)&&N(o.config)&&OC(o.config.gatewayUrl,e))return!0}catch{}return!1},async routingExpected(e){return e.includes(Fs)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await je(Zo());for(let a of Object.values(Mf(t))){if(!N(a))continue;let s=N(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=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=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 je(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}=Lf(n.data,await Bo(t),Al,hn()),a=await gl();return await Bs(Yo(),wl(r)),o?(await sn(t,n,r,!1),await oe(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${hn()}`]:[]],changedFiles:[t]}):(await oe(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${hn()}`]:[]]})}};import{execFile as bB}from"node:child_process";import{readFile as AB}from"node:fs/promises";import{homedir as oi,platform as Ar}from"node:os";import{join as bn}from"node:path";import{isDeepStrictEqual as Om,promisify as CB}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 $M}from"node:crypto";import{promises as Gk}from"node:fs";import{platform as MM,tmpdir as BM}from"node:os";import{join as Ul}from"node:path";import{execFile as TN}from"node:child_process";import{promises as Us}from"node:fs";import{homedir as _N,platform as PN}from"node:os";import{delimiter as DN,join as Sl}from"node:path";import{promisify as LN}from"node:util";var NN=LN(TN),$N=15*6e4,MN=64*1024*1024,BN=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],PC=async(e={})=>{let t=(e.home??_N)(),n=e.env??process.env,r=BN(e.runtimePlatform??PN()),o=[Sl(t,".local","bin"),Sl(t,".claude","local"),...(n.PATH??"").split(DN).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=Sl(a,`claude${s}`);try{return await Us.access(i),i}catch{}}return null},FN=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},WN=async e=>{let t=Sl(e,"projects"),n;try{n=(await Us.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(!GN.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},UN=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:FN(n.projectList)}},HN=async e=>{let t,n;try{let r=await Us.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}},GN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,VN=/\.(?:cmd|bat)$/i,KN=(e,t)=>VN.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},DC=async(e,t={})=>{let n=t.exec??NN,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 Us.mkdir(e.configDir,{recursive:!0,mode:448}),await Us.mkdir(e.workDir,{recursive:!0,mode:448});let o=KN(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:$N,maxBuffer:MN,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=UN(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 HN(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await WN(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as jN}from"node:crypto";import{promises as Nn}from"node:fs";import{homedir as ZN,platform as YN}from"node:os";import{join as Ct}from"node:path";var LC=448,$n="local_",JN="local-agent-mode-sessions",Vf="-3p",XN="cowork_account_settings.json",Qr=(e={})=>{let t=(e.home??ZN)(),n=e.runtimePlatform??YN(),r=e.env??process.env;if(n==="darwin")return Ct(t,"Library","Application Support",`Claude${Vf}`);if(n==="win32"){let o=r.LOCALAPPDATA??Ct(t,"AppData","Local");return Ct(o,`Claude${Vf}`)}return null},Hs=(e={})=>{let t=Qr(e);return t?t.slice(0,-Vf.length):null},Kf=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)}`},Il=async e=>{let t=Ct(e,JN),n;try{n=(await Nn.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 Nn.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 Nn.access(Ct(i,XN)),r.push(i)}catch{}}}return r.length===0?{ok:!1,reason:"no-account",found:[]}:r.length>1?{ok:!1,reason:"ambiguous",found:r}:{ok:!0,dir:r[0]}},jf=async e=>{try{let t=await Nn.readdir(e);return new Set(t.filter(n=>n.startsWith($n)&&n.endsWith(".json")).map(n=>n.slice($n.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),zN=async(e,t)=>{let n=`${$n}${t.sessionId}`,r=Ct(e,n),o=Ct(r,"outputs"),a=Ct(r,".claude"),s=Ct(a,"projects",Kf(o));await Nn.mkdir(o,{recursive:!0,mode:LC}),await Nn.mkdir(s,{recursive:!0,mode:LC});let i=Ct(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${jN()}`;await Nn.copyFile(t.transcriptPath,c),await Nn.chmod(c,384),await Nn.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})},NC=async(e,t)=>{let n=await jf(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 zN(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 qN}from"node:os";import{dirname as QN,join as Gs}from"node:path";var e$=448,t$=["Documents","Claude","Projects"],n$="spaces.json",r$=(e={})=>Gs((e.home??qN)(),...t$),o$=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}}},a$=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},Zf=async e=>{try{return await zo.access(e),!0}catch{return!1}},s$=async(e,t,n)=>{let r=Gs(t,a$(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await Zf(r)?o:r;return a===o&&await Zf(o)?null:(await zo.mkdir(QN(a),{recursive:!0}),await zo.cp(e,a,{recursive:!0}),a)},i$=async e=>{try{let t=(await zo.readFile(Gs(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},$C=async e=>{let t=r$({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,n$),{spaces:a,readable:s}=await o$(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 Zf(d)){n.failed+=1;continue}let u=await s$(d,t,l);if(!u){n.skippedCollision+=1;continue}let p=await i$(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:e$}),await Y(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as u$}from"node:crypto";import{execFile as p$,spawnSync as ZC}from"node:child_process";import{constants as YC}from"node:fs";import{access as _l,chmod as f$,mkdir as m$,readdir as h$,readFile as Jf,rename as y$,rm as qo,stat as JC,writeFile as g$}from"node:fs/promises";import{homedir as w$,platform as b$,userInfo as A$}from"node:os";import{basename as C$,dirname as XC,isAbsolute as Qo,join as Lt,resolve as UC}from"node:path";import{isDeepStrictEqual as Ks,promisify as k$}from"node:util";var gr="__anyray-claude-desktop-credential",Vs="__anyray-claude-desktop-bootstrap-headers";var El=["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."],MC="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"],BC=["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"],c$=new Set(BC),l$=new Set(BC.map(e=>e.toLowerCase())),d$=new Set(Rl.map(e=>e.toLowerCase())),Ol=(e,t=!1)=>(t?l$:c$).has(t?e.toLowerCase():e),FC=(e,t=!1)=>t?d$.has(e.toLowerCase()):Rl.some(n=>n===e),WC=["*"],eo=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...WC]}),wr=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var js=/^[a-f0-9-]{36}$/,zC="Anyray",Xf=4,Js=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],Xs=["deploymentMode","awaitingSignIn"],qC=[...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}},v$=async e=>{try{let t=await h$(XC(e)),n=C$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},S$=async e=>{try{return await _l(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":v$(e)}},jt=(e={})=>{let t=(e.home??w$)(),n=(e.username??(()=>A$().username))(),r=Lt(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",Lt("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:Lt(r,"configLibrary"),meta:Lt(r,"configLibrary","_meta.json"),appConfig:Lt(r,"claude_desktop_config.json"),helper:Lt(t,".anyray","bin","claude-desktop-credential-helper"),journal:Lt(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Pl=()=>{let e=ZC("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},QC=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],I$=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...QC(t)]}},zf=(e="json")=>{let t=en(QC(e)),n=UC(t.command),r=UC(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:te()&&(!o||r!==n)}},E$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,qf=e=>[e.command,...e.args].map(E$).join(" "),x$=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")},ek=(e,t)=>{x$(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}`)},tk=e=>(ek(e,"--json"),`#!/bin/sh
|
|
194
|
+
exec ${qf(e)}
|
|
195
|
+
`),R$=`#!/bin/sh
|
|
196
|
+
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,nk=e=>{ek(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),gr]};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 ${qf(t)}`,""].join(`
|
|
197
|
+
`)},O$=e=>e.args.at(-1)==="--passthrough-headers"?nk(e):tk(e),Dl=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++}},T$=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=
|
|
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
|
|
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},U$=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=Lt(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(Lt(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]}}},H$=(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}}),G$=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]}),V$=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}`)]}},K$=g$(i$),j$=new Set(Rl),Z$=async e=>{try{let{stdout:t}=await K$("/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??Z$;for(let r of e.managedPolicies){let o=await b$(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)&&!j$.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??m$)()==="darwin",ok=async(e,t,n={})=>{if(!nm(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=jt(n),a=await to(o,n);if(a&&r.push({audience:"admin",message:tm(a)}),r.length>0)return V$(r);let s=!1,i=!1,c=[o.journal];try{let l=ee(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??T$)())throw new Error("Claude subscription mode requires a readable Claude Code sign-in in the macOS Keychain; run `claude` and sign in, then re-run Connect");let d=l?"passthrough":"json",u=A$((n.credentialCommand??(()=>Xf(d)))(),d),p=S$(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 U$(o,f,n.randomUUID??s$),w=Lt(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=H$(e,o.helper),k=await G$(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 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 E of Js)Zf(C,E,b[E]);await Mn(w,C),h.metaToWrite&&await Mn(o.meta,h.metaToWrite);let S=it(g.value),I=rk();for(let E of Xs)Zf(S,E,I[E]);return await Mn(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.",...El]}}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(!nm(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=jt(t);try{let r=await em(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Lt(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 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 qo(o,{force:!0}):await Mn(o,i)),l.present&&(u?await qo(n.meta,{force:!0}):Ks(l.value,d)||await Mn(n.meta,d));let p=await gn(n.appConfig);if(p.present){let m=VC(p.value,r.deployment,Xs,a);!r.deploymentFileExisted&&Object.keys(m).length===0?await qo(n.appConfig,{force:!0}):await Mn(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 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.`)}},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(Lt(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=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}},sk=async(e={})=>{try{let t=jt(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 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=tk(a.content??"");return s?await(t.helperLauncherAvailable??_$)(s):!1}catch{return!1}};import{createHash as vk,randomUUID as Sk}from"node:crypto";import{spawn as Y$,spawnSync as J$}from"node:child_process";import{link as dm,mkdir as om,open as Ik,readFile as am,readdir as Ek,rename as xk,rm as Zt,stat as Rk}from"node:fs/promises";import{homedir as um}from"node:os";import{basename as Ok,dirname as Qs,join as sa,win32 as X$}from"node:path";import{isDeepStrictEqual as ea}from"node:util";var Te="HKCU\\SOFTWARE\\Policies\\Claude",qs="HKLM\\SOFTWARE\\Policies\\Claude",Bl=5,ia="inferenceGatewayApiKey",Pe=["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.",z$=e=>/^[A-Za-z]:[\\/]/.test(e)&&X$.isAbsolute(e),uk=e=>{if(!z$(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")},pm=(e={})=>sa((e.home??um)(),".anyray","bin","claude-desktop-credential-helper.cmd"),q$=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},Q$=e=>(_k(e),["@echo off",`REM ${Tk}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(q$).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=Dl(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 tk(i)===e?i:void 0}catch{return}},_$=e=>{if(!e.startsWith(R$))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)!==gr)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return nk(a)===e?a:void 0}catch{return}},P$=`#!/bin/sh
|
|
201
|
+
# Anyray subscription pass-through credential helper`,D$=e=>{let t=Dl(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=$(${qf(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
|
+
`)},L$=e=>{if(!e.startsWith(P$))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 D$(a)===e?a:void 0},rk=e=>T$(e)??_$(e)??L$(e),N$=async()=>{let e=ZC("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},$$=async e=>{let t=[e.command,...Dl(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>JC(r)))).every(r=>r.isFile())?(await _l(e.command,YC.X_OK),!0):!1}catch{return!1}},M$=0,Ll=async(e,t,n)=>{await m$(XC(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${M$++}.tmp`;try{await g$(r,t,{mode:n}),await f$(r,n),await y$(r,e)}catch(o){throw await qo(r,{force:!0}).catch(()=>{}),o}},Mn=async(e,t)=>{await Ll(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 Jf(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 JC(e);return{present:!0,content:await Jf(e,"utf-8"),mode:t.mode&511}},ok=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:it(e[t])}:{present:!1},Yf=(e,t,n)=>{n.present?e[t]=it(n.value):delete e[t]},HC=e=>yn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),B$=e=>yn(e)&&HC(e.original)&&HC(e.lastWritten),F$=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),GC=(e,t)=>yn(e)&&t.every(n=>B$(e[n])),W$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],U$=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],em=(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!==zC||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!GC(e.config,r)||r.some(o=>e.config[o].original.present)||!GC(e.deployment,Xs)||!yn(e.helper)||e.helper.path!==t.helper||!F$(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),H$=(e,t)=>em(e,t,Xf,Js),G$=(e,t)=>em(e,t,2,W$),V$=(e,t)=>em(e,t,3,U$),K$=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),VC=e=>({...e,version:Xf,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),tm=async e=>{if(!await Zs(e.journal))return;let t;try{t=JSON.parse(await Jf(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(H$(t,e))return t;if(V$(t,e))return VC(t);if(G$(t,e))return VC(K$(t));throw new Error(`${e.journal} is not a valid ownership journal`)},KC=async(e,t)=>{await Ll(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},j$=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=Lt(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(Lt(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:zC};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?it(r.value):{},appliedId:s,entries:[...a,i]}}},Z$=(e,t)=>{let n=eo(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},ak=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),Y$=async(e,t,n,r,o,a,s)=>{let i=ak(),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??ok(r.value,d),lastWritten:i[d]}]));return{version:Xf,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]}),J$=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}`)]}},X$=k$(p$),z$=new Set(Rl),q$=async e=>{try{let{stdout:t}=await X$("/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??q$;for(let r of e.managedPolicies){let o=await S$(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)&&!z$.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},nm=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.`},rm=e=>(e.platform??b$)()==="darwin",sk=async(e,t,n={})=>{if(!rm(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=jt(n),a=await to(o,n);if(a&&r.push({audience:"admin",message:nm(a)}),r.length>0)return J$(r);let s=!1,i=!1,c=[o.journal];try{let l=ee(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??N$)())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=I$((n.credentialCommand??(()=>zf(d)))(),d),p=O$(u),f=await tm(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 j$(o,f,n.randomUUID??u$),w=Lt(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=Z$(e,o.helper),k=await Y$(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 KC(o.journal,k),i=!0,await Ll(o.helper,p,448),k.helper.previousWritten!==void 0&&(delete k.helper.previousWritten,await KC(o.journal,k));let C=it(y.value);for(let E of Js)Yf(C,E,b[E]);await Mn(w,C),h.metaToWrite&&await Mn(o.meta,h.metaToWrite);let S=it(g.value),I=ak();for(let E of Xs)Yf(S,E,I[E]);return await Mn(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.",...El]}}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.`)}},jC=(e,t,n,r)=>{let o=it(e);for(let a of n){let s=t[a];Ks(ok(e,a),s.lastWritten)?Yf(o,a,s.original):r.push(a)}return o},ik=async(e,t={})=>{if(!rm(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=jt(t);try{let r=await tm(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=Lt(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=jC(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 qo(o,{force:!0}):await Mn(o,i)),l.present&&(u?await qo(n.meta,{force:!0}):Ks(l.value,d)||await Mn(n.meta,d));let p=await gn(n.appConfig);if(p.present){let m=jC(p.value,r.deployment,Xs,a);!r.deploymentFileExisted&&Object.keys(m).length===0?await qo(n.appConfig,{force:!0}):await Mn(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 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.`)}},om=async(e,t={})=>{if(!rm(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(Lt(n.library,`${o}.json`)),s=await gn(n.appConfig);if(!a.present||!s.present)return!1;await _l(n.helper,YC.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}},ck=async(e={})=>{try{let t=jt(e),n=await zs(t.helper);if(!n.present||typeof n.content!="string")return;let r=rk(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},lk=async(e,t={})=>{if(!await om(e,t))return!1;let n=jt(t);try{let r=await tm(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=rk(a.content??"");return s?await(t.helperLauncherAvailable??$$)(s):!1}catch{return!1}};import{createHash as Ik,randomUUID as Ek}from"node:crypto";import{spawn as Q$,spawnSync as eM}from"node:child_process";import{link as um,mkdir as am,open as xk,readFile as sm,readdir as Rk,rename as Ok,rm as Zt,stat as Tk}from"node:fs/promises";import{homedir as pm}from"node:os";import{basename as _k,dirname as Qs,join as sa,win32 as tM}from"node:path";import{isDeepStrictEqual as ea}from"node:util";var Te="HKCU\\SOFTWARE\\Policies\\Claude",qs="HKLM\\SOFTWARE\\Policies\\Claude",Bl=5,ia="inferenceGatewayApiKey",Pe=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",ia],dk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",ia],uk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",ia],pk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",ia],Pk="Managed by anyray-connect; dynamic credential only.",nM=e=>/^[A-Za-z]:[\\/]/.test(e)&&tM.isAbsolute(e),fk=e=>{if(!nM(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)},Dk=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!fk(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&&!fk(e.args[0]))throw new Error("the credential helper does not use print-key --json")},fm=(e={})=>sa((e.home??pm)(),".anyray","bin","claude-desktop-credential-helper.cmd"),rM=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},oM=e=>(Dk(e),["@echo off",`REM ${Pk}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(rM).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
205
|
+
`)),aM=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},Lk=e=>{let t=e.split(`\r
|
|
206
|
+
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${Pk}`||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(aM);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return Dk(s),s}catch{return}},sM=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>Tk(r)))).every(r=>r.isFile())}catch{return!1}},iM=async(e,t)=>{let n=Lk(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??sM)(n)}catch{return!1}},im=e=>({sha256:no(e),content:e}),mk=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Nt(t,["sha256","content"])&&hM(t.sha256)&&typeof t.content=="string"&&no(t.content)===t.sha256&&Lk(t.content)!==void 0},mm=()=>{let e=eM("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??"")},cM=async(e,t)=>{await am(Qs(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await xk(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await um(n,e)}finally{await Zt(n,{force:!0}).catch(()=>{})}},lM=e=>`${_k(e)}.anyray-old-`,dM=e=>`${e}.anyray-old-${process.pid}-${Ek()}`,Nk=async(e,t)=>{try{await um(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await Zt(t,{force:!0}),!0},$l=async(e,t,n,r,o)=>{let a=dM(e),s=n===void 0?void 0:no(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${Ek()}`,c=!1;try{if(i&&n!==void 0){let d=await xk(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 Ok(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await oa(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await um(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await aa(e)!==s))throw new Error("credential helper publication verification failed");await Zt(a,{force:!0}),c=!1}catch(l){throw c&&await Nk(e,a).catch(()=>!1),l}finally{i&&await Zt(i,{force:!0}).catch(()=>{})}},cm=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,uM=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
|
-
}`,Fn=async e=>new Promise((t,n)=>{let r=
|
|
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
|
|
277
|
-
`;t.writeJournalFile?await t.writeJournalFile(n,r):await we(n,r)},wM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,bM=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),AM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),CM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),kM=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===CM(t).toUpperCase(),Ck=(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},vM=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,SM=(e,t)=>{if(!Ol(e,!0))return!1;let n=vM(t);if(AM.has(n))return!1;if(bM.has(n))return n==="REG_EXPAND_SZ"?!0:!MC(e,!0)},IM=(e,t)=>{let n=Lk(),r=!1,o=!1,a=!1,s=t.toUpperCase()===qs.toUpperCase(),i=(l,d)=>{if(!s)return;let u=SM(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||kM(d,t))continue;let u=wM.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}},Bn=async(e,t=Te)=>{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 IM(n.stdout,t)},wr=async e=>{let t=await Bn(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 Wl=(e,t)=>gr(eo(e,t)),Nk=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],EM=(e,t)=>{let n=Wl(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}]}))},xM=(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}}),RM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,cm=e=>Object.fromEntries(Pe.map(t=>[t,lM(t,e[t])])),kk=(e,t,n,r)=>({version:Bl,registryKey:Te,keyExisted:e,lastWritten:cm(t),helper:{path:n,lastWritten:sm(r)}}),OM=(e,t,n,r,o,a)=>({version:Bl,registryKey:Te,keyExisted:e,lastWritten:cm(t),pending:cm(n),helper:{path:r,...o?{lastWritten:sm(o)}:{},pending:sm(a)}}),lm=(e,t,n)=>ta(n,e.lastWritten[t])||e.pending!==void 0&&ta(n,e.pending[t]),oa=async e=>{try{let t=await am(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=oM(e),r;try{r=await Ek(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 Zt(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},bm=async(e,t,n)=>(n.present?await e(Nk(Te,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Te,"/v",t,"/f"])).code===0,TM=async(e,t,n)=>{let r=!0,o=await Bn(e);for(let a of Pe)if(!ea(o.values[a],t[a])){if(!ea(o.values[a],n[a])){r=!1;continue}await bm(e,a,t[a])||(r=!1),o=await Bn(e)}return r&&Pe.every(a=>ea(o.values[a],t[a]))},Qe=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[$t(n)]}}),$k=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=Q$((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??Fn,c=$t(r),l;if(!n.dryRun)try{l=await mm(r)}catch(h){return Qe(h 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,m=!1;try{let h=await wr(i);if(h)return Qe(wm(h),!1,r);let w=await gm(r,!n.dryRun);n.dryRun||await Ml(o,w);let y=await Bn(i),g=EM(e,o),b=await oa(o),k=b?.sha256,C=!1;if(d=w,u=y,p=g,w){let E=Pe.find(T=>!lm(w,T,y.values[T]));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&&!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=RM(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(F=>y.values[F].present),T=Pe.every(F=>ea(y.values[F],g[F])),O=Pe.every(F=>ea(y.values[F],xM(e,t.trim())[F]));if(E&&!T&&!O)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=O,T&&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 Nl(kk(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=OM(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 Nl(S,r),m=!0;for(let E of Pe){let T=await Bn(i);if(!ta(T.values[E],S.lastWritten[E])&&!ta(T.values[E],S.pending[E]))throw new Error("registry value changed during apply");if(!ea(T.values[E],g[E])&&!await bm(i,E,g[E]))throw new Error("registry write failed")}let I=await Bn(i);if(!Pe.every(E=>ta(I.values[E],S.pending[E])))throw new Error("registry verification failed");if(k!==s&&(k===void 0?await rM(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 ${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.",...El]}}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 Ml(o,f);let h=!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),h=await aa(o)===f.helper.lastWritten.sha256):await $l(o,y.sha256,void 0,"rollback",r):h=w===void 0&&f.helper.lastWritten===void 0),h&&await TM(i,u.values,p))return d?await Nl(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?.()}},Mk=async(e,t={})=>{let n=t.runReg??Fn,r=$t(t),o;if(!e.dryRun)try{o=await mm(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 gm(t,!e.dryRun);a&&!e.dryRun&&await Ml(a.helper.path,a);let s=await Bn(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 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 ${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 Bn(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 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 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?[]:xl]})}catch{return Qe(`Could not safely inspect or revert ${Te}; no unproven value was removed.`,!1,t)}finally{await o?.()}},Bk=async(e,t={})=>{let n=t.runReg??Fn;if(!await x($t(t)))return;let r;try{r=await mm(t);let o=await gm(t);if(o&&await Ml(o.helper.path,o),!o||o.pending||await wr(n)!==void 0)return;let a=await Bn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Ht(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&Pe.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 nM(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=PM())=>e==="win32"?fm:Pl,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??ca(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await Uk.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 Il(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??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=Ul(t.stagingRoot??DM(),`anyray-history-${process.pid}-${_M()}`);try{let s=await(t.runImporter??_C)({binary:o,exportPath:e,configDir:Ul(a,"config"),workDir:Ul(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 DC(r.dir,s.conversations),c=await LC({stagedProjectsDir:Ul(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 Uk.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as vt}from"node:fs";import{homedir as tB}from"node:os";import{join as Jt,sep as nB}from"node:path";import{isDeepStrictEqual as jl}from"node:util";import{constants as LM}from"node:fs";import{promises as G}from"node:fs";import{dirname as la,isAbsolute as km,join as ne,relative as Gl,resolve as Yt,sep as ei}from"node:path";import{randomUUID as Zl}from"node:crypto";var wn=448,ti=384,Kk=448,NM=4,vm=3e4,jk=5e3,$M=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"),Zk=(e,t)=>{let n=Gl(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,MM=e=>{try{return process.kill(e,0),!0}catch(t){return kt(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=ne(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||!MM(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>vm&&t-e.createdAtMs>$M},BM=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(!kt(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)<=vm)return}let l=ne(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(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{}})()},
|
|
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()}},Yl=async(e,t)=>{for(let n=0;n<
|
|
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{}})()},
|
|
281
|
-
`)}},Em=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),cv=async e=>{let t=[];for(let n of aB)t.push({lane:n,sources:await iB(e,n)});return t},lv=async(e={})=>{let t=(e.firstPartyRoot??(()=>Hs()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([cv(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??tB)(),n=(e.firstPartyRoot??(()=>Hs()))(),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),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 av(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 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 rB(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:m}of o){if(m.length===0){d.push(Im(f));continue}let h=await cB(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 uB(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 fB=e=>[Ve(e)],dv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...fB(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",gB=yB(mB),wB=async e=>{try{let{stdout:t}=await gB("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},bB=async e=>{try{return await hB(e)}catch{return}},pv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",AB=["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??=mv({}),fv):mv(e),fv,mv=async e=>{let t=(e.home??oi)(),n=["/Applications/Claude.app",bn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??wB,o=e.readClaudeAppBundle??bB;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??br)(),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"),wv=()=>{let e=Ge("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])},CB=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),kB=e=>{if(!ao(e)||!bv(e,["command","args"]))return!1;let t=wv();return e.command===t.command&&CB(e.args,t.args)},vB=e=>ao(e)&&Array.isArray(e.args)&&e.args.at(-1)===gv,SB=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)===Xn&&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))},IB=e=>e===void 0?"absent":kB(e)?"exact":vB(e)||SB(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 M(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)?.[Xl];return{path:e,fileExisted:t,json:n,entry:o,ownership:IB(o)}},ql=e=>{if(e.ownership==="foreign")throw new Me(`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},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 Mn(e.path,Av(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=Av(t.json,e.reading.entry);await Mn(e.reading.path,n)},EB=async e=>{if(!te())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(zl(e));ql(t);let n=Pm(e),r=(e.platform??br)()==="darwin"&&n!==t.path?await so(n):void 0;return r&&ql(r),{active:t,...r?{legacy:r}:{}}},hv=async e=>{let t=await so(zl(e));ql(t);let n=Pm(e),r=(e.platform??br)()==="darwin"&&n!==t.path?await so(n):void 0;return r&&ql(r),{active:t,...r?{legacy:r}:{}}},xB=async e=>{let t=[];try{let n=await Om(e.active,wv());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)}}},RB=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)},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)."]},OB={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},Ql="claude-desktop",_m="migrate",Cv=new Set(["app-running","store-missing"]),TB={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},_B={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"}},PB="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",kv=e=>{let t=(e.platform??br)(),n=e.home??oi;return{home:n,appRunning:e.appRunning??ca(t),firstPartyRoot:()=>Hs({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=TB[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=_B[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??[],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(!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,_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."]}},DB=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await ar(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."]}},LB=e=>dv({id:Ql,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??br)(),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`."]}),NB=(e={})=>{let t=LB(e),n=()=>(e.platform??br)()==="darwin",r=()=>(e.platform??br)()==="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??br)()))(),quitTarget:OB,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)(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(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 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=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 wr(e.runReg??Fn)}catch{return{status:"manual",manualAudience:"admin",messages:[PB,...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 da(e);if(!p.supported)return{status:"manual",messages:[p.message??"Claude Desktop version is unsupported."]}}let c;try{c=await EB(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 xB(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()?AB:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=zl(e),c=await DB(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 hv(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()?$t(e):void 0;if(!(h!==void 0&&p.changedFiles?.includes(h)===!0&&!await x(h)))return l(p)}let f;try{f=await RB(await hv(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 oe(i);let m=Pm(e);return n()&&m!==i&&await oe(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(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};try{let s=await so(zl(e));return s.ownership!=="exact"||!ao(s.entry)?{registered:!1,command:null,reason:s.fileExisted?s.ownership==="absent"?"absent":s.ownership==="stale-owned"?"stale":"foreign":"no-config"}:{registered:!0,command:typeof s.entry.command=="string"?s.entry.command:null}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async pointsAt(s){return n()?(await da(e)).supported?rm(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($t(e))?await wr(e.runReg??Fn)?["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 da(e)).supported}return r()&&await x($t(e))?!await wr(e.runReg??Fn):!1}catch{return!1}}}},Iv=NB();import{homedir as lF}from"node:os";import{join as dF}from"node:path";import{rm as cd}from"node:fs/promises";import{constants as Ev,accessSync as $B,statSync as MB}from"node:fs";import{platform as Dm}from"node:os";import{delimiter as BB,posix as FB,resolve as WB,win32 as UB}from"node:path";var HB="0.59.0",GB="1.1.4",Wn="Anyray \xB7 Claude",Un="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=Dm())=>e==="win32"?"npx.cmd":"npx",nd=(e=process.env.PATH,t=Dm())=>{if(!e)return;let n=td(t);for(let r of e.split(BB)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=WB(o,n);try{if(!MB(a).isFile())continue;return $B(a,t==="win32"?Ev.F_OK:Ev.X_OK),a}catch{}}},rd=(e,t=Dm())=>{let n=t==="win32"?UB:FB;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==td(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},VB="https://chatgpt.com/backend-api/codex",KB="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=>ue({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),jB=(e,t={})=>{let n=ee(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":VB,"x-anyray-forward-headers":KB}:{},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}}}:{}}},ZB=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={})=>({[Wn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${HB}`],env:tn(e).env},[Un]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${GB}`],env:{CODEX_CONFIG:JSON.stringify(jB(e,n)),...ZB(e)}}}),ai=(e=td(),t="jetbrains")=>({[Wn]:xv("claude",e,t),[Un]: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 YB}from"node:zlib";import{open as JB,readFile as Bm,readdir as id}from"node:fs/promises";import{dirname as Dv,join as fe}from"node:path";import{homedir as Mv,platform as Fm}from"node:os";var ad="2025.3.2",ua="253.30387.147",si="com.intellij.ml.llm",Lm=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),XB=1e4,zB=256*1024*1024,qB=16*1024*1024,Nm=1024*1024,$m=22,QB=$m+65535,Mm=vl,eF=()=>{let e=Mv(),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"}]}},tF=()=>Fm()==="linux"?fe(Mv(),".local","share","JetBrains"):Ve("JetBrains"),nF=()=>Fm()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),rF=async(e,t=XB)=>{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)]},oF=e=>{let t=Dv(e);return t.endsWith(`${fe("Contents","Resources")}`)?Dv(t):t},aF=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:oF(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},sF=async(e,t)=>{let n;try{n=await JB(e,"r");let{size:r}=await n.stat();if(r<$m||r>zB)return;let o=Math.min(r,QB),a=await sd(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>qB||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),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 sd(n,30,y);if(!k||k.readUInt32LE(0)!==67324752)return;let C=k.readUInt16LE(26),S=k.readUInt16LE(28),I=await sd(n,p,y+30+C+S);return I?u===0?I.toString("utf8"):u===8?YB(I,{maxOutputLength:Nm}).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}},iF=async(e,t)=>{let n=fe(e,"META-INF","plugin.xml");if(await x(n))try{let o=Lv(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 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 sF(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=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 iF(fe(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},cF=async e=>{try{return(await Bm(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?(Mm(n,t)??-1)>0?n:t:n,void 0),Bv=async(e={})=>{let t=e.configRoot??Ve("JetBrains"),n=e.userPluginsRoot??tF(),r=await rF(e.productRoots?e.productRoots.map(m=>({path:m,layout:"recursive"})):eF(),e.scanBudget),o=(await Promise.all(r.map(m=>aF(m)))).filter(m=>m!==void 0),a=o.length>0||await x(t);if(e.wsl??nF())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,ad)??-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 Nv(g);if(b.present){y=b;break}}if(y??=await Nv(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 cF(h)){c=!0;continue}if(!((Mm(y.descriptor.version,ua)??-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=$v(o.map(m=>m.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 uF=[Wn,Un],Wm=()=>dF(lF(),".jetbrains","acp.json"),co=()=>`${Wm()}.anyray-state`,pF=(e,t,n="npx")=>{let r=io(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,ai(n,"jetbrains")),{...e,agent_servers:r}},fF=(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 uF)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}},mF=(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=Wm(),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 M(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:pF(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 oe(n),await cd(co(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await M(n)}catch{return t.dryRun||(await oe(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 M(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 M(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await Dr(n);let l=fF(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 oe(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():ji(n,co(),r)}}),Fv=mF();import{homedir as dd}from"node:os";import{join as ud}from"node:path";import{rm as Um}from"node:fs/promises";var Hm="1.0.0",pd=["anyray-claude-acp","anyray-codex-acp"],hF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Gm=()=>ud(dd(),".windsurf","acp","registry.json"),Vm=()=>ud(dd(),".windsurf-next","acp","registry.json"),pa=e=>`${e}.anyray-state`,Wv=e=>({binary:Object.fromEntries(hF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Hv=(e="npx")=>{let t=ai(e,"windsurf");return[{id:pd[0],name:Wn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Wv(t[Wn])},{id:pd[1],name:Un,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Wv(t[Un])}]},ld=e=>!Array.isArray(e)||e.some(t=>!io(t)||typeof t.id!="string")?null:e,yF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Hm||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:Hm,agents:[...n.filter(o=>!r.has(o.id)),...Hv(t)],extensions:e.extensions??[]}},gF=(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===Hm&&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}},Uv=async()=>{let e=[];return(await x(Vm())||await x(ud(dd(),".windsurf-next")))&&e.push(Vm()),(await x(Gm())||await x(ud(dd(),".windsurf"))||await x(Ve("Devin"))||await x(Ve("Windsurf")))&&e.push(Gm()),e},Gv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await Uv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await Uv();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 M(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=yF(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=Hv(r);await Zi({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=[Gm(),Vm()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await x(a)){e.dryRun||(await oe(a),await Um(pa(a),{force:!0}).catch(()=>{}));return}let i;try{i=await M(a)}catch{n.push(`Could not parse ${a}; remove the anyray-* ACP agents manually.`),o=!0;return}let c=[],l=!1,d=!1;try{let f=await M(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 M(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 Dr(a);let p=gF(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 Um(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 oe(a),await Um(pa(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await ji(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,Lw,ks,MA,dC,kC,OC,Fv,Iv,Gv,Hw],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,Vv=3e4,wF=1440*60*1e3,bF=e=>new Promise(t=>setTimeout(t,e)),AF=async(e=D,t=fn)=>(await Be(e,t))?.target,CF=e=>mt(e)?.quitGated,Kv=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??CF,o=t.readPending??Hc,a=t.clearPending??Tp,s=t.targetFromProfile??AF,i=t.sleep??bF,c=t.now??Date.now,l=t.maxWaitMs??wF;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(Vv,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(Vv,f*2);continue}if(await a(n,m)!=="superseded")return 0;await i(f),f=Km}}catch{return 0}};import{writeFileSync as lW}from"node:fs";import{chmod as rh,stat as dW}from"node:fs/promises";import{platform as kS}from"node:os";import{dirname as vS,isAbsolute as uW}from"node:path";var kF="https://app.anyray.ai",vF=new Set(["localhost","::1","[::1]"]),SF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,IF=e=>vF.has(e)||SF.test(e),jm=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&IF(t.hostname)},EF=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)?kF:EF(e)};import{createHash as FF,generateKeyPairSync as WF,randomBytes as Jm}from"node:crypto";import{createPrivateKey as xF,sign as RF}from"node:crypto";var Ar=async(e,t)=>{let n=xF(t);return RF(null,new TextEncoder().encode(e),n).toString("base64url")};var OF=["HTTPS_PROXY","https_proxy"],jv=new Set(["SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_UNTRUSTED"]),Zv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Yv=new Set(["ENOTFOUND","EAI_AGAIN"]),Jv=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),Xv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),TF=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 _F(e)},_F=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...jv,...Zv,...Yv,...Jv,...Xv])if(t.includes(n))return n}},PF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",DF=e=>OF.filter(t=>(e[t]??"").trim()!==""),LF=(e,t=process.env)=>{let n=TF(e),r=DF(t);return{kind:n&&jv.has(n)?"tls-unknown-issuer":n&&Zv.has(n)?"tls-invalid-cert":n&&Yv.has(n)?"dns":PF(e)||n&&Xv.has(n)?"timeout":n&&Jv.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},NF=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)=>NF(LF(e,t));var $F="enl_",zv="enp_",qv=e=>e.startsWith($F)||e.startsWith(zv),Zm=e=>e.startsWith(zv),MF=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],Ym=e=>MF.find(t=>e.startsWith(t.prefix)),Qv=/^\/enroll\/([^/]+)\/?$/,eS=/^\/i\/([^/]+)\/?$/,tS=e=>{let t=e.match(Qv);if(t)return Ym(t[1])?void 0:t[1];let n=e.match(eS);return n&&qv(n[1])?n[1]:void 0},BF=1e4,fd=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=tS(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!Ym(t))return{cpOrigin:Hn(),token:t}},nS=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(Qv)??o.pathname.match(eS);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:tS(n.pathname)!==void 0}catch{return qv(t)}},fa=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},ii=e=>typeof e=="string"&&e.trim()?e.trim():void 0,rS=async(e,t={})=>{let n=t.timeoutMs??BF,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 fa(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(",")}}`,oS="stable-key-heartbeat-v1",aS="key-heartbeat",UF=["reapply_config","remint","revert"],zm=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var sS=e=>FF("sha256").update(e).digest("hex"),Ze=e=>typeof e=="string"&&e.trim()?e.trim():void 0,HF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],iS={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"},GF=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${iS[e]}. Ask your IT admin.`,VF=e=>typeof e=="string"&&e in iS,qm=async e=>{try{let t=await e.json(),n=Ze(t?.message),r=Ze(t?.error),o=VF(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:GF(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},KF=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}},cS=e=>e instanceof fa||e instanceof lt&&e.policyCode==="sso_required",ma=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`)}},md=()=>{let{publicKey:e,privateKey:t}=WF("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=Ze(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:Jm(16).toString("hex"),...zm(t,r.machineUuid)},c=await Qm(i,n,"verification",r.signer??Ar),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=Ze(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=Ze(f.user);if(!h)throw new Error("developer verification failed: the gateway response is missing the user");let w=jF(f.directive),y=HF(f.capabilities);return{key:m,user:h,team:Ze(f.team),expiresAt:Ze(f.expiresAt),...y.length>0?{capabilities:y}:{},...w?{directive:w}:{}}},lS=async(e,t,n,r,o={})=>{let a=o.timeoutMs??Xm,s=`${e}/connect/key/heartbeat`,i=Ze(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:Jm(16).toString("hex"),purpose:aS,...zm(n,o.machineUuid)},l=await Qm(c,r,"heartbeat",o.signer??Ar),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 ma(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=Ze(f.expiresAt);if(!m||!Number.isFinite(Date.parse(m))||f.credentialMode!==oS||f.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:m,credentialMode:oS}},dS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??Xm,i=`${e.replace(/\/$/,"")}/connect/machine`,c=Ze(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Jm(16).toString("hex"),purpose:aS,...zm(n,o)},d=await Qm(l,r,"heartbeat",a.signer??Ar),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=Ze(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!UF.includes(r)?null:{id:n,kind:r}},ZF=1e4,YF=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!Ze(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!Ze(r.deploymentId)&&!!Ze(r.user)&&!!Ze(r.devPublicKey)&&!!Ze(r.issuedAt)&&!!Ze(r.expiresAt)},JF=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??ZF,s=`${e}/v1/enroll`,i=new AbortController,c=setTimeout(()=>i.abort(),a),l;try{l=await fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:t,devPublicKey:n,...r.email?{email:r.email}:{},...r.team?{team:r.team}:{},...r.machineId?{machineId:r.machineId}:{},...r.deploymentId?{deploymentId:r.deploymentId}:{}}),signal:i.signal})}catch(u){let 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 KF(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new fa(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(!YF(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},uS=(e,t,n,r,o,a,s)=>{if(!e)return!1;let i=t?Date.parse(t):NaN;return!(!Number.isFinite(i)||i<=r||n&&e.payload.deploymentId!==n||o&&o!==a||s&&e.payload.user.trim().toLowerCase()!==s.trim().toLowerCase())},pS=async e=>{let t={timeoutMs:e.timeoutMs,machineUuid:e.machineUuid,signer:e.signer},{cert:n,privateKeyPem:r,publicKeyPem:o}=e.reuse?e.reuse:await(async()=>{let s=md();return{cert:await JF(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,XF=900*1e3,mS="tnt_",zF=/^\/sso\/([^/]+)\/?$/,qF=/^\/i\/([^/]+)\/?$/,QF=e=>{let t=e.match(zF);if(t)return t[1];let n=e.match(qF);return n?.[1].startsWith(mS)?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=QF(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(mS))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}},Mt=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)}},eW=e=>new Promise(t=>setTimeout(t,e)),hd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??md)(),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??XF,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}`),tW(p.verificationUriComplete,e.cpOrigin)&&e.open?.(p.verificationUriComplete),p},tW=(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??eW,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 Mt("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 Mt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Mt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Mt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var fS="sdc_",hS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(fS))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(fS)))return{cpOrigin:n.origin,claim:r}},yS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??md)(),o;try{o=await th(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},eh,t)}catch(s){throw new Mt("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 Mt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Mt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Mt("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 nW}from"node:fs/promises";import{isAbsolute as rW,posix as gS,win32 as nh}from"node:path";var li=(e=process.platform,t=process.env)=>e==="darwin"?gS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?nh.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):gS.join("/etc","anyray","bootstrap.json"),oW=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),wS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(rW(e)||nh.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),aW=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}},Cr=async(e=li())=>{try{let t=await nW(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!oW(n)||n.v!==1||typeof n.sso!="string")return;let r=St(n.sso);if(!r)return;let o=aW(n.gateway)?n.gateway:void 0,a=wS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},bS=(e,t,n)=>{let r=St(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!wS(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 ha=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,gd=ha(process.stdout,process.env),
|
|
284
|
-
${V(e)}`),$=e=>console.log(v(e)),B=e=>console.log(`${
|
|
275
|
+
}`,Fn=async e=>new Promise((t,n)=>{let r=Q$("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",uM],{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(cm(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(cm({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),$t=(e={})=>sa((e.home??pm)(),".anyray","claude-desktop-windows.json"),pM=e=>sa((e.home??pm)(),".anyray","claude-desktop-windows.lock"),ra=class extends Error{},fM=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},hm=async e=>{let t=pM(e);await am(Qs(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=Ik("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=sa(t,"owner.json");try{await am(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 sm(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!fM(i.pid)}catch{try{s=Date.now()-(await Tk(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new ra;await Zt(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await sm(o,"utf8")).nonce===r&&await Zt(t,{recursive:!0,force:!0})}catch{}}}throw new ra},$k=()=>Object.fromEntries(Pe.map(e=>[e,{present:!1}])),no=e=>Ik("sha256").update(e).digest("hex"),mM=(e,t)=>t.present?e===ia?{present:!0,type:t.type,sha256:no(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},ta=(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,Nt=(e,t)=>Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),Fl=(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===ia?Nt(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:Nt(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},hk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Nt(e,Pe)&&Pe.every(t=>Fl(e[t],t)),yk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Nt(e,dk)&&dk.every(t=>Fl(e[t],t)),hM=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),ym=(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 Nt(n,r)&&n.path===fm(t)&&(n.lastWritten===void 0||mk(n.lastWritten))&&(n.pending===void 0||mk(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},yM=(e,t)=>Nt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Bl&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&hk(e.lastWritten)&&(e.pending===void 0||hk(e.pending))&&ym(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),gM=e=>Nt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===Te&&typeof e.keyExisted=="boolean"&&yk(e.lastWritten)&&(e.pending===void 0||yk(e.pending)),gk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Nt(e,uk)&&uk.every(t=>Fl(e[t],t)),wM=(e,t)=>Nt(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"&&gk(e.lastWritten)&&(e.pending===void 0||gk(e.pending))&&ym(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),wk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Nt(e,pk)&&pk.every(t=>Fl(e[t],t)),bM=(e,t)=>Nt(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"&&wk(e.lastWritten)&&(e.pending===void 0||wk(e.pending))&&ym(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),bk=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),gm=e=>{let{pending:t,...n}=e;return{...n,version:Bl,lastWritten:bk(e.lastWritten),...t?{pending:bk(t)}:{}}},Ak=e=>({...e,chatTabEnabled:{present:!1}}),AM=e=>{let{pending:t,...n}=e;return gm({...n,version:4,lastWritten:Ak(e.lastWritten),...t?{pending:Ak(t)}:{}})},Ck=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),CM=(e,t)=>gm({version:4,registryKey:Te,keyExisted:e.keyExisted,lastWritten:Ck(e.lastWritten),...e.pending?{pending:Ck(e.pending)}:{},helper:{path:fm(t)}}),wm=async(e,t=!0)=>{let n=$t(e),r=Qs(n),o=`${_k(n)}.anyray-old-`,a=(await Rk(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>sa(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 Ok(a[0],n):s=a[0]}let i=await M(s),c=gM(i)?CM(i,e):wM(i,e)?AM(i):bM(i,e)?gm(i):yM(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},kk=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceGatewayApiKey:e.inferenceGatewayApiKey}),kM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0?{version:2,registryKey:Te,keyExisted:e.keyExisted,lastWritten:kk(e.lastWritten),...e.pending?{pending:kk(e.pending)}:{}}:e,Nl=async(e,t)=>{let n=$t(t),r=`${JSON.stringify(kM(e),null,2)}
|
|
277
|
+
`;t.writeJournalFile?await t.writeJournalFile(n,r):await we(n,r)},vM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,SM=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),IM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),EM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),xM=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===EM(t).toUpperCase(),vk=(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},RM=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,OM=(e,t)=>{if(!Ol(e,!0))return!1;let n=RM(t);if(IM.has(n))return!1;if(SM.has(n))return n==="REG_EXPAND_SZ"?!0:!FC(e,!0)},TM=(e,t)=>{let n=$k(),r=!1,o=!1,a=!1,s=t.toUpperCase()===qs.toUpperCase(),i=(l,d)=>{if(!s)return;let u=OM(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),vk(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||xM(d,t))continue;let u=vM.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),vk(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},Bn=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 TM(n.stdout,t)},br=async e=>{let t=await Bn(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},bm=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)=>wr(eo(e,t)),Mk=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],_M=(e,t)=>{let n=Wl(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}]}))},PM=(e,t)=>({inferenceProvider:{present:!0,type:"REG_SZ",value:"gateway"},inferenceGatewayBaseUrl:{present:!0,type:"REG_SZ",value:e.anthropicBaseUrl},inferenceGatewayAuthScheme:{present:!0,type:"REG_SZ",value:"bearer"},chatTabEnabled:{present:!1},coworkEgressAllowedHosts:{present:!1},inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},inferenceGatewayApiKey:{present:!0,type:"REG_SZ",value:t}}),DM=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,lm=e=>Object.fromEntries(Pe.map(t=>[t,mM(t,e[t])])),Sk=(e,t,n,r)=>({version:Bl,registryKey:Te,keyExisted:e,lastWritten:lm(t),helper:{path:n,lastWritten:im(r)}}),LM=(e,t,n,r,o,a)=>({version:Bl,registryKey:Te,keyExisted:e,lastWritten:lm(t),pending:lm(n),helper:{path:r,...o?{lastWritten:im(o)}:{},pending:im(a)}}),dm=(e,t,n)=>ta(n,e.lastWritten[t])||e.pending!==void 0&&ta(n,e.pending[t]),oa=async e=>{try{let t=await sm(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=lM(e),r;try{r=await Rk(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 Nk(e,a))throw new Error("credential helper changed during recovery");return}if(t&&na(t,s.sha256)&&na(t,i.sha256)){await Zt(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},Am=async(e,t,n)=>(n.present?await e(Mk(Te,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Te,"/v",t,"/f"])).code===0,NM=async(e,t,n)=>{let r=!0,o=await Bn(e);for(let a of Pe)if(!ea(o.values[a],t[a])){if(!ea(o.values[a],n[a])){r=!1;continue}await Am(e,a,t[a])||(r=!1),o=await Bn(e)}return r&&Pe.every(a=>ea(o.values[a],t[a]))},Qe=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[$t(n)]}}),Bk=async(e,t,n,r={})=>{if(!Ee(t))return Qe("A valid personal ark_ gateway key is required.",!1,r);let o=fm(r),a;try{a=oM((r.credentialCommand??zf)())}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??Fn,c=$t(r),l;if(!n.dryRun)try{l=await hm(r)}catch(h){return Qe(h 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,m=!1;try{let h=await br(i);if(h)return Qe(bm(h),!1,r);let w=await wm(r,!n.dryRun);n.dryRun||await Ml(o,w);let y=await Bn(i),g=_M(e,o),b=await oa(o),k=b?.sha256,C=!1;if(d=w,u=y,p=g,w){let E=Pe.find(T=>!dm(w,T,y.values[T]));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&&!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=DM(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(F=>y.values[F].present),T=Pe.every(F=>ea(y.values[F],g[F])),O=Pe.every(F=>ea(y.values[F],PM(e,t.trim())[F]));if(E&&!T&&!O)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=O,T&&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 Nl(Sk(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??mm)()}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=LM(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 Nl(S,r),m=!0;for(let E of Pe){let T=await Bn(i);if(!ta(T.values[E],S.lastWritten[E])&&!ta(T.values[E],S.pending[E]))throw new Error("registry value changed during apply");if(!ea(T.values[E],g[E])&&!await Am(i,E,g[E]))throw new Error("registry write failed")}let I=await Bn(i);if(!Pe.every(E=>ta(I.values[E],S.pending[E])))throw new Error("registry verification failed");if(k!==s&&(k===void 0?await cM(o,a):await $l(o,k,a,"apply",r)),await aa(o)!==s)throw new Error("credential helper verification failed");return await Nl(Sk(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.",...El]}}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 Ml(o,f);let h=!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),h=await aa(o)===f.helper.lastWritten.sha256):await $l(o,y.sha256,void 0,"rollback",r):h=w===void 0&&f.helper.lastWritten===void 0),h&&await NM(i,u.values,p))return d?await Nl(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?.()}},Fk=async(e,t={})=>{let n=t.runReg??Fn,r=$t(t),o;if(!e.dryRun)try{o=await hm(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 wm(t,!e.dryRun);a&&!e.dryRun&&await Ml(a.helper.path,a);let s=await Bn(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&&!dm(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 ${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 Bn(n)).values[f];if(h.present){if(!dm(a,f,h)){u.add(f);continue}await Am(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 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?[]:xl]})}catch{return Qe(`Could not safely inspect or revert ${Te}; no unproven value was removed.`,!1,t)}finally{await o?.()}},Wk=async(e,t={})=>{let n=t.runReg??Fn;if(!await x($t(t)))return;let r;try{r=await hm(t);let o=await wm(t);if(o&&await Ml(o.helper.path,o),!o||o.pending||await br(n)!==void 0)return;let a=await Bn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Ht(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&Pe.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 iM(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?.()}},Uk=async(e,t={})=>await Wk(e,t)!==void 0,Hk=async(e,t={})=>await Wk(e,t)==="dynamic";var ca=(e=MM())=>e==="win32"?mm:Pl,Cm="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:Cm};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 Gk.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 Il(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 "+Cm}:{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??PC)();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=Ul(t.stagingRoot??BM(),`anyray-history-${process.pid}-${$M()}`);try{let s=await(t.runImporter??DC)({binary:o,exportPath:e,configDir:Ul(a,"config"),workDir:Ul(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. "+Cm};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 NC(r.dir,s.conversations),c=await $C({stagedProjectsDir:Ul(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 Gk.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as vt}from"node:fs";import{homedir as sB}from"node:os";import{join as Jt,sep as iB}from"node:path";import{isDeepStrictEqual as jl}from"node:util";import{constants as FM}from"node:fs";import{promises as G}from"node:fs";import{dirname as la,isAbsolute as vm,join as ne,relative as Gl,resolve as Yt,sep as ei}from"node:path";import{randomUUID as Zl}from"node:crypto";var wn=448,ti=384,Zk=448,WM=4,Sm=3e4,Yk=5e3,UM=10*6e4,km=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"),Jk=(e,t)=>{let n=Gl(Yt(e),Yt(t));return n===""||!n.startsWith(`..${ei}`)&&n!==".."&&!vm(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,HM=e=>{try{return process.kill(e,0),!0}catch(t){return kt(t)&&t.code==="EPERM"}},Xk=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=ne(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}},zk=e=>{if(e.pid===void 0||!HM(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Sm&&t-e.createdAtMs>UM},GM=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(!kt(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(!zk(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)<=Sm)return}let l=ne(t,Xk(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{}})()},Yk);return s.unref(),async()=>{clearInterval(s);try{(await Vl(t))?.nonce===n&&await G.rm(t,{recursive:!0,force:!0})}catch{}}},VM=async(e,t,n)=>{await G.mkdir(la(e),{recursive:!0,mode:wn});let r=await GM(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}-${Zl()}`;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()}},Yl=async(e,t)=>{for(let n=0;n<WM;n+=1){let r=await ro(e);if(!r)return"failed";let o=t(r.value);if(!o||jl(o,r.value))return"unchanged";try{if(await VM(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},Vk=async e=>{try{return(await G.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},Jl=async e=>{let t=[];for(let n of await Vk(e))for(let r of await Vk(ne(e,n)))t.push(ne(e,n,r));return t},KM=e=>Array.isArray(e.skills)?e.skills.filter(t=>ct(t)&&ni(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],jM=async e=>{let t=ne(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await Jl(t)){let o=await ro(ne(r,"manifest.json"));if(!o)continue;let a=r.split(ei).at(-1)??"";for(let s of KM(o.value))n.push({account:a,packageDir:r,entry:s})}return n},ZM=async e=>{let t=await ro(ne(e,".claude-plugin","plugin.json"));return!!t&&ni(t.value.name)},YM=(e,t)=>{let n=vm(t)?Yt(t):Yt(e,t);if(!Jk(e,n)||n===Yt(e))return;let r=Gl(Yt(e),n);return r.length>0?{absolute:n,relative:r}:void 0},JM=async e=>{let t=await Jl(ne(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(ei).includes("skills-plugin"))continue;let o=ne(r,"cowork_plugins"),a=await ro(ne(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=YM(o,l.installPath);!d||!await ZM(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:ne(r,"cowork_account_settings.json")})}}return n},XM=async e=>{let t=await ro(ne(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)))},qk=async e=>{let[t,n,r]=await Promise.all([jM(e),JM(e),XM(e)]);return{skills:t,plugins:n,localMcpServers:r}},Im=async e=>{let t=await qk(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)}},Kk=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=ne(n,o.name);if(o.isSymbolicLink())return!1;if(o.isDirectory()){if(!await t(a))return!1}else if(!o.isFile())return!1}return!0};return t(e)},zM=async e=>{let t=async n=>{let r=await G.readdir(n,{withFileTypes:!0});for(let o of r){let a=ne(n,o.name);if(o.isDirectory())await t(a),await G.chmod(a,wn);else if(o.isFile()){let s=await G.stat(a);await G.chmod(a,(s.mode&73)!==0?Zk:ti)}}};await t(e),await G.chmod(e,wn)},Qk=async(e,t)=>{try{let[n,r]=await Promise.all([G.readFile(e),G.readFile(t)]);return n.equals(r)}catch{return!1}},Kl=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(!jl(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 Kl(ne(e,s),ne(t,s)))return!1}else if(!i.isFile()||!await Qk(ne(e,s),ne(t,s)))return!1}return!0}catch{return!1}},ev=e=>`${e}.anyray-incomplete`,tv=async(e,t)=>{let n=!1;if(t){await G.mkdir(la(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=Zl(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let p;try{p=await Vl(e)}catch{return}if(p){if(!zk(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)<=Sm)return}let u=ne(e,Xk(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{}})()},Yk);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await Vl(e))?.nonce===r&&await G.rm(e,{recursive:!0,force:!0})}catch{}}}},nv=async e=>{let t=await tv(e,!1);t&&await t.complete()},qM=async(e,t,n)=>{let r=ev(t),o=!1;try{let c=await G.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await Kl(e,t))return await nv(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 tv(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=ne(c,u.name),f=ne(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,FM.COPYFILE_EXCL);let m=await G.stat(p);await G.chmod(f,(m.mode&73)!==0?Zk:ti)}catch(m){if(!kt(m)||m.code!=="EEXIST")throw m;if(!await Qk(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 Kl(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},rv=async(e,t,n,r)=>{if(!await Kk(e))return"invalid";try{let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await Kl(e,t))return await nv(ev(t)),"present"}catch(a){if(!kt(a)||a.code!=="ENOENT")return"failed"}await G.mkdir(la(t),{recursive:!0,mode:wn});let o=ne(la(t),`.anyray-stage-${Zl()}`);try{return await G.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await Kk(o)?(await zM(o),await n?.(t),await qM(o,t,r)):"invalid"}catch{return"failed"}finally{try{await G.rm(o,{recursive:!0,force:!0})}catch{}}},jk=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),QM=async e=>{let t=await Jl(ne(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await ro(ne(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},eB=async e=>{let t=await Jl(ne(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(ei).includes("skills-plugin"))try{await G.access(ne(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},tB=async(e,t,n,r,o)=>{let a=ne(t,"manifest.json");for(let s of e){let i=ne(s.packageDir,"skills",s.entry.name);try{await G.access(ne(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=ne(t,"skills",s.entry.name),l=await rv(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 Yl(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}},ov=(e,t)=>({...e,installPath:t}),nB=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=vm(r.installPath)?Yt(r.installPath):Yt(o,r.installPath),s=ov(e,Gl(Yt(t),Yt(n))),i={...r,installPath:Gl(Yt(o),a)};return jl(s,i)},rB=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":Yl(t,a=>{let s=ct(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},oB=async(e,t,n,r,o)=>{let a=ne(t,"cowork_plugins"),s=ne(a,"installed_plugins.json"),i=ne(t,"cowork_account_settings.json");for(let c of e){let l=ne(a,c.relativeInstallPath);if(!Jk(a,l)){n.invalid+=1;continue}let d=await rv(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 Yl(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=nB(c.entry,la(c.settingsFile),c.packageDir,g,t),p=!u;return}let b=ov(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 rB(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},aB=async(e,t,n)=>{let r=ne(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await Yl(r,c=>{let l=ct(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=jl(l[o],a)?"present":"conflict";return}return{...c,mcpServers:{...l,[o]:a}}})==="failed"?n.failed+=1:s.value==="present"?n.alreadyPresent+=1:s.value==="conflict"?n.conflicts+=1:n.migrated+=1}},av=async(e,t,n={})=>{let r=await qk(e),o=km("skill"),a=km("plugin"),s=km("local-mcp"),i=[],c=[],l=jk(r.skills,n.account,n.allAccounts),d=jk(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 QM(t);p.state==="found"?await tB(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 eB(t);p.state==="found"?await oB(d,p.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):p.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await aB(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 cB=async e=>{try{return await vt.access(e),!0}catch{return!1}},sv=448,lB=384,cv={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},dB=["code","cowork"],Rm=(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.",Em=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),lv=async e=>{let t;try{t=(await vt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&Xo(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()&&Xo(a.name)).map(a=>a.name);for(let a of o)n.push(Jt(e,r,a))}catch{}return n},uB=async e=>{try{return(await vt.readdir(e)).filter(t=>t.startsWith($n)&&t.endsWith(".json")).map(t=>t.slice($n.length,-5)).filter(Xo)}catch{return[]}},pB=async(e,t)=>{let n=await lv(Jt(e,cv[t])),r=[];for(let o of n){let a=await uB(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(iB).slice(-2)[0]})}return r},fB=async(e,t)=>{if(t==="cowork"){let r=await Il(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await lv(Jt(e,cv.code));return n.length===1?{dir:n[0]}:{missing:n.length===0?"no-account":"ambiguous"}},mB=async(e,t)=>{let n=`${t}.anyray-tmp-${process.pid}`;await vt.copyFile(e,n),await vt.chmod(n,lB),await vt.rename(n,t)},hB=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||!Xo(o)?!1:(await vt.access(Jt(t,".claude","projects",Kf(r),`${o}.jsonl`)),!0)}catch{return!1}},yB=async(e,t,n,r)=>{let o=Em(e),a=await jf(n);for(let s of t)await gB(e,s,n,r,a,o);return o},gB=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${$n}${s}.json`,c=Jt(t.dir,i);try{if(e==="code"){if(!await hB(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=Jt(t.dir,`${$n}${s}`),d=Jt(n,`${$n}${s}`),u=await vt.readdir(l);await vt.mkdir(d,{mode:sv});for(let p of u)await vt.cp(Jt(l,p),Jt(d,p),{recursive:!0,force:!1,errorOnExist:!0});await vt.chmod(d,sv)}await mB(c,Jt(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},iv=(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
|
+
`)}},xm=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),dv=async e=>{let t=[];for(let n of dB)t.push({lane:n,sources:await pB(e,n)});return t},uv=async(e={})=>{let t=(e.firstPartyRoot??(()=>Hs()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([dv(t),Im(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=xm(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??sB)(),n=(e.firstPartyRoot??(()=>Hs()))(),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([dv(n),Im(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=xm(o);for(let w of m)h.add(w);if(h.size>1)return iv(o,e.command??"anyray-connect desktop --migrate",`"${f}" matches ${h.size} accounts`,m);s=[...h]}else if(!e.allAccounts){let f=xm(o);for(let m of a.accounts)f.add(m);if(f.size>1)return iv(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 cB(r),l=await av(n,r,{account:e.account,allAccounts:e.allAccounts,allowedAccounts:s});if(l.sourceChanged)return{ok:!1,kind:"account-ambiguous",reason:"the previous Claude Desktop profile changed during migration and now holds local data for another account",remedy:`Re-run \`${i}\` so the account choice is made from a fresh snapshot.`};let d=[],u=[];for(let{lane:f,sources:m}of o){if(m.length===0){d.push(Em(f));continue}let h=await fB(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(Em(f));continue}d.push(await yB(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:Rm(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 wB=e=>[Ve(e)],pv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...wB(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 fv="1.21459.0",kB=CB(bB),vB=async e=>{try{let{stdout:t}=await kB("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},SB=async e=>{try{return await AB(e)}catch{return}},mv="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",IB=["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?(hv??=yv({}),hv):yv(e),hv,yv=async e=>{let t=(e.home??oi)(),n=["/Applications/Claude.app",bn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??vB,o=e.readClaudeAppBundle??SB;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} ${mv}`}),c=vl(s,fv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${fv} or newer.`);let l=await o(bn(a,"Contents","Resources","app.asar"));return l?qC.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. ${mv}`}},Xl="anyray",bv="--anyray-owner=claude-desktop-v1",zl=(e={})=>{let t=(e.platform??Ar)(),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")},Dm=(e={})=>bn((e.home??oi)(),"Library","Application Support","Claude","claude_desktop_config.json"),Av=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,bv]}},ao=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Cv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},EB=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),xB=e=>{if(!ao(e)||!Cv(e,["command","args"]))return!1;let t=Av();return e.command===t.command&&EB(e.args,t.args)},RB=e=>ao(e)&&Array.isArray(e.args)&&e.args.at(-1)===bv,OB=e=>{if(!ao(e)||!Cv(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)===zn&&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))},TB=e=>e===void 0?"absent":xB(e)?"exact":RB(e)||OB(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 M(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)?.[Xl];return{path:e,fileExisted:t,json:n,entry:o,ownership:TB(o)}},ql=e=>{if(e.ownership==="foreign")throw new Me(`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.`)},kv=(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},Tm=async(e,t)=>{if(Om(e.entry,t))return;let n=await so(e.path);if(!Om(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 Mn(e.path,kv(n.json,t)),{reading:e,afterEntry:t}},_m=async e=>{let t=await so(e.reading.path);if(!Om(t.entry,e.afterEntry))throw new Me(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=kv(t.json,e.reading.entry);await Mn(e.reading.path,n)},_B=async e=>{if(!te())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(zl(e));ql(t);let n=Dm(e),r=(e.platform??Ar)()==="darwin"&&n!==t.path?await so(n):void 0;return r&&ql(r),{active:t,...r?{legacy:r}:{}}},gv=async e=>{let t=await so(zl(e));ql(t);let n=Dm(e),r=(e.platform??Ar)()==="darwin"&&n!==t.path?await so(n):void 0;return r&&ql(r),{active:t,...r?{legacy:r}:{}}},PB=async e=>{let t=[];try{let n=await Tm(e.active,Av());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Tm(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await _m(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 _m(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)}}},DB=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Tm(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await _m(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)},wv=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)."]},LB={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},Ql="claude-desktop",Pm="migrate",vv=new Set(["app-running","store-missing"]),NB={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},$B={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"}},MB="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",Sv=e=>{let t=(e.platform??Ar)(),n=e.home??oi;return{home:n,appRunning:e.appRunning??ca(t),firstPartyRoot:()=>Hs({home:n,runtimePlatform:t}),thirdPartyRoot:()=>Qr({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},Iv=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=NB[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.`:"")},Ev=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=$B[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=Sv(e),r=await(e.pendingDesktopMigrationCount??uv)(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=Iv(a.lanes),l=Ev(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,Pm);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(!vv.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,Pm);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."]}},BB=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await sr(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."]}},FB=e=>pv({id:Ql,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??Ar)(),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:",...wv(t)]:["Claude desktop org/API lane:",...wv(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`."]}),WB=(e={})=>{let t=FB(e),n=()=>(e.platform??Ar)()==="darwin",r=()=>(e.platform??Ar)()==="win32",o=(s,i)=>n()?sk(s,i,e):Bk(s,s.clientKey??"",i,e),a=s=>n()?ik(s,e):Fk(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??ca((e.platform??Ar)()))(),quitTarget:LB,needsTarget:()=>!1,async complete(s){if(s!==Pm)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)(Sv(e));if(i.ok){let c=Iv(i.lanes),l=Ev(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 vv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?lk(s,e):r()?Hk(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:[nm(f),...await ri(e,i)]}}if(r()){let p;try{p=await br(e.runReg??Fn)}catch{return{status:"manual",manualAudience:"admin",messages:[MB,...await ri(e,i)]}}if(p)return{status:"manual",manualAudience:"admin",messages:[bm(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 _B(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 PB(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()?IB:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=zl(e),c=await BB(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 gv(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()?$t(e):void 0;if(!(h!==void 0&&p.changedFiles?.includes(h)===!0&&!await x(h)))return l(p)}let f;try{f=await DB(await gv(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 oe(i);let m=Dm(e);return n()&&m!==i&&await oe(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(!te())return{registered:!1,command:null,reason:"ephemeral-runtime"};try{let s=await so(zl(e));return s.ownership!=="exact"||!ao(s.entry)?{registered:!1,command:null,reason:s.fileExisted?s.ownership==="absent"?"absent":s.ownership==="stale-owned"?"stale":"foreign":"no-config"}:{registered:!0,command:typeof s.entry.command=="string"?s.entry.command:null}}catch{return{registered:!1,command:null,reason:"unreadable"}}},async pointsAt(s){return n()?(await da(e)).supported?om(s,e):!1:r()?Uk(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await da(e)).supported)return["unknown"];let s=await ck(e);return s?[s]:["unknown"]}if(r())return await x($t(e))?await br(e.runReg??Fn)?["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 da(e)).supported}return r()&&await x($t(e))?!await br(e.runReg??Fn):!1}catch{return!1}}}},xv=WB();import{homedir as mF}from"node:os";import{join as hF}from"node:path";import{rm as cd}from"node:fs/promises";import{constants as Rv,accessSync as UB,statSync as HB}from"node:fs";import{platform as Lm}from"node:os";import{delimiter as GB,posix as VB,resolve as KB,win32 as jB}from"node:path";var ZB="0.59.0",YB="1.1.4",Wn="Anyray \xB7 Claude",Un="Anyray \xB7 Codex",ed="__anyray-acp-agent",Ov=(e,t,n)=>{let{command:r,args:o}=en([ed,e,t,n]);return{command:r,args:o,env:{}}},td=(e=Lm())=>e==="win32"?"npx.cmd":"npx",nd=(e=process.env.PATH,t=Lm())=>{if(!e)return;let n=td(t);for(let r of e.split(GB)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=KB(o,n);try{if(!HB(a).isFile())continue;return UB(a,t==="win32"?Rv.F_OK:Rv.X_OK),a}catch{}}},rd=(e,t=Lm())=>{let n=t==="win32"?jB:VB;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==td(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},JB="https://chatgpt.com/backend-api/codex",XB="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",Tv="ANYRAY_ACP_CODEX_AUTHORIZATION",_v="ANYRAY_ACP_CODEX_CLIENT_KEY",Pv="ANYRAY_ACP_CODEX_METADATA",Dv=e=>ue({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),zB=(e,t={})=>{let n=ee(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":JB,"x-anyray-forward-headers":XB}:{},o=n?{...e.clientKey?{"x-anyray-api-key":_v}:{}}:{Authorization:Tv};return Dv(e)&&(o["x-anyray-metadata"]=Pv),{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}}}:{}}},qB=e=>{let t=ee(e,"openai"),n=Dv(e);return{...t?e.clientKey?{[_v]:e.clientKey}:{}:{[Tv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[Pv]:n}:{}}},Lv=(e,t=td(),n={})=>({[Wn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${ZB}`],env:tn(e).env},[Un]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${YB}`],env:{CODEX_CONFIG:JSON.stringify(zB(e,n)),...qB(e)}}}),ai=(e=td(),t="jetbrains")=>({[Wn]:Ov("claude",e,t),[Un]:Ov("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 QB}from"node:zlib";import{open as eF,readFile as Fm,readdir as id}from"node:fs/promises";import{dirname as Nv,join as fe}from"node:path";import{homedir as Fv,platform as Wm}from"node:os";var ad="2025.3.2",ua="253.30387.147",si="com.intellij.ml.llm",Nm=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),tF=1e4,nF=256*1024*1024,rF=16*1024*1024,$m=1024*1024,Mm=22,oF=Mm+65535,Bm=vl,aF=()=>{let e=Fv(),t=fe(e,".cache","JetBrains","RemoteDev");switch(Wm()){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"}]}},sF=()=>Wm()==="linux"?fe(Fv(),".local","share","JetBrains"):Ve("JetBrains"),iF=()=>Wm()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),cF=async(e,t=tF)=>{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)]},lF=e=>{let t=Nv(e);return t.endsWith(`${fe("Contents","Resources")}`)?Nv(t):t},dF=async e=>{try{let t=JSON.parse(await Fm(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:lF(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},uF=async(e,t)=>{let n;try{n=await eF(e,"r");let{size:r}=await n.stat();if(r<Mm||r>nF)return;let o=Math.min(r,oF),a=await sd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-Mm;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>rF||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),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>$m||f>$m)return;let k=await sd(n,30,y);if(!k||k.readUInt32LE(0)!==67324752)return;let C=k.readUInt16LE(26),S=k.readUInt16LE(28),I=await sd(n,p,y+30+C+S);return I?u===0?I.toString("utf8"):u===8?QB(I,{maxOutputLength:$m}).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}},pF=async(e,t)=>{let n=fe(e,"META-INF","plugin.xml");if(await x(n))try{let o=$v(await Fm(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 uF(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}},Mv=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=Nm.has(o.name.toLowerCase()),i=Nm.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=Nm.has(o.name.toLowerCase());if(!a){let i=fe(e,o.name,"META-INF","plugin.xml");if(!await x(i))continue}let s=await pF(fe(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},fF=async e=>{try{return(await Fm(fe(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(si)}catch{return!1}},Bv=e=>e.reduce((t,n)=>t?(Bm(n,t)??-1)>0?n:t:n,void 0),Wv=async(e={})=>{let t=e.configRoot??Ve("JetBrains"),n=e.userPluginsRoot??sF(),r=await cF(e.productRoots?e.productRoots.map(m=>({path:m,layout:"recursive"})):aF(),e.scanBudget),o=(await Promise.all(r.map(m=>dF(m)))).filter(m=>m!==void 0),a=o.length>0||await x(t);if(e.wsl??iF())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=>(Bm(m.version,ad)??-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 Mv(g);if(b.present){y=b;break}}if(y??=await Mv(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 fF(h)){c=!0;continue}if(!((Bm(y.descriptor.version,ua)??-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=Bv(o.map(m=>m.version)),p=Bv(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 yF=[Wn,Un],Um=()=>hF(mF(),".jetbrains","acp.json"),co=()=>`${Um()}.anyray-state`,gF=(e,t,n="npx")=>{let r=io(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,ai(n,"jetbrains")),{...e,agent_servers:r}},wF=(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 yF)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}},bF=(e=Wv)=>({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=Um(),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 M(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:gF(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=Um(),r=async()=>{if(!await x(n))return t.dryRun||(await oe(n),await cd(co(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await M(n)}catch{return t.dryRun||(await oe(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 M(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 M(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await Dr(n);let l=wF(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 oe(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():ji(n,co(),r)}}),Uv=bF();import{homedir as dd}from"node:os";import{join as ud}from"node:path";import{rm as Hm}from"node:fs/promises";var Gm="1.0.0",pd=["anyray-claude-acp","anyray-codex-acp"],AF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],Vm=()=>ud(dd(),".windsurf","acp","registry.json"),Km=()=>ud(dd(),".windsurf-next","acp","registry.json"),pa=e=>`${e}.anyray-state`,Hv=e=>({binary:Object.fromEntries(AF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),Vv=(e="npx")=>{let t=ai(e,"windsurf");return[{id:pd[0],name:Wn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Hv(t[Wn])},{id:pd[1],name:Un,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:Hv(t[Un])}]},ld=e=>!Array.isArray(e)||e.some(t=>!io(t)||typeof t.id!="string")?null:e,CF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==Gm||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:Gm,agents:[...n.filter(o=>!r.has(o.id)),...Vv(t)],extensions:e.extensions??[]}},kF=(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===Gm&&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}},Gv=async()=>{let e=[];return(await x(Km())||await x(ud(dd(),".windsurf-next")))&&e.push(Km()),(await x(Vm())||await x(ud(dd(),".windsurf"))||await x(Ve("Devin"))||await x(Ve("Windsurf")))&&e.push(Vm()),e},Kv={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await Gv();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await Gv();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 M(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=CF(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=Vv(r);await Zi({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=[Vm(),Km()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await x(a)){e.dryRun||(await oe(a),await Hm(pa(a),{force:!0}).catch(()=>{}));return}let i;try{i=await M(a)}catch{n.push(`Could not parse ${a}; remove the anyray-* ACP agents manually.`),o=!0;return}let c=[],l=!1,d=!1;try{let f=await M(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 M(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 Dr(a);let p=kF(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 oe(a),await Hm(pa(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await ji(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=[er,$w,ks,FA,pC,SC,_C,Uv,xv,Kv,Vw],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 jm=5e3,jv=3e4,vF=1440*60*1e3,SF=e=>new Promise(t=>setTimeout(t,e)),IF=async(e=D,t=fn)=>(await Be(e,t))?.target,EF=e=>mt(e)?.quitGated,Zv=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??EF,o=t.readPending??Hc,a=t.clearPending??_p,s=t.targetFromProfile??IF,i=t.sleep??SF,c=t.now??Date.now,l=t.maxWaitMs??vF;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),p=c(),f=jm;for(;;){let m=await o(n);if(!m||c()-p>l)return 0;if(d.isRunning()){await i(f),f=Math.min(jv,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=jm;continue}if((await u(m.op,h,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(f),f=Math.min(jv,f*2);continue}if(await a(n,m)!=="superseded")return 0;await i(f),f=jm}}catch{return 0}};import{writeFileSync as mW}from"node:fs";import{chmod as oh,stat as hW}from"node:fs/promises";import{platform as SS}from"node:os";import{dirname as IS,isAbsolute as yW}from"node:path";var xF="https://app.anyray.ai",RF=new Set(["localhost","::1","[::1]"]),OF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,TF=e=>RF.has(e)||OF.test(e),Zm=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&TF(t.hostname)},_F=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||!Zm(e)?xF:_F(e)};import{createHash as VF,generateKeyPairSync as KF,randomBytes as Xm}from"node:crypto";import{createPrivateKey as PF,sign as DF}from"node:crypto";var Cr=async(e,t)=>{let n=PF(t);return DF(null,new TextEncoder().encode(e),n).toString("base64url")};var LF=["HTTPS_PROXY","https_proxy"],Yv=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"]),Jv=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Xv=new Set(["ENOTFOUND","EAI_AGAIN"]),zv=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),qv=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),NF=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 $F(e)},$F=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...Yv,...Jv,...Xv,...zv,...qv])if(t.includes(n))return n}},MF=e=>e?.name==="AbortError"||e?.name==="TimeoutError",BF=e=>LF.filter(t=>(e[t]??"").trim()!==""),FF=(e,t=process.env)=>{let n=NF(e),r=BF(t);return{kind:n&&Yv.has(n)?"tls-unknown-issuer":n&&Jv.has(n)?"tls-invalid-cert":n&&Xv.has(n)?"dns":MF(e)||n&&qv.has(n)?"timeout":n&&zv.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},WF=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)=>WF(FF(e,t));var UF="enl_",Qv="enp_",eS=e=>e.startsWith(UF)||e.startsWith(Qv),Ym=e=>e.startsWith(Qv),HF=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],Jm=e=>HF.find(t=>e.startsWith(t.prefix)),tS=/^\/enroll\/([^/]+)\/?$/,nS=/^\/i\/([^/]+)\/?$/,rS=e=>{let t=e.match(tS);if(t)return Jm(t[1])?void 0:t[1];let n=e.match(nS);return n&&eS(n[1])?n[1]:void 0},GF=1e4,fd=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=rS(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!Jm(t))return{cpOrigin:Hn(),token:t}},oS=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(tS)??o.pathname.match(nS);if(!a)return;n=a[1]}catch{}let r=Jm(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:rS(n.pathname)!==void 0}catch{return eS(t)}},fa=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},ii=e=>typeof e=="string"&&e.trim()?e.trim():void 0,aS=async(e,t={})=>{let n=t.timeoutMs??GF,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 fa(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 zm=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(",")}}`,sS="stable-key-heartbeat-v1",iS="key-heartbeat",jF=["reapply_config","remint","revert"],qm=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var cS=e=>VF("sha256").update(e).digest("hex"),Ze=e=>typeof e=="string"&&e.trim()?e.trim():void 0,ZF=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],lS={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"},YF=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${lS[e]}. Ask your IT admin.`,JF=e=>typeof e=="string"&&e in lS,Qm=async e=>{try{let t=await e.json(),n=Ze(t?.message),r=Ze(t?.error),o=JF(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:YF(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},XF=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}},dS=e=>e instanceof fa||e instanceof lt&&e.policyCode==="sso_required",ma=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}},eh=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`)}},md=()=>{let{publicKey:e,privateKey:t}=KF("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??zm,a=`${e}/connect/verify`,s=Ze(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:Xm(16).toString("hex"),...qm(t,r.machineUuid)},c=await eh(i,n,"verification",r.signer??Cr),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=Ze(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=Ze(f.user);if(!h)throw new Error("developer verification failed: the gateway response is missing the user");let w=zF(f.directive),y=ZF(f.capabilities);return{key:m,user:h,team:Ze(f.team),expiresAt:Ze(f.expiresAt),...y.length>0?{capabilities:y}:{},...w?{directive:w}:{}}},uS=async(e,t,n,r,o={})=>{let a=o.timeoutMs??zm,s=`${e}/connect/key/heartbeat`,i=Ze(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:Xm(16).toString("hex"),purpose:iS,...qm(n,o.machineUuid)},l=await eh(c,r,"heartbeat",o.signer??Cr),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 ma(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=Ze(f.expiresAt);if(!m||!Number.isFinite(Date.parse(m))||f.credentialMode!==sS||f.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:m,credentialMode:sS}},pS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??zm,i=`${e.replace(/\/$/,"")}/connect/machine`,c=Ze(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:Xm(16).toString("hex"),purpose:iS,...qm(n,o)},d=await eh(l,r,"heartbeat",a.signer??Cr),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)}},zF=e=>{if(e===null||typeof e!="object")return null;let t=e,n=Ze(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!jF.includes(r)?null:{id:n,kind:r}},qF=1e4,QF=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!Ze(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!Ze(r.deploymentId)&&!!Ze(r.user)&&!!Ze(r.devPublicKey)&&!!Ze(r.issuedAt)&&!!Ze(r.expiresAt)},eW=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??qF,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 XF(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new fa(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(!QF(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},fS=(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())},mS=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=md();return{cert:await eW(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 th=1e4,tW=900*1e3,yS="tnt_",nW=/^\/sso\/([^/]+)\/?$/,rW=/^\/i\/([^/]+)\/?$/,oW=e=>{let t=e.match(nW);if(t)return t[1];let n=e.match(rW);return n?.[1].startsWith(yS)?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=oW(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(yS))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}},Mt=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},nh=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)}},aW=e=>new Promise(t=>setTimeout(t,e)),hd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??md)(),a;try{a=await nh(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},th,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??tW,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}`),sW(p.verificationUriComplete,e.cpOrigin)&&e.open?.(p.verificationUriComplete),p},sW=(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??aW,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 nh(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},th,o)}catch(c){throw new Mt("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 Mt("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Mt("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Mt("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var hS="sdc_",gS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(hS))return{cpOrigin:Hn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!Zm(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(hS)))return{cpOrigin:n.origin,claim:r}},wS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??md)(),o;try{o=await nh(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},th,t)}catch(s){throw new Mt("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 Mt("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Mt("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Mt("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 iW}from"node:fs/promises";import{isAbsolute as cW,posix as bS,win32 as rh}from"node:path";var li=(e=process.platform,t=process.env)=>e==="darwin"?bS.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?rh.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):bS.join("/etc","anyray","bootstrap.json"),lW=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),AS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(cW(e)||rh.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),dW=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}},kr=async(e=li())=>{try{let t=await iW(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!lW(n)||n.v!==1||typeof n.sso!="string")return;let r=St(n.sso);if(!r)return;let o=dW(n.gateway)?n.gateway:void 0,a=AS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},CS=(e,t,n)=>{let r=St(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!AS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&rh.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 ha=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,gd=ha(process.stdout,process.env),kS=ha(process.stderr,process.env),ya=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,V=e=>ya("1",e,gd),v=e=>ya("2",e,gd),uW=e=>ya("32",e,gd),pW=e=>ya("33",e,kS),fW=e=>ya("31",e,kS),et=e=>ya("36",e,gd),A=e=>console.log(e),H=e=>console.log(`
|
|
284
|
+
${V(e)}`),$=e=>console.log(v(e)),B=e=>console.log(`${uW("\u2713")} ${e}`),P=e=>console.error(`${pW("!")} ${e}`),R=e=>console.error(`${fW("\u2717")} ${e}`);var ah=`${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
|
-
`)},bd=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}
|
|
369
|
-
`),
|
|
370
|
-
`),Ye(v("# acp.json for ~/.jetbrains/acp.json (per user).")),Ye(v(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ye(v("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ye(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},
|
|
371
|
-
`),Ye(v(`# managed-settings.json for ${Tt()}`)),n)Ye(v("# Deferred SSO: hooks only; no credential or managed env block.")),Ye(v(`# Push the binary to ${n.binaryPath} before this file.`)),Ye(v("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of
|
|
372
|
-
`+
|
|
373
|
-
`+
|
|
367
|
+
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,vS=["claude-code","jetbrains","shell","bootstrap"],gW=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(!vS.includes(a))throw new Error(`unknown --tool ${a} (expected ${vS.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 wd(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(es(t.binaryPath,[ze]),{matcher:"*"})],UserPromptSubmit:[kn(es(t.binaryPath,o),{timeout:30}),kn(es(t.binaryPath,[Jn]))],SessionStart:[kn(es(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 wW=(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 Mr)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,ju(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},bW=e=>{let t=e.env,n=ju(e);if(t){for(let r of Mr)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},ES=async e=>{let t=async n=>{try{return(await hW(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(IS(e))!==void 0}},xS=async(e,t)=>(t.dirExisted||await oh(IS(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await oh(e,420),{mode:420,keptRestricted:!1}):(await oh(e,t.mode),{mode:t.mode,keptRestricted:!0})),RS=(e,t)=>{t.keptRestricted&&(P(`${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.")))},OS=()=>process.getuid?.()===0,Ye=e=>{process.stderr.write(`${e}
|
|
368
|
+
`)},bd=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}mW(e.out,t,"utf8"),Ye(v(`# Wrote ${e.out}`))},sh=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??""}),ih=e=>yW(e)||/^[A-Za-z]:[\\/]/.test(e),TS=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&&!te())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(!ih(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}},_S=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)"}`],ch=(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:{[Wn]:{command:e,args:[ed,"claude",t,"jetbrains"],env:{}},[Un]:{command:e,args:[ed,"codex",t,"jetbrains"],env:{}}}}),CW=e=>["# Managed by anyray-connect (fleet). Routes shell/SDK traffic through the Anyray gateway.","# Per-user keys come from enrollment (`anyray-connect --enroll/--sso`); never add a key here.",`export OPENAI_BASE_URL=${ve(e.openaiBaseUrl)}`,`export ANTHROPIC_BASE_URL=${ve(e.anthropicBaseUrl)}`,""].join(`
|
|
369
|
+
`),kW=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(!ih(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(!rd(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return bd(e,`${JSON.stringify(AW(e.bin,e.npx),null,2)}
|
|
370
|
+
`),Ye(v("# acp.json for ~/.jetbrains/acp.json (per user).")),Ye(v(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ye(v("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ye(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},vW=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&&!ih(e.bin))throw new Error("--bin must be an absolute fleet-stable path");return bd(e,CS(e.sso,e.gateway,e.bin)),Ye(v(`# Fleet bootstrap for ${li("linux")}`)),Ye(v(`# macOS: ${li("darwin")}`)),Ye(v(`# Windows: ${li("win32",{ProgramData:"C:\\ProgramData"})}`)),Ye(v("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},SW=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=sh(e);return bd(e,CW(t)),Ye(v("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),ch(t,Ye),0},IW=e=>{let t=sh(e),n=TS(e),r=n?wd(t,n):wd(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(bd(e,`${JSON.stringify(r,null,2)}
|
|
371
|
+
`),Ye(v(`# managed-settings.json for ${Tt()}`)),n)Ye(v("# Deferred SSO: hooks only; no credential or managed env block.")),Ye(v(`# Push the binary to ${n.binaryPath} before this file.`)),Ye(v("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of _S(t))Ye(v(`# ${o}`));ch(t,Ye)}return 0},EW=async e=>{let t=SS();if(t!=="darwin"&&t!=="linux")return R("`managed --write` is supported on macOS and Linux only. Use `managed --print` and deploy the JSON via your MDM."),1;if(!OS())return R("Refusing to write the system managed-settings.json without root \u2014 re-run with `sudo` (it lives under a system-owned path)."),A(v(" For MDM packaging, use `managed --print` instead and push the file with Jamf / Intune / Ansible.")),1;let n=sh(e),r=TS(e);r||ch(n,u=>P(u.replace(/^!\s*/,"")));let o=Tt(t),a=await M(o),s=r?wd(n,r):wd(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=wW(a,s),l=await ES(o);await Y(o,c);let d=await xS(o,l);B(`Wrote ${o}`),RS(o,d);for(let{name:u,cloud:p}of i)P(`${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 _S(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},xW=async()=>{let e=SS();if(e!=="darwin"&&e!=="linux")return R("`managed --revert` is supported on macOS and Linux only (remove the deployed file via your MDM elsewhere)."),1;if(!OS())return R("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=Tt(e);if(!await x(t))return A(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=await M(t);if(!bW(n))return A(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await ES(t);await Y(t,n);let o=await xS(t,r);return B(`Removed Anyray-owned keys from ${t} (other keys left intact).`),RS(t,o),0},PS=async e=>{let t;try{t=gW(e)}catch(n){return R(n instanceof Error?n.message:"invalid managed arguments"),A(`
|
|
372
|
+
`+ah),1}if(t.help||e.length===0&&!t.mode)return A(ah),0;if(!t.mode)return R("Specify a mode: --print, --write, or --revert."),A(`
|
|
373
|
+
`+ah),1;if(t.out!==void 0&&t.mode!=="print")return R(`--out is valid with --print only, not --${t.mode}.`),1;if(t.scrubDirectMode){let n=t.sso!==void 0?"--sso emits a hooks-only file with no env block":(t.tool??"claude-code")!=="claude-code"?`--tool ${t.tool} does not write Claude Code env`:t.mode==="revert"?"--revert already removes the pin (and leaves a truthy value alone)":void 0;if(n)return R(`--scrub-direct-mode cannot be combined with this mode: ${n}.`),1}try{let n=t.tool??"claude-code";return n!=="claude-code"?t.mode!=="print"?(R(`--tool ${n} supports --print only; deploy the artifact with your MDM.`),1):n==="jetbrains"?kW(t):n==="bootstrap"?vW(t):SW(t):t.mode==="print"?IW(t):t.mode==="write"?await EW(t):await xW()}catch(n){return R(n instanceof Error?n.message:"managed settings failed"),1}};import{spawn as LU}from"node:child_process";import{homedir as NU}from"node:os";import{join as gI}from"node:path";import{readFile as $U,writeFile as wI,chmod as MU,stat as BU,unlink as iI}from"node:fs/promises";var RW=["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},ga=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},lh=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(RW.map(o=>[o,"unreadable"]))})}return n},DS=e=>e.filter(t=>!t.integrationStatus),OW=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},Bt=async(e,t)=>{let n=[];for(let r of e)try{let o=await r.apply(t,{dryRun:!1});n.push({id:r.id,title:r.title,status:o.status,...o.errorClass?{errorClass:o.errorClass}:{}})}catch(o){let a=OW(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 _W,writeFile as PW}from"node:fs/promises";import{join as NS}from"node:path";import{z as De}from"zod";var wa="required",TW=e=>e==="subscription"?"subscription":"placeholder",LS=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?TW(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}:{}}},Ad=(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]??wa,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 DW=1e4,LW=1,NW=De.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),$W=De.object({id:NW,name:De.string().min(1),version:De.string().min(1),body:De.string()}),MW=De.object({version:De.literal(LW).optional(),skills:De.array($W),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()}),ba=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="TeamPolicyFetchError"}},dh=e=>e instanceof ba&&e.kind==="auth",BW=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",uh=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",Aa=async(e,t,n={})=>{let r=n.timeoutMs??DW,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 ba("unavailable",`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new ba(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 ba("malformed","team policy fetch failed: the gateway returned a malformed response")}return MW.parse(c)},$S=/^[a-z0-9][a-z0-9-]{0,31}$/,MS=64,FW=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>$S.test(o)).slice(0,MS).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>$S.test(o)).slice(0,MS).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]??wa)==="locked":!1},Ca=async(e,t={})=>{let n=t.loadProfile??D,r=t.saveProfile??ae,o=t.targetFromProfile??Be,a=t.adapters??le,s=t.repairTools??Bt,i=t.recordManaged??jn,c=await n(),l={...c},d=LS(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=Ad(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 O=new Set(h);I=[];for(let F of a)if(O.has(F.id))try{(await F.detect()).installed&&I.push(F)}catch{}}else I=await ga(h,S.target.origin,a);let E=new Set(w),T=[];for(let O of a)if(E.has(O.id))try{(await O.detect()).installed&&T.push(O)}catch{}if(y=I.length+T.length,y>0){let O=await s([...I,...T],S.target);g=O.filter(po).length;let F=O.filter(q=>E.has(q.id));if(b=F.filter(po).length,F.length>0)try{await i(F,!1)}catch{}}}}let k=FW(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}},BS=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!BW(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=NS(d,i.id),p=NS(u,"SKILL.md");await _W(u,{recursive:!0}),await PW(p,WW(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}},WW=e=>e.endsWith(`
|
|
374
374
|
`)?e:`${e}
|
|
375
|
-
`;import{randomBytes as $W}from"node:crypto";var MW=1e4,BW="machine:",MS=e=>e.startsWith(BW),FW="cert-renew",WW=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)},BS=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:$W(16).toString("hex"),purpose:FW},c;try{c=await(n.signer??Ar)(lo(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),MW),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 WW(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 UW=["claude","codex","cursor","opencode"],HW=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],GW=new Set(["missing_key","key_expired"]);var VW=600*1e3,KW=600*1e3,FS=1440*60*1e3,jW=1440*60*1e3,ZW=10080*60*1e3,YW=3600*1e3,JW=720*60*1e3,XW=e=>Math.min(JW,YW*2**Math.max(0,e-1)),ui=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ka=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,WS=e=>typeof e=="string"&&HW.includes(e),An=e=>{if(!ui(e))return{};let t={};if(ka(e.watchSince)&&(t.watchSince=e.watchSince),ui(e.invoked)){let n={};for(let r of UW){let o=e.invoked[r];ka(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return ui(e.authFailure)&&ka(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...WS(e.authFailure.code)?{code:e.authFailure.code}:{}}),ui(e.repair)&&ka(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,...ka(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Cd=e=>{try{let n=JSON.parse(e);if(ui(n)&&WS(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&&GW.has(e),mh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=VW},US=(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>=KW},HS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),GS=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,VS=(e,t,n)=>{if(n==="repair_failed"||n==="unverified")return{...e,repair:{at:t,outcome:n,failures:(e.repair?.failures??0)+1}};let{authFailure:r,...o}=e;return n==="repaired"?{...o,repair:{at:t,outcome:n}}:o},KS=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>FS||!fh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<XW(r.failures??1))},kd=e=>{let t=Object.values(e?.invoked??{}).filter(ka);return t.length>0?Math.max(...t):null},yh=(e,t)=>{if(kd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=ZW},jS=(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<=FS)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var gh="x-anyray-retrieve-probe",vd=8e3,zW=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",ZS=(e,t)=>{let n=Vt(e);return t?.probe&&(n[gh]="1"),n},va=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:ZS(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=zW(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:ZS(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 qW=5e3,QW=2048,eU=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}"`))},Sa=async(e={})=>{let t=e.readTarget??nt,n=e.fetch??fetch,r=e.timeoutMs??qW,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,QW);if(!eU(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)}},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 rU}from"node:crypto";import{execSync as bh}from"node:child_process";import{hostname as tU}from"node:os";var nU=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""}},Id=(e={platform:process.platform,read:()=>nU(process.platform),hostname:tU})=>e.read().trim()||e.hostname().trim();var Ft=(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??(()=>Id());try{return r().trim().toLowerCase()}catch{return""}}return""};var oU=500,YS=2e3,aU=2e3,sU=250,JS=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),oU);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)}},iU=e=>{let t=e.headers?.get?.("retry-after");if(!t)return;let n=Number(t.trim());return Number.isFinite(n)&&n>=0?n*1e3:void 0},cU=e=>new Promise(t=>setTimeout(t,e)),lU=async(e,t,n=cU)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),YS),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=iU(i)??sU,s>aU))return!1}finally{clearTimeout(a)}await n(s)}},dU=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:rU(16).toString("hex"),events:e},i;try{i=await(t.signer??Ar)(lo(s),o)}catch{return!1}return await(t.post??lU)(`${t.origin??Hn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},uU=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:YS,machineUuid:(n.machineUuid??Ft)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},XS=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 uU(n.origin,e),r)return;await dU(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 qS=128,QS=300*1e3,pU=["repaired","repair_failed","flapping","pending"],fU=["settings_not_writable","mcp_unreadable","mcp_not_writable","mcp_foreign","mcp_not_persisted","apply_unconfirmed","apply_threw"],eI=["rebroke_same_day","repeat_days"],tI=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),nI=e=>fi(e,ho),Ed=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},kr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,pi=e=>{if(!(!Array.isArray(e)||!e.every(nI)))return Gn(e)},mU=e=>{if(!mo(e))return;let t=pi(e.checks);if(!(!kr(e.since)||!fi(e.reason,eI)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},hU=e=>{if(!mo(e))return;let t={};Ed(e.day)&&(t.day=e.day),kr(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),Ed(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),kr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),mo(e.lastRepaired)){let i={};for(let c of ho){let l=e.lastRepaired[c];kr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=mU(e.flapping);return s&&(t.flapping=s),t},yU=e=>{if(!mo(e)||!Ed(e.day)||!kr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!tI.has(e.tool)||!nI(e.checkId)||!fi(e.status,pU)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!fi(e.errorClass,fU))return;t=e.errorClass}else if(e.status==="flapping"){if(!fi(e.errorClass,eI))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,...kr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},zS=e=>{if(!mo(e))return{};let t={};if(mo(e.adapters)){let n={};for(let r of tI){let o=hU(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(yU).filter(n=>n!==void 0).slice(-qS)),kr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),mo(e.report)&&Ed(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...kr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},gU=e=>new Date(e).toISOString().slice(0,10),wU=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,Gn=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}:{}}},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(-qS),nextSequence:r}},bU=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),AU=async e=>await Be(async()=>e)??null,CU=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)},rI=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:wU(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:Gn([...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:Gn([...i?.checks??[],...t])}}:{}},slowFlap:a}},kU=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 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=rI(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)},vU=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)),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:Gn([...l.brokenReportedChecks??[],...y]),flapping:{since:g?.since??a,reason:"rebroke_same_day",checks:Gn([...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:Gn([...d,...p]),confirmedChecks:u.filter(y=>!p.includes(y)),brokenReportedChecks:Gn([...l.brokenReportedChecks??[],...f]),...f.length>0?{flapping:{since:h?.since??a,reason:"rebroke_same_day",checks:Gn([...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),SU=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:Gn([...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=rI(l,d,o,a);c[e]=p.adapter;let f=n.status==="failed"?n.errorClass??"apply_threw":n.errorClass??"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)},IU=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>=QS));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(bU),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)},EU=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??sr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=jS(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},xU=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<QS?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await EU(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)},oI=async(e,t,n)=>{let r=n.now??Date.now,o=gU(r()),a=e.managedTools??[],s={...n,readState:async()=>zS(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(zS(l)),c)};try{let i=await(s.findIntegrations??ch)(a);await CU(i,o,s);let c=await(s.listPending??or)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await kU(i,l,o,r(),s);let d=await(s.resolveTarget??AU)(e),u=d?await(s.findDrifted??ga)(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??te)();if(d)for(let{adapter:y,checks:g}of f.values()){let b=h?ho.filter(O=>g[O]==="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(O=>[O,"unreadable"]))}let C=b.filter(O=>k[O]==="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 vU(y.id,C,S,l.has(y.id),o,r(),s);if(!I)continue;let[E]=await(s.repair??Bt)([y],d.target);if(!E)continue;m=!0;let T;E.status==="configured"&&y.integrationStatus&&(T=await y.integrationStatus().catch(()=>{})),await SU(y.id,I.checks,E,T,o,r(),s)}await IU(o,r(),t,s),i=await(s.findIntegrations??ch)(a);let w=await(s.listPending??or)().catch(()=>[]);return await xU(e,i,w,o,r(),t,s),m}catch{return!1}};var LU=14,NU=.35,$U=900*1e3,sI=360*60*1e3,MU=.2,BU=1800*1e3,iI=3600*1e3,FU=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),WU=300*1e3,UU=30*1e3,HU=900*1e3,GU=(e=0)=>Math.min(HU,UU*2**Math.max(0,e)),cI=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}},lI=1440*60*1e3,VU=300*1e3,KU=.25,jU=.5,dI=3600*1e3,ZU=720*60*60*1e3,YU=360*60*1e3,JU=1440*60*1e3,XU=()=>hI(TU(),".anyray"),Ch=()=>hI(XU(),"refresh-state.json"),kh=e=>process.env?.[e],gI=()=>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:LU)*JU},Od=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},wI=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),zU=10080*60*1e3,bI=(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)<=zU},Sh=e=>{let t=vh(),n=e?Od(e):void 0;if(!n)return t;let r=Math.max($U,Math.round(n*NU));return Math.min(t,r)},qU=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(sI,Math.max(BU,Math.round(e*MU))):sI},It=async()=>{try{let e=await _U(Ch(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Td=async e=>{try{let t=Ch(),n=`${t}.${process.pid}.tmp`;await yI(n,JSON.stringify(e),{mode:384}),await he(n,t),await PU(t,384).catch(()=>{})}catch{}},QU=3e4,eH=()=>`${Ch()}.lock`,uI=async e=>{try{return await yI(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??Td,s=eH(),i=!1;try{if(i=await uI(s),!i){if(await DU(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<QU)return t;await aI(s).catch(()=>{}),i=await uI(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await aI(s).catch(()=>{})}},Rd=async(e,t={})=>{await dt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Ia=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(()=>{})},tH=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(ZU,Math.max(dI,Math.round(o*jU))):dI},AI=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??ae,a=n.loadProfile??D,s=n.loadDevKey??$e,i=n.renew??BS,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(MS(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()>tH(e))return{outcome:"not-due",profile:e};if(!await dt(w=>r()-(w.lastCertRenewAt??0)<YU?{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 AI(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}},pI=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*KU):lI,r=Math.min(lI,n);return Math.min(r,VU*2**Math.max(0,e-1))},nH=()=>{let{command:e,args:t}=er(Jn);return{exe:e,args:t}},vr=async(e={})=>{if(gI())return;let t=e.now??Date.now,n=e.readState??It,r=e.writeState??Td,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=nH();OU(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await dt(s=>t()-(s.lastSpawnAt??0)<qU(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},rH=ph,oH=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 ga(n,r.target.origin),a=t?_S(o):o;return a.length===0?!1:(await Bt(a,r.target),!0)}catch{return!1}},aH=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}},sH=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??It,a=t.writeState??Td;return oI(e,Ae,{now:r,deadWatcherObserved:n,readHookLane:()=>_d({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})})},_d=async(e={})=>{let n=await(e.readState??It)().catch(()=>({}));return An(n.hookLane)},CI=async(e,t={})=>{try{let n=t.now??Date.now,r=await _d(t);if(!mh(r,e,n()))return;await dt(o=>{let a=An(o.hookLane);return mh(a,e,n())?{next:{...o,hookLane:US(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},kI=async(e,t={})=>{try{let n=t.now??Date.now,r=await _d(t);if(!hh(r,n()))return;await dt(o=>{let a=An(o.hookLane);return hh(a,n())?{next:{...o,hookLane:HS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},iH=async(e={})=>{try{let t=e.now??Date.now;if((await _d(e)).watchSince!==void 0)return;await dt(n=>{let r=An(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:GS(r,t())},result:void 0}},void 0,e)}catch{}},fI=async(e,t={})=>{try{let n=t.now??Date.now;await dt(r=>{let o=An(r.hookLane),a=VS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},vI=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??Ng)())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??Bt)(s,i.target),"repathed")}catch{return"skipped"}},SI=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??Bt)(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"}},cH=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await Aa(e.gateway,e.clientKey),n=await Ca(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},mI=async(e,t,n)=>{let o=await(t.reconcilePolicy??cH)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>oH(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},zt=async(e={})=>{if(gI())return"disabled";let t=e.now??Date.now,n=e.loadProfile??D,r=e.saveProfile??ae,o=e.loadDevKey??$e,a=e.readState??It,s=e.writeState??Td,i=e.remint??Xt,c=e.heartbeat??lS,l=e.detectSeat??fn,d=e.rewriteTools??rH,u=e.rewriteHookLaneTools??uh,p=e.probeHookLane??Sa,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 fI("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 fI(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=>sH(I,{now:t,readState:a,writeState:s},y)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await or().then(W=>W.some(Z=>!sr(Z.watcherPid))).catch(()=>!1),await iH({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??nb)();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 T=(e.resolveMachineUuid??Ft)()||void 0,O=await Ih(C,E,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=O.profile;let F=O.outcome==="renewed",q=C.enrolledCert;if(!q)return"not-enrolled";let de=Date.parse(C.clientKeyExpiresAt??""),ce=Number.isFinite(de)?de-t():0,K=await a(),ge=!C.clientKey||ce<=Sh(C);if(!m&&KS(An(K.hookLane),t())&&await f().catch(()=>"unreadable")!=="foreign"&&(m=!0,g=!0),C.clientKey&&(m||ge)){let W=await dt(Z=>{let X=t()-(Z.lastAttemptAt??0);return X<iI?{result:"throttled"}:Z.failureCount&&X<pI(Z.failureCount,Z.keyTtlMs)?{result:"backoff"}:{next:{...Z,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(W!=="ok")return W;try{let Z=await c(S,C.clientKey,q,E,{machineUuid:T}),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:Je,...We})=>({...We,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Od(C)??We.keyTtlMs}),{now:t,readState:a,writeState:s}),g?await b(await aH(C,S,C.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Z){let X=cI(Z);return await Rd(Je=>({...Je,lastAttemptAt:t(),failureCount:(Je.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 ma&&Z.policyCode==="managed_device_required"&&console.error(Z.message),Z instanceof ma?Z.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!m&&C.clientKey&&!ge){let W=await mI(C,e,n),Z=await k();return W||Z?"repaired":F?"cert-renewed":"not-due"}let me=await dt(W=>{let Z=t()-(W.lastAttemptAt??0);if(m)return Z<GU(W.failureCount)?{result:"throttled"}:{next:{...W,lastAttemptAt:t()},result:"ok"};let X=W.lastError?.code!==void 0&&FU.has(W.lastError.code)?WU:iI;return Z<X?{result:"throttled"}:W.failureCount&&Z<pI(W.failureCount,W.keyTtlMs)?{result:"backoff"}:{next:{...W,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(me!=="ok")return me;try{let W=await i(S,q,E,{machineUuid:T}),Z=await l().catch(()=>{}),X=xe({origin:S,clientKey:W.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),_=null;We.enrolledCert&&await AI(We,q.sig,E,o)&&(_={...We,clientKey:W.key,clientKeyExpiresAt:W.expiresAt??We.clientKeyExpiresAt},await r(_));let L=W.expiresAt?Date.parse(W.expiresAt):NaN,J=Od(C)??(Number.isFinite(L)&&L-t()>0?L-t():void 0);return await Rd(({lastError:pe,...ut})=>({...ut,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:J??ut.keyTtlMs}),{now:t,readState:a,writeState:s}),_&&await mI(_,e,n),await b(_?"repaired":"repair_failed"),await k(),"refreshed"}catch(W){let Z=cI(W);return await Rd(X=>({...X,lastAttemptAt:t(),failureCount:(X.failureCount??0)+1,lastError:{name:W instanceof Error?W.name:"Error",...Z!==void 0?{code:Z}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),W instanceof lt&&W.policyCode==="managed_device_required"&&console.error(W.message),W instanceof lt?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await k()}catch{}}};var lH=`anyray-connect print-key [--json | --passthrough-headers]
|
|
375
|
+
`;import{randomBytes as UW}from"node:crypto";var HW=1e4,GW="machine:",FS=e=>e.startsWith(GW),VW="cert-renew",KW=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)},WS=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:UW(16).toString("hex"),purpose:VW},c;try{c=await(n.signer??Cr)(lo(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),HW),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 KW(f)?{ok:!0,cert:f}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var ph=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}},fh=async(e,t=e.origin,n=le)=>(await ph(e,t,n)).complete;var jW=["claude","codex","cursor","opencode"],ZW=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],YW=new Set(["missing_key","key_expired"]);var JW=600*1e3,XW=600*1e3,US=1440*60*1e3,zW=1440*60*1e3,qW=10080*60*1e3,QW=3600*1e3,eU=720*60*1e3,tU=e=>Math.min(eU,QW*2**Math.max(0,e-1)),ui=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ka=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,HS=e=>typeof e=="string"&&ZW.includes(e),An=e=>{if(!ui(e))return{};let t={};if(ka(e.watchSince)&&(t.watchSince=e.watchSince),ui(e.invoked)){let n={};for(let r of jW){let o=e.invoked[r];ka(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return ui(e.authFailure)&&ka(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...HS(e.authFailure.code)?{code:e.authFailure.code}:{}}),ui(e.repair)&&ka(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,...ka(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Cd=e=>{try{let n=JSON.parse(e);if(ui(n)&&HS(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"},mh=e=>e!==void 0&&YW.has(e),hh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=JW},GS=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),yh=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=XW},VS=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),KS=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,jS=(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},ZS=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>US||!mh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<tU(r.failures??1))},kd=e=>{let t=Object.values(e?.invoked??{}).filter(ka);return t.length>0?Math.max(...t):null},gh=(e,t)=>{if(kd(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=qW},YS=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=zW)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=US)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var wh="x-anyray-retrieve-probe",vd=8e3,nU=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",JS=(e,t)=>{let n=Vt(e);return t?.probe&&(n[wh]="1"),n},va=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:JS(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=nU(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:JS(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 rU=5e3,oU=2048,aU=e=>{let t=e.toLowerCase();return t.includes("client key required")?!0:["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},Sa=async(e={})=>{let t=e.readTarget??nt,n=e.fetch??fetch,r=e.timeoutMs??rU,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[wh]="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,oU);if(!aU(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)}},bh=(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 cU}from"node:crypto";import{execSync as Ah}from"node:child_process";import{hostname as sU}from"node:os";var iU=e=>{try{if(e==="darwin"){let t=Ah("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=Ah('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 Ah("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Id=(e={platform:process.platform,read:()=>iU(process.platform),hostname:sU})=>e.read().trim()||e.hostname().trim();var Ft=(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??(()=>Id());try{return r().trim().toLowerCase()}catch{return""}}return""};var lU=500,XS=2e3,dU=2e3,uU=250,zS=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),lU);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)}},pU=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},fU=e=>new Promise(t=>setTimeout(t,e)),mU=async(e,t,n=fU)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),XS),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=pU(i)??uU,s>dU))return!1}finally{clearTimeout(a)}await n(s)}},hU=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:cU(16).toString("hex"),events:e},i;try{i=await(t.signer??Cr)(lo(s),o)}catch{return!1}return await(t.post??mU)(`${t.origin??Hn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},yU=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:XS,machineUuid:(n.machineUuid??Ft)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},qS=async(e,t)=>{if(e.length!==0)try{let n=await nt(),r=n&&await zS(n.origin,Vt(n),e,t);if(n&&await yU(n.origin,e),r)return;await hU(e)}catch{}},Ch=async(e,t,n={readTarget:()=>nt("profile"),post:zS})=>{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 eI=128,tI=300*1e3,gU=["repaired","repair_failed","flapping","pending"],wU=["settings_not_writable","mcp_unreadable","mcp_not_writable","mcp_foreign","mcp_not_persisted","apply_unconfirmed","apply_threw"],nI=["rebroke_same_day","repeat_days"],rI=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),oI=e=>fi(e,ho),Ed=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},vr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,pi=e=>{if(!(!Array.isArray(e)||!e.every(oI)))return Gn(e)},bU=e=>{if(!mo(e))return;let t=pi(e.checks);if(!(!vr(e.since)||!fi(e.reason,nI)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},AU=e=>{if(!mo(e))return;let t={};Ed(e.day)&&(t.day=e.day),vr(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),Ed(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),vr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),mo(e.lastRepaired)){let i={};for(let c of ho){let l=e.lastRepaired[c];vr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=bU(e.flapping);return s&&(t.flapping=s),t},CU=e=>{if(!mo(e)||!Ed(e.day)||!vr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!rI.has(e.tool)||!oI(e.checkId)||!fi(e.status,gU)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!fi(e.errorClass,wU))return;t=e.errorClass}else if(e.status==="flapping"){if(!fi(e.errorClass,nI))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,...vr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},QS=e=>{if(!mo(e))return{};let t={};if(mo(e.adapters)){let n={};for(let r of rI){let o=AU(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(CU).filter(n=>n!==void 0).slice(-eI)),vr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),mo(e.report)&&Ed(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...vr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},kU=e=>new Date(e).toISOString().slice(0,10),vU=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,Gn=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}:{}}},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(-eI),nextSequence:r}},SU=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),IU=async e=>await Be(async()=>e)??null,EU=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)},aI=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:vU(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:Gn([...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:Gn([...i?.checks??[],...t])}}:{}},slowFlap:a}},xU=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 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=aI(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)},RU=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)),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:Gn([...l.brokenReportedChecks??[],...y]),flapping:{since:g?.since??a,reason:"rebroke_same_day",checks:Gn([...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:Gn([...d,...p]),confirmedChecks:u.filter(y=>!p.includes(y)),brokenReportedChecks:Gn([...l.brokenReportedChecks??[],...f]),...f.length>0?{flapping:{since:h?.since??a,reason:"rebroke_same_day",checks:Gn([...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),OU=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:Gn([...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=aI(l,d,o,a);c[e]=p.adapter;let f=n.status==="failed"?n.errorClass??"apply_threw":n.errorClass??"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)},TU=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>=tI));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??Ch)(o.map(SU),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)},_U=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??ir)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=YS(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},PU=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<tI?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await _U(e,t,n,c,o,s);await(s.report??Ch)(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)},sI=async(e,t,n)=>{let r=n.now??Date.now,o=kU(r()),a=e.managedTools??[],s={...n,readState:async()=>QS(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(QS(l)),c)};try{let i=await(s.findIntegrations??lh)(a);await EU(i,o,s);let c=await(s.listPending??ar)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await xU(i,l,o,r(),s);let d=await(s.resolveTarget??IU)(e),u=d?await(s.findDrifted??ga)(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??te)();if(d)for(let{adapter:y,checks:g}of f.values()){let b=h?ho.filter(O=>g[O]==="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(O=>[O,"unreadable"]))}let C=b.filter(O=>k[O]==="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 RU(y.id,C,S,l.has(y.id),o,r(),s);if(!I)continue;let[E]=await(s.repair??Bt)([y],d.target);if(!E)continue;m=!0;let T;E.status==="configured"&&y.integrationStatus&&(T=await y.integrationStatus().catch(()=>{})),await OU(y.id,I.checks,E,T,o,r(),s)}await TU(o,r(),t,s),i=await(s.findIntegrations??lh)(a);let w=await(s.listPending??ar)().catch(()=>[]);return await PU(e,i,w,o,r(),t,s),m}catch{return!1}};var FU=14,WU=.35,UU=900*1e3,cI=360*60*1e3,HU=.2,GU=1800*1e3,lI=3600*1e3,VU=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),KU=300*1e3,jU=30*1e3,ZU=900*1e3,YU=(e=0)=>Math.min(ZU,jU*2**Math.max(0,e)),dI=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}},uI=1440*60*1e3,JU=300*1e3,XU=.25,zU=.5,pI=3600*1e3,qU=720*60*60*1e3,QU=360*60*1e3,eH=1440*60*1e3,tH=()=>gI(NU(),".anyray"),kh=()=>gI(tH(),"refresh-state.json"),vh=e=>process.env?.[e],bI=()=>vh("ANYRAY_REFRESH_DISABLE")==="true",Sh=()=>{let e=vh("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:FU)*eH},Od=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},AI=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),nH=10080*60*1e3,CI=(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)<=nH},Ih=e=>{let t=Sh(),n=e?Od(e):void 0;if(!n)return t;let r=Math.max(UU,Math.round(n*WU));return Math.min(t,r)},rH=e=>{let t=vh("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(cI,Math.max(GU,Math.round(e*HU))):cI},It=async()=>{try{let e=await $U(kh(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Td=async e=>{try{let t=kh(),n=`${t}.${process.pid}.tmp`;await wI(n,JSON.stringify(e),{mode:384}),await he(n,t),await MU(t,384).catch(()=>{})}catch{}},oH=3e4,aH=()=>`${kh()}.lock`,fI=async e=>{try{return await wI(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??Td,s=aH(),i=!1;try{if(i=await fI(s),!i){if(await BU(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<oH)return t;await iI(s).catch(()=>{}),i=await fI(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await iI(s).catch(()=>{})}},Rd=async(e,t={})=>{await dt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Ia=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(()=>{})},sH=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(qU,Math.max(pI,Math.round(o*zU))):pI},kI=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,Eh=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??ae,a=n.loadProfile??D,s=n.loadDevKey??$e,i=n.renew??WS,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(FS(c.payload.user))return{outcome:"not-due",profile:e};let l=Date.parse(e.enrolledCertExpiry??c.payload.expiresAt??"");if(!Number.isFinite(l))return{outcome:"not-due",profile:e};if(l-r()>sH(e))return{outcome:"not-due",profile:e};if(!await dt(w=>r()-(w.lastCertRenewAt??0)<QU?{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 kI(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}},mI=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*XU):uI,r=Math.min(uI,n);return Math.min(r,JU*2**Math.max(0,e-1))},iH=()=>{let{command:e,args:t}=tr(Xn);return{exe:e,args:t}},Sr=async(e={})=>{if(bI())return;let t=e.now??Date.now,n=e.readState??It,r=e.writeState??Td,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=iH();LU(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await dt(s=>t()-(s.lastSpawnAt??0)<rH(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},cH=fh,lH=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 ga(n,r.target.origin),a=t?DS(o):o;return a.length===0?!1:(await Bt(a,r.target),!0)}catch{return!1}},dH=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}},uH=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??It,a=t.writeState??Td;return sI(e,Ae,{now:r,deadWatcherObserved:n,readHookLane:()=>_d({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})})},_d=async(e={})=>{let n=await(e.readState??It)().catch(()=>({}));return An(n.hookLane)},vI=async(e,t={})=>{try{let n=t.now??Date.now,r=await _d(t);if(!hh(r,e,n()))return;await dt(o=>{let a=An(o.hookLane);return hh(a,e,n())?{next:{...o,hookLane:GS(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},SI=async(e,t={})=>{try{let n=t.now??Date.now,r=await _d(t);if(!yh(r,n()))return;await dt(o=>{let a=An(o.hookLane);return yh(a,n())?{next:{...o,hookLane:VS(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},pH=async(e={})=>{try{let t=e.now??Date.now;if((await _d(e)).watchSince!==void 0)return;await dt(n=>{let r=An(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:KS(r,t())},result:void 0}},void 0,e)}catch{}},hI=async(e,t={})=>{try{let n=t.now??Date.now;await dt(r=>{let o=An(r.hookLane),a=jS(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},II=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??Mg)())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??Bt)(s,i.target),"repathed")}catch{return"skipped"}},EI=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??Bt)(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"}},fH=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await Aa(e.gateway,e.clientKey),n=await Ca(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},yI=async(e,t,n)=>{let o=await(t.reconcilePolicy??fH)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>lH(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},zt=async(e={})=>{if(bI())return"disabled";let t=e.now??Date.now,n=e.loadProfile??D,r=e.saveProfile??ae,o=e.loadDevKey??$e,a=e.readState??It,s=e.writeState??Td,i=e.remint??Xt,c=e.heartbeat??uS,l=e.detectSeat??fn,d=e.rewriteTools??cH,u=e.rewriteHookLaneTools??ph,p=e.probeHookLane??Sa,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 hI("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 hI(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=>uH(I,{now:t,readState:a,writeState:s},y)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await ar().then(W=>W.some(Z=>!ir(Z.watcherPid))).catch(()=>!1),await pH({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??ob)();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 T=(e.resolveMachineUuid??Ft)()||void 0,O=await Eh(C,E,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=O.profile;let F=O.outcome==="renewed",q=C.enrolledCert;if(!q)return"not-enrolled";let de=Date.parse(C.clientKeyExpiresAt??""),ce=Number.isFinite(de)?de-t():0,K=await a(),ge=!C.clientKey||ce<=Ih(C);if(!m&&ZS(An(K.hookLane),t())&&await f().catch(()=>"unreadable")!=="foreign"&&(m=!0,g=!0),C.clientKey&&(m||ge)){let W=await dt(Z=>{let X=t()-(Z.lastAttemptAt??0);return X<lI?{result:"throttled"}:Z.failureCount&&X<mI(Z.failureCount,Z.keyTtlMs)?{result:"backoff"}:{next:{...Z,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(W!=="ok")return W;try{let Z=await c(S,C.clientKey,q,E,{machineUuid:T}),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:Je,...We})=>({...We,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:Od(C)??We.keyTtlMs}),{now:t,readState:a,writeState:s}),g?await b(await dH(C,S,C.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Z){let X=dI(Z);return await Rd(Je=>({...Je,lastAttemptAt:t(),failureCount:(Je.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 ma&&Z.policyCode==="managed_device_required"&&console.error(Z.message),Z instanceof ma?Z.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!m&&C.clientKey&&!ge){let W=await yI(C,e,n),Z=await k();return W||Z?"repaired":F?"cert-renewed":"not-due"}let me=await dt(W=>{let Z=t()-(W.lastAttemptAt??0);if(m)return Z<YU(W.failureCount)?{result:"throttled"}:{next:{...W,lastAttemptAt:t()},result:"ok"};let X=W.lastError?.code!==void 0&&VU.has(W.lastError.code)?KU:lI;return Z<X?{result:"throttled"}:W.failureCount&&Z<mI(W.failureCount,W.keyTtlMs)?{result:"backoff"}:{next:{...W,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(me!=="ok")return me;try{let W=await i(S,q,E,{machineUuid:T}),Z=await l().catch(()=>{}),X=xe({origin:S,clientKey:W.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),_=null;We.enrolledCert&&await kI(We,q.sig,E,o)&&(_={...We,clientKey:W.key,clientKeyExpiresAt:W.expiresAt??We.clientKeyExpiresAt},await r(_));let L=W.expiresAt?Date.parse(W.expiresAt):NaN,J=Od(C)??(Number.isFinite(L)&&L-t()>0?L-t():void 0);return await Rd(({lastError:pe,...ut})=>({...ut,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:J??ut.keyTtlMs}),{now:t,readState:a,writeState:s}),_&&await yI(_,e,n),await b(_?"repaired":"repair_failed"),await k(),"refreshed"}catch(W){let Z=dI(W);return await Rd(X=>({...X,lastAttemptAt:t(),failureCount:(X.failureCount??0)+1,lastError:{name:W instanceof Error?W.name:"Error",...Z!==void 0?{code:Z}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),W instanceof lt&&W.policyCode==="managed_device_required"&&console.error(W.message),W instanceof lt?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await k()}catch{}}};var mH=`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
|
+
`,hH=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}},yH=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=Ih(e):!0},xI=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},RI=(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()},xh=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,gH=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${xh(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 \`${xh(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 \`${xh(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(xI(o),!o.enrolledCert){if(!RI(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||yH(o,r)){let i=gH(await n(),o);if(i){if(!RI(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(xI(s),!Ee(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},OI=e=>ue({user:e.name,team:e.team}),Pd=({profile:e,token:t})=>{let n={},r=OI(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Rh=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=OI(e);return r&&(n["x-anyray-metadata"]=r),n},wH=e=>JSON.stringify(Rh(e)),TI=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=hH(e);if(o.help)return n.write(mH),0;let a=await hi(t);a.warning&&r.write(`${a.warning}
|
|
388
|
+
`);let s=o.passthroughHeaders?wH(a):o.json?Pd(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 _I=`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 m of l){let h=m.id===f?"*":" ",w=
|
|
402
|
+
`,bH=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},AH=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})},CH=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(" / ")},kH=(e,t,n)=>`${e.origin.replace(/\/+$/,"")}/v1${Ns(t)}/${Tn(n)==="responses"?"responses":"chat/completions"}`,PI=async(e=[],t={})=>{let n=bH(e);if(n.help)return process.stdout.write(_I),0;if(n.error)return R(n.error),process.stdout.write(_I),1;let r=await(t.loadTarget??Be)();if(!r)return R("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??ul)({allowKeychainPrompt:!0});if(!a.token)return R("No Copilot sign-in Connect can read \u2014 run `copilot` once and `/login` (say YES to storing credentials locally), then retry."),1;let s=a.token.token,i=a.capiSegment??"default",c=await(t.fetchCatalog??Ko)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=wf(c);if(l.length===0)return R("Could not fetch your seat's model catalog from GitHub (offline, or the sign-in lost its Copilot seat)."),1;if(!n.modelId){let 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:Tn(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=CH(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 R(`'${n.modelId}' is not in your seat's catalog \u2014 run \`anyray-connect models\` to list it.`),1;let u=await(t.probeChat??dl)(kH(o,i,d.id),{...gf(),authorization:`Bearer ${s}`,...o.clientKey?{"x-anyray-api-key":o.clientKey}:{}},d.id);if(u==="rejected")return R(`GitHub refuses chat as '${d.id}' for this sign-in (it is in the catalog, but chat entitlement is narrower). Pick another id from \`anyray-connect models\`.`),1;u==="unreachable"?P("Could not verify the model over the lane (offline?) \u2014 applying anyway."):B(`'${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??AH)(o);if(f.status!=="configured"){for(let m of f.messages)A(m);return R("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 B(`Copilot CLI startup model \u2192 ${d.id}`),$("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};var vH=`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
|
+
`,DI=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(vH),0;A(V("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??HA)();if(!n)return R("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??GA)(n);if(r.status!=="ok")return R(r.status==="denied"?"Sign-in was declined in the browser.":r.status==="expired"?"The code expired before sign-in completed \u2014 run the command again.":"GitHub refused the sign-in. Run the command again."),1;let o=(t.now??(()=>new Date))().toISOString(),a=await(t.save??VA)(r.token,o);B(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??df)(r.token);if(s.verdict==="no-copilot")return R("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??Ko)(r.token,{},s.capiSegment,c);return l.length===0?P("Signed in, but no model list came back \u2014 that is usually this machine or its network, not the sign-in. Continue with `anyray-connect --tools copilot-cli`; it verifies the model with a live check of its own."):B(`${l.length} models available (e.g. ${l[0].id}).`),$("Now run: anyray-connect --tools copilot-cli"),0};import{randomBytes as SH}from"node:crypto";import{chmod as IH,readFile as EH,rm as NI,writeFile as xH}from"node:fs/promises";import{join as RH}from"node:path";var OH=/^[A-Za-z0-9_-]{43}$/,LI=3900,TH=1e4,Oh=()=>RH(Q(),"device-token.json"),_H=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&OH.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},$I=async()=>{try{let e=JSON.parse(await EH(Oh(),"utf-8"));return _H(e)?e:null}catch{return null}},PH=0,DH=async e=>{await tt();let t=Oh(),n=`${t}.${process.pid}.${PH++}.tmp`;try{await xH(n,`${JSON.stringify(e)}
|
|
412
|
+
`,{mode:384}),await IH(n,384),await he(n,t)}catch(r){throw await NI(n,{force:!0}).catch(()=>{}),r}},Dd=async()=>{await NI(Oh(),{force:!0}).catch(()=>{})},LH=()=>SH(32).toString("base64url"),NH=e=>e instanceof Error?e.name:"UnknownError",MI=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=LH(),i=new AbortController,c=setTimeout(()=>i.abort(),TH),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:LI}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await DH({v:1,token:s,expiresAt:t()+LI*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${NH(r)}`),!1}};var BI=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??MI)(),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
|
|
414
|
+
`),0)};import{join as ZI,dirname as jH}from"node:path";import{mkdir as ZH,readFile as Nh,rm as YI,writeFile as JI}from"node:fs/promises";import{fstatSync as FH,openSync as WH,statSync as UH}from"node:fs";import{createInterface as HH}from"node:readline/promises";import{ReadStream as GH}from"node:tty";import{execFileSync as FI}from"node:child_process";import $H from"node:os";var Th=e=>{try{return FI("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},MH=e=>{try{return FI("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},BH=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"]),_h=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:BH.has(t):!0},Ld=()=>{try{return $H.userInfo().username||void 0}catch{return}},WI=()=>Th("user.name")??Th("user.email")??Ld()??"unknown",UI=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Th),global:e.globalGitConfig??(t||MH)}},go=e=>{try{return e()?.trim()||void 0}catch{return}},Ph=(e={})=>{let t=UI(e),n=go(e.osUsername??Ld),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")},HI=(e={})=>{let t=Ph(e);if(_h(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=UI(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 Wt=()=>!!process.stdin.isTTY,VH=()=>{try{let e=FH(0);return e.isCharacterDevice()&&e.rdev===UH("/dev/tty").rdev}catch{return!1}},Dh=()=>{if(VH()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new GH(WH(`/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"}},GI=async(e,t)=>{let n=t.input??Dh(),r=t.output??process.stdout,o=HH({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()}},Ea=async(e,t={})=>{let n=(await GI(`${e} ${v("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},xa=async(e,t,n={})=>{let r=t?` ${v(`[${t}]`)}`:"";return(await GI(`${e}${r}: `,n)).trim()||t},VI=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=WI();return n||!Wt()?($(`Your name: ${r} ${v("(auto-detected \u2014 pass --user to change)")}`),r):xa("? Your name",r)},KI=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||!Wt()))return xa("? Team (optional)")},Ir=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return Qt(e??n)},jI=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,Ra="claude-desktop",Nd=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await br(e.runReg??Fn))return n("managed-policy")}catch{return n("policy-unreadable")}let s=$t({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 da({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")}},$d=e=>e.id!==Ra||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",KH={"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"},Md=(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=KH[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 Lh=["claude-code","codex"],YH="anyray-connect print-key",$h=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),JH=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:ja,authMode:"placeholder",metadata:{}}),Mh=e=>ZI(e,".claude","settings.json"),XH=async(e,t,n)=>{let r=Mh(e),o=await M(r),{env:a}=tn(t,{includeAuthToken:!1,includeClientKey:!1}),s=$h(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Br(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=YH,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]}},XI=async(e=process.cwd())=>{let t=[],n=Mh(e);try{if(await x(n)){let o=await M(n),a=$h(o.env)?o.env:{};(Mr.some(s=>s in a)||Br(o))&&t.push(n)}}catch{}let r=Bh(e);try{if(await x(r)){let o=await Nh(r,"utf-8");hp(o)&&t.push(r)}}catch{}return t},zH=async(e,t)=>{let n=Mh(e);if(!await x(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await M(n),o=!1;if($h(r.env)){let s={...r.env};for(let i of Mr)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Br(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 YI(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]}},Bh=e=>ZI(e,".codex","config.toml"),qH=async(e,t,n)=>{let r=Bh(e),o=await Nh(r,"utf-8").catch(()=>""),a=xc(o,us(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await ZH(jH(r),{recursive:!0}),await JI(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]}},QH=async(e,t)=>{let n=Bh(e);if(!await x(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await Nh(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 YI(n,{force:!0}):await JI(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},zI=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...Lh],r=n.filter(s=>!Lh.includes(s));if(r.length>0)return R(`--project supports ${Lh.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 R("--project needs a gateway: pass --gateway <url>, or run `anyray-connect` once on this machine so it is cached."),1;try{let c=new URL(i.trim());if(c.protocol!=="http:"&&c.protocol!=="https:")throw new Error("not http(s)")}catch{return R(`invalid gateway URL: "${i}" \u2014 must start with http:// or https://`),1}o=JH(Ht(i))}if(A(V(e.revert?"Anyray connect \u2014 remove project config":"Anyray connect \u2014 project config")),H("Project"),A(` Directory: ${t}`),o&&A(` Gateway: ${o.origin}`),A(` Tools: ${n.join(", ")}`),e.revert||(P(`
|
|
415
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(!Wt())return R(`
|
|
416
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 Ea(`
|
|
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){H(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await
|
|
419
|
-
`),1;let o;try{o=await hi(t)}catch(i){let c=i instanceof Error&&i.message?i.message:
|
|
420
|
-
`),1}let a=o.profile.authMode??"auto",s;if(a==="placeholder")s=Pd(o);else try{s=await
|
|
418
|
+
Dry run \u2014 no files will be written.`);let a=[];for(let s of n){H(s==="claude-code"?"Claude Code":"Codex");let i=o?s==="claude-code"?await XH(t,o,e.dryRun):await qH(t,o,e.dryRun):s==="claude-code"?await zH(t,e.dryRun):await QH(t,e.dryRun);for(let c of i.messages)A(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(H("Next"),e.revert)B(" Project config removed. Commit the change to propagate it.");else{B(" Commit these files to route every checkout of this repo:");for(let s of a)A(` ${s}`);A(v(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as eG}from"node:child_process";var tG="/usr/bin/security",nG=["find-generic-password","-s","Claude Code-credentials","-w"],rG=1e4,oG=64*1024,aG=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,Fh="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",sG=(e,t,n)=>new Promise((r,o)=>{eG(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),qI=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),iG=e=>{let t=JSON.parse(e);if(!qI(t)||!qI(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!aG.test(n))throw new Error("unexpected keychain access token");return n},cG=async(e,t)=>{let n=Rh(e),r=await(t.execSecurity??sG)(tG,[...nG],{encoding:"utf8",timeout:rG,maxBuffer:oG,shell:!1});return JSON.stringify({token:iG(r.stdout),headers:n})},QI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${Fh}
|
|
419
|
+
`),1;let o;try{o=await hi(t)}catch(i){let c=i instanceof Error&&i.message?i.message:Fh;return r.write(`${c}
|
|
420
|
+
`),1}let a=o.profile.authMode??"auto",s;if(a==="placeholder")s=Pd(o);else try{s=await cG(o,t)}catch{if(a==="subscription")return r.write(`${Fh}
|
|
421
421
|
`),1;s=Pd(o)}return o.warning&&r.write(`${o.warning}
|
|
422
422
|
`),n.write(`${s}
|
|
423
|
-
`),0};var
|
|
423
|
+
`),0};var eE="Anyray: could not resolve the Anyray client key for the Claude Desktop bootstrap fetch. Run `anyray-connect` and try again.",tE=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${eE}
|
|
424
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(`${eE}
|
|
427
|
+
`),1}};import{mkdir as DG,writeFile as LG}from"node:fs/promises";import{dirname as NG}from"node:path";import{Buffer as $G}from"node:buffer";import{constants as nE}from"node:fs";import{access as lG,chmod as dG,lstat as uG,mkdir as pG,open as fG,readFile as mG,realpath as hG,rm as yG,stat as oE,writeFile as gG}from"node:fs/promises";import{randomUUID as wG}from"node:crypto";import{platform as Uh}from"node:os";import{dirname as bG,join as AG,posix as CG,win32 as aE}from"node:path";var wi="/usr/local/bin/anyray-credential-helper",bi="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Bd="/usr/local/bin/anyray-bootstrap-headers-helper",Fd="C:\\Program Files\\Anyray\\anyray-bootstrap-headers-helper.cmd",gi="Managed by anyray-connect desktop helper; do not edit.",Wd="__anyray-refresh-desktop-helpers",kG=`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
|
|
@@ -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",`# ${gi}`,'if [ "$#" -eq 0 ]; then',` exec ${
|
|
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"]}},
|
|
474
|
-
`),0}if(s!==
|
|
469
|
+
`,Wh=(e=Uh())=>e==="win32"?"windows":"posix",sE=e=>e==="windows"?bi:wi,iE=e=>e==="windows"?Fd:Bd,rE=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},vG=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":rE(t,"write");break;case"--print":rE(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},SG=e=>/[\0\r\n]/.test(e),IG=e=>/^[A-Za-z]:[\\/]/.test(e)&&aE.isAbsolute(e),Ai=(e,t)=>!SG(e)&&(t==="windows"?IG(e):CG.isAbsolute(e)),yi=e=>e.replace(/\\/g,"/").toLowerCase(),Ud=(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"?aE.normalize(e):e,Hh=e=>`'${e.replace(/'/g,`'"'"'`)}'`,cE=(e,t)=>{if(!Ud(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}" ${gr}`,"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} ${gr}`,"fi",'if [ "$#" -eq 1 ] && [ "$1" = "--token" ]; then',` exec ${r} print-key`,"fi","exit 64",""].join(`
|
|
471
|
+
`)},lE=(e,t)=>{if(!Ud(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"]}},dE=async e=>{try{return await mG(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw new Error(`could not inspect existing helper at ${e}`)}},EG=async(e,t)=>{try{let n=await hG(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!Ud(r,t))throw new Error;if(!(await oE(n)).isFile())throw new Error;await lG(n,t==="posix"?nE.X_OK:nE.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},uE=e=>e.slice(0,300).includes(gi),pE=async(e,t,n)=>{let r=await dE(e);if(r!==void 0&&r!==t&&!uE(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 oE(e)).mode&511)===493)return"unchanged"}catch{}}let o=bG(e);try{await pG(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=AG(o,`.anyray-helper.${process.pid}.${wG()}.tmp`),s=!1;try{await gG(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await dG(a,493);let i=await fG(a,"r");try{await Kn(i)}finally{await i.close()}await he(a,e),s=!0}catch{throw new Error(`could not install helper at ${e}`)}finally{s||await yG(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},xG=(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)},Gd=async(e,t={})=>{let n=Wh((t.platform??Uh)());if(!Ud(e,n))return;let r=[{path:t.helperPath??sE(n),content:cE(n,e)},{path:t.bootstrapHeadersHelperPath??iE(n),content:lE(n,e)}];for(let o of r)try{if((await uG(o.path).catch(()=>{}))?.isSymbolicLink())continue;let a=await dE(o.path);if(a===void 0||a===o.content||!uE(a)||!xG(a,e,n))continue;await pE(o.path,o.content,n)}catch{}},fE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=vG(e);if(o.help)return n.write(kG),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??Uh)(),s=o.targetPlatform??Wh(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,sE(s)),content:cE(s,i)},{kind:"bootstrap-headers",label:"bootstrap-headers helper",path:c("--bootstrap-headers-path",o.bootstrapHeadersHelperPath,iE(s)),content:lE(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!==Wh(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await EG(i,s);for(let d of l){let u=await pE(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 RG=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),OG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,TG=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.")},_G=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Vd=(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!==""||TG(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Oa=(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()}},mE=e=>{if(!_G(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!RG.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Oa(e.clientId,"clientId",!0),r=Oa(e.scopes,"scopes",!0),o=Oa(e.issuer,"issuer",!1),a=Oa(e.authorizationUrl,"authorizationUrl",!1),s=Oa(e.tokenUrl,"tokenUrl",!1),i=Oa(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:Vd(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:Vd(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:Vd(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},hE=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return mE(t)},Gh=e=>e==="windows"?Fd:Bd,PG=(e,t)=>{let n=new URL(e);return n.searchParams.set("os",t),n.toString()},Kd=(e,t)=>{let n=PG(Vd(e.url,"--bootstrap-url"),t),r=e.oidc?mE(e.oidc):void 0,o;if(e.deploymentOrganizationUuid!==void 0&&(o=e.deploymentOrganizationUuid.trim(),!OG.test(o)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:n,bootstrapHeadersHelper:Gh(t),...r?{bootstrapOidc:r}:{},...o?{deploymentOrganizationUuid:o}:{}}},yE=(e,t)=>wr(Kd(e,t));var MG=`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>${Vn(t)}</string>`,
|
|
522
|
+
`,BG=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",FG=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),WG=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[BG(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...FG(o)]},UG=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),Vh=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>UG.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"]},Vn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),gE=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),HG=(e,t)=>` <key>${Vn(e)}</key>
|
|
523
|
+
<string>${Vn(t)}</string>`,Kh=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>HG(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>${Vn(n)}</string>
|
|
554
554
|
</dict>
|
|
555
555
|
</plist>
|
|
556
|
-
`},ki={disableDeploymentModeChooser:!0},
|
|
557
|
-
`,
|
|
558
|
-
`,
|
|
559
|
-
`),
|
|
556
|
+
`},ki={disableDeploymentModeChooser:!0},bE=(e,t)=>Kh("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",wr({...eo(e,t),...ki})),GG=(e,t)=>`${JSON.stringify({...eo(e,t),...ki},null,2)}
|
|
557
|
+
`,VG=e=>Kh("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",wr({...Kd(e,"macos"),...ki})),KG=e=>`${JSON.stringify({...Kd(e,"linux"),...ki},null,2)}
|
|
558
|
+
`,AE=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries({...e,...wr(ki)}).map(([n,r])=>`"${gE(n)}"="${gE(r)}"`),""].join(`
|
|
559
|
+
`),CE=(e,t)=>{let n=Wl(e,t);return AE(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},jG=e=>AE(yE(e,"windows")),kE=(e,t,n)=>{if(t==="darwin"){let r=wi;return{path:`${n}/claude-desktop-anyray.mobileconfig`,content:bE(e,r),helperPath:r}}if(t==="win32"){let r=bi;return{path:`${n}\\claude-desktop-anyray.reg`,content:CE(e,r),helperPath:r}}},vE=(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."],ZG=(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`${us(e,o).join(`
|
|
560
560
|
`)}
|
|
561
|
-
`},
|
|
561
|
+
`},YG=e=>Kh("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:$G.from(e,"utf-8").toString("base64")}),JG=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},XG=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:ja,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},wE=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??DG,o=n.writeFile??LG;await r(NG(t),{recursive:!0}),await o(t,e)},zG=(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
|
+
`)},qG=(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 ${Gh(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
|
+
`)},QG=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 ${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=
|
|
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},SE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=WG(e);if(o[0]==="helper")return fE(o.slice(1),t);let a=JG(o);if(a.help)return n.write(MG),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 QG(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:hE(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},p=a.artifact==="reg"?jG(u):a.artifact==="json"?KG(u):VG(u);return await wE(p,a.path,t),qG(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=XG(a),d;if(a.target==="claude")d=a.artifact==="reg"?CE(l,i):a.artifact==="json"?GG(l,i):bE(l,i);else{let u=ZG(l,i);d=a.artifact==="mobileconfig"?YG(u):u}return await wE(d,a.path,t),zG(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 e1=`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
|
+
`,t1=`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
|
+
`,IE=(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},n1=e=>e.replace(/[\t\r\n]+/g," ").trim(),EE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=IE(e,!1);if(o.help)return n.write(e1),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??va)(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}},
|
|
608
|
+
`),1}},xE=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=IE(e,!0);if(o.help)return n.write(t1),0;let a=o.positional?.trim();if(!a)return r.write(`A query is required: anyray-connect recall "what to find" (see --help)
|
|
609
609
|
`),1;let s=await(t.readTarget??nt)(o.source),i=await(t.recall??Sd)(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} ${n1(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 R1}from"node:fs";var Cn=e=>typeof e=="string"?e:"",r1=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()},o1=e=>{let t=Cn(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},a1=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=r1(r);if(!o)continue;let a=Cn(r.created_at).trim();t.push({role:o1(r),text:o,...a?{createdAt:a}:{}})}return t},jd=e=>{let t;try{t=JSON.parse(e)}catch{return{ok:!1,conversations:[],skipped:0,message:"the file is not valid JSON"}}let n=Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.conversations)?t.conversations:null;if(!n)return{ok:!1,conversations:[],skipped:0,message:"expected a list of conversations \u2014 is this the conversations.json from a Claude data export?"};let r=[],o=0;for(let a of n){if(!a||typeof a!="object"){o+=1;continue}let s=a,i=a1(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 k1}from"node:crypto";import{promises as Ii}from"node:fs";import{homedir as LE}from"node:os";import{join as Yd}from"node:path";import{promises as RE}from"node:fs";import jh from"node:path";var s1=4e4,i1=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=jh.resolve(r,n),a=jh.relative(r,o);if(a.startsWith("..")||jh.isAbsolute(a))return vi(n,"path is outside the workspace");let s=t.maxBytes??s1,i;try{let w=await RE.stat(o);if(!w.isFile())return vi(n,"not a regular file");let y=t.maxFileBytes??i1;if(w.size>y)return vi(n,`file too large to read (${w.size} bytes; limit ${y})`);i=await RE.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
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}:{}}}},
|
|
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}:{}}}},Zh=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(I=>S.includes(I))&&(u.push({file:
|
|
621
|
+
${e.content}`};import{spawn as c1}from"node:child_process";import{promises as Yh}from"node:fs";import Jh from"node:path";var Xh=400,l1=240,d1=4e3,u1=4e3,p1=512*1024,f1=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),TE=(e,t)=>e.length>t?e.slice(0,t):e,m1=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"]),h1=8,y1=2e3,g1=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],w1=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")},_E=e=>{let t=new Set,n=[];for(let r of e.trim().split(/\s+/)){if(r.length<2)continue;let o=r.toLowerCase();if(!m1.has(o)&&!t.has(o)&&(t.add(o),n.push(r),n.length>=h1))break}return n},PE=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},b1=(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)},OE=(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:TE(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 g1)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=c1("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=OE(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=OE(d,o,r+1),w=h.length>r;p({ok:!0,matches:w?h.slice(0,r):h,truncated:w,engine:"ripgrep"})})}),C1=async(e,t,n,r,o,a,s)=>{let i=PE(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 Yh.readdir(h,{withFileTypes:!0})}catch{return}for(let y of w){if(u.length>=r||Date.now()>a){f=!0;return}let g=Jh.join(h,y.name);if(y.isDirectory()){if(f1.has(y.name))continue;await m(g)}else if(y.isFile()){if(p>=u1){f=!0;return}if(d.length&&!d.some(C=>y.name.endsWith(C))||w1(Jh.relative(t,g)))continue;p+=1;let b;try{if((await Yh.stat(g)).size>p1)continue;b=await Yh.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:Jh.relative(t,g),line:C+1,text:TE(k[C],o)}),u.length>=r)){f=!0;return}}}}};return await m(t),{ok:!0,matches:u,truncated:f,engine:"walk"}},Zd=async(e,t={})=>{let n=e.trim();if(!n)return{ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"query is required"};let r=t.cwd??process.cwd(),o=t.globs??[],a=t.maxMatches??Xh,s=t.maxColumns??l1,i=t.timeoutMs??d1,c=Date.now()+i,l=_E(n),d=l.length>1,u=Math.min(a*4,y1),p=(y,g)=>C1(n,r,o,y,s,c,g),f=async y=>{let g=await y(u,l);if(!g.ok)return g;let b=b1(g.matches,l,PE(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))},DE=(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=_E(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 NE=448,v1=384,S1=4e4,xr=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=Yd(LE(),".anyray");try{if((await Ii.stat(t)).isDirectory())return Yd(t,"history")}catch{}return Yd(LE(),".anyray-history")},I1=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:E1(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},E1=e=>{let t=k1("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)},x1=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
|
-
`},Jd=async e=>{let t=await
|
|
634
|
+
`},Jd=async e=>{let t=await xr();await Ii.mkdir(t,{recursive:!0,mode:NE});try{await Ii.chmod(t,NE)}catch{}let n=0,r=0;for(let o of e)try{await Ii.writeFile(Yd(t,I1(o)),x1(o),{mode:v1}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Ta=async()=>{try{let e=await xr();return(await Ii.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},$E=async e=>{let t=await xr();return Zd(e,{cwd:t,globs:["*.md"]})},ME=async e=>{let t=await xr();return Si(e,{cwd:t,maxBytes:S1})};var BE=`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
|
+
`,O1=async e=>{try{return{raw:await R1.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"})`}}},T1=async e=>{let t=e.find(a=>!a.startsWith("-"));if(!t)return R("Usage: anyray-connect history import <conversations.json>"),A(v("Get the file from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await O1(t);if("error"in n)return R(n.error),1;let r=jd(n.raw);if(!r.ok)return R(`Could not read that export: ${r.message??"unrecognized format"}`),A(v("Expected the conversations.json from a Claude data export (claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data).")),1;if(r.conversations.length===0)return R("That export contains no conversations with readable messages."),1;let o;try{o=await Jd(r.conversations)}catch(a){let s=a?.code;return R(`Could not create the history archive (${s??"write failed"}).`),A(v("Check that ~/.anyray is a writable directory, then try again.")),1}return B(`Imported ${o.written} conversation${o.written===1?"":"s"} into ${o.dir}`),r.skipped>0&&A(v(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&P(`${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},_1=async e=>{let t=e.find(r=>!r.startsWith("-"));if(!t)return R("Usage: anyray-connect history restore <export.zip>"),A(v("Get the .zip from claude.ai \u2192 Settings \u2192 Privacy \u2192 Export data.")),1;let n=await Hl(t);return n.ok?(B(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&A(v(` ${n.skipped} already present, left untouched.`)),n.failed>0&&P(`${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):(R(`Could not restore into Claude Desktop: ${n.reason}`),A(v(` ${n.remedy}`)),1)},P1=async()=>{let e=await xr(),t=await Ta();return t===0?(A(`No conversations imported yet. Archive would live at ${e}`),A(v(" Import one with: anyray-connect history import <conversations.json>")),0):(B(`${t} conversation${t===1?"":"s"} in ${e}`),0)},FE=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(BE),0):t==="import"?T1(e.slice(1)):t==="restore"?_1(e.slice(1)):t==="status"?P1():(R(`Unknown history command: ${t}`),console.log(BE),1)};import{promises as D1}from"node:fs";var L1=`anyray-connect migrate [options]
|
|
656
656
|
|
|
657
657
|
Bring what Claude Desktop was showing you onto Anyray. Quit Claude Desktop first.
|
|
658
658
|
|
|
@@ -681,56 +681,56 @@ 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(` ${
|
|
684
|
+
`,N1=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},WE={code:"Claude Code sessions",cowork:"Cowork tasks"},$1=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`${WE[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},M1=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){R(` ${n.reason}`);for(let s of n.remedy.split(`
|
|
685
|
+
`).filter(Boolean))A(` ${s}`);return!1}for(let s of n.lanes)A(` ${$1(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&&P(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&P(` 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&&P(` ${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??[])P(` ${WE[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),A(` ${Rm(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},B1=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){R(` ${n.reason}`),A(` ${n.remedy}`);return}B(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),A(v(" They are listed under Cowork \u2014 the Chat tab has no local store."));let r=n.projects;if(r.imported+r.alreadyPresent+r.skippedCollision+r.failed>0){let a=[r.alreadyPresent>0?`${r.alreadyPresent} already there`:"",r.skippedCollision>0?`${r.skippedCollision} skipped, a folder of that name already exists`:"",r.failed>0?`${r.failed} failed`:""].filter(Boolean);B(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&A(v(` Instructions and docs are in ${r.root}, listed under Projects.`))}},F1=async e=>{if(A(""),A(V("3. Searchable from every Anyray client")),!e.conversations){let o=await Ta();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 D1.readFile(e.conversations,"utf8")}catch{R(` could not read ${e.conversations}`);return}let n=jd(t);if(!n.ok){R(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await Jd(n.conversations);B(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),A(v(` Ask any Anyray-connected client about a past chat. ${await xr()}`))},W1=e=>{A(""),A(V("Next")),A(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||P(" 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`."))},UE=async(e,t={})=>{let n;try{n=N1(e)}catch(o){return R(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(L1),0;A(V("Migrating Claude Desktop onto Anyray")),A(v("Claude Desktop must be fully quit.")),A("");let r=await M1(n,t);return await B1(n,!r),await F1(n),r?(W1(n),0):(A(""),P("Fix the item above and re-run to finish the migration."),1)};var U1=3e3,Xd=async(e,t={})=>{let n=t.timeoutMs??U1,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 VE}from"node:child_process";import{lstatSync as H1,readFileSync as G1}from"node:fs";import V1 from"node:os";var KE="ai.anyray.connect",Qh="EnrollmentEmail",ey="EnrollmentUrl",K1="HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Anyray\\Connect",HE="/etc/anyray/anyray-enroll.json",j1=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Z1=254,Y1=2048,J1=64*1024,X1=e=>e.isFile()&&e.uid===0&&(e.mode&63)===0&&e.size<=J1,z1=()=>`/Library/Managed Preferences/${KE}.plist`,q1=e=>`/Library/Managed Preferences/${e}/${KE}.plist`;var zh=e=>{try{let t=JSON.parse(e);return{...typeof t[Qh]=="string"?{email:t[Qh]}:{},...typeof t[ey]=="string"?{enrollmentUrl:t[ey]}:{}}}catch{return{}}},GE=(e,t)=>{for(let n of e.split(/\r?\n/u)){let r=/^\s*(\S+)\s+REG_SZ\s+([^\r\n]+)$/u.exec(n);if(r?.[1]===t)return r[2]?.trim()||void 0}},jE=e=>{if(!e)return;let t=e.trim().toLowerCase();if(!(!t||t.length>Z1))return j1.test(t)?t:void 0},Q1=e=>{if(!e)return;let t=e.trim();if(!(!t||t.length>Y1))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}},eV=e=>{try{return VE("plutil",["-convert","json","-o","-",e],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},tV=()=>{try{return V1.userInfo().username||void 0}catch{return}},nV=()=>{try{return VE("reg",["query",K1],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},rV=()=>{try{let e=H1(HE);return X1(e)?G1(HE,"utf8"):void 0}catch{return}},ZE={platform:process.platform,readMacPlistJson:eV,username:tV,readWindowsRegQuery:nV,readLinuxJson:rV},qh=(e,t)=>{let n=e.map(jE).find(o=>o!==void 0),r=Q1(t);return{...n?{email:n}:{},...r?{enrollmentUrl:r}:{}}},ty=(e=ZE)=>{try{if(e.platform==="darwin"){let t=e.username(),n=t?zh(e.readMacPlistJson(q1(t))??""):{},r=zh(e.readMacPlistJson(z1())??"");return qh([n.email,r.email],r.enrollmentUrl)}if(e.platform==="win32"){let t=e.readWindowsRegQuery();return t?qh([GE(t,Qh)],GE(t,ey)):{}}if(e.platform==="linux"){let t=zh(e.readLinuxJson?.()??"");return qh([t.email],t.enrollmentUrl)}return{}}catch{return{}}},YE=(e,t)=>{if(!e?.length)return;let n=t?.trim().split(/[\\/]/).at(-1)?.toLowerCase();if(n)return jE(`${n}@${e[0]}`)},JE=(e=ZE)=>ty(e).email;import{spawn as oV}from"node:child_process";import{platform as aV}from"node:os";var _a=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=aV(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=oV(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var XE=()=>Dh(),zE=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??XE)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},sV=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},qE=async(e,t={})=>{let n=(t.openInput??XE)(),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=ha(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
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
|
|
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 sV(S)){if(I===""||I==="\x1B"||I==="q"){y({kind:"cancelled"});return}if(e.items.length===0){(I==="\r"||I===`
|
|
689
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((O,F)=>({item:O,index:F})).filter(({item:O})=>O.requiresExplicitChoice!==!0),T=!E.every(({index:O})=>a[O]);for(let{index:O}of E)a[O]=T;d()}else if(I==="\r"||I===`
|
|
690
|
-
`){y({kind:"ok",values:e.items.filter((E,T)=>a[T]).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
|
|
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&&Pa(e.current,e.minVersion)<0&&Pa(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},hV=e=>Pa(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},Da=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",yV=(e=process.execPath)=>{let t=Uu(e);return t?xr(t):xr(xr(e))},gV=async(e=ft())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=Fe(yV(e.execPath),"bin",Da());try{if(await eu(t)!==await eu(e.execPath))return}catch{return}return t},sy=async(e=ft(),t=Q())=>{let n=await gV(e);if(n)return{kind:"managed",root:xr(xr(n)),link:n,entryPath:jn(e)};let r=jn(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}},nu=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)}},iy=async(e=Oi)=>{let t=await nu(`${tx}/latest`,e,{redirect:"manual"});return mV(t.headers.get("location"))},wV=async e=>{try{let t=await nu(`${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"}},cy=async(e,t,n)=>{let r=await nu(e,uV);if(!r.ok||!r.body)throw new Ri(r.status);let o=sV("sha256"),a=0;if(await cV(iV.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>dV)throw new Error("asset exceeds size cap");o.update(c),yield c}},rV(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},bV=e=>qd(e)===Da()?qd(xr(e)):qd(e),AV=async e=>{let t=await tu(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Et(Fe(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 zd(e,r),o=!0}catch{}try{await ny(t,e),await aV(qa(e),bV(t))}catch(a){throw o&&await zd(r,e).catch(()=>{}),a}await Et(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Et(n,{force:!0}),await oV(t,n),await zd(n,e)},CV=".anyray",ly=(e,t)=>e===t||qd(e)===CV?448:493,xi=async(e,t)=>{let n=(await ex(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await QE(e,n&4095|t).catch(()=>{})},Qd=async(e,t)=>{await oy(e,{recursive:!0,mode:t}),await xi(e,t)},kV=async(e,t,n)=>{let r=ly(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 tu(o).catch(()=>[]))await xi(Fe(o,a),r)}await(n.refreshDesktopHelpers??Gd)(t)},vV=async(e,t={})=>{let n=Fe(e.root,"bin"),r=Fe(e.root,"versions"),o=Fe(n,Da()),a=ly(e.root,(t.privateRoot??Q)());await Qd(n,a),await Qd(r,a);let s=Fe(r,e.version),c=(await ry(s).catch(()=>{}))?.isFile()?s:Fe(s,Da());if(!(await ry(c).catch(()=>{}))?.isFile()){let d=await(t.fetchResponse??nu)(`${e.tagUrl}/SHA256SUMS`,Oi),u=d.ok?ay(await d.text(),e.asset):void 0;if(!u)throw new Error("no published checksum");await Qd(xr(c),a),await AV(xr(c));let p=`${c}.part-${process.pid}`;try{await(t.download??cy)(`${e.tagUrl}/${e.asset}`,p,u),await QE(p,493),await zd(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}},SV=async e=>{qE(e.target,[Wd,e.link],{stdio:"ignore",timeout:Oi})},IV=async e=>{let t=qE(e,["--version"],{stdio:"ignore",timeout:Oi});return!t.error&&t.status===0},EV=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??Bt)(r,o.target)).every(po))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??nr)()).ok)},xV=async e=>{let t=await e.install();if(!await(e.smoke??IV)(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},RV=async(e,t)=>{let n=await tu(e).catch(()=>[]);for(let r of n)t.includes(r)||await Et(Fe(e,r),{force:!0,recursive:!0}).catch(()=>{})},OV=async e=>{let t=await tu(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Et(Fe(e,n),{force:!0}).catch(()=>{})},TV=async(e,t)=>{let n=async()=>{await Et(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await oy(e,{recursive:!1}),n}catch{}let r=await ex(e).catch(()=>{});if(!(!r||t-r.mtimeMs<fV)){await n();try{return await oy(e,{recursive:!1}),n}catch{return}}},ty=e=>Fe(e,"update-state.json"),_V=async e=>{let t=await M(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},La=async(e={})=>{let t=e.now??Date.now,n=Ae;if(In(nn(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??ft(),o=e.root??Q(),a;try{let s=await sy(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 kV(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??iy)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let p=a;if(!i&&p===n)return{outcome:"current",current:n,latest:p};if(i&&Pa(p,n)<0)return{outcome:"migration-deferred",current:n,latest:p};let f=await _V(ty(o));if((e.respectFailureBackoff===!0||!c)&&f.failedVersion===p&&f.failedAt!==void 0&&t()-f.failedAt<pV)return{outcome:"failed",current:n,latest:p};let m=`${tx}/download/${nx}${p}`,h=d||c?void 0:await(e.minimumVersion??wV)(m),w={current:n,latest:p,autoUpdate:d,forced:c,minVersion:h},y=i?hV(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 Qd(o,ly(o,Q()));let g=await TV(Fe(o,"update.lock"),t());if(!g)return{outcome:i?"migration-available":"available",current:n,latest:p};let b,k;try{await OV(Fe(o,"bin"));let C=await eu(Fe(o,"versions")).catch(()=>{}),S=await eu(Fe(o,"bin",Da())).catch(()=>{}),I=S&&Qi(S,C)?S:void 0,E=Fe(o,"bin",Da());i&&process.platform==="win32"&&(await ry(E).catch(()=>{}))?.isFile()&&(k=`${E}.rollback-${process.pid}`,await ny(E,k));let T=()=>(e.installBinary??vV)({root:o,version:p,asset:u,tagUrl:m});i?b=await xV({install:T,smoke:e.smoke,rollback:async({link:O,target:F})=>{k?(await ny(k,O),await Et(qa(O),{force:!0}).catch(()=>{})):I&&I!==F?await ax(O,I):(await Et(O,{force:!0}),await Et(qa(O),{force:!0}).catch(()=>{}))},repoint:async O=>e.repoint?e.repoint(l,O):EV(l),prune:async()=>{await(e.pruneDurable??(O=>ec(O)))(r)}}):b=await T(),await RV(b.versionsDir,[p,n]),await(e.refreshHelpersFromInstalled??SV)(b).catch(()=>{}),await Et(ty(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(ty(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},sx=async(e={})=>{let t=e.context??ft(),n=await sy(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}:La({...e,context:t,allowNpmMigration:!0})},wo=async(e={})=>{let t=e.context??ft(),n=e.root??Q(),r=await sy(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&&!!rx(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=In(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 PV=5e3,DV=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??PV);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=DV.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 LV=12e3,NV="anyray-wiring-probe-not-a-real-token",$V={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},uy={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},ux=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},py=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."],MV=e=>e.includes("no provider key configured for"),fy=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},my=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."]}),BV=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:MV(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")?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?fy(t)?my(e):py(t)?Ti(e):ux(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).",...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}: ${bo(t)}`,remedy:[]},FV=(e,t)=>{if(py(t))return Ti(e);if(fy(t))return my(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}: ${bo(t)}`,remedy:[]}},WV=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),UV=(e,t)=>{if(py(t))return Ti(e);if(fy(t))return my(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")||WV(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 (${uy.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."]}},dy=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)}},HV=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)}},GV=(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??LV,r=ue(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await HV(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 dy(`${e.anthropicBaseUrl}/v1/messages`,l,uy,n);return UV(d,u)}if(ee(e,"anthropic")){let l={Authorization:`Bearer ${NV}`,"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 dy(`${e.anthropicBaseUrl}/v1/messages`,l,uy,n);return FV(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await dy(`${e.openaiBaseUrl}/chat/completions`,s,$V,n);return BV(i,c,t.tools??[])}catch(o){return GV(n,o)}};var px=async e=>{let t=await D(),n;try{n=Sr(e.gateway,t)}catch(o){return A(V("Anyray connect \u2014 status")),$(`Gateway: ${o.message}`),0}A(V("Anyray connect \u2014 status")),H("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)"),H("Identity"),A(` Name: ${t.name??v("(not set)")}`),A(` Team: ${t.team??v("(not set)")}`);let r=nn();r&&(H("Environment"),A(` Remote dev context: ${To(r)}`),In(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&&(H("Credential renewal"),B(" Direct gateway routing with a proof-backed key heartbeat."),$(" Renewal extends the same key; tool configuration is not rewritten.")),H("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")){B(` ${o.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}B(` ${o.title}: pointed at Anyray`)}else{let i=null,c=null;if(o.id===Ra&&o.mcpStatus)try{let l=(await o.mcpStatus()).registered,d=await Nd();i=$d({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=Md(i,c);P(` ${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 aK}from"node:fs";import{isAbsolute as sK}from"node:path";import{access as VV}from"node:fs/promises";import{constants as KV}from"node:fs";import{platform as jV}from"node:os";var ZV=async e=>{try{return await VV(e,KV.F_OK),!0}catch{return!1}},YV=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??jV(),n=e.exists??ZV;for(let r of YV(t))if(await n(r))return!0;return!1};import{execFile as JV}from"node:child_process";import{readFile as XV}from"node:fs/promises";import{homedir as zV,platform as qV}from"node:os";import{promisify as QV}from"node:util";var eK=QV(JV),tK="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",fx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nK=async e=>{let t;try{t=await XV(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(!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}}},rK=async(e=async()=>(await eK("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(qV()==="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(`${tK}=(\\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"},oK=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",ru=(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."}},mx=async(e={})=>{let{installedVariant:t=Uo,receiptMode:n=nl,awaitingReload:r=tl,readSettings:o=nK,probeBridge:a=rK,home:s=zV()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:ru("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.":ru("not-applicable","unknown")}}let l=await o(xs(i)),d=await a(),u=oK({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:ru(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:ru("not-applicable","unknown")}}};var qt="connect",ou=e=>e.replace(/-/g,"_"),hx=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=ou(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":ou(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:ou(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)if(i.installed){if(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp){let c=!i.mcp.registered&&!i.routingHeld;t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing",...c&&i.mcp.reason?{errorClass:ou(i.mcp.reason)}:{}})}a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"})}return t.push({tool:qt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function iK(){return Ae}var cK="ctx_doctor-probe-synthetic",lK=(e,t={mode:"unknown",ssoLink:null})=>{if(e.ok||e.kind==="not-found")return{kind:"ok",detail:"Retrieval loop healthy: gateway answered, key authorized, optimizer retrieval wired.",remedy:[]};switch(e.kind){case"auth":return{kind:"auth",detail:"The gateway rejected the retrieval call (no valid personal key).",remedy:[`Fix: ${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 dK(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function uK(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=>$d({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),hy=e=>e.pointedAt===!1&&e.tombstoned!==!0&&yx(e)!=="unverifiable",gx=e=>e.registered&&e.command&&sK(e.command)?aK(e.command):null,pK=e=>{switch(e.mcp?.reason){case"ephemeral-runtime":return"this Connect is running from a temporary npx/cache path, so a registration naming it would rot \u2014 install it durably (`curl -fsSL https://app.anyray.ai/connect.sh | sh`) and re-run.";case"no-config":return`${e.title} has not written its config yet \u2014 launch it once, then re-run \`anyray-connect\`.`;case"stale":return"the entry was written by an older Connect \u2014 re-run `anyray-connect` to refresh it.";case"foreign":return"an MCP server named `anyray` that Connect did not write is already there, and it was left untouched. Rename or remove it, then re-run `anyray-connect`.";case"unreadable":return`${e.title}'s config could not be read or parsed \u2014 repair it (or check its permissions), then re-run \`anyray-connect\`.`;case"absent":return"re-run `anyray-connect` to register it.";default:return"re-run `anyray-connect` to register it."}},yy=e=>(hy(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),fK=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,mK=async(e,t)=>{if(e.length===0)return!1;for(let n of e){let r=t.find(a=>a.id===n);if(!r?.inferenceAuthLanes)return!1;let o=await r.inferenceAuthLanes().catch(()=>["unknown"]);if(o.length===0||o.some(a=>a!=="subscription"&&a!=="native"))return!1}return!0},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},hK=(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},yK=async(e,t,n,r,o,a,s=n,i=_i,c=!0,l=Po,d=wo,u=It,p=Sa)=>{let f=c?await Xd(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=uK({ssoLink:b,enrolledViaToken:!!t.enrolledTokenHash}),C=gt(),S=await Mw(C),I=S?[]:Nc(xe({origin:e})),E=[];for(let j of r){let _e=await j.detect(),ke=null;if(_e.installed&&j.mcpStatus)try{let Ka=await j.mcpStatus();ke={...Ka,commandOk:gx(Ka)}}catch{}let Xe=_e.installed&&j.id===Ra?await o():void 0,pt=_e.installed&&j.pointsAt?await j.pointsAt(e):null,_r=await fK(pt,j,t.managedTools??[]),Gi=pt===!1&&_r===null,Ua=_r===!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:Ga}=Vi,Va=t.fleetToolPolicy,ko=Va?.enabled.includes(j.id)?Va.tiers?.[j.id]??wa:void 0;E.push({id:j.id,title:j.title,installed:_e.installed,..._e.detail?{detail:_e.detail}:{},pointedAt:_r,...Gi?{routingHeld:!0}:{},...Ua?{routingPendingReload:!0}:{},...Ha.length?{routingOverrides:Ha}:{},...Ga===void 0?{}:{claudeCodeHookPolicy:Ga},mcp:ke,...ko?{policyTier:ko}:{},...t.revertedTools?.includes(j.id)?{tombstoned:!0}:{},...j.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...Xe===void 0?{}:{inferenceIntrospectable:Xe.authoritative,...Xe.authoritative?{}:{inferenceUnverifiableReason:Xe.reason}}})}let T=s?await(async()=>{let{kind:j,detail:_e,remedy:ke}=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:ke}})():null,O=T?.kind==="provider-rejected"&&await mK(t.managedTools??[],r),F=T?{...T,...O?{notApplicableSubscription:!0}:{}}:null,q=n?lK(await va({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:ue({user:t.name,team:t.team})},cK,{probe:!0}),{mode:k,ssoLink:b}):null,de=await u().catch(()=>({})),ce=An(de.hookLane),K=s?await wx(r):!1,ge=K?await(async()=>{let j=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...wh(j,{hookRegistered:K,neverInvoked:yh(ce,Date.now())}),lastInvokedAt:kd(ce)}})():null,me=(await or()).map(j=>({adapter:j.adapter,op:j.op,requestedAt:j.requestedAt,watcherAlive:sr(j.watcherPid)})),W=me.find(j=>j.adapter==="cursor"),Z=W?{op:W.op,requestedAt:W.requestedAt,watcherAlive:W.watcherAlive}:null,X=!!t.refreshSchedulerEnabled,Je=await _o(),We=await d(),_=t.persistenceOwner==="tray",L=_?await l(t)==="healthy":null,J=await Sw({schedulerEnabled:X&&!_,schedulerInstalled:Je,binaryDurable:!He(tr())}),pe=0;f&&!f.reachable&&(pe+=1),_?X&&!L&&(pe+=1):X&&!Je&&(pe+=1);for(let j of E)pe+=yy(j);F&&F.kind!=="ok"&&!F.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 mx();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:iK(),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:Je,owner:_?"tray":"os",..._?{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:Ad(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Z,pendingOps:me,ambientRepairs:hK(de,r),verify:F,retrieval:q,hookLane:ge,agentsWindow:ut,problems:pe}},gK=e=>{if(e.serviceRemoval.suspected){H("Endpoint security"),P(" Anyray installed these background services, but their files are gone from disk \u2014"),P(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),P(" 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."))}},wK=e=>{switch(A(V("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(H("Environment"),A(` Remote dev context: ${To(e.connect.remoteContext)}`),In(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."))),H("CLI updates"),e.connect.selfUpdate.state){case"managed":B(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||P(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":P(" 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":P(" Self-update is unavailable on this platform because no standalone binary is published."),A(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":A(v(" This copy is externally managed; update it with the method that installed it."));break;case"container":A(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(H("Gateway"),e.gateway.reachable===null?A(v(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?B(` Reachable: ${e.gateway.origin} ${v(`(${e.gateway.detail})`)}`):(R(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),A(v(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.refreshScheduler.enabled&&(H("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?B(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."):(R(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),A(v(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?B(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(R(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||A(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),gK(e),H("Personal key"),dK(e)){case"env":B(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":B(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":P(" 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:P(" 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?P(` Enrollment cert expired ${v(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):B(` Enrollment cert valid until ${e.enrollment.expiresAt} ${v(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(H("Shell"),R(" This terminal still exports Anyray, but the config is gone."),A(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),A(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),A(v(" Anything you start from this terminal keeps reaching the gateway with")),A(v(" no credential, and fails with 401.")),A(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),A(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),A(v(" reuses the environment it captured at launch, so a new terminal")),A(v(" (or Reload Window) keeps serving the old one.")));let t=e.tools.find(c=>c.installed&&c.claudeCodeHookPolicy!==void 0&&c.claudeCodeHookPolicy!=="fine");if(t?.claudeCodeHookPolicy){let c={state:t.claudeCodeHookPolicy};H("Claude Code hook policy"),R(` ${sc(c)}.`),A(v(` ${ic(c)}`))}H("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])R(` ${c.title}: ${l.problem}.`),A(v(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(R(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),A(v(" Fix: re-run `anyray-connect` to re-register the current binary."))):B(` ${c.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(P(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),A(v(` Fix: ${pK(c)}`))))};for(let c of e.tools){if(!c.installed){A(v(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){A(v(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){B(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}B(` ${c.title}: pointed at ${e.gateway.origin}`),o(c),c.id==="claude-code"&&A(v(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===Ra&&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=Md(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});P(` ${c.title}: ${d.headline}`);for(let u of d.detail)A(v(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(P(` ${c.title}: reverted locally against admin policy (out of compliance)`),A(v(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?P(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):A(v(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(R(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),A(v(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(R(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),A(v(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(P(" No tools are pointed at this gateway yet."),A(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){H("Queued operations");for(let c of e.pendingOps){let l=mt(c.adapter)?.title??c.adapter;c.watcherAlive?P(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(R(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),A(v(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){H("Ambient repairs");let c=l=>l==="hook_registration"?"hook re-installed":l==="mcp_registration"?"MCP registration re-installed":"hook binary repaired";for(let l of e.ambientRepairs){let d=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(p):A(p)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){H("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&&P(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(H("Auth probe"),e.verify.notApplicableSubscription)B(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")B(` ${e.verify.detail}`);else{R(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)A(v(` ${c}`))}if(e.retrieval)if(H("Retrieval loop"),e.retrieval.kind==="ok")B(` ${e.retrieval.detail}`);else{R(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)A(v(` ${c}`))}if(e.hookLane){if(H("Hook lane"),e.hookLane.verdict==="live")B(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){R(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}else{P(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}e.hookLane.lastInvokedAt!==null&&A(v(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(H("VS Code Agents window"),P(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(H("VS Code Agents window"),B(` ${e.agentsWindow.detail}`)),H("Summary"),e.problems===0?(e.verify?B(" No problems found."):B(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),A(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):R(` ${e.problems} problem(s) found \u2014 see fixes above.`)},bK=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??Sa,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 wx(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:kd(c)},note:d}},CK=async(e,t,n={})=>{let r=n.adapters??le,o=n.resolveTarget??Be,a=n.applyTools??Bt,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&&(hy(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],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(O=>O.id===g.id);if(!b)continue;let k=r.find(O=>O.id===g.id),C=b.mcp;if(k?.mcpStatus)try{let O=await k.mcpStatus();C={...O,commandOk:gx(O)}}catch{}let S=hy(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 O=await k.runtimeDiagnostics();I=O.routingOverrides.length?O.routingOverrides:void 0,E=O.claudeCodeHookPolicy}catch{}else if(k?.routingOverrides)try{let O=await k.routingOverrides();I=O.length?O:void 0}catch{}let T={...b,pointedAt:S,mcp:C,...I?{routingOverrides:I}:{},...E===void 0?{}:{claudeCodeHookPolicy:E}};I||delete T.routingOverrides,E===void 0&&delete T.claudeCodeHookPolicy,w.set(g.id,T),y+=yy(b)-yy(T)}return{entries:p,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:f}},kK=e=>{H("Repair"),e.entries.length===0&&B(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?B(` ${t.title}: re-applied`):t.status==="queued"?B(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?A(v(` ${t.title}: ${t.status}`)):R(` ${t.title}: ${t.status}`);for(let t of e.notes)A(v(` ${t}`))},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 Iw())A(c?` ${c}`:"")}return 0}let r;try{r=Sr(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")),R(` Gateway URL: ${c.message}`),A(v(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.silent||(e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(A(V("Anyray connect \u2014 doctor")),R(" --quick skips the network probes; it cannot be combined with --verify."))),1;let o=!e.noVerify&&!e.quick,a=await yK(r,n,!!e.verify&&!e.quick,t.adapters??le,t.inferenceIntrospection??Nd,t.fleetBootstrap??Cr,o,t.verifyAuth??_i,!e.quick,t.checkTray??Po,t.updateStatus??wo,t.readRefreshState??It,t.probeHookLane??Sa),s=e.repair?await CK(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(bK(i),null,2)):(wK(i),s&&kK(s)));try{e.quick||await(t.reportHealth??XS)(hx(i),i.connect.version)}catch{}return i.problems===0?0:1};var vK=()=>{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=Sr(e.gateway,t)}catch(s){return R(s.message),1}$(`Gateway: ${n}`);let r=VI(t.clientKey,"anyray-placeholder"),o;try{o=await Aa(n,r)}catch(s){return R(`Team policy sync failed: ${dh(s)}`),1}let a=vK();if(a.length===0)SK();else if(o.skills.length===0)$("No team skills published yet \u2014 nothing to sync.");else{let s=await $S(o,a,t.syncedSkills??{});H("Skills");for(let i of s.results)i.written?B(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):$(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await ae({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){$(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}H("Summary"),A(` ${et(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Ca(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},SK=()=>{$("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as R2}from"node:zlib";import{promisify as O2}from"node:util";var Rr={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=>`
|
|
690
|
+
`){y({kind:"ok",values:e.items.filter((E,T)=>a[T]).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 QE=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],iV=80,Ei=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&ha(r,n.env??process.env)))return r.write(`${e}
|
|
691
|
+
`),t();let a=0,s=()=>{r.write(`\r${QE[a++%QE.length]} ${e}`)};s();let i=setInterval(s,iV);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as cV}from"node:fs";import{spawnSync as ex}from"node:child_process";import{chmod as tx,copyFile as ry,lstat as oy,mkdir as ay,readdir as tu,realpath as eu,rename as zd,rm as Et,stat as nx,symlink as lV,writeFile as dV}from"node:fs/promises";import{createHash as uV}from"node:crypto";import{basename as qd,dirname as Rr,join as Fe}from"node:path";import{Readable as pV}from"node:stream";import{pipeline as fV}from"node:stream/promises";var rx="https://github.com/anyrayHQ/install/releases",ox="connect-v",mV=new RegExp(`/releases/tag/${ox}([0-9][0-9A-Za-z.-]*)$`),hV=300*1024*1024,Oi=1e4,yV=5*6e4,gV=360*6e4,wV=30*6e4,Pa=(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)},ax=(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"}},bV=e=>{if(e)return mV.exec(e.trim())?.[1]},sy=(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()}},sx=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&&Pa(e.current,e.minVersion)<0&&Pa(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},AV=e=>Pa(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}:{...sx(e),downgradeBlocked:!1},Da=()=>process.platform==="win32"?"anyray-connect.exe":"anyray-connect",CV=(e=process.execPath)=>{let t=Hu(e);return t?Rr(t):Rr(Rr(e))},kV=async(e=ft())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=Fe(CV(e.execPath),"bin",Da());try{if(await eu(t)!==await eu(e.execPath))return}catch{return}return t},iy=async(e=ft(),t=Q())=>{let n=await kV(e);if(n)return{kind:"managed",root:Rr(Rr(n)),link:n,entryPath:Zn(e)};let r=Zn(e);return Vu(r,t)?{kind:"durable",root:t,entryPath:r}:Wu(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},nu=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),t);try{return await fetch(e,{...n,signal:r.signal})}finally{clearTimeout(o)}},cy=async(e=Oi)=>{let t=await nu(`${rx}/latest`,e,{redirect:"manual"});return bV(t.headers.get("location"))},vV=async e=>{try{let t=await nu(`${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"}},ly=async(e,t,n)=>{let r=await nu(e,yV);if(!r.ok||!r.body)throw new Ri(r.status);let o=uV("sha256"),a=0;if(await fV(pV.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>hV)throw new Error("asset exceeds size cap");o.update(c),yield c}},cV(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},SV=e=>qd(e)===Da()?qd(Rr(e)):qd(e),IV=async e=>{let t=await tu(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await Et(Fe(e,n),{force:!0}).catch(()=>{})},ix=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await Et(r,{force:!0}).catch(()=>{});let o=!1;try{await zd(e,r),o=!0}catch{}try{await ry(t,e),await dV(qa(e),SV(t))}catch(a){throw o&&await zd(r,e).catch(()=>{}),a}await Et(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await Et(n,{force:!0}),await lV(t,n),await zd(n,e)},EV=".anyray",dy=(e,t)=>e===t||qd(e)===EV?448:493,xi=async(e,t)=>{let n=(await nx(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await tx(e,n&4095|t).catch(()=>{})},Qd=async(e,t)=>{await ay(e,{recursive:!0,mode:t}),await xi(e,t)},xV=async(e,t,n)=>{let r=dy(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 tu(o).catch(()=>[]))await xi(Fe(o,a),r)}await(n.refreshDesktopHelpers??Gd)(t)},RV=async(e,t={})=>{let n=Fe(e.root,"bin"),r=Fe(e.root,"versions"),o=Fe(n,Da()),a=dy(e.root,(t.privateRoot??Q)());await Qd(n,a),await Qd(r,a);let s=Fe(r,e.version),c=(await oy(s).catch(()=>{}))?.isFile()?s:Fe(s,Da());if(!(await oy(c).catch(()=>{}))?.isFile()){let d=await(t.fetchResponse??nu)(`${e.tagUrl}/SHA256SUMS`,Oi),u=d.ok?sy(await d.text(),e.asset):void 0;if(!u)throw new Error("no published checksum");await Qd(Rr(c),a),await IV(Rr(c));let p=`${c}.part-${process.pid}`;try{await(t.download??ly)(`${e.tagUrl}/${e.asset}`,p,u),await tx(p,493),await zd(p,c)}catch(f){throw await Et(p,{force:!0}).catch(()=>{}),f}}return await(t.activate??ix)(o,c),{link:o,target:c,versionsDir:r}},OV=async e=>{ex(e.target,[Wd,e.link],{stdio:"ignore",timeout:Oi})},TV=async e=>{let t=ex(e,["--version"],{stdio:"ignore",timeout:Oi});return!t.error&&t.status===0},_V=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??Bt)(r,o.target)).every(po))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&!(await(t.installScheduler??rr)()).ok)},PV=async e=>{let t=await e.install();if(!await(e.smoke??TV)(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},DV=async(e,t)=>{let n=await tu(e).catch(()=>[]);for(let r of n)t.includes(r)||await Et(Fe(e,r),{force:!0,recursive:!0}).catch(()=>{})},LV=async e=>{let t=await tu(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await Et(Fe(e,n),{force:!0}).catch(()=>{})},NV=async(e,t)=>{let n=async()=>{await Et(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await ay(e,{recursive:!1}),n}catch{}let r=await nx(e).catch(()=>{});if(!(!r||t-r.mtimeMs<wV)){await n();try{return await ay(e,{recursive:!1}),n}catch{return}}},ny=e=>Fe(e,"update-state.json"),$V=async e=>{let t=await M(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},La=async(e={})=>{let t=e.now??Date.now,n=Ae;if(In(nn(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??ft(),o=e.root??Q(),a;try{let s=await iy(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 xV(o,s.link,e).catch(()=>{});let u=ax(e.platform??process.platform,e.arch??process.arch);if(!u)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??cy)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let p=a;if(!i&&p===n)return{outcome:"current",current:n,latest:p};if(i&&Pa(p,n)<0)return{outcome:"migration-deferred",current:n,latest:p};let f=await $V(ny(o));if((e.respectFailureBackoff===!0||!c)&&f.failedVersion===p&&f.failedAt!==void 0&&t()-f.failedAt<gV)return{outcome:"failed",current:n,latest:p};let m=`${rx}/download/${ox}${p}`,h=d||c?void 0:await(e.minimumVersion??vV)(m),w={current:n,latest:p,autoUpdate:d,forced:c,minVersion:h},y=i?AV(w):{...sx(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 Qd(o,dy(o,Q()));let g=await NV(Fe(o,"update.lock"),t());if(!g)return{outcome:i?"migration-available":"available",current:n,latest:p};let b,k;try{await LV(Fe(o,"bin"));let C=await eu(Fe(o,"versions")).catch(()=>{}),S=await eu(Fe(o,"bin",Da())).catch(()=>{}),I=S&&Qi(S,C)?S:void 0,E=Fe(o,"bin",Da());i&&process.platform==="win32"&&(await oy(E).catch(()=>{}))?.isFile()&&(k=`${E}.rollback-${process.pid}`,await ry(E,k));let T=()=>(e.installBinary??RV)({root:o,version:p,asset:u,tagUrl:m});i?b=await PV({install:T,smoke:e.smoke,rollback:async({link:O,target:F})=>{k?(await ry(k,O),await Et(qa(O),{force:!0}).catch(()=>{})):I&&I!==F?await ix(O,I):(await Et(O,{force:!0}),await Et(qa(O),{force:!0}).catch(()=>{}))},repoint:async O=>e.repoint?e.repoint(l,O):_V(l),prune:async()=>{await(e.pruneDurable??(O=>ec(O)))(r)}}):b=await T(),await DV(b.versionsDir,[p,n]),await(e.refreshHelpersFromInstalled??OV)(b).catch(()=>{}),await Et(ny(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(ny(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},cx=async(e={})=>{let t=e.context??ft(),n=await iy(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}:La({...e,context:t,allowNpmMigration:!0})},wo=async(e={})=>{let t=e.context??ft(),n=e.root??Q(),r=await iy(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&&!!ax(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=In(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 lx}from"zod";var MV=5e3,BV=lx.object({lane:lx.enum(["subscription","org"]).optional().catch(void 0)}),dx=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??MV);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)}},ux=(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 FV=12e3,WV="anyray-wiring-probe-not-a-real-token",UV={model:"anyray-default",messages:[{role:"user",content:"ping"}],max_tokens:1},py={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},fx=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},fy=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},px=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."],HV=e=>e.includes("no provider key configured for"),my=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},hy=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."]}),GV=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:HV(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")?px([" \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?my(t)?hy(e):fy(t)?Ti(e):fx(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).",...px([" \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:[]},VV=(e,t)=>{if(fy(t))return Ti(e);if(my(t))return hy(e);if(fx(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:[]}},KV=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),jV=(e,t)=>{if(fy(t))return Ti(e);if(my(t))return hy(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")||KV(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 (${py.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."]}},uy=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)}},ZV=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)}},YV=(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??FV,r=ue(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await ZV(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 uy(`${e.anthropicBaseUrl}/v1/messages`,l,py,n);return jV(d,u)}if(ee(e,"anthropic")){let l={Authorization:`Bearer ${WV}`,"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 uy(`${e.anthropicBaseUrl}/v1/messages`,l,py,n);return VV(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await uy(`${e.openaiBaseUrl}/chat/completions`,s,UV,n);return GV(i,c,t.tools??[])}catch(o){return YV(n,o)}};var mx=async e=>{let t=await D(),n;try{n=Ir(e.gateway,t)}catch(o){return A(V("Anyray connect \u2014 status")),$(`Gateway: ${o.message}`),0}A(V("Anyray connect \u2014 status")),H("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)"),H("Identity"),A(` Name: ${t.name??v("(not set)")}`),A(` Team: ${t.team??v("(not set)")}`);let r=nn();r&&(H("Environment"),A(` Remote dev context: ${To(r)}`),In(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&&(H("Credential renewal"),B(" Direct gateway routing with a proof-backed key heartbeat."),$(" Renewal extends the same key; tool configuration is not rewritten.")),H("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")){B(` ${o.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}B(` ${o.title}: pointed at Anyray`)}else{let i=null,c=null;if(o.id===Ra&&o.mcpStatus)try{let l=(await o.mcpStatus()).registered,d=await Nd();i=$d({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=Md(i,c);P(` ${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 dK}from"node:fs";import{isAbsolute as uK}from"node:path";import{access as JV}from"node:fs/promises";import{constants as XV}from"node:fs";import{platform as zV}from"node:os";var qV=async e=>{try{return await JV(e,XV.F_OK),!0}catch{return!1}},QV=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??zV(),n=e.exists??qV;for(let r of QV(t))if(await n(r))return!0;return!1};import{execFile as eK}from"node:child_process";import{readFile as tK}from"node:fs/promises";import{homedir as nK,platform as rK}from"node:os";import{promisify as oK}from"node:util";var aK=oK(eK),sK="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",hx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iK=async e=>{let t;try{t=await tK(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(!hx(n))return{readable:!1};let r=n[dn],o=n[un];return{readable:!0,supportsAnyray:hx(r)?r[z]===!0:void 0,bridgeEnabled:typeof o=="boolean"?o:void 0}}catch{return{readable:!1}}},cK=async(e=async()=>(await aK("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(rK()==="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(`${sK}=(\\w*)`).exec(r);if(!o)continue;let a=r.replace(/\bVSCODE_[A-Z0-9_]*=\S*/g,"");if(/Code Helper|MacOS\/Code|VSCodium|Visual Studio Code|agentHost/i.test(a)&&(n=!0,o[1]==="true"))return"on"}return n?"off":"unknown"},lK=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",ru=(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."}},yx=async(e={})=>{let{installedVariant:t=Uo,receiptMode:n=nl,awaitingReload:r=tl,readSettings:o=iK,probeBridge:a=cK,home:s=nK()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:ru("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.":ru("not-applicable","unknown")}}let l=await o(xs(i)),d=await a(),u=lK({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:ru(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:ru("not-applicable","unknown")}}};var qt="connect",ou=e=>e.replace(/-/g,"_"),gx=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=ou(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":ou(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:ou(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)if(i.installed){if(i.pointedAt!==null?t.push({tool:i.id,checkId:"routing",status:i.inferenceIntrospectable===!1&&i.pointedAt===!1?"held":i.pointedAt?i.routingOverrides?.some(c=>c.bypass!==!1)?"bypassed":"ok":i.routingPendingReload?"reload_required":"fail"}):i.routingHeld&&t.push({tool:i.id,checkId:"routing",status:"held"}),i.inferenceUnverifiableReason==="managed-policy"&&t.push({tool:i.id,checkId:"machine_policy",status:"blocked"}),i.mcp){let c=!i.mcp.registered&&!i.routingHeld;t.push({tool:i.id,checkId:"mcp_registration",status:i.mcp.registered?i.mcp.commandOk===!1?"command_gone":"ok":i.routingHeld?"held":"missing",...c&&i.mcp.reason?{errorClass:ou(i.mcp.reason)}:{}})}a.has(i.id)?t.push({tool:i.id,checkId:"fleet_compliance",status:"reverted_required"}):s.has(i.id)&&t.push({tool:i.id,checkId:"fleet_compliance",status:"ok"})}return t.push({tool:qt,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};function pK(){return Ae}var fK="ctx_doctor-probe-synthetic",mK=(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: ${wy(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 hK(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function yK(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function wy(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 wx=e=>$d({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),yy=e=>e.pointedAt===!1&&e.tombstoned!==!0&&wx(e)!=="unverifiable",bx=e=>e.registered&&e.command&&uK(e.command)?dK(e.command):null,gK=e=>{switch(e.mcp?.reason){case"ephemeral-runtime":return"this Connect is running from a temporary npx/cache path, so a registration naming it would rot \u2014 install it durably (`curl -fsSL https://app.anyray.ai/connect.sh | sh`) and re-run.";case"no-config":return`${e.title} has not written its config yet \u2014 launch it once, then re-run \`anyray-connect\`.`;case"stale":return"the entry was written by an older Connect \u2014 re-run `anyray-connect` to refresh it.";case"foreign":return"an MCP server named `anyray` that Connect did not write is already there, and it was left untouched. Rename or remove it, then re-run `anyray-connect`.";case"unreadable":return`${e.title}'s config could not be read or parsed \u2014 repair it (or check its permissions), then re-run \`anyray-connect\`.`;case"absent":return"re-run `anyray-connect` to register it.";default:return"re-run `anyray-connect` to register it."}},gy=e=>(yy(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),wK=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,bK=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},Ax=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},AK=(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},CK=async(e,t,n,r,o,a,s=n,i=_i,c=!0,l=Po,d=wo,u=It,p=Sa)=>{let f=c?await Xd(e):null,m=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,h=j=>j&&_h(j)?"machine_default":null,w=t.enrolledCert?.payload,y=w?.expiresAt??t.enrolledCertExpiry??null,b=(await a())?.sso??null,k=yK({ssoLink:b,enrolledViaToken:!!t.enrolledTokenHash}),C=gt(),S=await Fw(C),I=S?[]:Nc(xe({origin:e})),E=[];for(let j of r){let _e=await j.detect(),ke=null;if(_e.installed&&j.mcpStatus)try{let Ka=await j.mcpStatus();ke={...Ka,commandOk:bx(Ka)}}catch{}let Xe=_e.installed&&j.id===Ra?await o():void 0,pt=_e.installed&&j.pointsAt?await j.pointsAt(e):null,Pr=await wK(pt,j,t.managedTools??[]),Gi=pt===!1&&Pr===null,Ua=Pr===!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:Ga}=Vi,Va=t.fleetToolPolicy,ko=Va?.enabled.includes(j.id)?Va.tiers?.[j.id]??wa:void 0;E.push({id:j.id,title:j.title,installed:_e.installed,..._e.detail?{detail:_e.detail}:{},pointedAt:Pr,...Gi?{routingHeld:!0}:{},...Ua?{routingPendingReload:!0}:{},...Ha.length?{routingOverrides:Ha}:{},...Ga===void 0?{}:{claudeCodeHookPolicy:Ga},mcp:ke,...ko?{policyTier:ko}:{},...t.revertedTools?.includes(j.id)?{tombstoned:!0}:{},...j.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...Xe===void 0?{}:{inferenceIntrospectable:Xe.authoritative,...Xe.authoritative?{}:{inferenceUnverifiableReason:Xe.reason}}})}let T=s?await(async()=>{let{kind:j,detail:_e,remedy:ke}=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:ke}})():null,O=T?.kind==="provider-rejected"&&await bK(t.managedTools??[],r),F=T?{...T,...O?{notApplicableSubscription:!0}:{}}:null,q=n?mK(await va({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:ue({user:t.name,team:t.team})},fK,{probe:!0}),{mode:k,ssoLink:b}):null,de=await u().catch(()=>({})),ce=An(de.hookLane),K=s?await Ax(r):!1,ge=K?await(async()=>{let j=await p().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...bh(j,{hookRegistered:K,neverInvoked:gh(ce,Date.now())}),lastInvokedAt:kd(ce)}})():null,me=(await ar()).map(j=>({adapter:j.adapter,op:j.op,requestedAt:j.requestedAt,watcherAlive:ir(j.watcherPid)})),W=me.find(j=>j.adapter==="cursor"),Z=W?{op:W.op,requestedAt:W.requestedAt,watcherAlive:W.watcherAlive}:null,X=!!t.refreshSchedulerEnabled,Je=await _o(),We=await d(),_=t.persistenceOwner==="tray",L=_?await l(t)==="healthy":null,J=await Ew({schedulerEnabled:X&&!_,schedulerInstalled:Je,binaryDurable:!He(nr())}),pe=0;f&&!f.reachable&&(pe+=1),_?X&&!L&&(pe+=1):X&&!Je&&(pe+=1);for(let j of E)pe+=gy(j);F&&F.kind!=="ok"&&!F.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 yx();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:pK(),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:Je,owner:_?"tray":"os",..._?{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:Ad(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Z,pendingOps:me,ambientRepairs:AK(de,r),verify:F,retrieval:q,hookLane:ge,agentsWindow:ut,problems:pe}},kK=e=>{if(e.serviceRemoval.suspected){H("Endpoint security"),P(" Anyray installed these background services, but their files are gone from disk \u2014"),P(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),P(" 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."))}},vK=e=>{switch(A(V("Anyray connect \u2014 doctor")),e.connect.remoteContext&&(H("Environment"),A(` Remote dev context: ${To(e.connect.remoteContext)}`),In(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."))),H("CLI updates"),e.connect.selfUpdate.state){case"managed":B(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.autoUpdate||P(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":P(" 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":P(" Self-update is unavailable on this platform because no standalone binary is published."),A(v(" Use `npx anyray-connect@latest` to stay current."));break;case"unmanaged":A(v(" This copy is externally managed; update it with the method that installed it."));break;case"container":A(v(" Self-update is off in this container; updates arrive when it is rebuilt."));break}switch(H("Gateway"),e.gateway.reachable===null?A(v(` Probe skipped (--quick): ${e.gateway.origin} not contacted.`)):e.gateway.reachable?B(` Reachable: ${e.gateway.origin} ${v(`(${e.gateway.detail})`)}`):(R(` Unreachable: ${e.gateway.origin} (${e.gateway.detail})`),A(v(" Fix: start the gateway, or check the URL with `anyray-connect status`."))),e.refreshScheduler.enabled&&(H("Automatic key refresh"),e.refreshScheduler.owner==="tray"?e.refreshScheduler.trayHealthy?B(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh."):(R(" The Anyray Connect app owns the background services on this machine, but it is missing or no longer passes its signature check."),A(v(" Fix: run `anyray-connect` to restore the background services (it reinstalls the OS schedule and clears the app takeover)."))):e.refreshScheduler.installed?B(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):(R(" Enabled but the OS schedule is missing \u2014 a long session can still 401 when your key lapses."),e.serviceRemoval.kinds.includes("scheduler")||A(v(" Fix: re-run `anyray-connect` to reinstall it, or `anyray-connect --no-key-refresh` to opt out.")))),kK(e),H("Personal key"),hK(e)){case"env":B(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":B(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":P(" 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:P(" Enrollment required \u2014 no personal gateway key is available."),A(v(` Fix: ${wy(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?P(` Enrollment cert expired ${v(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):B(` Enrollment cert valid until ${e.enrollment.expiresAt} ${v(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(H("Shell"),R(" This terminal still exports Anyray, but the config is gone."),A(v(` Still set here: ${e.shell.staleExports.join(", ")}`)),A(v(` No Anyray block in ${e.shell.profilePath} \u2014 so these came from before a revert.`)),A(v(" Anything you start from this terminal keeps reaching the gateway with")),A(v(" no credential, and fails with 401.")),A(v(` Fix: unset ${e.shell.staleExports.join(" ")}`)),A(v(" Or open a new terminal. In VS Code, quit the app entirely (Cmd+Q) \u2014 it")),A(v(" reuses the environment it captured at launch, so a new terminal")),A(v(" (or Reload Window) keeps serving the old one.")));let t=e.tools.find(c=>c.installed&&c.claudeCodeHookPolicy!==void 0&&c.claudeCodeHookPolicy!=="fine");if(t?.claudeCodeHookPolicy){let c={state:t.claudeCodeHookPolicy};H("Claude Code hook policy"),R(` ${sc(c)}.`),A(v(` ${ic(c)}`))}H("Tools");let n=!1,r=!1,o=c=>{for(let l of c.routingOverrides??[])R(` ${c.title}: ${l.problem}.`),A(v(` ${l.fix}`))},a=c=>{c.mcp&&(c.mcp.registered?c.mcp.commandOk===!1?(R(` ${c.title}: retrieval MCP server registered, but its binary is gone (${c.mcp.command}).`),A(v(" Fix: re-run `anyray-connect` to re-register the current binary."))):B(` ${c.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(P(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),A(v(` Fix: ${gK(c)}`))))};for(let c of e.tools){if(!c.installed){A(v(` ${c.title}: not installed (skipped)`));continue}if(c.pointedAt===null){A(v(` ${c.title}: installed (config not introspectable)`)),a(c);continue}if(c.pointedAt){if(n=!0,c.id==="cursor"&&c.nativeSubscription){B(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}B(` ${c.title}: pointed at ${e.gateway.origin}`),o(c),c.id==="claude-code"&&A(v(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===Ra&&A(v(` ${MC}`)),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=wx(c);if(l==="not-routed"||l==="unverifiable"){let d=Md(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});P(` ${c.title}: ${d.headline}`);for(let u of d.detail)A(v(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(P(` ${c.title}: reverted locally against admin policy (out of compliance)`),A(v(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?P(` ${c.title}: reverted locally but locked by admin policy \u2014 the next reconcile re-applies it`):A(v(` ${c.title}: reverted by you (not managed) \u2014 re-enroll with \`anyray-connect --tools ${c.id}\``)):c.routingPendingReload?(R(` ${c.title}: configured, but ${c.title} is still running the previous Anyray build`),A(v(" Fix: reload the app completely (quit and reopen \u2014 a window reload is not enough), then re-run `anyray-connect`."))):(R(` ${c.title}: installed but not pointed at ${e.gateway.origin}`),A(v(" Fix: run `anyray-connect` to (re)configure it.")))}}let s=(e.repairs?.length??0)>0;if(!n&&!r&&!s&&e.problems===0&&(P(" No tools are pointed at this gateway yet."),A(v(" Fix: run `anyray-connect` to configure your tools."))),e.pendingOps.length>0){H("Queued operations");for(let c of e.pendingOps){let l=mt(c.adapter)?.title??c.adapter;c.watcherAlive?P(` ${l} ${c.op} queued since ${c.requestedAt} \u2014 completes automatically when ${l} quits.`):(R(` ${l} ${c.op} queued since ${c.requestedAt}, but its watcher is not running.`),A(v(` Fix: quit ${l} and re-run \`anyray-connect\` to complete it.`)))}}if(e.ambientRepairs.length>0){H("Ambient repairs");let c=l=>l==="hook_registration"?"hook re-installed":l==="mcp_registration"?"MCP registration re-installed":"hook binary repaired";for(let l of e.ambientRepairs){let d=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(p):A(p)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){H("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&&P(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(H("Auth probe"),e.verify.notApplicableSubscription)B(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")B(` ${e.verify.detail}`);else{R(` ${e.verify.kind}: ${e.verify.detail}`);for(let c of e.verify.remedy)A(v(` ${c}`))}if(e.retrieval)if(H("Retrieval loop"),e.retrieval.kind==="ok")B(` ${e.retrieval.detail}`);else{R(` ${e.retrieval.kind}: ${e.retrieval.detail}`);for(let c of e.retrieval.remedy)A(v(` ${c}`))}if(e.hookLane){if(H("Hook lane"),e.hookLane.verdict==="live")B(` ${e.hookLane.detail}`);else if(e.hookLane.verdict==="dark"){R(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}else{P(` ${e.hookLane.reason}: ${e.hookLane.detail}`);for(let c of e.hookLane.remedy)A(v(` ${c}`))}e.hookLane.lastInvokedAt!==null&&A(v(` Last hook run: ${new Date(e.hookLane.lastInvokedAt).toISOString()}`))}e.agentsWindow&&e.agentsWindow.state!=="not-applicable"&&e.agentsWindow.state!=="ready"?(H("VS Code Agents window"),P(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(H("VS Code Agents window"),B(` ${e.agentsWindow.detail}`)),H("Summary"),e.problems===0?(e.verify?B(" No problems found."):B(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),A(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):R(` ${e.problems} problem(s) found \u2014 see fixes above.`)},SK=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}),IK=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!mh(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??Sa,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=bh(i,{hookRegistered:await Ax(t.adapters??le).catch(()=>!1),neverInvoked:gh(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}},EK=async(e,t,n={})=>{let r=n.adapters??le,o=n.resolveTarget??Be,a=n.applyTools??Bt,s=await IK(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&&(yy(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 ${wy(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(O=>O.id===g.id);if(!b)continue;let k=r.find(O=>O.id===g.id),C=b.mcp;if(k?.mcpStatus)try{let O=await k.mcpStatus();C={...O,commandOk:bx(O)}}catch{}let S=yy(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 O=await k.runtimeDiagnostics();I=O.routingOverrides.length?O.routingOverrides:void 0,E=O.claudeCodeHookPolicy}catch{}else if(k?.routingOverrides)try{let O=await k.routingOverrides();I=O.length?O:void 0}catch{}let T={...b,pointedAt:S,mcp:C,...I?{routingOverrides:I}:{},...E===void 0?{}:{claudeCodeHookPolicy:E}};I||delete T.routingOverrides,E===void 0&&delete T.claudeCodeHookPolicy,w.set(g.id,T),y+=gy(b)-gy(T)}return{entries:p,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:f}},xK=e=>{H("Repair"),e.entries.length===0&&B(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?B(` ${t.title}: re-applied`):t.status==="queued"?B(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?A(v(` ${t.title}: ${t.status}`)):R(` ${t.title}: ${t.status}`);for(let t of e.notes)A(v(` ${t}`))},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 xw())A(c?` ${c}`:"")}return 0}let r;try{r=Ir(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")),R(` Gateway URL: ${c.message}`),A(v(" Fix: pass a gateway URL, e.g. `anyray-connect doctor http://localhost:8787`.")),1)}if(e.quick&&e.verify)return e.silent||(e.json?console.log(JSON.stringify({error:"--quick cannot be combined with --verify"})):(A(V("Anyray connect \u2014 doctor")),R(" --quick skips the network probes; it cannot be combined with --verify."))),1;let o=!e.noVerify&&!e.quick,a=await CK(r,n,!!e.verify&&!e.quick,t.adapters??le,t.inferenceIntrospection??Nd,t.fleetBootstrap??kr,o,t.verifyAuth??_i,!e.quick,t.checkTray??Po,t.updateStatus??wo,t.readRefreshState??It,t.probeHookLane??Sa),s=e.repair?await EK(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(SK(i),null,2)):(vK(i),s&&xK(s)));try{e.quick||await(t.reportHealth??qS)(gx(i),i.connect.version)}catch{}return i.problems===0?0:1};var RK=()=>{let e=[];for(let t of le){let n=t.skillsDir?.();n&&e.push(n)}return e},Cx=async e=>{let t=await D();A(V("Anyray connect \u2014 sync"));let n;try{n=Ir(e.gateway,t)}catch(s){return R(s.message),1}$(`Gateway: ${n}`);let r=jI(t.clientKey,"anyray-placeholder"),o;try{o=await Aa(n,r)}catch(s){return R(`Team policy sync failed: ${uh(s)}`),1}let a=RK();if(a.length===0)OK();else if(o.skills.length===0)$("No team skills published yet \u2014 nothing to sync.");else{let s=await BS(o,a,t.syncedSkills??{});H("Skills");for(let i of s.results)i.written?B(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):$(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await ae({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){$(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}H("Summary"),A(` ${et(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Ca(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: ${uh(s)}`)}return 0},OK=()=>{$("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as D2}from"node:zlib";import{promisify as L2}from"node:util";var Or={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},by=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),kx=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
|
|
697
|
+
`,su=(e,t={})=>{if(typeof e!="string")return by(String(e??""));let n=Math.max(1,t.maxChars??Or.maxChars);if(e.length<=n)return by(e);let r=e.length,o=Math.max(0,t.headChars??Or.headChars),a=Math.max(0,t.tailChars??Or.tailChars),s=Math.max(0,t.middleWindows??Or.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
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+=
|
|
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+=kx(y-h)),m+=e.slice(y,g),h=g;if(r>h&&(m+=kx(r-h)),m.length>=r)return by(e);let w=r-m.length;return{text:m,trimmed:!0,originalChars:r,trimmedChars:m.length,charsRemoved:w,estTokensSaved:Math.round(w/3.3)}},TK=["stdout","content","output","text","result"],vx=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=TK.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 _K=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++,_K(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"},Ex=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")||Ex.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},Cy=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},DK={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},LK=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,NK=(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},xx=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(Ex.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&LK.test(i)}let a=r[1]?lu(r[1]):void 0;if(NK(o,a,r))return!1;let s=DK[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},$K=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==="]"},MK=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},BK=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=MK(t);return r>0&&t[r+1]===":"},FK=80,WK=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/FK),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,BK(e[o])&&r++;return n>0&&r/n>.3},UK=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,HK=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();(UK.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},GK=[/\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],Ay=8192,VK=e=>{let t=e.length>2*Ay?`${e.slice(0,Ay)}
|
|
705
|
+
${e.slice(-Ay)}`:e;return GK.some(n=>n.test(t))},KK=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),jK=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),ZK=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},YK=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),Sx=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(jK(i)){t.push(Di(i));continue}let c=ZK(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(Di(c)),o=12;continue}KK(i)||YK(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}},JK=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,Rx=e=>{let t=JK.exec(e);return t&&/[/.]/.test(t[1])?t:null},XK=/^([^\s:]+)-(\d+)-/,zK=e=>{if(e==="--")return!0;let t=XK.exec(e);return t!=null&&/[/.]/.test(t[1])},qK=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>Rx(r)!=null).length;return n>=3&&n/t.length>=.7},Ix=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=Rx(c);if(!l){if(zK(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}},QK=e=>e.replace(/\d{4}-\d\d-\d\d[T ]\d\d:\d\d:\d\d(?:\.\d+)?Z?/g,"<TS>").replace(/\b\d\d:\d\d:\d\d\b/g,"<TS>").replace(/\b[0-9a-f]{2,}(?:-[0-9a-f]{2,}){2,}\b/gi,"<ID>").replace(/\b0x[0-9a-f]+\b/gi,"<HEX>").replace(/\b\d{8,}\b/g,"<NUM>").trim(),e2=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=QK(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}},Ox=(e,t)=>{if(typeof t!="string"||t.length===0||$K(t))return null;let n=t.split(`
|
|
709
|
+
`).filter(s=>s.trim()!==""),r=Cy(e),o=VK(t),a=null;return r==="test-run"&&o?a=Sx(n):r==="grep"&&(a=Ix(n,.5)),a||(o?a=Sx(n):qK(n)?a=Ix(n,.7):!HK(n)&&!WK(n)&&(a=e2(n))),!a||a.text.length>=t.length?null:a},Tx=e=>`full output: Read ${e}`,ky=(e,t)=>t?`
|
|
710
|
+
|
|
711
|
+
\u2026[anyray-hook digest \u2014 ${e}; ${Tx(t)}]\u2026`:`
|
|
712
|
+
|
|
713
|
+
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,_x=e=>`
|
|
714
|
+
|
|
715
|
+
\u2026[anyray-hook \u2014 ${Tx(e)}]\u2026`;import{createHash as t2}from"node:crypto";import{homedir as n2}from"node:os";import{join as Tr}from"node:path";import{chmod as r2,mkdir as o2,readdir as Nx,stat as Ni,unlink as Li,utimes as a2,writeFile as Sy}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},$x=".swept",s2=".sweeping",Px=64,Dx=448,Iy=384,Ey=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",Mx=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,xy=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=Q();try{if((await Ni(t)).isDirectory())return Tr(t,"hook-tee")}catch{}return Tr(n2(),".anyray-hook-tee")},i2=/^(?:ctx_)?([0-9a-f]{16})$/,Ry=e=>e.trim().match(i2)?.[1]??null,Oy=async e=>{let t=Ry(e);return t?Tr(await xy(),`${t}.txt`):null},c2=async(e,t={})=>{let n=t.limits??du;try{let r=Date.now(),o=(await Nx(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=Px)await Promise.all(o.slice(c,c+Px).map(async l=>{let d=Tr(e,l);try{let u=await Ni(d);if(!u.isFile())return;let p=r-u.mtimeMs>n.ttlMs||r-Mx(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{}},Bx=async e=>{try{return Date.now()-(await Ni(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},Lx=async e=>{try{return await Sy(e,"",{mode:Iy,flag:"wx"}),!0}catch{return!1}},l2=async(e,t)=>{let n=du,r=Tr(e,s2),o=Tr(e,$x);if(!await Lx(r)){let a=0;try{a=Date.now()-(await Ni(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await Li(r).catch(()=>{}),!await Lx(r)))return!1}try{return await Bx(o)<n.sweepIntervalMs?!1:(await Sy(o,"",{mode:Iy}).catch(()=>{}),await c2(e,{protect:t}),!0)}finally{await Li(r).catch(()=>{})}},vy=async(e,t)=>await Bx(Tr(e,$x))<du.sweepIntervalMs?!1:l2(e,t),d2=async()=>{try{let e=await xy();if(!(await Nx(e)).some(t=>t.endsWith(".txt")))return;await vy(e)}catch{}},Fx=async e=>{if(Ey())return await d2(),null;try{let t=await xy();await o2(t,{recursive:!0,mode:Dx}),await r2(t,Dx).catch(()=>{});let n=`${t2("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=Tr(t,n),o=Date.now();try{let a=await Ni(r);if(a.isFile()){if(o-Mx(a)<=du.maxAgeMs){let s=new Date(o);return await a2(r,s,s).catch(()=>{}),await vy(t,r),r}await Li(r).catch(()=>{})}}catch{}return await Sy(r,e,{mode:Iy}),await vy(t,r),r}catch{return null}};import{createHash as u2}from"node:crypto";import{homedir as Wx}from"node:os";import{join as Ty}from"node:path";import{readFile as p2,writeFile as f2,chmod as m2,stat as h2,unlink as y2}from"node:fs/promises";var g2=200,w2=1440*60*1e3,b2=4e6,Ux=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",Hx=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},A2=()=>Hx("ANYRAY_HOOK_CACHE_MAX_ENTRIES",g2),Gx=()=>Hx("ANYRAY_HOOK_CACHE_TTL_MS",w2),Vx=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=Ty(Wx(),".anyray");try{if((await h2(t)).isDirectory())return Ty(t,"hook-cache.json")}catch{}return Ty(Wx(),".anyray-hook-cache.json")},Kx=(e,t,n)=>u2("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),jx=async e=>{try{let t=JSON.parse(await p2(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},Zx=async e=>{if(Ux())return null;try{let n=(await jx(await Vx())).entries[e];return!n||Date.now()-n.at>Gx()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},C2=e=>{let t=Date.now(),n=Gx(),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=A2();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>b2&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},Yx=async(e,t)=>{if(Ux())return;let n;try{let r=await Vx(),o=await jx(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=C2(o.entries),n=`${r}.${process.pid}.tmp`,await f2(n,JSON.stringify(o),{mode:384}),await m2(n,384),await he(n,r)}catch{if(n)try{await y2(n)}catch{}}};import{open as k2,stat as v2}from"node:fs/promises";var Jx=600,S2=3,I2=256e3,E2=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
|
+
`):"",x2=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),R2=e=>{let t=[];for(let n of e)if(!(!n||!n.trim()))try{let r=JSON.parse(n);r&&typeof r=="object"&&!Array.isArray(r)&&t.push(r)}catch{}return t},O2=e=>{let t=[],n=0;for(let r=e.length-1;r>=0;r--){let o=e[r];if(!o||o.type!=="user"||o.isMeta||o.isSidechain)continue;let a=E2(o.message?.content).trim();if(!(!a||x2(a))&&(t.unshift(a),n+=a.length,t.length>=S2||n>=Jx))break}return t.join(`
|
|
717
|
+
`).slice(0,Jx)};var T2=e=>/(^|[\\/])subagents[\\/]/i.test(e),_2=e=>/\.jsonl$/i.test(e),P2=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),Xx=async e=>{let t={intent:"",kind:"unknown"};if(!e||!_2(e))return t;let n;try{let{size:r}=await v2(e),o=Math.max(0,r-I2),a=r-o;if(a<=0)return t;n=await k2(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=R2(i.split(`
|
|
719
|
+
`));return P2(c)?{intent:O2(c),kind:T2(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var N2=3e3,$2=1500,M2=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:N2},B2={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},F2=new Set(["claude","opencode"]),W2=(e,t)=>{let n={};if(e)try{let r=JSON.parse(e);r&&typeof r=="object"&&!Array.isArray(r)&&(n=r)}catch{}return JSON.stringify({...n,tool:B2[t]})},U2={cacheGet:async()=>null,cachePut:async()=>{}},H2=(e,t={cacheGet:Zx,cachePut:Yx,tee:Fx})=>e==="claude"?t:U2,G2=1e3,V2=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),uu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),K2=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}},j2=e=>{try{let t=JSON.parse(e);return uu(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},Z2=e=>uu(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
|
|
720
|
+
`:"",_y=e=>Math.round(Math.max(0,e)/4),zx=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",Y2=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),J2=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),X2=["tool_output","tool_response","tool_result"],z2=e=>{for(let t of X2)if(t in e)return e[t]},q2=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},Q2=120,ej=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??G2))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=ky(r.stat,null).length+Q2;if(r.text.length+o>=n.length)return null;let a=null;if(e.tee)try{a=await e.tee(n)}catch{a=null}let s=ky(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}}},tj=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(Y2.has(o)||J2(o))return n;let a=vx(z2(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(qx(o)&&l.retrievalContext!=="available")return n;let d=await ej(t,q2(o,r.tool_input),i),u=d?.body??i,p=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!iu(i,{minChars:$2})))return n;let f=i.length-u.length-p.length,m=async(S,I,E=S.length+p.length)=>{let T=d?.teePath??null;if(!T&&t.tee)try{T=await t.tee(i)}catch{T=null}let O=T?S.replaceAll("; not retrievable in this context]","]"):S,F=T&&!p?_x(T):"",q=O+p+F,de=F.length,ce=q;if(t.finalizeOutput)try{let W=t.finalizeOutput(q);W.length<=q.length&&(ce=W)}catch{ce=q}let K=q.length-ce.length,ge=_y(Math.max(0,f-de))+I+_y(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(ce);return{stdout:V2(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
|
+
${zx(r.tool_input)}`:zx(r.tool_input),y=Kx(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=ij(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:_y(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")},nj=()=>{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")}},rj=L2(D2),oj=async e=>{try{let t=await rj(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},qx=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),aj=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},sj=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),ij=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),cj=2048,lj=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,cj),n=Cd(t);if(!n)return;await SI({at:Date.now(),status:e.status,code:n})}catch{}},dj=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),M2());try{let c=await oj(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...qx(t)||aj(t)&&a==="available"?{reversible:!0}:{},...sj(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 lj(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)}},Qx=async(e="claude")=>{let t=await $i();if(e!=="cursor"&&j2(t))return 0;let n=e==="cursor"?K2(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await Py(n,e);if(e==="cursor"){let a=Z2(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},Py=async(e,t="claude",n)=>{await Sr(),await vI(t);let r=nj(),o=await nt(),a=o&&{...o,metadata:W2(o.metadata,t)},s=H2(t);return tj(e,{optimize:(i,c,l,d,u)=>dj(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await Xx(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??Or.maxChars,digestCommand:Ox,tee:s.tee,mediumBand:F2.has(t),finalizeOutput:n})};var e0=async()=>0;import{spawn as gj}from"node:child_process";import{homedir as wj}from"node:os";import{join as bj}from"node:path";import{chmod as uj,readFile as pj,rm as t0,writeFile as fj}from"node:fs/promises";import{join as mj}from"node:path";var Dy=()=>mj(Q(),"sso-gate.json"),hj=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))},Na=async()=>{try{let e=JSON.parse(await pj(Dy(),"utf-8"));return hj(e)?e:null}catch{return null}},yj=0,pu=async e=>{await tt();let t=Dy(),n=`${t}.${process.pid}.${yj++}.tmp`;try{await fj(n,`${JSON.stringify(e)}
|
|
722
|
+
`,{mode:384}),await uj(n,384),await he(n,t)}catch(r){throw await t0(n,{force:!0}).catch(()=>{}),r}},n0=async()=>{await t0(Dy(),{force:!0}).catch(()=>{})},r0=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 Aj=3e4,Cj=5*6e4,kj=30*6e4,vj=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},Sj=()=>bj(wj(),".claude","settings.json"),Ij=async e=>{try{let n=(await M(Sj())).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}},Ej=async e=>{await er.apply(e,{dryRun:!1})},xj=()=>{let{command:e,args:t}=tr("__anyray-sso-poll");return{exe:e,args:t}},Rj=()=>{let{exe:e,args:t}=xj(),n=gj(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))}}},Oj=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},o0=(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}),$a=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},a0=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
|
+
`,Ly=(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 K;await h();let ge=(t.resolveMachineUuid??Ft)()||void 0;try{K=await d(E,b.enrolledCert,C,{timeoutMs:1e4,machineUuid:ge})}catch(me){if(!(me instanceof lt))return $a(e,
|
|
731
|
-
`}catch{return}},
|
|
729
|
+
`,Tj=e=>Math.min(Cj,Aj*2**Math.max(0,e-1)),_j=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?kj:Tj(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??ae,a=t.loadDevKey??$e,s=t.readGateState??Na,i=t.writeGateState??pu,c=t.isProcessAlive??r0,l=t.startGrant??hd,d=t.verify??Xt,u=t.routingIntact??Ij,p=t.applyClaudeCode??Ej,f=t.maybeSpawnRefresh??Sr,m=t.recordMint??Ia,h=t.reserveMint??yo,w=t.spawnPoller??Rj,y=t.openBrowser??_a;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=Oj(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=o0(E,b,e.team,b.clientKey);return await u(me)?(de-n()<=Sh()&&await f(),{exitCode:0}):(await p(me),$a(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
|
|
730
|
+
`))}let K;await h();let ge=(t.resolveMachineUuid??Ft)()||void 0;try{K=await d(E,b.enrolledCert,C,{timeoutMs:1e4,machineUuid:ge})}catch(me){if(!(me instanceof lt))return $a(e,Ly("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(o0(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 $a(e,a0(k))}if(k){let de=_j(k,n());if(de)return $a(e,Ly(de,g.cpOrigin))}let T;try{T=await l({cpOrigin:g.cpOrigin,tenantId:g.tenantId,gatewayUrl:e.gateway,now:n})}catch(de){let ce=de instanceof uo?de.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:k?.lastFailure===ce?(k.failureCount??0)+1:1,lastFailure:ce}),$a(e,Ly(ce,g.cpOrigin))}let O={v:1,status:"pending",userCode:T.userCode,verificationUriComplete:T.verificationUriComplete,grantExpiresAt:T.grantExpiresAt,startedAt:T.startedAt,lastAttemptAt:n(),failureCount:0};await i(O);let F=w(),q={...O,pollerPid:F.pid};if(await i(q),F.handoff({deviceCode:T.deviceCode,privateKeyPem:T.privateKeyPem,publicKeyPem:T.publicKeyPem,cpOrigin:T.cpOrigin,tenantId:T.tenantId,intervalMs:T.intervalMs,grantExpiresAt:T.grantExpiresAt,startedAt:T.startedAt,gatewayUrl:T.gatewayUrl,gatewayOverride:e.gateway,team:e.team}),e.sessionStart)try{y(T.verificationUriComplete)}catch{}return $a(e,a0(q))}catch{return{exitCode:0}}},Pj=async()=>{try{for await(let e of process.stdin);}catch{}},s0=async e=>{await Pj();try{let t=await Co(vj(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var Dj=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},Lj=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??kr)();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}},Nj=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=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")}},Mj=(e,t)=>{let n=t.minChars??Pi.minChars,r={maxChars:Math.min(Or.maxChars,n)},o=su(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},i0=async()=>{let e=await Nj(),t=await Lj(e);t&&process.stdout.write(t);let n=$j(),r=await nt();return await Dj(e,{isPaste:o=>iu(o,n),measure:o=>Mj(o,n),beacon:o=>lc(r,"prompt",o)}),0};import{spawn as Bj}from"node:child_process";var c0=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Fj=/[|&;<>`$()\n]/,l0=e=>{if(Fj.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},Wj=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!c0(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!c0(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(Zu)||!t.isRecognized(o)||l0(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},Uj=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?l0(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},
|
|
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},Hj=16*1024*1024,Gj=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=Bj(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>Hj){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)}}),Vj=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await Py(n,"cursor");return typeof r=="string"?r:t},d0=e=>{let t=e[0]==="--b64"?e[1]:void 0;return Uj(t,{exec:Gj,trim:Vj,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},u0=async()=>{let e=await $i();if(process.platform==="win32")return 0;let t=Wj(e,{isRecognized:n=>Cy(n)!==null||xx(n),wrap:n=>Rt(Zu,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as Kj}from"node:crypto";import{homedir as p0}from"node:os";import{extname as jj,isAbsolute as Zj,join as Ny,resolve as Mi,sep as f0}from"node:path";import{chmod as Yj,readFile as Jj,stat as w0,unlink as Xj,writeFile as zj}from"node:fs/promises";var My=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),qj=16*1024,m0=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],Qj=["pattern","query","regex","search"],eZ=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"]),tZ=720*60*1e3,nZ=512,$y=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},rZ=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],h0=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(f0)?n:n+f0)),oZ=(e,t,n)=>Zj(e)?[Mi(e)]:[...new Set([Mi(t,e),...n.map(r=>Mi(r,e))])],y0=(e,t,n)=>Kj("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),g0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),aZ=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!My(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!My(o))return"";let a=rZ(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=$y(o,Qj);if(!d)return"";let u=$y(o,m0);return u&&!h0(Mi(s,u),a)||!await t.remember(y0(i,"Grep",d))?"":g0(`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=$y(o,m0);if(!c||eZ.has(jj(c).toLowerCase()))return"";let l=await t.resolveFile(oZ(c,s,a));return!l||l.bytes<qj||!h0(l.path,a)||!await t.remember(y0(i,"Read",l.path))?"":g0(`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.`)},sZ=async e=>{for(let t of e)try{let n=await w0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},iZ=async()=>{let e=Ny(p0(),".anyray");try{if((await w0(e)).isDirectory())return Ny(e,"cursor-redirects.json")}catch{}return Ny(p0(),".anyray-cursor-redirects.json")},cZ=async e=>{let t;try{let n=await iZ(),r=Date.now(),o={};try{let s=JSON.parse(await Jj(n,"utf-8"));if(s?.v===1&&My(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=tZ&&(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,nZ);return t=`${n}.${process.pid}.tmp`,await zj(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await Yj(t,384),await he(t,n),!0}catch{if(t)try{await Xj(t)}catch{}return!1}},b0=async()=>{let e=await $i(),t="";try{t=await aZ(e,{resolveFile:sZ,remember:cZ})}catch{t=""}return t&&process.stdout.write(t),0};import{execFileSync as yY}from"node:child_process";import{createReadStream as lZ}from"node:fs";import{spawnSync as _0}from"node:child_process";import{createHash as dZ}from"node:crypto";import{access as P0,chmod as Wy,copyFile as uZ,lstat as pZ,mkdir as fZ,mkdtemp as D0,readFile as gu,rename as mZ,rm as _r,stat as hZ,writeFile as yZ}from"node:fs/promises";import{constants as L0}from"node:fs";import{platform as Fa,tmpdir as gZ}from"node:os";import{dirname as wZ,isAbsolute as bZ,join as mu}from"node:path";import{z as Le}from"zod";var AZ="fleetd-installer-v4.89.2",A0=`https://github.com/anyrayHQ/install/releases/download/${AZ}`,CZ=1e4,kZ=1e4,C0=31,vZ=1500,N0=20*1024,By=20,SZ="0.25",IZ="/var/tmp",Ba="/Library/LaunchDaemons/com.fleetdm.orbit.plist",hu="/etc/default/orbit",Fi="/opt/orbit/anyray-enroll-secret.txt",$0="/opt/orbit/secret-orbit-node-key.txt",EZ="/opt/orbit/bin/orbit/orbit",Wi="C:\\Program Files\\Orbit",xZ=`${Wi}\\bin\\orbit`,M0=`${Wi}\\secret-orbit-node-key.txt`,Bi=`${Wi}\\secret.txt`,RZ=`${Wi}\\fleet_url.txt`,B0=`${Wi}\\anyray-managed.txt`,yu="Fleet osquery",Uy="C:\\Windows\\System32\\sc.exe",Ky="C:\\Windows\\System32\\whoami.exe",fu="C:\\Windows\\System32\\icacls.exe",OZ="C:\\Windows\\System32\\msiexec.exe",Hy="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",k0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],TZ=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],_Z=`anyray-connect endpoint install
|
|
734
734
|
|
|
735
735
|
Install Fleet's signed endpoint agent and enroll this machine in Anyray.
|
|
736
736
|
|
|
@@ -738,11 +738,11 @@ Supported on macOS, Linux and Windows.
|
|
|
738
738
|
|
|
739
739
|
The command uses the current seat's stored gateway key. Administrator access is
|
|
740
740
|
required: on macOS and Linux Connect asks through sudo once when /dev/tty is
|
|
741
|
-
available; on Windows, run it from a shell started as Administrator.`,
|
|
742
|
-
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",Fi)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},
|
|
743
|
-
`&&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},
|
|
741
|
+
available; on Windows, run it from a shell started as Administrator.`,jy=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),F0=(e,t=Fa())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),W0=(e,t=Fa(),n=!1)=>(jy(e)||n)&&t!=="win32",se=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},PZ=Le.object({kind:Le.enum(["pkg","deb","rpm","msi"]),path:Le.string().min(1).refine(bZ),sha256:Le.string().regex(/^[0-9a-f]{64}$/)}).strict(),DZ=Le.object({action:Le.literal("restart"),os:Le.enum(["darwin","linux","win32"])}).strict(),LZ=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:PZ.optional()}).strict(),NZ=Le.discriminatedUnion("action",[DZ,LZ]),Ui=(e,t)=>{let n=_0(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 P0(e,L0.F_OK),!0}catch{return!1}},$Z=async e=>{try{let t=await hZ(e);return t.isFile()&&t.size>0}catch{return!1}},Yy=(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}},Fy=(e,t)=>Yy(e,t)!==null,v0=e=>e==="win32"?Bi:Fi,MZ=e=>e==="win32"?M0:$0,BZ=e=>Fy(e,"ORBIT_FLEET_URL")&&Fy(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${Fi}</string>`)&&!Fy(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),FZ=e=>{let t=(n,r)=>e.split(`
|
|
742
|
+
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",Fi)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},Gy=(e,t)=>{if(e==="win32"){let a="--fleet-url ",s=t.indexOf(a);if(s<0)return;let i=t.slice(s+a.length),c;if(i.startsWith('"')){let d=i.indexOf('"',1);if(d<0)return;c=i.slice(1,d)}else{let d=i.indexOf(" ");c=d<0?i:i.slice(0,d)}let l=c.trim();return l.length>0?l:void 0}if(e==="darwin"){let a=t.indexOf("<key>ORBIT_FLEET_URL</key>");if(a<0)return;let s=t.indexOf("<string>",a),i=t.indexOf("</string>",s);return s<0||i<0?void 0:t.slice(s+8,i).replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&").trim()}let n='Environment="ORBIT_FLEET_URL=',r=t.indexOf(n);if(r<0)return;let o=t.indexOf('"',r+n.length);return o<0?void 0:t.slice(r+n.length,o).trim()},U0=e=>{let t=e(Uy,["qc",yu,"8192"]);return t.status===0?t.stdout:""},Vy=e=>{let t=e(Hy,TZ(yu)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},WZ=async e=>{try{return e==="win32"?Gy(e,U0(Ui)):Gy(e,await gu(e==="darwin"?Ba:hu,"utf8"))}catch{return}},UZ=async e=>{try{if(e==="win32")return await Zy(B0)&&Gy(e,U0(Ui))!==void 0;let n=await gu(e==="darwin"?Ba:hu,"utf8");return e==="darwin"?BZ(n):FZ(n)}catch{return!1}},H0=async(e,t={})=>{let n=t.exists??Zy,r=t.command??Ui,o,a="absent";if(e==="win32")a=Vy(r),o=await n(xZ)&&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(EZ)&&l}let s=await(t.configured??UZ)(e),i=await(t.hasNodeKey??(()=>$Z(MZ(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}},HZ=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),G0=(e,t)=>{let n=Yy(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]===`
|
|
743
|
+
`&&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},GZ=(e,t)=>{let n=G0(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},S0=(e,t,n)=>{let r=`
|
|
744
744
|
<key>${t}</key>
|
|
745
|
-
<string>${
|
|
745
|
+
<string>${HZ(n)}</string>`,o=G0(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=Yy(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)},VZ=(e,t,n=Fi)=>{let r=GZ(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=S0(r,"ORBIT_FLEET_URL",t),S0(r,"ORBIT_ENROLL_SECRET_PATH",n)},KZ=(e,t,n=Fi)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
|
|
746
746
|
`).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(`
|
|
747
747
|
`).trimEnd()}
|
|
748
748
|
|
|
@@ -752,17 +752,17 @@ available; on Windows, run it from a shell started as Administrator.`,Ky=e=>!!(e
|
|
|
752
752
|
# file, never in this world-readable one.
|
|
753
753
|
ORBIT_FLEET_URL=${t}
|
|
754
754
|
ORBIT_ENROLL_SECRET_PATH=${n}
|
|
755
|
-
`},
|
|
756
|
-
`,384);e.os!=="win32"&&await
|
|
757
|
-
`,384),e.os==="win32"&&
|
|
758
|
-
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??
|
|
759
|
-
sudo anyray-connect endpoint install`),"deferred"},
|
|
760
|
-
`;if(Buffer.byteLength(t)>
|
|
761
|
-
`).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}},V0=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??W0)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??R0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??NZ)(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??S0)(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??R0)(),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??S0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let p=await(t.packageKind??(()=>VZ(r)))();if(i=await(t.stagePackage??ZZ)(p),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${Yy(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??lY)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},Jy=e=>e instanceof se?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",K0=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return A(EZ),0;if(e.length!==1||e[0]!=="install")return R("Usage: anyray-connect endpoint install"),1;try{let t=await V0();return t.message&&(t.outcome==="installed"?B(t.message):$(t.message)),0}catch(t){return R(Jy(t)),1}},dY=async()=>{let e=[],t=0;for await(let o of process.stdin){let a=Buffer.isBuffer(o)?o:Buffer.from(o);if(t+=a.length,t>D0)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=TZ.safeParse(n);if(!r.success||r.data.os!==Fa()||r.data.action==="configure"&&!H0(r.data.fleetUrl))throw new se("The privileged endpoint plan is invalid.");return r.data},j0=async e=>{if((process.getuid?.()??-1)!==0)return R("The privileged endpoint step must run as root."),1;if(e.length!==0)return R("The privileged endpoint step does not accept arguments."),1;try{return await G0(await dY()),0}catch(t){return R(Jy(t)),1}},Z0=async(e,t=V0)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?B(n.message):$(n.message)),n.outcome}catch(n){$(`Endpoint agent: ${Jy(n)} Tool routing remains configured.`);return}};var pY=new Set(["darwin","win32","linux"]),fY=new Set(["S-1-5-18","S-1-5-19","S-1-5-20"]),mY=e=>{let t=e.match(/S-\d(?:-\d+)+/i)?.[0]?.toUpperCase();return t!==void 0&&!fY.has(t)},Y0=(e,t)=>{let n=new Set(t);return e.filter(r=>!n.has(r.id))},J0=async e=>{try{if(!pY.has(e.platform)||e.isUserSession?.()===!1)return 0;let t=await e.loadProfile();if(t.managedEnrollmentDisabled===!0)return 0;let n=e.readManagedEnrollment().enrollmentUrl;return n?await e.runApply(["--enroll",n,"--yes"],t.revertedTools??[]):0}catch{return 1}},X0=e=>({platform:process.platform,readManagedEnrollment:ey,loadProfile:D,isUserSession:()=>{try{if(process.platform==="win32"){let t=uY(Vy,["/user","/fo","csv","/nh"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return mY(t)}return process.getuid?.()!==0}catch{return!1}},runApply:e});var Hi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},Xy=e=>typeof e=="string"&&e.trim()?e.trim():void 0,hY=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Hi(n,"deviceCode"),o=Hi(n,"privateKeyPem"),a=Hi(n,"publicKeyPem"),s=Hi(n,"cpOrigin"),i=Hi(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=Xy(n.gatewayUrl),p=Xy(n.gatewayOverride),f=Xy(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}},yY=e=>new Promise(t=>setTimeout(t,e)),gY=async(e,t)=>{let n=await t.readGateState()??{v:1};await t.writeGateState({v:1,lastAttemptAt:t.now(),failureCount:(n.failureCount??0)+1,lastFailure:e})},wY=async(e,t={})=>{let n=t.poll??yd,r=t.verify??Xt,o=t.loadProfile??D,a=t.saveProfile??ae,s=t.saveDevKey??Ji,i=t.readGateState??Na,c=t.writeGateState??pu,l=t.clearGateState??e0,d=t.sleep??yY,u=t.now??Date.now,p=t.recordMint??Ia,f=t.reserveMint??yo,m=t.applyClaudeCode??(async E=>{await Qn.apply(E,{dryRun:!1})}),h=E=>gY(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 T=E instanceof Mt?E.kind:"cp-unreachable";return await h(T),T}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??Ft)()||void 0;for(let E=0;E<3;E++)try{C=await r(g,y.cert,y.privateKeyPem,{timeoutMs:1e4,machineUuid:S});break}catch(T){if(T 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"}},bY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},z0=async()=>{let e=hY(await bY());if(e)try{await wY(e)}catch{}return 0};var AY=1e4,zy=/^[\w.:-]{1,64}$/,Ut=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},qy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,q0=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),AY);try{let a=await n(e,{...t,signal:r.signal}),s={};try{s=await a.json()}catch{s={}}return{status:a.status,body:s}}catch{throw new Ut("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},CY=e=>{let t=qy(e);if(!t)return;let n=t.browser_url;try{if(typeof n!="string")return;let r=new URL(n);if(r.protocol!=="http:"&&r.protocol!=="https:")return}catch{return}if(!(typeof t.id!="string"||!t.id||typeof t.user_code!="string"||!t.user_code||typeof t.poll_secret!="string"||!t.poll_secret||typeof t.interval!="number"||!Number.isFinite(t.interval)||t.interval<=0||typeof t.expires_in!="number"||!Number.isFinite(t.expires_in)||t.expires_in<=0))return{id:t.id,browser_url:n,user_code:t.user_code,poll_secret:t.poll_secret,interval:t.interval,expires_in:t.expires_in}},kY=e=>{let t=qy(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&zy.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&zy.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},vY=e=>{let t=qy(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ee(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!zy.test(t.team)))return{status:"complete",key:t.key,user:t.user,team:t.team,...typeof t.expires_at=="string"&&{expires_at:t.expires_at}}},SY=e=>new Promise(t=>setTimeout(t,e)),IY=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Ut("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}A("Available teams:"),e.forEach((i,c)=>A(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await xa("Choose a team",r),a=o?Number.parseInt(o,10):NaN,s=Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:o;if(!s||!e.includes(s))throw new Ut("invalid-team","Choose one of the teams shown above.");return s},EY=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??SY,a=t.loadProfile??D,s=t.saveProfile??ae,i=t.clearDevKey??Ja,c=t.chooseTeam??IY,l=t.apply??(async y=>{await Qn.apply(y,{dryRun:!1})}),d=t.log??$,u=await a(),p=Sr(e.gateway,u),f=await q0(`${p}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),m=CY(f.body);if(f.status!==200||!m)throw new Ut("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${m.browser_url}`),d(`Enter this code in the browser: ${m.user_code}`),(t.openBrowser??_a)(m.browser_url);let h=r()+m.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<h;){let y=await q0(`${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 Ut("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(y.status===410)throw new Ut("expired","SSO login expired before it completed. Run anyray-connect login again.");let g=kY(y.body);if(y.status===200&&g){if(w&&!g.teams.includes(w))throw new Ut("invalid-team",`Team ${w} is not available for this account.`);w=await c(g.teams,g.default_team,e.interactive??Wt());continue}let b=vY(y.body);if(y.status!==200||!b)throw new Ut("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 Ut("expired","SSO login expired before it completed. Run anyray-connect login again.")},xY=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
755
|
+
`},V0=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}},jZ=Le.object({code:Le.string().min(1).optional(),message:Le.string().min(1).optional()}).passthrough(),I0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},ZZ=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=jZ.safeParse(t);if(!r.success)return n;let o=I0(r.data.message??""),a=I0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},E0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??kZ),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(ZZ(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||!V0(i.data.fleetUrl))throw new se("The gateway returned invalid endpoint enrollment data.");return i.data},YZ=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.")},JZ=async e=>e==="darwin"?"pkg":e==="win32"?"msi":YZ(),Jy=e=>`fleetd.${e}`,XZ=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",zZ=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),CZ);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},qZ=async(e,t={})=>{let n=Jy(e),r=t.fetchResponse??fetch,o;try{o=await zZ(`${A0}/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=sy(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await D0(mu(gZ(),"anyray-endpoint-")),i=mu(s,n);try{await Wy(s,448),await(t.download??ly)(`${A0}/${n}`,i,a)}catch(c){if(await _r(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:()=>_r(s,{recursive:!0,force:!0})}},QZ=async(e,t,n)=>{await fZ(wZ(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await _r(r,{force:!0});try{await yZ(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await mZ(r,e)}catch(o){throw await _r(r,{force:!0}).catch(()=>{}),o}},x0=async e=>{let t=dZ("sha256");for await(let n of lZ(e))t.update(n);return t.digest("hex")},eY=async(e,t={})=>{let n=await pZ(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 x0(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 D0(mu(IZ,"anyray-endpoint-root-")),o=mu(r,Jy(e.kind));try{if(await Wy(r,448),await uZ(e.path,o),await Wy(o,384),await x0(o)!==e.sha256)throw new se("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>_r(r,{recursive:!0,force:!0})}}catch(a){throw await _r(r,{recursive:!0,force:!0}).catch(()=>{}),a}},Ma=(e,t)=>{if(e.status!==0)throw new se(t)},R0="com.fleetdm.fleetd.config",tY="com.fleetdm.fleetd.enroll.secret",nY=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",$0],rY=[RZ,M0],oY=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(R0))throw new se(`This machine already receives its endpoint configuration from an MDM profile (${R0}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},O0=async(e,t,n)=>{let r=n.removeFile??(o=>_r(o,{force:!0}));for(let o of e==="win32"?rY:nY)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",tY,"/Library/Keychains/System.keychain"])},aY=e=>{e(fu,[Bi,"/inheritance:r"]),e(fu,[Bi,"/grant:r","*S-1-5-18:(F)"]),e(fu,[Bi,"/grant:r","*S-1-5-32-544:(F)"]),e(fu,[Bi,"/remove:g","*S-1-5-32-545"])},sY=(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(OZ,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},iY=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<By;r++){if(n=t("/bin/launchctl",["bootstrap","system",Ba]),n.status===0)return;t("/bin/sleep",[SZ])}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(Uy,["stop",yu]);for(let n=0;n<By;n++){let r=Vy(t);if(r==="Stopped"||r==="absent")break;t(Hy,k0)}for(let n=0;n<By;n++){if(t(Uy,["start",yu]).status===0||Vy(t)==="Running")return;t(Hy,k0)}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.")},cY=e=>new Promise(t=>setTimeout(t,e)),K0=async(e,t={})=>{let n=t.command??Ui,r=t.readText??(c=>gu(c,"utf8")),o=t.writeText??QZ,a=t.removeSecret??(()=>_r(v0(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&oY(n),e.package&&!XZ(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 O0(e.os,n,t),e.package){let d=await(t.preparePackage??eY)(e.package);i=d.cleanup,sY(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(Ba);await o(Ba,VZ(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(hu);await o(hu,KZ(d,e.fleetUrl),420)}else await o(B0,`anyray
|
|
756
|
+
`,384);e.os!=="win32"&&await O0(e.os,n,t),await o(v0(e.os),`${e.enrollSecret}
|
|
757
|
+
`,384),e.os==="win32"&&aY(n),s=e.os!=="win32"}iY(e.os,n);let c=t.checkIn??(async d=>{let u=await H0(d);return u.running&&u.checkedIn}),l=t.wait??cY;for(let d=0;d<(t.attempts??C0);d++){if(await c(e.os))return;d+1<(t.attempts??C0)&&await l(vZ)}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(()=>{})}},lY=async()=>{try{return await P0("/dev/tty",L0.R_OK),!0}catch{return!1}},dY=12288,uY=e=>{let t=e(Ky,["/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>=dY},pY=async(e,t={})=>{if((t.os??Fa())==="win32")return(t.elevated??(()=>uY(t.command??Ui)))()?(await e(),"direct"):((t.print??A)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
|
|
758
|
+
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??lY)()){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:
|
|
759
|
+
sudo anyray-connect endpoint install`),"deferred"},fY=async e=>{let t=`${JSON.stringify(e)}
|
|
760
|
+
`;if(Buffer.byteLength(t)>N0)throw new se("The privileged endpoint plan is unexpectedly large.");let n=en(["__anyray-endpoint-install"]);return _0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},mY=async(e,t={})=>(t.withRoot??pY)(()=>(t.apply??K0)(e),{...t.root,reexec:()=>(t.sudo??fY)(e)}),T0=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 gu("/etc/passwd","utf8")).split(`
|
|
761
|
+
`).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}},j0=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??H0)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??T0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??WZ)(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??E0)(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??T0)(),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??E0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let p=await(t.packageKind??(()=>JZ(r)))();if(i=await(t.stagePackage??qZ)(p),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${Jy(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??mY)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},Xy=e=>e instanceof se?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",Z0=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return A(_Z),0;if(e.length!==1||e[0]!=="install")return R("Usage: anyray-connect endpoint install"),1;try{let t=await j0();return t.message&&(t.outcome==="installed"?B(t.message):$(t.message)),0}catch(t){return R(Xy(t)),1}},hY=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>N0)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=NZ.safeParse(n);if(!r.success||r.data.os!==Fa()||r.data.action==="configure"&&!V0(r.data.fleetUrl))throw new se("The privileged endpoint plan is invalid.");return r.data},Y0=async e=>{if((process.getuid?.()??-1)!==0)return R("The privileged endpoint step must run as root."),1;if(e.length!==0)return R("The privileged endpoint step does not accept arguments."),1;try{return await K0(await hY()),0}catch(t){return R(Xy(t)),1}},J0=async(e,t=j0)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?B(n.message):$(n.message)),n.outcome}catch(n){$(`Endpoint agent: ${Xy(n)} Tool routing remains configured.`);return}};var gY=new Set(["darwin","win32","linux"]),wY=new Set(["S-1-5-18","S-1-5-19","S-1-5-20"]),bY=e=>{let t=e.match(/S-\d(?:-\d+)+/i)?.[0]?.toUpperCase();return t!==void 0&&!wY.has(t)},X0=(e,t)=>{let n=new Set(t);return e.filter(r=>!n.has(r.id))},z0=async e=>{try{if(!gY.has(e.platform)||e.isUserSession?.()===!1)return 0;let t=await e.loadProfile();if(t.managedEnrollmentDisabled===!0)return 0;let n=e.readManagedEnrollment().enrollmentUrl;return n?await e.runApply(["--enroll",n,"--yes"],t.revertedTools??[]):0}catch{return 1}},q0=e=>({platform:process.platform,readManagedEnrollment:ty,loadProfile:D,isUserSession:()=>{try{if(process.platform==="win32"){let t=yY(Ky,["/user","/fo","csv","/nh"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return bY(t)}return process.getuid?.()!==0}catch{return!1}},runApply:e});var Hi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},zy=e=>typeof e=="string"&&e.trim()?e.trim():void 0,AY=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Hi(n,"deviceCode"),o=Hi(n,"privateKeyPem"),a=Hi(n,"publicKeyPem"),s=Hi(n,"cpOrigin"),i=Hi(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=zy(n.gatewayUrl),p=zy(n.gatewayOverride),f=zy(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}},CY=e=>new Promise(t=>setTimeout(t,e)),kY=async(e,t)=>{let n=await t.readGateState()??{v:1};await t.writeGateState({v:1,lastAttemptAt:t.now(),failureCount:(n.failureCount??0)+1,lastFailure:e})},vY=async(e,t={})=>{let n=t.poll??yd,r=t.verify??Xt,o=t.loadProfile??D,a=t.saveProfile??ae,s=t.saveDevKey??Ji,i=t.readGateState??Na,c=t.writeGateState??pu,l=t.clearGateState??n0,d=t.sleep??CY,u=t.now??Date.now,p=t.recordMint??Ia,f=t.reserveMint??yo,m=t.applyClaudeCode??(async E=>{await er.apply(E,{dryRun:!1})}),h=E=>kY(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 T=E instanceof Mt?E.kind:"cp-unreachable";return await h(T),T}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??Ft)()||void 0;for(let E=0;E<3;E++)try{C=await r(g,y.cert,y.privateKeyPem,{timeoutMs:1e4,machineUuid:S});break}catch(T){if(T 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"}},SY=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},Q0=async()=>{let e=AY(await SY());if(e)try{await vY(e)}catch{}return 0};var IY=1e4,qy=/^[\w.:-]{1,64}$/,Ut=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},Qy=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,eR=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),IY);try{let a=await n(e,{...t,signal:r.signal}),s={};try{s=await a.json()}catch{s={}}return{status:a.status,body:s}}catch{throw new Ut("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},EY=e=>{let t=Qy(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}},xY=e=>{let t=Qy(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&qy.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&qy.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},RY=e=>{let t=Qy(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ee(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!qy.test(t.team)))return{status:"complete",key:t.key,user:t.user,team:t.team,...typeof t.expires_at=="string"&&{expires_at:t.expires_at}}},OY=e=>new Promise(t=>setTimeout(t,e)),TY=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Ut("invalid-team",`Multiple teams are available (${e.join(", ")}). Re-run with --team <name>.`)}A("Available teams:"),e.forEach((i,c)=>A(` ${c+1}. ${i}`));let r=t&&e.includes(t)?t:e[0],o=await xa("Choose a team",r),a=o?Number.parseInt(o,10):NaN,s=Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:o;if(!s||!e.includes(s))throw new Ut("invalid-team","Choose one of the teams shown above.");return s},_Y=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??OY,a=t.loadProfile??D,s=t.saveProfile??ae,i=t.clearDevKey??Ja,c=t.chooseTeam??TY,l=t.apply??(async y=>{await er.apply(y,{dryRun:!1})}),d=t.log??$,u=await a(),p=Ir(e.gateway,u),f=await eR(`${p}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),m=EY(f.body);if(f.status!==200||!m)throw new Ut("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${m.browser_url}`),d(`Enter this code in the browser: ${m.user_code}`),(t.openBrowser??_a)(m.browser_url);let h=r()+m.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<h;){let y=await eR(`${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 Ut("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(y.status===410)throw new Ut("expired","SSO login expired before it completed. Run anyray-connect login again.");let g=xY(y.body);if(y.status===200&&g){if(w&&!g.teams.includes(w))throw new Ut("invalid-team",`Team ${w} is not available for this account.`);w=await c(g.teams,g.default_team,e.interactive??Wt());continue}let b=RY(y.body);if(y.status!==200||!b)throw new Ut("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 Ut("expired","SSO login expired before it completed. Run anyray-connect login again.")},PY=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
762
762
|
|
|
763
763
|
Start browser SSO, choose a team, mint a personal gateway key, and configure
|
|
764
764
|
the subscription-backed Connect lane. In a non-interactive shell, --team may be
|
|
765
|
-
omitted only when the identity authority supplies a default or sole team.`,
|
|
765
|
+
omitted only when the identity authority supplies a default or sole team.`,tR=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(PY),0;if(a==="--gateway"||a==="--team"){let s=e[++o];if(!s)return R(`${a} requires a value.`),1;a==="--gateway"?n=s:r=s;continue}return R(`unknown login option: ${a}`),1}try{let o=await _Y({gateway:n,team:r},t);return B(`Signed in as ${o.user} for team ${o.team}. Your personal key was saved and configured.`),0}catch(o){if(o instanceof yt)throw o;return R(o instanceof Ut?o.message:"SSO login failed."),1}};var nR=`anyray-connect update [--check] [--auto on|off] [--json]
|
|
766
766
|
|
|
767
767
|
Keep this machine's anyray-connect binary on the published release. Runs
|
|
768
768
|
automatically about every 30 minutes; this command forces it now.
|
|
@@ -773,34 +773,34 @@ Options:
|
|
|
773
773
|
Off still accepts a release the Anyray team marks mandatory.
|
|
774
774
|
--json Emit the result as JSON.
|
|
775
775
|
--help Show this help.
|
|
776
|
-
`,
|
|
776
|
+
`,DY=e=>{let t={check:!1,json:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--check")t.check=!0;else if(r==="--json")t.json=!0;else if(r==="--help"||r==="-h")t.help=!0;else if(r==="--auto"){let o=e[++n];if(o!=="on"&&o!=="off")throw new Error("--auto takes `on` or `off`.");t.auto=o==="on"}else throw new Error(`Unknown option: ${r}`)}return t},LY=e=>{switch(e.outcome){case"current":return`Already on the published version (${e.current}).`;case"available":return`Version ${e.latest} is published; this machine is on ${e.current}.`;case"updated":return`Updated ${e.current} \u2192 ${e.latest}. New commands run it immediately.`;case"migrated":return`Installed the managed ${e.latest} binary at ${e.managedPath}.`;case"migration-available":return`Version ${e.latest} will migrate this npm runtime to the managed standalone binary.`;case"migration-deferred":return`The published standalone binary (${e.latest}) is older than this npm runtime (${e.current}); migration was deferred.`;case"disabled":return`Automatic updates are off. Version ${e.latest} is published; this machine is on ${e.current}.`;case"unmanaged":return"This copy is not an Anyray-managed or npm runtime, so it updates elsewhere.";case"container":return"Self-update is skipped inside a container \u2014 it updates by rebuild, not by download-and-swap.";case"platform-unsupported":return"Self-update is unavailable because this platform has no published standalone binary.";case"unavailable":return"Could not reach the release feed to check for a newer version.";case"failed":return`Could not install ${e.latest??"the published version"} \u2014 staying on ${e.current}.`}},rR=async e=>{let t;try{t=DY(e)}catch(o){return R(o.message),process.stderr.write(nR),1}if(t.help)return process.stdout.write(nR),0;if(t.auto!==void 0){let o=await D();if(o.autoUpdate!==!1!==t.auto&&await ae({...o,autoUpdate:t.auto}),t.json||(B(`Automatic updates ${t.auto?"enabled":"disabled"}.`),t.auto||A("A release the Anyray team marks mandatory still installs \u2014 that lever is for security fixes.")),!t.auto)return t.json&&process.stdout.write(`${JSON.stringify({autoUpdate:!1},null,2)}
|
|
777
777
|
`),0}let n=await La({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)}
|
|
778
|
-
`),n.outcome==="failed"?1:0}let r=
|
|
778
|
+
`),n.outcome==="failed"?1:0}let r=LY(n);switch(n.outcome){case"updated":case"migrated":B(r);break;case"current":B(r);break;case"available":case"migration-available":A(r),t.check&&A(`Run ${V("anyray-connect update")} to install it.`);break;case"migration-deferred":P(r),A(v("Use the newer npm runtime until that standalone release is published."));break;case"disabled":P(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":P(r),A(v("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":P(r);break;case"failed":return R(r),1}return 0};var NY=3e3,oR=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>cy(NY)),o=e.updateStatus??wo;t(`anyray-connect ${Ae}
|
|
779
779
|
`);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&Pa(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}
|
|
780
780
|
${i}
|
|
781
|
-
`)}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
|
|
782
|
-
`),0};import
|
|
783
|
-
`)},
|
|
784
|
-
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,
|
|
781
|
+
`)}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 $Y=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},MY=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),BY=async(e={})=>{try{let t=await(e.readBootstrap??kr)().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??Na)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!$Y(a)||!MY(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"}}},aR=async(e={})=>{let t=await BY(e);return process.stdout.write(`${JSON.stringify(t)}
|
|
782
|
+
`),0};import FY from"node:path";var WY="2025-06-18",UY={name:"anyray",version:"1"},sR={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}},HY=20,iR={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}},pR=Xh,GY=e=>{if(e==null||typeof e=="string"&&e.trim()==="")return;let t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return;let n=Math.round(t);return n<1?1:Math.min(n,pR)},VY=e=>e==="paths"||e==="lines"||e==="full"?e:"full",cR={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-${pR}). 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}},lR={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}},KY=8,jY=3,dR={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}},ZY=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(`
|
|
783
|
+
`)},YY=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
|
|
784
|
+
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,KY).map(([a,s])=>{let i=s.slice(0,jY).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
|
|
785
785
|
`)});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(`
|
|
786
|
-
`)},be=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),
|
|
786
|
+
`)},be=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),eg=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}}),uR=e=>e?.name??"error",ye=(e,t=!1)=>{let n=e;if(n.length>4e4){let r=t?`
|
|
787
787
|
|
|
788
788
|
[anyray: error output cut to fit the tool-result limit \u2014 ${n.length} chars total.]`:`
|
|
789
789
|
|
|
790
790
|
[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(`
|
|
791
|
-
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},
|
|
792
|
-
`+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 ${
|
|
793
|
-
${m.content}`))}return be(n??null,ye(m.content))}if(a.name===
|
|
794
|
-
`)}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
|
|
795
|
-
`))>=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",
|
|
791
|
+
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},JY=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:WY,capabilities:{tools:{}},serverInfo:UY});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return be(n??null,{});case"tools/list":{let a=[sR,iR];t.advertiseContextTools!==!1&&a.push(cR,lR);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(dR),be(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===sR.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=Ry(i);if(f){let w=await Oy(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.]
|
|
792
|
+
`+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 ${HY} 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}
|
|
793
|
+
${m.content}`))}return be(n??null,ye(m.content))}if(a.name===iR.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(ZY(l.matches)):ye(l.message,!0))}if(a.name===cR.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=GY(s.maxResults),d=VY(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(DE(i,u,d)):ye(u.message??"search failed",!0))}if(a.name===dR.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(Zh(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(YY(c,l)):ye(l.message??"history search failed",!0))}if(a.name===lR.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(Zh(l)):ye(l.message??"read failed",!0))}return eg(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:eg(n??null,-32601,`method not found: ${o}`)}},XY=async e=>{if(!e)return;let t=new AbortController,n=setTimeout(()=>t.abort(),vd);try{await fetch(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:Vt(e),signal:t.signal})}catch{}finally{clearTimeout(n)}},zY=(e,t=!0)=>({retrieve:async(n,r)=>va(await e(),n,r),recall:async(n,r)=>Sd(await e(),n,r),search:(n,r,o)=>Zd(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>Si(n,r),readTee:async(n,r)=>{if(Ey())return{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"the hook tee is off (ANYRAY_HOOK_TEE=off)"};let o=await Oy(n);return o?{...await Si(o,{cwd:FY.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=>ME(n),historyAvailable:async()=>await Ta()>0,advertiseContextTools:t,heartbeat:()=>{e().then(XY).catch(()=>{})}}),fR=async(e="auto",t={})=>{let n=zY(()=>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,Sr().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=p=>{try{o.write(JSON.stringify(p)+`
|
|
794
|
+
`)}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 JY(m,n)}catch(w){console.error("anyray mcp: dispatch error",uR(w)),h=m?.id===void 0?null:eg(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(`
|
|
795
|
+
`))>=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",uR(p))}finally{clearInterval(d)}return 0};import{spawn as qY}from"node:child_process";var QY=e=>e==="jetbrains"||e==="windsurf"?e:void 0,eJ=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(`
|
|
796
796
|
`);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}})}
|
|
797
|
-
`),!0)}catch{return!1}},
|
|
797
|
+
`),!0)}catch{return!1}},tJ={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},nJ=(e,t,n)=>{let r=new Set(tJ[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}},mR=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
|
|
798
798
|
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!rd(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
|
|
799
|
-
`),1;await(n.refreshIfDue??zt)().catch(()=>{});let s=await(n.loadProfile??D)(),i=await(n.readBootstrap??
|
|
800
|
-
`),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=
|
|
801
|
-
`),1;w=n.comSpec??a.ComSpec??"cmd.exe",y=["/d","/s","/c",`"${m.command}" ${m.args.join(" ")}`]}return await new Promise(g=>{let b=
|
|
802
|
-
`),g(1)}),k.once("exit",(C,S)=>{g(typeof C=="number"?C:S?1:0)})})};import{randomUUID as
|
|
803
|
-
`,"utf8"),await a.chmod(384),await
|
|
799
|
+
`),1;await(n.refreshIfDue??zt)().catch(()=>{});let s=await(n.loadProfile??D)(),i=await(n.readBootstrap??kr)().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 eJ(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.
|
|
800
|
+
`),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=QY(n.clientTool);u&&(d.metadata.tool=u);let p=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",f=(n.hookBinaryIsDurable??te)(),m=Lv(d,t,{mcpServer:f?Ge("profile"):void 0})[p],h=n.spawn??qY,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.
|
|
801
|
+
`),1;w=n.comSpec??a.ComSpec??"cmd.exe",y=["/d","/s","/c",`"${m.command}" ${m.args.join(" ")}`]}return await new Promise(g=>{let b=nJ(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.
|
|
802
|
+
`),g(1)}),k.once("exit",(C,S)=>{g(typeof C=="number"?C:S?1:0)})})};import{randomUUID as rJ}from"node:crypto";import{open as oJ,rm as aJ}from"node:fs/promises";import{join as sJ}from"node:path";import{z as Se}from"zod";var wu=Se.string().min(1).refine(e=>Number.isFinite(Date.parse(e)),"expected an ISO-8601 timestamp"),iJ=Se.enum(["reconcile","refresh","repair","status","offboard"]),tg=Se.union([Se.literal(0),Se.literal(1),Se.literal(2),Se.literal(3),Se.literal(4)]),cJ=Se.enum(["locked","required","recommended","optional"]),bu=Se.object({schemaVersion:Se.literal(1),generatedAt:wu,connectVersion:Se.string().min(1),fleetManaged:Se.boolean(),enrollment:Se.object({state:Se.enum(["enrolled","degraded","broken","none"]),lastRefreshAt:wu.optional(),lastRefreshOutcome:Se.enum(["ok","failed"]).optional()}).strict(),keyExpiresAt:wu.optional(),tools:Se.array(Se.object({id:Se.string().min(1),tier:cJ,routed:Se.boolean()}).strict()),lastVerb:Se.object({verb:iJ,exitCode:tg,at:wu}).strict()}).strict(),hR=(e,t)=>{if(!e)return!1;let n=Date.parse(e);return Number.isFinite(n)&&n>t},lJ=(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||!hR(o,n)?"broken":!e.clientKey||e.clientKeyExpiresAt&&!hR(e.clientKeyExpiresAt,n)?"degraded":"enrolled"},dJ=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"}},yR=(e,t)=>e.fleetToolPolicy?.tiers?.[t]??"required",uJ=async(e,t)=>{let n=new Set(e.managedTools??[]),r=new Set(e.revertedTools??[]),o=(e.fleetToolPolicy?.enabled??[]).filter(c=>{let l=yR(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:yR(e,c),routed:d})}return i},gR=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:lJ(r,!!o,n()),...dJ(a)},...r.clientKeyExpiresAt&&Number.isFinite(Date.parse(r.clientKeyExpiresAt))?{keyExpiresAt:r.clientKeyExpiresAt}:{},tools:await uJ(r,t.toolById??mt),lastVerb:e};return bu.parse(s)},pJ=()=>sJ(Q(),"status.json"),wR=async(e,t={})=>{let n=bu.parse(e);await(t.ensureStateDir??tt)();let r=pJ(),o=`${r}.${process.pid}.${rJ()}.tmp`,a;try{a=await oJ(o,"wx",384),await a.writeFile(`${JSON.stringify(n,null,2)}
|
|
803
|
+
`,"utf8"),await a.chmod(384),await Kn(a),await a.close(),a=void 0,await(t.publish??he)(o,r)}catch(s){throw a&&await a.close().catch(()=>{}),await aJ(o,{force:!0}).catch(()=>{}),s}},ng=e=>e.enrollment.state==="none"||e.enrollment.state==="broken"?3:e.enrollment.state==="degraded"?4:e.tools.every(t=>t.routed)?0:4;var fJ=1e4,Wa=e=>e?.name??"Error",rg=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(fJ)})}catch(o){console.error(`anyray seat offboard report: ${Wa(o)}`)}},mJ=e=>e==="reverted"||e==="queued",Au=async(e={})=>{let t=e.loadProfile??D,n=e.clearDeviceTokenState??Dd,r=e.reportSeatOffboarded??rg,o=e.clearEnrollment??Xi,a=e.recordManagedTools??jn,s=e.markSeatOffboarded??zi,i=e.adapterById??mt,c=e.uninstallScheduler??or,l=e.unitsPresent??kc,d=e.saveProfile??ae,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: ${Wa(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}),mJ(I.status)?w.push(C):y.push(C)}catch(I){console.error(`anyray offboard: reverting ${C}: ${Wa(I)}`),y.push(C)}}let g=!0;try{await a(h,!0,!0)}catch(C){g=!1,console.error(`anyray offboard: recording managed tools: ${Wa(C)}`)}let b=y.length===0&&g,k=!1;if(b)try{await s(),k=!0}catch(C){console.error(`anyray offboard: stamping offboard: ${Wa(C)}`)}try{((await t()).refreshSchedulerEnabled||await l())&&await c(),await d({...await t(),refreshSchedulerEnabled:!1})}catch(C){console.error(`anyray offboard: unit teardown: ${Wa(C)}`)}return{reverted:w,unresolved:y,enrollmentCleared:f,credentialHeld:m,recordPersisted:g,offboardMarked:k,ok:y.length===0&&!m&&g&&k}};var ie={success:0,unexpected:1,usage:2,authBroken:3,partial:4},hJ=`Stable non-interactive runtime commands:
|
|
804
804
|
anyray-connect reconcile
|
|
805
805
|
anyray-connect refresh
|
|
806
806
|
anyray-connect repair
|
|
@@ -816,7 +816,7 @@ Exit codes:
|
|
|
816
816
|
1 unexpected error
|
|
817
817
|
2 usage error (unknown flag or argument)
|
|
818
818
|
3 authentication broken; re-enrollment required
|
|
819
|
-
4 partial; the command ran but drift remains`,
|
|
819
|
+
4 partial; the command ran but drift remains`,yJ={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"},gJ=e=>e.replaceAll("-","_"),CR=e=>{let t=e[0];if(!t)return;let n=yJ[gJ(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}},og=e=>{let t=e?.name;return typeof t=="string"&&/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(t)?t:"Error"},wJ=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 Aa(n.gateway,n.clientKey);return await Ca(i)}catch(i){if(dh(i))return o?"credential-degraded":"auth-broken";throw i}},bJ=e=>e==="auth-broken"?ie.authBroken:e==="credential-degraded"||e.toolsApplied<e.toolsRequested||e.toolsTombstoned.length>0?ie.partial:ie.success,AJ=e=>e.refresh==="not-enrolled"||e.refresh==="cert-expired"||e.refresh==="cert-rejected"?ie.authBroken:e.refresh==="failed"?ie.unexpected:e.partial||e.refresh==="disabled"||e.refresh==="backoff"||e.refresh==="throttled"||e.refresh==="gateway-incompatible"?ie.partial:ie.success,CJ=e=>!e.enrollment.enrolled||e.enrollment.expired===!0||e.verify?.kind==="enrollment-required",bR=async e=>{let t;return{code:await au({repair:e,quick:!e,silent:!0},{captureReport:r=>t=r}),authBroken:t?CJ(t):!1}},AR=e=>typeof e!="number"&&e.authBroken?ie.authBroken:(typeof e=="number"?e:e.code)===0?ie.success:ie.partial,kJ=(e,t)=>{let n=ng(t);return n===ie.authBroken?n:e!==0||n===ie.partial?ie.partial:ie.success},vJ=async(e,t)=>{if(e==="reconcile")return bJ(await(t.reconcile??(()=>wJ(t.loadProfile)))());if(e==="refresh"){if(!t.refresh)throw new Error("refresh runtime is unavailable");return AJ(await t.refresh())}return e==="repair"?AR(await(t.repair??(()=>bR(!0)))()):e==="status"?AR(await(t.status??(()=>bR(!1)))()):(await(t.offboard??Au)()).ok?ie.success:ie.partial},ag=(e,t)=>bu.parse({...e,lastVerb:{...e.lastVerb,exitCode:t}}),kR=async(e,t={})=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.help)return n(hJ),ie.success;let o=t.now??Date.now,a=new Date(o()).toISOString(),s=t.withProfileLock??Xa,i=t.buildStatus??gR,c=t.writeStatus??wR,l,d=e.usageError?ie.usage:ie.unexpected;e.usageError&&r(`anyray-connect ${e.verb}: UsageError`);try{await s(async()=>{if(!e.usageError)try{d=tg.parse(await vJ(e.verb,t))}catch(u){d=dh(u)?ie.authBroken:ie.unexpected,r(`anyray-connect ${e.verb}: ${og(u)}`)}if(l=await i({verb:e.verb,exitCode:d,at:a},{now:o}),(e.verb==="repair"||e.verb==="status")&&d!==ie.unexpected&&d!==ie.usage&&d!==ie.authBroken)d=kJ(d===0?0:1,l);else if(e.verb!=="offboard"&&d!==ie.unexpected&&d!==ie.usage){let u=ng(l);(u===ie.authBroken||d===ie.success)&&(d=u)}l=ag(l,d);try{await c(l)}catch(u){d=ie.unexpected,l=ag(l,d),r(`anyray-connect ${e.verb}: ${og(u)}`)}})}catch(u){d=ie.unexpected,r(`anyray-connect ${e.verb}: ${og(u)}`);try{l=ag(await i({verb:e.verb,exitCode:d,at:a},{now:o}),d)}catch{l=void 0}}return n(JSON.stringify(l||{schemaVersion:1,generatedAt:a,connectVersion:"unknown",fleetManaged:!1,enrollment:{state:"broken"},tools:[],lastVerb:{verb:e.verb,exitCode:d,at:a}})),d};var SJ=new Set(["not-due","repaired","cert-renewed","heartbeat-refreshed","refreshed"]),vR=async(e,t={})=>await(t.fleetdPresent??Ao)()?SJ.has(e)?{retired:!0,messages:(await(t.uninstallScheduler??or)()).messages}:{retired:!1,reason:"refresh-unhealthy",messages:[]}:{retired:!1,reason:"no-fleetd",messages:[]};var SR=["reapply_config","remint","revert","revert_tool","update"],IJ=/^[a-z0-9][a-z0-9-]{0,31}$/;var EJ=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"||!SR.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&IJ.test(t.tool):t.tool===void 0},sg=e=>e?.name??"error",IR=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":SR.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!EJ(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",sg(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",sg(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:",sg(i))}return a.kind};var ER=e=>e?.name??"Error",xR=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??D,r=t.recordManagedTools??jn,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}: ${ER(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${ER(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{platform as OR}from"node:os";var TR=`${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.`,_R=`${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]
|
|
@@ -1063,22 +1063,22 @@ ${V("What it does")}
|
|
|
1063
1063
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
1064
1064
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
1065
1065
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
1066
|
-
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,
|
|
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?`}`,
|
|
1068
|
-
${o} ${n} tool target(s)?`;return await(r.confirm??Ea)(a)?"proceed":"declined"},jJ=async(e=La)=>{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}},ZJ=async()=>{let e=!1,t=await zt({runAmbientSelfcheck:!0});await cp(),await vI(),await SI()==="retry"&&(e=!0);let n=await D().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await ae(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await Ao().catch(()=>!1);if(n&&(await CR(t,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey)){let o=n.gateway,a=n.clientKey,s=Ft(),i=n.enrolledCert;if(s&&i){let l=await $e().catch(()=>{});l&&await dS(o,a,i,l,s).catch(()=>{})}await vR(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 IR(d):l==="update"?u=await jJ():u=(await Au()).ok?"ok":"failed",u==="failed"&&(e=!0),u}}).catch(()=>{})}return r||await La(),{refresh:t,...e?{partial:!0}:{}}},YJ=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 z0();if(e[0]==="__anyray-managed-enroll")try{return await Xa(()=>J0(X0((r,o)=>NR(r,!1,{managedEnrollmentRevertedTools:o}))),{waitMs:DR})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return rR();if(e[0]==="__anyray-spawn-refresh")return await vr(),0;if(e[0]==="__anyray-mcp-server"){let r=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return uR(r)}if(e[0]==="__anyray-acp-agent")return pR(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return j0(e.slice(1));let t=bR(e);if(t)return AR(t,{refresh:ZJ});if(e[0]==="__anyray-persistence")return Cw(e.slice(1));if(e[0]==="__anyray-quit-watch")return Kv(e.slice(1));if(e[0]===yr)return zI(e.slice(1));if(e[0]===Vs)return QI(e.slice(1));if(e[0]===Wd){let r=e[1];return r&&await Gd(r),0}if(e[0]==="--version"||e[0]==="-V")return nR();try{let r=await Mg(e);if(r!==void 0)return r}catch(r){return R(`Could not persist anyray-connect for long-lived integrations: ${r instanceof Error?r.message:String(r)}`),1}if(GJ(e)){let r=HJ(await sx());r?.level==="warn"?P(r.message):r&&console.error(r.message)}if(e[0]==="managed")return TS(e.slice(1));if(e[0]==="endpoint")return K0(e.slice(1));if(e[0]==="print-key")return RI(e.slice(1));if(e[0]==="models")return TI(e.slice(1));if(e[0]==="copilot-login")return _I(e.slice(1));if(e[0]==="desktop"){let r=e.slice(1),o=Gh(r);return o?ig(o,!1):kE(r)}if(e[0]==="retrieve")return SE(e.slice(1));if(e[0]==="recall")return IE(e.slice(1));if(e[0]==="history")return ME(e.slice(1));if(e[0]==="migrate")return FE(e.slice(1));if(e[0]==="login")return Q0(e.slice(1));if(e[0]==="update")return tR(e.slice(1));let n=e[0];if(n&&WJ.has(n)){let r=e.slice(1),o;try{o=TR(r)}catch(a){return R(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"?$I():ig(r,!0)}return ig(e,!1)},LR=async e=>{try{return await YJ(e)}catch(t){if(t instanceof yt)return console.error(v("Cancelled.")),130;throw t}},NR=async(e,t,n={})=>{let r=n.isInteractive??Wt,o;try{o=TR(e)}catch(_){return R(_.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 R("--revert cannot be combined with --sso, --enroll or --claim. It removes Anyray configuration; re-run with --sso <link> --yes (without --revert) to configure a new CLI."),1;if(o.project)return o.sso||o.enroll||o.subscription||o.upstream?(R("--project cannot be combined with --sso/--enroll (per-machine enrollment) or --subscription/--upstream (per-dev credential lanes). It writes an org-lane, credential-free repo config."),1):JI({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return R("--upstream and --upstream-key go together: the URL says where your personal key is valid, the key is what the gateway forwards there."),1;if(o.upstream&&(o.subscription||o.placeholder))return R("--upstream cannot be combined with --subscription or --org: BYO passthrough sends your personal upstream key \u2014 not a seat OAuth token, and never the org's server-held key."),1;let a;if(o.upstream){let _;try{_=new URL(o.upstream.trim())}catch{return R(`invalid --upstream URL: "${o.upstream}"`),1}if(_.protocol!=="http:"&&_.protocol!=="https:")return R(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let L=o.upstreamKey.trim();if(!L)return R("--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&&Wt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??MJ)(o,s),c=!0);let l;try{if(l=vJ(o.tools),n.managedEnrollmentRevertedTools){let _=[...n.managedEnrollmentRevertedTools,...s.revertedTools??[]];l=Y0(l,_)}}catch(_){return R(_.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 _=fd(o.enroll);if(_&&(!o.gateway||s.enrolledCert||Zm(_.token)))try{let L=await Ei("Resolving enrollment link\u2026",()=>rS(_)),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(_.token))return R(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 R(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 _=hS(o.claim);if(!_)return R("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let L=await Ei("Connecting this machine\u2026",()=>yS({cpOrigin:_.cpOrigin,claim:_.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 R(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 _=St(o.sso);if(!_)return R(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 hd({cpOrigin:_.cpOrigin,tenantId:_.tenantId,gatewayUrl:o.gateway,log:pe=>$(pe),open:r()?_a:void 0}),J=await Ei("Waiting for SSO sign-in\u2026",()=>yd(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 R(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(_){return R(_.message),1}let b,k;y&&!o.revert&&$(`Gateway: ${g} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&lg(g)&&P(`${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,T,O,F,q,de=async _=>{await yo();let L=sS(_.token),J=uS(s.enrolledCert,s.enrolledCertExpiry,_.deploymentId,Date.now(),L,s.enrolledTokenHash,_.expectedUser),pe=J?await $e():void 0,ut=Ft()||void 0,j=J&&pe&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:pe,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,_e=pt=>pS({cpOrigin:_.cpOrigin,token:_.token,gatewayOrigin:g,email:_.email,team:_.team,machineId:_.machineId,deploymentId:_.deploymentId,machineUuid:ut,reuse:pt?j:void 0}),ke=!!j,Xe=await(async()=>{try{return await _e(ke)}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"),ke=!1,await _e(!1);throw pt}})();S=Xe.clientKey,o.user=Cu(o.user,Xe.user),o.team=Cu(o.team,Xe.team),I=Xe.cert,E=Xe.cert.payload.expiresAt,q=Xe.expiresAt,F=void 0,ke||(T=Xe.privateKeyPem),ke||(O=L),B(`Enrolled${Xe.user?` as ${Xe.user}`:""}${ke?" (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 _=fd(o.enroll);if(!_){let L=nS(o.enroll);return R(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?Id():void 0,J=p==="mdm"&&!u?ZE():void 0,pe=p==="mdm"&&!u&&!J?jE(f,Ld()):void 0,ut=J??pe;if(ut){let ke=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 ${ke}.`:`Enrolling as ${ke}.`)}let j=u??ut??kJ(o.user);if(!o.machine&&!o.user&&!u&&!ut){let ke=WI();ke.distinct||(P(` Enrolling as "${ke.identity}" \u2014 this may not be unique to you.`),P(ke.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"),P(ke.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."),P(" Re-run with `--user you@company.com` (or set `git config --global"),P(" user.email`) so your usage is attributed to you."))}let _e=o.machine?`machine:${L}`:m?j:void 0;await de({cpOrigin:_.cpOrigin,token:_.token,email:j,team:o.team,machineId:L,deploymentId:d,expectedUser:_e})}catch(L){return R(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."),cS(L)?3:1}}if(h){await yo();try{let _=Ft()||void 0,L=await Xt(g,h.cert,h.privateKeyPem,{machineUuid:_});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,T=h.privateKeyPem,q=L.expiresAt;let J=o.sso?St(o.sso):void 0;F=J?`${J.cpOrigin}/sso/${J.tenantId}`:w,B(`Enrolled${L.user?` as ${L.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(_){return R(_ instanceof Error?_.message:String(_)),_ instanceof lt&&_.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 _=o.yes;b=await HI(o.user,s.name,_),k=await GI(o.team,s.team,_)}if(!o.revert&&!o.dryRun){let _=lx(await cx(g,S),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if(_.lane){let L=_.lane==="subscription";o.subscription=L,o.placeholder=!L;let J=L?"your own subscription seat":"the organization's provider account";_.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 ce;!o.revert&&!o.subscription&&!o.placeholder&&(ce=await fn(),H("Detecting your sign-ins"),A(` Claude (Anthropic): ${a?et("BYO upstream key (passthrough)"):ce.anthropic?et("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),A(` Codex (ChatGPT): ${ce.openai?et("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),!ce.anthropic&&!ce.openai&&!ce.copilot&&Fr()&&(P(" No subscription sign-ins found on this host. Sign-ins do not cross the"),P(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),P(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),P(" 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:ce,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 R("Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key."),1;if(!o.revert&&!K.clientKey){H("Enrollment required");let _="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(P(` ${_}`),$(" Dry run only \u2014 no placeholder configuration will be written."),await ER(l,"after-enrollment"),$(`
|
|
1069
|
-
Dry run complete \u2014 no files were written.`),0):(R(` ${_}`),1)}o.revert||
|
|
1070
|
-
Dry run \u2014 no files will be written.`);let W=await
|
|
1066
|
+
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,xJ=e=>{let t=e?.trim();return t||Ph()},Cu=(e,t)=>t||e,PR=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},RJ=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}),OJ=(e,t)=>{if(H("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 (${_t(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 (${_t(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 (${_t(e.clientKey)}) ${v("rides x-anyray-api-key")}`)):e.clientKey?A(` Auth: personal gateway key (${_t(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)")}`)},RR=async(e,t)=>{H("Selected tools");for(let n of e){let r=await n.detect();r.installed?A(` ${n.title} ${v(`(${n.id})`)} \u2014 ${t==="plan"?"will configure":"would configure after enrollment"}${r.detail?`; ${r.detail}`:""}`):$(` ${n.title} ${v(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},TJ=(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},_J={loadDevKey:$e,saveDevKey:Ji,clearDevKey:Ja,saveProfile:ae},PJ=async(e,t,n,r=_J,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}H(`${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"?B(` ${f.status}`):f.status==="manual"?(s.push(u.title),f.manualAudience==="admin"?(i.push(u.title),c.push(u.id),P(" blocked by machine policy \u2014 your IT team owns this one")):P(" 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"}),R(` 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}},LJ=(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},NJ=(e,t,n)=>{if(t.revert)return[];if((t.tools?.length??0)>0)return[];let r=new Set(n??[]);return e.filter(o=>DR(o)&&!r.has(o.id))},$J=async e=>{let t=kE(e,process.platform,Q());if(t){await we(t.path,t.content);for(let n of vE(t,process.platform))A(` ${n}`)}},MJ=async(e,t,n=OR())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!pb(i,n)||!ub(i,n))continue;let c=lb(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:db(i),quitTarget:i,isRunning:()=>s.isRunning()})}}return r},BJ=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,FJ=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?`}`,WJ=async(e,t={})=>{let n=t.requestQuit??(a=>mb(a)),r=t.waitFor??(a=>hb(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),B(` Closed ${a.title}.`);continue}P(` ${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},UJ=(e,t={})=>{let n=t.relaunch??(o=>yb(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),B(` Reopened ${o.title}.`)):P(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},DR=e=>e.changesBilling===!0||e.changesOrgManagement===!0,LR=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,ig=e=>!DR(e),HJ=async(e,t,n={})=>{let r=n.hasEnrollment??$u,o=n.canMultiSelect??zE,a=n.multiSelect??qE,s=n.prompt??xa,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){H("How do you want to connect?");let c;for(let l=0;l<3&&!c;l++){if(o()){let d=await a({title:"Choose a connection method",single:!0,items:[{value:"enroll",label:"Paste an enrollment link",selected:!0},{value:"sso",label:"Sign in with SSO"},{value:"gateway",label:"I already have a gateway URL"}]});if(d.kind==="cancelled")throw new 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||P("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)&&fd(d)){e.enroll=d;break}P("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}P("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{P("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){H("Tools detected");let c=[],l=[];for(let u of i){if(!(await u.detect()).installed){l.push(u);continue}c.push(u)}let d=c.filter(u=>ig(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:LR(m),selected:ig(m),requiresExplicitChoice:!ig(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){P(`Unknown or unavailable tool id${h.length===1?"":"s"}. Choose from: ${c.map(w=>w.id).join(", ")}.`);continue}}if(p.length===0){P("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},GJ=async(e,t)=>{H("Verifying the connection");let n=await Ei("Checking the gateway\u2026",()=>_i(e,{tools:t}));n.kind==="ok"?B(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?P(` ${n.detail}`):R(` ${n.detail}`);for(let r of n.remedy)A(v(` ${r}`))},VJ=async(e,t={})=>{if(e.dryRun)return;let n=t.install??rr,r=t.uninstall??or;if(e.want&&e.trayManaged){H("Automatic key refresh"),B(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh.");return}if(e.want){let o=await n();H("Automatic key refresh");for(let a of o.messages)A(` ${a}`);o.ok&&B(" Your gateway key now renews every ~30 min \u2014 no tool will 401 on a stale key mid-session."),o.ok||await ae({...await D(),refreshSchedulerEnabled:!1});return}if(!e.scopedRevert&&e.wasEnabled){H("Automatic key refresh");let o=await r();for(let a of o.messages)A(` ${a}`);await ae({...await D(),refreshSchedulerEnabled:!1}),B(" Removed the automatic key-refresh schedule.")}},KJ=new Set(["login","wizard","status","doctor","sync","device-url"]),jJ=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint"]),ZJ=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."}},YJ=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=Vh(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]||!jJ.has(e[0])},cg=async(e,t)=>{try{return await MR(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 R("Another Connect update is in progress. Try again."),1;throw n}},NR=12e4,JJ=async(e,t,n,r=Xa)=>e&&!t?r(n,{waitMs:NR}):n(),XJ=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??Wt)())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??Ea)(a)?"proceed":"declined"},zJ=async(e=La)=>{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}},qJ=async()=>{let e=!1,t=await zt({runAmbientSelfcheck:!0});await lp(),await II(),await EI()==="retry"&&(e=!0);let n=await D().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await ae(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await Ao().catch(()=>!1);if(n&&(await vR(t,{fleetdPresent:async()=>r}).catch(()=>{}),r&&n.gateway&&n.clientKey)){let o=n.gateway,a=n.clientKey,s=Ft(),i=n.enrolledCert;if(s&&i){let l=await $e().catch(()=>{});l&&await pS(o,a,i,l,s).catch(()=>{})}await IR(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 xR(d):l==="update"?u=await zJ():u=(await Au()).ok?"ok":"failed",u==="failed"&&(e=!0),u}}).catch(()=>{})}return r||await La(),{refresh:t,...e?{partial:!0}:{}}},QJ=async e=>{if(e[0]==="__anyray-hook"){let r=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return Qx(r)}if(e[0]==="__anyray-codex-hook")return e0();if(e[0]==="__anyray-prompt-hook")return i0();if(e[0]==="__anyray-shell-pretool")return u0();if(e[0]==="__anyray-shell-run")return d0(e.slice(1));if(e[0]==="__anyray-read-pretool")return b0();if(e[0]==="__anyray-sso-gate")return s0(e.slice(1));if(e[0]==="__anyray-sso-poll")return Q0();if(e[0]==="__anyray-managed-enroll")try{return await Xa(()=>z0(q0((r,o)=>MR(r,!1,{managedEnrollmentRevertedTools:o}))),{waitMs:NR})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return aR();if(e[0]==="__anyray-spawn-refresh")return await Sr(),0;if(e[0]==="__anyray-mcp-server"){let r=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return fR(r)}if(e[0]==="__anyray-acp-agent")return mR(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return Y0(e.slice(1));let t=CR(e);if(t)return kR(t,{refresh:qJ});if(e[0]==="__anyray-persistence")return vw(e.slice(1));if(e[0]==="__anyray-quit-watch")return Zv(e.slice(1));if(e[0]===gr)return QI(e.slice(1));if(e[0]===Vs)return tE(e.slice(1));if(e[0]===Wd){let r=e[1];return r&&await Gd(r),0}if(e[0]==="--version"||e[0]==="-V")return oR();try{let r=await Fg(e);if(r!==void 0)return r}catch(r){return R(`Could not persist anyray-connect for long-lived integrations: ${r instanceof Error?r.message:String(r)}`),1}if(YJ(e)){let r=ZJ(await cx());r?.level==="warn"?P(r.message):r&&console.error(r.message)}if(e[0]==="managed")return PS(e.slice(1));if(e[0]==="endpoint")return Z0(e.slice(1));if(e[0]==="print-key")return TI(e.slice(1));if(e[0]==="models")return PI(e.slice(1));if(e[0]==="copilot-login")return DI(e.slice(1));if(e[0]==="desktop"){let r=e.slice(1),o=Vh(r);return o?cg(o,!1):SE(r)}if(e[0]==="retrieve")return EE(e.slice(1));if(e[0]==="recall")return xE(e.slice(1));if(e[0]==="history")return FE(e.slice(1));if(e[0]==="migrate")return UE(e.slice(1));if(e[0]==="login")return tR(e.slice(1));if(e[0]==="update")return rR(e.slice(1));let n=e[0];if(n&&KJ.has(n)){let r=e.slice(1),o;try{o=PR(r)}catch(a){return R(a.message),A("\nRun `npx anyray-connect --help` for usage."),1}return o.help?(A(o.helpAll?_R:TR),0):n==="status"?mx({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"?Cx({gateway:o.gateway}):n==="device-url"?BI():cg(r,!0)}return cg(e,!1)},$R=async e=>{try{return await QJ(e)}catch(t){if(t instanceof yt)return console.error(v("Cancelled.")),130;throw t}},MR=async(e,t,n={})=>{let r=n.isInteractive??Wt,o;try{o=PR(e)}catch(_){return R(_.message),A("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return A(o.helpAll?_R:TR),0;if(o.revert&&(o.sso||o.enroll||o.claim))return R("--revert cannot be combined with --sso, --enroll or --claim. It removes Anyray configuration; re-run with --sso <link> --yes (without --revert) to configure a new CLI."),1;if(o.project)return o.sso||o.enroll||o.subscription||o.upstream?(R("--project cannot be combined with --sso/--enroll (per-machine enrollment) or --subscription/--upstream (per-dev credential lanes). It writes an org-lane, credential-free repo config."),1):zI({gateway:o.gateway,tools:o.tools,revert:o.revert,dryRun:o.dryRun,yes:o.yes});if(!!o.upstream!=!!o.upstreamKey)return R("--upstream and --upstream-key go together: the URL says where your personal key is valid, the key is what the gateway forwards there."),1;if(o.upstream&&(o.subscription||o.placeholder))return R("--upstream cannot be combined with --subscription or --org: BYO passthrough sends your personal upstream key \u2014 not a seat OAuth token, and never the org's server-held key."),1;let a;if(o.upstream){let _;try{_=new URL(o.upstream.trim())}catch{return R(`invalid --upstream URL: "${o.upstream}"`),1}if(_.protocol!=="http:"&&_.protocol!=="https:")return R(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let L=o.upstreamKey.trim();if(!L)return R("--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&&Wt()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,c=!1;(t||i)&&r()&&(o=await(n.runWizard??HJ)(o,s),c=!0);let l;try{if(l=RJ(o.tools),n.managedEnrollmentRevertedTools){let _=[...n.managedEnrollmentRevertedTools,...s.revertedTools??[]];l=X0(l,_)}}catch(_){return R(_.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 _=fd(o.enroll);if(_&&(!o.gateway||s.enrolledCert||Ym(_.token)))try{let L=await Ei("Resolving enrollment link\u2026",()=>aS(_)),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(Ym(_.token))return R(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 R(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 _=gS(o.claim);if(!_)return R("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let L=await Ei("Connecting this machine\u2026",()=>wS({cpOrigin:_.cpOrigin,claim:_.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 R(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 _=St(o.sso);if(!_)return R(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 hd({cpOrigin:_.cpOrigin,tenantId:_.tenantId,gatewayUrl:o.gateway,log:pe=>$(pe),open:r()?_a:void 0}),J=await Ei("Waiting for SSO sign-in\u2026",()=>yd(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 R(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(_){return R(_.message),1}let b,k;y&&!o.revert&&$(`Gateway: ${g} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&dg(g)&&P(`${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||TJ(s),I,E,T,O,F,q,de=async _=>{await yo();let L=cS(_.token),J=fS(s.enrolledCert,s.enrolledCertExpiry,_.deploymentId,Date.now(),L,s.enrolledTokenHash,_.expectedUser),pe=J?await $e():void 0,ut=Ft()||void 0,j=J&&pe&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:pe,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,_e=pt=>mS({cpOrigin:_.cpOrigin,token:_.token,gatewayOrigin:g,email:_.email,team:_.team,machineId:_.machineId,deploymentId:_.deploymentId,machineUuid:ut,reuse:pt?j:void 0}),ke=!!j,Xe=await(async()=>{try{return await _e(ke)}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"),ke=!1,await _e(!1);throw pt}})();S=Xe.clientKey,o.user=Cu(o.user,Xe.user),o.team=Cu(o.team,Xe.team),I=Xe.cert,E=Xe.cert.payload.expiresAt,q=Xe.expiresAt,F=void 0,ke||(T=Xe.privateKeyPem),ke||(O=L),B(`Enrolled${Xe.user?` as ${Xe.user}`:""}${ke?" (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 _=fd(o.enroll);if(!_){let L=oS(o.enroll);return R(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?Id():void 0,J=p==="mdm"&&!u?JE():void 0,pe=p==="mdm"&&!u&&!J?YE(f,Ld()):void 0,ut=J??pe;if(ut){let ke=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 ${ke}.`:`Enrolling as ${ke}.`)}let j=u??ut??xJ(o.user);if(!o.machine&&!o.user&&!u&&!ut){let ke=HI();ke.distinct||(P(` Enrolling as "${ke.identity}" \u2014 this may not be unique to you.`),P(ke.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"),P(ke.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."),P(" Re-run with `--user you@company.com` (or set `git config --global"),P(" user.email`) so your usage is attributed to you."))}let _e=o.machine?`machine:${L}`:m?j:void 0;await de({cpOrigin:_.cpOrigin,token:_.token,email:j,team:o.team,machineId:L,deploymentId:d,expectedUser:_e})}catch(L){return R(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."),dS(L)?3:1}}if(h){await yo();try{let _=Ft()||void 0,L=await Xt(g,h.cert,h.privateKeyPem,{machineUuid:_});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,T=h.privateKeyPem,q=L.expiresAt;let J=o.sso?St(o.sso):void 0;F=J?`${J.cpOrigin}/sso/${J.tenantId}`:w,B(`Enrolled${L.user?` as ${L.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(_){return R(_ instanceof Error?_.message:String(_)),_ instanceof lt&&_.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 _=o.yes;b=await VI(o.user,s.name,_),k=await KI(o.team,s.team,_)}if(!o.revert&&!o.dryRun){let _=ux(await dx(g,S),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if(_.lane){let L=_.lane==="subscription";o.subscription=L,o.placeholder=!L;let J=L?"your own subscription seat":"the organization's provider account";_.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 ce;!o.revert&&!o.subscription&&!o.placeholder&&(ce=await fn(),H("Detecting your sign-ins"),A(` Claude (Anthropic): ${a?et("BYO upstream key (passthrough)"):ce.anthropic?et("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),A(` Codex (ChatGPT): ${ce.openai?et("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),!ce.anthropic&&!ce.openai&&!ce.copilot&&Fr()&&(P(" No subscription sign-ins found on this host. Sign-ins do not cross the"),P(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),P(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),P(" 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:ce,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 R("Invalid personal gateway key: expected a minted ark_ credential. Re-run with --enroll/--sso, or set ANYRAY_CLIENT_KEY to a valid key."),1;if(!o.revert&&!K.clientKey){H("Enrollment required");let _="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(P(` ${_}`),$(" Dry run only \u2014 no placeholder configuration will be written."),await RR(l,"after-enrollment"),$(`
|
|
1069
|
+
Dry run complete \u2014 no files were written.`),0):(R(` ${_}`),1)}o.revert||OJ(K,l),c&&!o.revert&&await RR(l,"plan"),o.dryRun&&$(`
|
|
1070
|
+
Dry run \u2014 no files will be written.`);let W=await XJ(o,c,l.length,{isInteractive:r,confirm:n.confirm});if(W==="non-interactive")return R(`
|
|
1071
1071
|
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(W==="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 _=await Xd(K.origin);if(!_.reachable)return R(`
|
|
1072
1072
|
Gateway ${K.origin} is not reachable (${_.detail}).`),A(v(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
|
|
1073
1073
|
that would break them until you re-run with --revert.`)),A(`
|
|
1074
|
-
Start the gateway and try again, or pass --force to configure anyway.`),1;B(`Gateway reachable (${_.detail}).`)}let Z=o.revert?[]:await
|
|
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,
|
|
1074
|
+
Start the gateway and try again, or pass --force to configure anyway.`),1;B(`Gateway reachable (${_.detail}).`)}let Z=o.revert?[]:await MJ(l,K.origin),X=[],Je=()=>{X.length!==0&&(H("Reopening"),UJ(X),X=[])};if(Z.length>0){let _=Z.map(J=>J.title),L=_.length===1?"it":"them";if(H("Open apps"),BJ(o,Wt()))o.quitApps===!0||await Ea(FJ(_))?X=await WJ(Z):$(` Leaving ${L} open \u2014 restart when convenient.`);else{let J=o.noQuitApps===!0?"":" (or pass --quit-apps)";$(o.dryRun?` Would offer to quit ${_.join(", ")} \u2014 dry run, nothing was closed.`:` ${_.join(", ")} ${_.length===1?"is":"are"} open; restart ${L} to pick this up${J}.`)}}let We=async()=>{if(!o.dryRun)try{await tt()}catch{return R("Could not prepare the owner-only Anyray state directory."),1}let _=CI(s,q),L=s.anyrayFleetManaged===!0&&await Ao().catch(()=>!1),J=W0(o,OR(),L),pe=!!(C&&K.clientKey===C&&!I),ut=!pe&&!!(I??s.enrolledCert),j=l.some(Ne=>AI.has(Ne.id)),_e=!o.revert&&o.noKeyRefresh!==!0&&ut&&(_||!j),ke=o.dryRun?await Po(s):await lp(),Xe=ke==="healthy";if(ke==="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:O??s.enrolledTokenHash,ssoLink:pe?void 0:h?F: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 PJ(s,Ne,T,void 0,pe)}catch{return R("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}q&&!pe&&await Ia({expiresAt:q})}if(ge)if(o.dryRun)await $u()&&(H("Enrollment"),A(" would remove the stored gateway credential"));else{await rg(s),await Dd().catch(()=>{});try{await Xi()&&(H("Enrollment"),B(" Removed the stored gateway credential."),$(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(Ne){H("Enrollment"),P(" Could not remove the stored gateway credential."),P(` 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,Pr=NJ(pt,o,s.managedTools);if(Pr.length>0){H("Not configured \u2014 needs your say-so");for(let Ie of Pr)P(` ${Ie.id}: ${LR(Ie)??"changes where inference is billed"}.`),A(` Configure it deliberately with \`npx anyray-connect --tools ${Ie.id}\`.`);let Ne=new Set(Pr.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){H("Fleet policy");for(let Ie of Ne)P(` ${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:Ua,manualAdminOnly:Vi,manualAdminOnlyIds:Ha,results:Ga}=await DJ(pt,K,me,o.revert,new Set(o.tools??[])),Va;if(jy(o)){H("Endpoint agent");try{Va=await(n.installEndpointAfterEnrollment??J0)({gateway:g,clientKey:K.clientKey})}catch{$("Endpoint agent setup did not complete. Tool routing remains configured.")}}let ko=J&&F0(Va),Ka=_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 ae({...await D(),refreshSchedulerEnabled:!1}).catch(()=>{}),o.dryRun||(await jn(Ga,o.revert,ge).catch(()=>{}),ge&&await zi().catch(()=>{})),await VJ({want:Ka,scopedRevert:!!o.revert&&!ge,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!Ka&&await kc(),trayManaged:Xe}),!o.revert&&!o.dryRun&&!pe){let Ne=T??await $e();Ne&&await Eh(await D(),Ne).catch(()=>{})}if(Je(),H("Summary"),o.dryRun)$("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){B(`Reverted (${Gi} file(s) touched).`),$("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let Ne=await XI();Ne.length>0&&(H("This repo carries its own Anyray routing"),P(` Committed here: ${Ne.join(", ")}`),P(" Those are tracked files, so they route every checkout of this"),P(" repo \u2014 this machine included, and your teammates' too. This"),P(" revert only removed THIS machine's own configuration."),A(`
|
|
1076
1076
|
Remove them from the repo (then commit):`),A(v(" anyray-connect --project --revert")));let Ie=Nc(K);Ie.length>0&&(H("This terminal still points at the gateway"),P(` Still exported here: ${Ie.join(", ")}`),P(" Removing the block from your shell profile cannot reach a shell"),P(" that already ran it. Until these are gone, your tools keep"),P(" reaching the gateway and now fail with 401."),A(`
|
|
1077
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(B(`Done (${Gi} file(s) written).`),Ua.length>0){let xt=Vi.length===Ua.length;H(xt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let
|
|
1079
|
-
Skipped the connection smoke test (--skip-verify).`):await
|
|
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(B(`Done (${Gi} file(s) written).`),Ua.length>0){let xt=Vi.length===Ua.length;H(xt?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let lg of LJ(Ua,Vi,Ha.includes("claude-desktop")?process.platform:void 0))P(lg);if(Ha.includes("claude-desktop")&&!o.dryRun)try{await $J(K)}catch{P(" Could not write the administrator profile locally. Your admin can generate it with `anyray-connect desktop fleet static macos <helper-path> --gateway <url>`.")}Wt()&&!o.yes&&!xt&&(await Ea("Have you applied the manual settings shown above?")?B("Acknowledged."):P("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 GJ(K,l.map(xt=>xt.id)),H("What's next");let Ne=new Set(Ga.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
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
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 \\
|
|
1082
1082
|
-H "Content-Type: application/json" \\
|
|
1083
1083
|
-H "Authorization: Bearer ${K.clientKey?`<your personal key (${_t(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
|
|
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 JJ(o.revert,o.dryRun,We,n.withProfileLock)}catch(_){if(_ instanceof Error&&_.message==="connect profile is busy; retry the command")return R("Another Connect update is in progress. Try again."),1;throw _}finally{Je()}};$R(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});
|