anyray-connect 0.11.188 → 0.11.189
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 +174 -174
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var sO="http://localhost:8787",rs="anyray-placeholder",Ae=e=>{let t=e?.trim();return!!(t&&/^ark_[A-Za-z0-9_-]{20,512}$/.test(t))},Kt=e=>{let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t},$u=(e,t)=>e?.trim()||process.env[t]?.trim()||void 0,iO=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),$g=e=>{try{let{protocol:t,hostname:n}=new URL(e);return t==="http:"&&!iO.has(n)}catch{return!1}},jt=e=>{let t=Kt(e||process.env.ANYRAY_GATEWAY_URL||sO),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},Re=(e={})=>{let t=jt(e.origin),n=e.placeholderKey?.trim()||rs,r=e.clientKey?.trim()||process.env.ANYRAY_CLIENT_KEY?.trim()||void 0,o={user:e.user?.trim()||void 0,team:e.team?.trim()||void 0,intent:$u(e.intent,"ANYRAY_METADATA_INTENT"),intentLabel:$u(e.intentLabel,"ANYRAY_METADATA_INTENT_LABEL"),session:$u(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 xc,platform as bp}from"node:os";import{join as Jr}from"node:path";import{mkdir as yp,readFile as FT,rename as WT,writeFile as Sc,rm as Yr}from"node:fs/promises";import{spawnSync as UT}from"node:child_process";import{homedir as kc}from"node:os";import{join as vc}from"node:path";import{access as hO,chmod as yO,mkdir as Bu,open as Gu,readFile as Vg,rm as Zt,stat as Fg,utimes as gO}from"node:fs/promises";import{createHash as wO,randomUUID as Kg}from"node:crypto";import{dirname as Vu,join as bO}from"node:path";import{isDeepStrictEqual as Bo}from"node:util";import{randomUUID as cO}from"node:crypto";import{lstat as lO,open as dO,readFile as Mu,rename as ec,rm as uO,writeFile as pO}from"node:fs/promises";import{platform as Mg}from"node:os";var Bg=e=>e?.code==="ENOENT",fO=new Set(["EBUSY","EXDEV","ETXTBSY"]),Qn=async(e,t=Mg())=>{try{await e.sync()}catch(n){if(t!=="win32")throw n}},mO=async(e,t,n={})=>{let r=await Mu(e),o;try{o=await Mu(t)}catch(s){if(!Bg(s))throw s;await pO(t,r);return}let a=async s=>{let i=await dO(t,"r+");try{await i.write(s,0,s.length,0),await i.truncate(s.length),await Qn(i)}finally{await i.close()}};try{if(await a(r),await n.corruptAfterWrite?.(t),!(await Mu(t)).equals(r))throw Object.assign(new Error("in-place publication did not persist"),{code:"EIO"})}catch(s){throw await a(o).catch(()=>{}),s}},ye=async(e,t,n=Mg(),r={})=>{let o=r.rename??ec;if(n!=="win32"){try{await o(e,t)}catch(i){if(!fO.has(i?.code??""))throw i;await mO(e,t,r)}return}let a=`${t}.anyray-old-${process.pid}-${cO()}`,s=!1;try{let i=await lO(t);if(!i.isFile()&&!i.isSymbolicLink())throw new Error("refusing to replace a non-file destination");await ec(t,a),s=!0}catch(i){if(!Bg(i))throw i}try{await ec(e,t)}catch(i){if(s)try{await ec(a,t)}catch{throw new Error(`failed to publish file and restore the previous destination; recovery copy remains at ${a}`)}throw i}s&&await uO(a,{force:!0})};var os=e=>`${e}.anyray-bak`,jg=async e=>{let t;try{t=await Gu(Vu(e),"r"),await t.sync()}catch(n){if(process.platform!=="win32")throw n}finally{await t?.close().catch(()=>{})}},Wg=async(e,t)=>{let n,r;try{n=await Gu(e,"wx",384),await n.writeFile(t,"utf-8"),await Qn(n)}catch(o){r=o}finally{await n?.close().catch(()=>{})}if(r)throw n&&await Zt(e,{force:!0}).catch(()=>{}),r;await jg(e)},AO=async e=>{let t;try{t=await Gu(e,"r"),await Qn(t)}finally{await t?.close().catch(()=>{})}await jg(e)},x=async e=>{try{return await hO(e),!0}catch{return!1}},B=async e=>{if(!await x(e))return{};let t=await Vg(e,"utf-8");if(!t.trim())return{};let n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n},X=async(e,t,n={})=>{await Bu(Vu(e),{recursive:!0,mode:448});let r=os(e);if(n.backup!==!1&&!await x(r)){let a=await x(e),s=a?await Vg(e,"utf-8"):`{}
|
|
3
3
|
`;if(a||n.tombstoneAbsent!==!1)try{await Wg(r,s)}catch(i){if(i.code!=="EEXIST")throw i}}let o=`${e}.anyray-tmp-${process.pid}-${Kg()}`;try{await Wg(o,`${JSON.stringify(t,null,2)}
|
|
4
|
-
`),await ye(o,e),await
|
|
5
|
-
`,{mode:384})}catch(s){throw await Wo(t,{recursive:!0,force:!0}).catch(()=>{}),s}return async()=>{try{JSON.parse(await as(n,"utf-8")).nonce===o&&await Wo(t,{recursive:!0,force:!0})}catch{}}}catch(s){if(s.code!=="EEXIST")throw s}if(!(await
|
|
6
|
-
`,{mode:384}),await Zu(r,384);try{await ye(r,n)}catch(o){throw await Wo(r,{force:!0}).catch(()=>{}),o}},ce=async e=>{if(rc.getStore()===!0){await Ku(e);return}let t=await Xu();try{await Ku(e)}finally{await t()}},nw=async e=>{let t=async()=>{let r=await P(),{next:o,result:a}=e(r);return o&&await Ku(o),a};if(rc.getStore()===!0)return t();let n=await Xu();try{return await t()}finally{await n()}},ju=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],qg="ssoLink",zu=async()=>{let e=await P();return ju.some(t=>e[t]!==void 0)?!0:await Fe()!==void 0},sc=async()=>{let e=await P(),t=ju.some(a=>e[a]!==void 0),n=e[qg]!==void 0,r=e.byoUpstream!==void 0,o=await Fe()!==void 0;if(t||n||r||e.managedEnrollmentDisabled!==!0){let a={...e};for(let s of ju)delete a[s];delete a[qg],delete a.byoUpstream,a.managedEnrollmentDisabled=!0,delete a.anyrayFleetManaged,await ce(a)}if(await ss(),await Fe())throw new Error(`could not remove the dev key from ${ee()}`);return t||n||r||o},er=async(e,t,n=!1)=>{let r=await P(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=r.offboardedAt;for(let p of e){let h=p.status==="configured"||p.status==="queued";!t&&h&&(o.add(p.id),a.delete(p.id),s=void 0),t&&(p.status==="reverted"||p.status==="queued")&&(o.delete(p.id),a.add(p.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((p,h)=>p===c[h])&&r.revertedTools!=null&&l.length===d.length&&l.every((p,h)=>p===d[h])&&s===r.offboardedAt)return;let{offboardedAt:f,...m}=r;await ce({...m,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},ic=async(e=new Date().toISOString())=>{await ce({...await P(),offboardedAt:e})};var Ho=e=>
|
|
7
|
-
`)},sn=(e,t={})=>{let n=e.byoUpstream,r=!n&&te(e,"anthropic"),o=me({...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}},Tw=async()=>{try{let e=await P();return e.gateway?{origin:new URL(e.gateway).origin,metadata:me({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},nt=async(e="auto")=>e==="profile"?Tw():e==="claude"?Ow():await Ow()??await Tw(),bc=async(e={})=>{let t=e.readTarget??nt,n=e.loadProfile??P,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a;try{a=new URL(r.gateway).origin}catch{return"unreadable"}return a===o.origin?"owned":"foreign"},Yt=e=>{let t={"content-type":"application/json"};return e.metadata&&(t["x-anyray-metadata"]=e.metadata),e.apiKey&&(t["x-anyray-api-key"]=e.apiKey),t},Ac=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),hT);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Yt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var ir=()=>vc(kc(),".claude","settings.json"),Cc=()=>vc(kc(),".claude.json"),yT=hc,On="anyray",gT=()=>({type:"stdio",...Ge("claude"),alwaysLoad:!0}),cr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wT=e=>e instanceof Error?e.name:"UnknownError",bT={unreadable:"mcp_unreadable",unwritable:"mcp_not_writable",foreign:"mcp_foreign","not-persisted":"mcp_not_persisted"},AT=(e,t)=>{switch(e){case"foreign":return`MCP name conflict in ${t}: mcpServers.${On} 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.`}},CT={readJson:B,writeJson:(e,t)=>X(e,t)},kT=async(e,t=CT)=>{for(let n=0;n<2;n+=1){let r;try{r=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}if(vT(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=cr(a)?a[On]:void 0;if(s&&_t(s,"claude"))return{outcome:"registered"}}return{outcome:"failed",failure:"not-persisted"}},vT=e=>{if("mcpServers"in e&&!cr(e.mcpServers))return"conflict";let t=cr(e.mcpServers)?{...e.mcpServers}:{},n=t[On];return n!==void 0&&!_t(n,"claude")?"conflict":(t[On]=gT(),e.mcpServers=t,"installed")},_w=e=>{let t=e.mcpServers;return!t||!(On in t)||!_t(t[On],"claude")?!1:(delete t[On],Object.keys(t).length===0&&delete e.mcpServers,!0)},ST=e=>{pc(e,"PostToolUse",Ye,xn(Tt(Ye),{matcher:"*"})),pc(e,"UserPromptSubmit",or,xn(Tt(or)))},ET=e=>{pc(e,"SessionStart",ar,xn(Tt(ar),{async:!0}))},Lw=e=>Vo(e,"SessionStart",ar),Pw=e=>{let t=Vo(e,"PostToolUse",Ye),n=Vo(e,"UserPromptSubmit",or),r=Lw(e);return t||n||r},IT="print-key",xT=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(De()),Kr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===IT&&xT(t)},RT=async(e,t)=>{let n=(await Ur(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of yT){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},OT=e=>typeof e.apiKeyHelper=="string"&&!Kr(e),Nw=async e=>{let t=await pp(),n=async()=>t,[r,o,a]=await Promise.all([Aw({userSettings:e,readManaged:n}),Iw({userSettings:e,readManaged:n}).catch(()=>[]),Ew({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},Dw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await Nw(e),o=up(t),a=Rw(n);return{routingOverrides:[...t.map(i=>({problem:dp(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:xw(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},lr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=vc(kc(),".claude"),t=await x(e);return{installed:t,detail:t?ir():"no ~/.claude directory"}},async apply(e,t){let n=ir(),r=await B(n),o=hw(r),a=await yw(e.origin,e.clientKey,o),s=gw(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=sn(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:m}=await Nw(r),p=f.filter(T=>!T.repairable),h=f.filter(T=>T.repairable),w=[...p.map(T=>`WARNING: ${dp(T)}.`),...p.length?[up(p)]:[],...m.state==="fine"?[]:[`WARNING: ${gc(m)}.`,wc(m)],...h.map(T=>Cw(T)),`${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:T}of Rn)h.some(W=>W.name===T)?g[T]="":g[T]===""&&(process.env[T]??"").trim()===""&&delete g[T];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 T of mw)delete g[T];let b=!!e.clientKey,k=oe(),C=OT(r);!c&&!l&&b&&k&&!C?(r.apiKeyHelper=fw(),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).")):Kr(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?(ET(r),w.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):Lw(r),oe()?(ST(r),w.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(Pw(r),w.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${De()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await X(n,r);let E=[n],I=Cc(),_;if(oe()){let T=await kT(I);T.outcome==="registered"?(E.push(I),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(AT(T.failure,I)),_=bT[T.failure])}else try{let T=await B(I);_w(T)&&(await X(I,T),E.push(I))}catch(T){w.push(`Could not clean up a stale Anyray MCP registration in ${I} (${wT(T)}).`)}return{status:"configured",messages:w,changedFiles:E,..._?{errorClass:_}:{}}},skillsDir(){return vc(kc(),".claude","skills")},async pointsAt(e){let t=ir();if(!await x(t))return!1;try{let o=(await B(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await B(ir()).catch(()=>({}));return Dw(e)},async routingOverrides(){let e=await B(ir()).catch(()=>({}));return(await Dw(e)).routingOverrides},async mcpStatus(){if(!oe())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=Cc();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let r=(await B(e)).mcpServers?.[On];return r?_t(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=ir();if(!await x(n))e="missing";else try{let s=await B(n);if(s.hooks===void 0)e="missing";else if(!cr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>rr(c,Ye))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>rr(c,Ye)&&cr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>cr(l)&&fc(l.command,Ye))))}}catch{e="unreadable"}let r,o=!0,a=Cc();if(!await x(a))r="missing";else try{let s=await B(a);if(s.mcpServers===void 0)r="missing";else if(!cr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[On];r=i===void 0?"missing":_t(i,"claude")?"owned":"foreign",r==="owned"&&(o=mc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Gr()?"owned":"missing",beacon_target:await bc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await B(ir()),t=cr(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=ir();if(!await x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await B(t),r=n.env,o=Pw(n),a=Kr(n);a&&delete n.apiKeyHelper;let s=r?await RT(t,r):[],i=ww(typeof n.model=="string"?n.model:void 0,(await Ur(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await X(t,n,{backup:!1});let c=[`removed Anyray keys from ${t}`];i!==void 0&&c.push(`Put model back to ${i} \u2014 dropped the [1m] alias Anyray added for your context window.`),o&&c.push("Removed the Anyray PostToolUse, UserPromptSubmit, and SessionStart hooks."),a&&c.push("Removed the Anyray apiKeyHelper."),s.length&&c.push(`Put back the ${s.join(" and ")} you had set before Anyray.`);let l=Cc();try{let d=await B(l);_w(d)&&(await X(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await ie(t),{status:"reverted",messages:c,changedFiles:[t]}}};import{delimiter as TT,dirname as _T}from"node:path";var dr=e=>{let{command:t,args:n}=an([e]);return{command:t,args:n}},jr=()=>nr(),gt=(e="",t=process.env.PATH??"",n=dc(),r=nr())=>{let a=t.split(TT).filter(Boolean).some(s=>s===n)||_T(r)!==n?"anyray-connect":r;return e?`${a} ${e}`:a};import{rm as PT,stat as DT}from"node:fs/promises";import{homedir as $w,platform as LT}from"node:os";import{join as NT}from"node:path";var fp="Anyray",$T=(e=$w())=>NT(e,"Applications",`${fp}.app`),mp=async(e={})=>{if((e.os??LT())!=="darwin")return{ok:!0,messages:[]};let n=$T(e.home??$w());try{return await DT(n).then(()=>!0,()=>!1)?(await PT(n,{recursive:!0,force:!0}),{ok:!0,messages:[`Removed the legacy ${fp}.app background item from ~/Applications.`]}):{ok:!0,messages:[]}}catch(r){return{ok:!1,messages:[`Could not remove the legacy ${fp}.app background item (${r?.name??"Error"}).`]}}};import{homedir as Mw,userInfo as MT}from"node:os";var Bw=()=>{try{return Mw()!==MT().homedir}catch{return!1}},hp=e=>[`Skipped ${e} \u2014 HOME (${Mw()}) 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 cn=(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,Zr=(e=process.env)=>cn(e)!==null,Tn=e=>e==="codespaces"||e==="devcontainer",Ko=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var Fw=()=>Jr(xc(),".anyray","logs"),wp=()=>Jr(Fw(),"connect-refresh.log"),Ic=1800,Rc="ai.anyray.connect.refresh",ys="anyray-refresh",Ap="\\AnyrayConnectKeyRefresh",Oc=Rc,gs=ys,hs=Ap,UT=String(Ic/60),Cp=(e,t)=>{let n=WT(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},kp=()=>Jr(xc(),"Library","LaunchAgents",`${Oc}.plist`),vp=()=>Jr(xc(),".config","systemd","user"),Ww=()=>Jr(vp(),`${gs}.service`),Ec=()=>Jr(vp(),`${gs}.timer`),gp=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Tc=()=>dr(ar),HT=(e=Tc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${gp(o)}</string>`).join(`
|
|
4
|
+
`),await ye(o,e),await yO(e,384),await AO(e)}finally{await Zt(o,{force:!0}).catch(()=>{})}},Zg=1,Ug=3e4,CO=5e3,kO=/^[a-f0-9]{64}$/,Yg=e=>`${e}.pending`,vO=e=>`${e}.lock`,Fu=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=>Fu(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${Fu(t[n])}`).join(",")}}`},Wu=(e,t)=>({exists:e,sha256:wO("sha256").update(Fu(t)).digest("hex")}),Uu=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Hg=e=>Uu(e)&&typeof e.exists=="boolean"&&typeof e.sha256=="string"&&kO.test(e.sha256),SO=e=>Uu(e)&&e.transactionVersion===Zg&&Hg(e.before)&&Hg(e.after)&&Uu(e.journal),Hu=(e,t)=>e.exists===t.exists&&e.sha256===t.sha256,Fo=async(e,t)=>{try{return await B(e)}catch{throw new Error(`${t} is malformed; no configuration was changed`)}},EO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Jg=async e=>{let t=vO(e),n=bO(t,"owner.json");await Bu(Vu(t),{recursive:!0,mode:448});for(let r=0;r<2;r++){let o=Kg();try{await Bu(t,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s;let i=!1;try{let c=await Fo(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=!EO(c.pid)||l>Ug}catch{try{i=Date.now()-(await Fg(t)).mtimeMs>Ug}catch{i=!1}}if(!i||r>0)throw new Error("ownership transaction already in progress");await Zt(t,{recursive:!0,force:!0});continue}try{await X(n,{pid:process.pid,nonce:o,createdAt:Date.now()},{backup:!1})}catch(s){throw await Zt(t,{recursive:!0,force:!0}).catch(()=>{}),s}let a=setInterval(()=>{(async()=>{try{if((await Fo(n,"ownership journal")).nonce!==o)return;let i=new Date;await gO(n,i,i)}catch{}})()},CO);return a.unref(),async()=>{clearInterval(a);try{(await Fo(n,"ownership journal")).nonce===o&&await Zt(t,{recursive:!0,force:!0})}catch{}}}throw new Error("ownership transaction already in progress")},Xg=async e=>{let t=await x(e),n={};if(t)try{n=await B(e)}catch{throw new Error("configuration is malformed during ownership recovery; it was left unchanged")}return{exists:t,value:n,fingerprint:Wu(t,n)}},zg=async(e,t)=>{let n=Yg(t);if(!await x(n))return;let r=await Fo(n,"prepared ownership transaction");if(!SO(r))throw new Error("prepared ownership transaction is invalid; no recovery write was attempted");let o=await Xg(e),a=await x(t),s=await x(os(e)),i=Hu(o.fingerprint,r.before),c=Hu(o.fingerprint,r.after),l=r.journal.fileExisted;if(c&&(a||l===!1||s)&&(!i||a||s)){await X(t,r.journal,{backup:!1}),await Zt(n,{force:!0});return}if(i){await Zt(n,{force:!0}),a||await ie(e);return}throw new Error("configuration changed during an interrupted ownership transaction; recovery files were preserved")},tc=async(e,t,n)=>{let r=await Jg(t);try{return await zg(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 Fo(e,"ownership journal");if(!(n&&Bo(a,t))){if(!Bo(a,r))throw new Error("journaled JSON rollback found a concurrent file edit");n?await X(e,t,{backup:!1}):await Zt(e,{force:!0})}},nc=async(e,t={})=>{let{configPath:n,current:r,next:o,journalPath:a,journal:s,fileExisted:i}=e,c=await Jg(a);try{await zg(n,a);let l=await Xg(n),d=Wu(i,r),u=await x(a),f=u?await Fo(a,"ownership journal"):void 0,m=f&&typeof f.fileExisted=="boolean"?{...s,fileExisted:f.fileExisted}:s;if(!Hu(l.fingerprint,d)){if(Bo(l.value,o)&&f&&Bo(f,m))return;throw new Error("configuration changed before the ownership transaction acquired its lock; retry")}if(l.exists&&Bo(l.value,o)&&f&&Bo(f,m))return;let p=await x(os(n));if(f?.fileExisted===!0&&!p)throw new Error("ownership backup is missing; configuration was left unchanged");if(p&&!f)throw new Error("an unjournaled ownership backup already exists; configuration was left unchanged");let h=Yg(a),g={transactionVersion:Zg,before:l.fingerprint,after:Wu(!0,o),journal:m};await X(h,g,{backup:!1});try{await X(n,o,f?{backup:!1}:{tombstoneAbsent:!1}),await(t.writeJournal??X)(a,m,{backup:!1}),await Zt(h,{force:!0})}catch(y){try{await Gg(n,l.value,l.exists,o)}catch(w){throw new AggregateError([y,w],"ownership journal publication failed and config rollback was incomplete")}try{await Gg(a,f??{},u,m),await Zt(h,{force:!0}),!p&&!f&&await ie(n)}catch(w){throw new AggregateError([y,w],"ownership journal publication failed after config rollback")}throw y}}finally{await c()}},Ur=async e=>{try{return await B(os(e))}catch{return{}}},ie=async e=>{await Zt(os(e),{force:!0}).catch(()=>{})};import{access as XO}from"node:fs/promises";import{spawnSync as NO}from"node:child_process";import{readFileSync as $O,realpathSync as cs,statSync as aw}from"node:fs";import{access as MO,cp as sw,mkdir as rw,readdir as BO,readFile as ep,realpath as FO,rename as WO,rm as qu,writeFile as UO}from"node:fs/promises";import{tmpdir as HO}from"node:os";import{basename as Uo,dirname as He,join as Pe,resolve as GO}from"node:path";import{writeFile as oc,readFile as as,chmod as Zu,stat as Yu,mkdir as Qg,rm as Wo}from"node:fs/promises";import{AsyncLocalStorage as IO}from"node:async_hooks";import{randomUUID as xO}from"node:crypto";import{homedir as ew}from"node:os";import{join as Hr}from"node:path";var ee=()=>Hr(ew(),".anyray"),tw=async()=>{let e=ee();try{if((await Yu(e)).isDirectory())return Hr(e,"connect.json")}catch{}return e},Ju=()=>Hr(ee(),"dev-key.pem"),et=async()=>{let e=ee(),t;try{if(!(await Yu(e)).isDirectory())t=await as(e,"utf-8").catch(()=>{}),await Wo(e,{force:!0});else return}catch{}if(await Qg(e,{recursive:!0,mode:448}),t!==void 0){let n=Hr(e,"connect.json");await oc(n,t,{mode:384}),await Zu(n,384)}},ac=async e=>{await et();let t=Ju();await oc(t,e,{mode:384}),await Zu(t,384)},Fe=async()=>{try{let e=await as(Ju(),"utf-8");return e.trim()?e:void 0}catch{return}},ss=async()=>{await Wo(Ju(),{force:!0}).catch(()=>{})},P=async()=>{try{let e=await as(await tw(),"utf-8"),t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?{}:t}catch{return{}}},RO=0,OO=3e4,TO=5e3,_O=25,PO=()=>Hr(ew(),".anyray-connect-profile.lock"),rc=new IO,DO=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},LO=async e=>{try{let t=JSON.parse(await as(Hr(e,"owner.json"),"utf-8"));if(typeof t.pid=="number"&&Number.isSafeInteger(t.pid)&&t.pid>0)return!DO(t.pid)}catch{}return Date.now()-(await Yu(e)).mtimeMs>OO},Xu=async(e=TO)=>{let t=PO(),n=Hr(t,"owner.json"),r=Date.now()+e;for(;;){let o=xO();try{await Qg(t,{mode:448});try{await oc(n,`${JSON.stringify({pid:process.pid,nonce:o})}
|
|
5
|
+
`,{mode:384})}catch(s){throw await Wo(t,{recursive:!0,force:!0}).catch(()=>{}),s}return async()=>{try{JSON.parse(await as(n,"utf-8")).nonce===o&&await Wo(t,{recursive:!0,force:!0})}catch{}}}catch(s){if(s.code!=="EEXIST")throw s}if(!(await LO(t).catch(()=>!1)&&await Wo(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,_O))}}},is=async(e,t={})=>{if(rc.getStore()===!0)return e();let n=await Xu(t.waitMs);try{return await rc.run(!0,e)}finally{await n()}},Ku=async e=>{let t=Object.fromEntries(Object.entries(e).filter(([,o])=>o!==void 0)),n=await tw(),r=`${n}.${process.pid}.${RO++}.tmp`;await oc(r,`${JSON.stringify(t,null,2)}
|
|
6
|
+
`,{mode:384}),await Zu(r,384);try{await ye(r,n)}catch(o){throw await Wo(r,{force:!0}).catch(()=>{}),o}},ce=async e=>{if(rc.getStore()===!0){await Ku(e);return}let t=await Xu();try{await Ku(e)}finally{await t()}},nw=async e=>{let t=async()=>{let r=await P(),{next:o,result:a}=e(r);return o&&await Ku(o),a};if(rc.getStore()===!0)return t();let n=await Xu();try{return await t()}finally{await n()}},ju=["clientKey","clientKeyExpiresAt","enrolledCert","enrolledCertExpiry","enrolledCertLifetimeMs","enrolledTokenHash"],qg="ssoLink",zu=async()=>{let e=await P();return ju.some(t=>e[t]!==void 0)?!0:await Fe()!==void 0},sc=async()=>{let e=await P(),t=ju.some(a=>e[a]!==void 0),n=e[qg]!==void 0,r=e.byoUpstream!==void 0,o=await Fe()!==void 0;if(t||n||r||e.managedEnrollmentDisabled!==!0){let a={...e};for(let s of ju)delete a[s];delete a[qg],delete a.byoUpstream,a.managedEnrollmentDisabled=!0,delete a.anyrayFleetManaged,await ce(a)}if(await ss(),await Fe())throw new Error(`could not remove the dev key from ${ee()}`);return t||n||r||o},er=async(e,t,n=!1)=>{let r=await P(),o=new Set(r.managedTools??[]),a=new Set(r.revertedTools??[]),s=r.offboardedAt;for(let p of e){let h=p.status==="configured"||p.status==="queued";!t&&h&&(o.add(p.id),a.delete(p.id),s=void 0),t&&(p.status==="reverted"||p.status==="queued")&&(o.delete(p.id),a.add(p.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((p,h)=>p===c[h])&&r.revertedTools!=null&&l.length===d.length&&l.every((p,h)=>p===d[h])&&s===r.offboardedAt)return;let{offboardedAt:f,...m}=r;await ce({...m,...s!==void 0?{offboardedAt:s}:{},managedTools:i,revertedTools:l})},ic=async(e=new Date().toISOString())=>{await ce({...await P(),offboardedAt:e})};var Ho=e=>GO(e).replace(/\\/g,"/").toLowerCase(),Qu=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",ls=e=>`${e}.source`,iw=e=>/(^|\/)_npx(\/|$)/.test(Ho(e)),tp=e=>/(^|\/)node_modules\/anyray-connect\/dist\/index\.js$/.test(Ho(e)),np=e=>{let t=Ho(e),n=[HO(),"/tmp","/private/tmp","/var/folders","/private/var/folders"].map(Ho);return iw(t)||n.some(r=>t===r||t.startsWith(`${r}/`))},ut=()=>({execPath:process.execPath,scriptPath:process.argv[1]}),ds=e=>/[\\/](node|node\.exe)$/i.test(e),tr=(e=ut())=>ds(e.execPath)&&e.scriptPath?e.scriptPath:e.execPath,ow=e=>{try{let t=aw(e);return t.isFile()?t.size:void 0}catch{return}},rp=e=>{let t=He(e);if(Uo(t)==="versions")return t;let n=He(t);return Uo(n)==="versions"?n:void 0},lc=(e,t)=>t!==void 0&&(He(e)===t||He(He(e))===t),VO=e=>{let t=rp(e);if(!t)return;let n=Pe(He(t),"bin",Qu());try{let r=cs(n);return r===cs(e)||lc(r,cs(t))?n:void 0}catch{return}},Go=(e=ee(),t=process.platform)=>{let n=Pe(e,"bin",Qu(t));try{let r=cs(n),o=cs(Pe(e,"versions"));if(lc(r,o))return n;if(t==="win32"){let a=$O(ls(n),"utf8").trim();if(!/^[0-9A-Za-z.-]+$/.test(a))return;let s=ow(Pe(o,a,Qu(t)))??ow(Pe(o,a));if(s!==void 0&&s===aw(n).size)return n}}catch{return}},nr=(e=ut())=>{let t=tr(e),n=tp(t)||ap(t)?Go():void 0;return VO(e.execPath)??n??t},cw=(e=ut())=>nr(e)!==tr(e),an=(e,t=ut())=>{let n=nr(t);return ds(t.execPath)&&t.scriptPath!==void 0&&n===tr(t)?{command:t.execPath,args:[n,...e],entryPath:n}:{command:n,args:e,entryPath:n}},dc=(e=ut())=>{let t=nr(e);return!ds(e.execPath)&&!np(t)?He(t):Pe(ee(),"bin")},cc=async e=>{try{return await MO(e),!0}catch{return!1}},KO=async e=>{let t=await FO(e),n=He(t),r=He(n),o=Pe(r,"package.json"),a=await ep(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 cc(Pe(n,"index.js")))throw new Error("published package is missing dist/index.js");return{root:r,dist:n,packageJson:o,version:s.version}},jO=async(e,t)=>{let n=t;for(;;){let r=Pe(n,"node_modules",e);if(await cc(Pe(r,"package.json")))return r;let o=He(n);if(o===n)return;n=o}},ZO=async(e,t)=>{let n=new Set,r=[e];for(;r.length>0;){let o=r.shift(),a=JSON.parse(await ep(Pe(o,"package.json"),"utf8"));for(let s of Object.keys(a.dependencies??{})){if(n.has(s))continue;n.add(s);let i=await jO(s,o);if(!i)throw new Error(`runtime dependency "${s}" is not installed`);await sw(i,Pe(t,s),{recursive:!0}),r.push(i)}}},YO=async(e=ut())=>{let t=Go();if(t)return{command:t,args:[],entryPath:t};if(!ds(e.execPath)||!e.scriptPath)return{command:e.execPath,args:[],entryPath:e.execPath};let n=await KO(e.scriptPath);await et();let r=Pe(ee(),"bin",`connect-runtime-${n.version}`),o=Pe(r,"dist","index.js");if(!await cc(o)){let a=`${r}.stage-${process.pid}-${Date.now()}`;await qu(a,{recursive:!0,force:!0}),await rw(a,{recursive:!0,mode:448});try{await sw(n.dist,Pe(a,"dist"),{recursive:!0}),await UO(Pe(a,"package.json"),await ep(n.packageJson),{mode:384}),await ZO(n.root,Pe(a,"node_modules")),await rw(He(r),{recursive:!0,mode:448});try{await WO(a,r)}catch(s){if(!await cc(o))throw s}}finally{await qu(a,{recursive:!0,force:!0})}}return{command:e.execPath,args:[o],entryPath:o}},op=/^connect-runtime-(?!.*\.stage-)[0-9A-Za-z][0-9A-Za-z.-]*$/,JO=e=>{let t=Uo(He(He(e)));return op.test(t)?t:void 0},ap=(e,t=ee())=>{let n=He(He(e));return Ho(He(n))===Ho(Pe(t,"bin"))&&op.test(Uo(n))&&Uo(He(e))==="dist"&&Uo(e)==="index.js"},uc=async(e=ut())=>{let t=Pe(ee(),"bin"),n=JO(tr(e)),r=[];for(let o of await BO(t).catch(()=>[])){if(!op.test(o)||o===n)continue;let a=Pe(t,o);await qu(a,{recursive:!0,force:!0}).then(()=>!0,()=>!1)&&r.push(a)}return r},lw=async(e,t=ut())=>{let n=tr(t);if(!ds(t.execPath)||!iw(n)||Go())return;let r=await YO(t),o=NO(r.command,[...r.args,...e],{stdio:"inherit",env:process.env});if(o.error)throw o.error;return o.status??1};var sp=e=>/^[A-Za-z0-9_./:=-]+$/.test(e)?e:`"${e.replace(/"/g,'\\"')}"`,us=(e,t)=>[e,...t].map(sp).join(" "),xn=(e,t={})=>({...t.matcher!==void 0?{matcher:t.matcher}:{},hooks:[{type:"command",command:e,...t.timeout!==void 0?{timeout:t.timeout}:{},...t.async!==void 0?{async:t.async}:{}}]}),rr=(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))},pc=(e,t,n,r,o="append")=>{let a=e.hooks??{},i=(Array.isArray(a[t])?a[t]:[]).filter(c=>!rr(c,n));a[t]=o==="prepend"?[r,...i]:[...i,r],e.hooks=a},Vo=(e,t,n)=>{let r=e.hooks;if(!r||!Array.isArray(r[t]))return!1;let o=r[t],a=o.filter(s=>!rr(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)},ip=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=>!rr(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 Ye="__anyray-hook",dw="__anyray-codex-hook",or="__anyray-prompt-hook",uw="__anyray-shell-pretool",cp="__anyray-shell-run",pw="__anyray-read-pretool",ar="__anyray-refresh",ps=(e,t=[])=>{let{command:n,args:r}=an([e,...t]);return{command:n,args:r}},Tt=(e,t=[])=>{let n=ps(e,t);return[n.command,...n.args].map(sp).join(" ")},fc=(e,t,n=[])=>typeof e=="string"&&e.trim()===Tt(t,n),fw=()=>Tt("print-key"),De=()=>nr(),tt=np,oe=()=>!tt(De()),Gr=async()=>{if(!oe())return!1;try{return await XO(De()),!0}catch{return!1}},sr="__anyray-mcp-server",Ge=e=>ps(sr,[e]),zO=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>n===t[r]),mc=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e,r=Ge(t);return n.command===r.command&&zO(n.args,r.args)},_t=(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)===sr&&r.at(-1)===t};var te=(e,t)=>e.authMode==="subscription"?!0:e.authMode==="placeholder"?!1:e.seat?.[t]??!1,me=e=>{let t=Object.entries(e).filter(([,n])=>n);if(t.length!==0)return JSON.stringify(Object.fromEntries(t))};var Vr=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],mw=["ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],hc=[...Vr,"CLAUDE_CODE_MAX_CONTEXT_TOKENS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],qO=(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
|
+
`)},sn=(e,t={})=>{let n=e.byoUpstream,r=!n&&te(e,"anthropic"),o=me({...e.metadata,tool:e.metadata.tool??"claude-code"}),a=t.includeClientKey!==!1,s=t.includeAuthToken!==!1,{contextWindowTokens:i}=t,c=qO(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 lp}from"zod";var QO=5e3,eT=1e3,tT=1e8,nT=lp.object({modelContext:lp.object({contextTokens:lp.number().int().min(eT).max(tT)}).optional()}),hw=e=>{let t=e.model;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0},yw=async(e,t,n,r={})=>{if(!t||!n)return;let o=r.timeoutMs??QO,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=nT.safeParse(await c.json());return l.success?l.data.modelContext?.contextTokens:void 0}catch{return}finally{clearTimeout(s)}};var rT=1e6,fs="[1m]",oT=e=>{let t=e.trim().toLowerCase();return!(t.startsWith("claude-")||t.split(/[/.]/).some(r=>r.startsWith("claude-")))},gw=(e,t)=>!e||t===void 0?{}:oT(e)?{envTokens:t}:t<rT?{}:e.toLowerCase().endsWith(fs)?{}:{model:`${e}${fs}`},ww=(e,t)=>{if(!(!e||!e.toLowerCase().endsWith(fs))&&typeof t=="string"&&!t.trim().toLowerCase().endsWith(fs))return e.slice(0,-fs.length)};import{platform as aT}from"node:os";var Pt=(e=aT())=>{switch(e){case"darwin":return"/Library/Application Support/ClaudeCode/managed-settings.json";case"win32":return"C:\\Program Files\\ClaudeCode\\managed-settings.json";default:return"/etc/claude-code/managed-settings.json"}};var Rn=[{name:"CLAUDE_CODE_USE_BEDROCK",cloud:"AWS Bedrock"},{name:"CLAUDE_CODE_USE_VERTEX",cloud:"Google Vertex AI"}],yc=e=>typeof e=="string"&&e.trim()!=="",sT=(e,t)=>typeof e[t]=="string"&&!yc(e[t]),bw=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},iT=()=>B(Pt()).catch(()=>({})),Aw=async(e={})=>{let t=e.env??process.env,n=bw(e.userSettings??{}),r=bw(await(e.readManaged??iT)().catch(()=>({}))),o=[];for(let{name:a,cloud:s}of Rn)yc(r[a])?o.push({name:a,cloud:s,kind:"managed",source:`managed settings (${Pt()})`,repairable:!1}):yc(n[a])?o.push({name:a,cloud:s,kind:"userSettings",source:"~/.claude/settings.json env block",repairable:!0}):!sT(n,a)&&yc(t[a])&&o.push({name:a,cloud:s,kind:"shell",source:"shell environment",repairable:!0});return o},dp=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`,up=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.",Cw=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 cT=Rn.map(e=>e.name),lT=hc.filter(e=>!cT.includes(e)),kw=e=>typeof e=="string"&&e.trim()!=="",vw=e=>{let t=e.env;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}},dT=(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)},uT=e=>{if(typeof e=="string")try{return new URL(e.trim()).origin}catch{return}},pp=()=>B(Pt()).catch(()=>({})),Sw=pp,pT=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=>rr(r,Ye))},Ew=async(e={})=>{let t=await(e.readManaged??Sw)().catch(()=>({}));return t.disableAllHooks===!0?{state:"disabled"}:t.allowManagedHooksOnly===!0&&!pT(t)?{state:"restricted_dropping_ours"}:{state:"fine"}},gc=e=>e.state==="disabled"?`disableAllHooks is true in managed settings (${Pt()}) \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 (${Pt()}), 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",wc=e=>e.state==="disabled"?"Fix: ask the MDM owner to drop `disableAllHooks`, then restart Claude Code. Connect never overrides machine policy.":e.state==="restricted_dropping_ours"?"Fix: ask the MDM owner to drop `allowManagedHooksOnly`, or add the Anyray hooks to the managed file. `anyray-connect managed --print --sso <link> --bin <path>` emits the credential-free block; then restart Claude Code.":"No action required.",Iw=async(e={})=>{let t=vw(e.userSettings??{}),n=vw(await(e.readManaged??Sw)().catch(()=>({}))),r=[];for(let o of lT){if(!kw(n[o])||!kw(t[o]))continue;let a=o==="ANTHROPIC_BASE_URL";if(dT(n[o],t[o],a))continue;let s=a?uT(n[o]):void 0;r.push({name:o,source:`managed settings (${Pt()})`,routing:a,...s?{managedOrigin:s}:{}})}return r},xw=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`,Rw=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 fT}from"node:os";import{join as mT}from"node:path";import{readFile as hT}from"node:fs/promises";var yT=400,Ow=async()=>{try{let e=mT(fT(),".claude","settings.json"),n=JSON.parse(await hT(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}},Tw=async()=>{try{let e=await P();return e.gateway?{origin:new URL(e.gateway).origin,metadata:me({user:e.name,team:e.team}),apiKey:e.clientKey}:null}catch{return null}},nt=async(e="auto")=>e==="profile"?Tw():e==="claude"?Ow():await Ow()??await Tw(),bc=async(e={})=>{let t=e.readTarget??nt,n=e.loadProfile??P,r;try{r=await n()}catch{return"unreadable"}if(!r.gateway)return"unreadable";let o;try{o=await t("claude")}catch{return"unreadable"}if(!o)return"missing";let a;try{a=new URL(r.gateway).origin}catch{return"unreadable"}return a===o.origin?"owned":"foreign"},Yt=e=>{let t={"content-type":"application/json"};return e.metadata&&(t["x-anyray-metadata"]=e.metadata),e.apiKey&&(t["x-anyray-api-key"]=e.apiKey),t},Ac=async(e,t,n,r)=>{if(!e)return;let o=new AbortController,a=setTimeout(()=>o.abort(),yT);try{await fetch(`${e.origin}/connect/hook-savings`,{method:"POST",headers:Yt(e),body:JSON.stringify({source:t,...r?{tool:r}:{},...n}),signal:o.signal})}catch{}finally{clearTimeout(a)}};var ir=()=>vc(kc(),".claude","settings.json"),Cc=()=>vc(kc(),".claude.json"),gT=hc,On="anyray",wT=()=>({type:"stdio",...Ge("claude"),alwaysLoad:!0}),cr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bT=e=>e instanceof Error?e.name:"UnknownError",AT={unreadable:"mcp_unreadable",unwritable:"mcp_not_writable",foreign:"mcp_foreign","not-persisted":"mcp_not_persisted"},CT=(e,t)=>{switch(e){case"foreign":return`MCP name conflict in ${t}: mcpServers.${On} 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.`}},kT={readJson:B,writeJson:(e,t)=>X(e,t)},vT=async(e,t=kT)=>{for(let n=0;n<2;n+=1){let r;try{r=await t.readJson(e)}catch{return{outcome:"failed",failure:"unreadable"}}if(ST(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=cr(a)?a[On]:void 0;if(s&&_t(s,"claude"))return{outcome:"registered"}}return{outcome:"failed",failure:"not-persisted"}},ST=e=>{if("mcpServers"in e&&!cr(e.mcpServers))return"conflict";let t=cr(e.mcpServers)?{...e.mcpServers}:{},n=t[On];return n!==void 0&&!_t(n,"claude")?"conflict":(t[On]=wT(),e.mcpServers=t,"installed")},_w=e=>{let t=e.mcpServers;return!t||!(On in t)||!_t(t[On],"claude")?!1:(delete t[On],Object.keys(t).length===0&&delete e.mcpServers,!0)},ET=e=>{pc(e,"PostToolUse",Ye,xn(Tt(Ye),{matcher:"*"})),pc(e,"UserPromptSubmit",or,xn(Tt(or)))},IT=e=>{pc(e,"SessionStart",ar,xn(Tt(ar),{async:!0}))},Lw=e=>Vo(e,"SessionStart",ar),Pw=e=>{let t=Vo(e,"PostToolUse",Ye),n=Vo(e,"UserPromptSubmit",or),r=Lw(e);return t||n||r},xT="print-key",RT=e=>e.includes("anyray-connect")||e.includes("connect-runtime")||e.includes(De()),Kr=e=>{let t=e.apiKeyHelper;if(typeof t!="string")return!1;let n=t.trim().split(/\s+/);return n[n.length-1]===xT&&RT(t)},OT=async(e,t)=>{let n=(await Ur(e)).env,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{},o=[];for(let a of gT){let s=r[a];typeof s=="string"?(t[a]=s,o.push(a)):delete t[a]}return o},TT=e=>typeof e.apiKeyHelper=="string"&&!Kr(e),Nw=async e=>{let t=await pp(),n=async()=>t,[r,o,a]=await Promise.all([Aw({userSettings:e,readManaged:n}),Iw({userSettings:e,readManaged:n}).catch(()=>[]),Ew({readManaged:n})]);return{directOverrides:r,managedOverrides:o,hookPolicy:a}},Dw=async e=>{let{directOverrides:t,managedOverrides:n,hookPolicy:r}=await Nw(e),o=up(t),a=Rw(n);return{routingOverrides:[...t.map(i=>({problem:dp(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:xw(i),fix:a,repairable:!1,bypass:i.routing}))],claudeCodeHookPolicy:r.state}},lr={id:"claude-code",title:"Claude Code",automatic:!0,async detect(){let e=vc(kc(),".claude"),t=await x(e);return{installed:t,detail:t?ir():"no ~/.claude directory"}},async apply(e,t){let n=ir(),r=await B(n),o=hw(r),a=await yw(e.origin,e.clientKey,o),s=gw(o,a),{env:i,subscription:c,byoUpstream:l,meta:d,headers:u}=sn(e,{contextWindowTokens:s.envTokens}),{directOverrides:f,hookPolicy:m}=await Nw(r),p=f.filter(T=>!T.repairable),h=f.filter(T=>T.repairable),g=[...p.map(T=>`WARNING: ${dp(T)}.`),...p.length?[up(p)]:[],...m.state==="fine"?[]:[`WARNING: ${gc(m)}.`,wc(m)],...h.map(T=>Cw(T)),`${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:g};s.model!==void 0&&(r.model=s.model);let y=r.env??{};r.env={...y,...i};let w=r.env;for(let{name:T}of Rn)h.some(W=>W.name===T)?w[T]="":w[T]===""&&(process.env[T]??"").trim()===""&&delete w[T];if(u||delete w.ANTHROPIC_CUSTOM_HEADERS,c&&(y.ANTHROPIC_AUTH_TOKEN&&g.push("Removed env.ANTHROPIC_AUTH_TOKEN \u2014 it would override your subscription sign-in."),delete w.ANTHROPIC_AUTH_TOKEN),l)for(let T of mw)delete w[T];let b=!!e.clientKey,k=oe(),C=TT(r);!c&&!l&&b&&k&&!C?(r.apiKeyHelper=fw(),w.ANTHROPIC_AUTH_TOKEN="",g.push("Installed an apiKeyHelper that reprints a fresh gateway key on demand \u2014 Claude Code refreshes it at startup and on any 401, so an idle session no longer 401s (no re-enrollment).")):Kr(r)&&delete r.apiKeyHelper,C&&!c&&!l&&b&&k&&g.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?(IT(r),g.push("Installed a SessionStart hook that refreshes your gateway key each session, so an idle subscription session no longer needs re-enrollment.")):Lw(r),oe()?(ET(r),g.push("Installed a PostToolUse hook (trims oversized tool outputs, cache-safe) and a UserPromptSubmit hook (beacons oversized pasted-data prompts) \u2014 both content-free.")):(Pw(r),g.push(`Skipped the Anyray hooks \u2014 anyray-connect is running from a temporary path (${De()}). Re-run via the installer (it persists the binary under ~/.anyray/bin) or a global install to enable cache-safe trimming and paste-savings beacons.`)),await X(n,r);let E=[n],I=Cc(),_;if(oe()){let T=await vT(I);T.outcome==="registered"?(E.push(I),g.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.")):(g.push(CT(T.failure,I)),_=AT[T.failure])}else try{let T=await B(I);_w(T)&&(await X(I,T),E.push(I))}catch(T){g.push(`Could not clean up a stale Anyray MCP registration in ${I} (${bT(T)}).`)}return{status:"configured",messages:g,changedFiles:E,..._?{errorClass:_}:{}}},skillsDir(){return vc(kc(),".claude","skills")},async pointsAt(e){let t=ir();if(!await x(t))return!1;try{let o=(await B(t)).env?.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.replace(/\/+$/,"")===e}catch{return!1}},async runtimeDiagnostics(){let e=await B(ir()).catch(()=>({}));return Dw(e)},async routingOverrides(){let e=await B(ir()).catch(()=>({}));return(await Dw(e)).routingOverrides},async mcpStatus(){if(!oe())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=Cc();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let r=(await B(e)).mcpServers?.[On];return r?_t(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=ir();if(!await x(n))e="missing";else try{let s=await B(n);if(s.hooks===void 0)e="missing";else if(!cr(s.hooks))e="unreadable";else{let i=s.hooks.PostToolUse;e=i===void 0?"missing":Array.isArray(i)?i.some(c=>rr(c,Ye))?"owned":"missing":"unreadable",e==="owned"&&Array.isArray(i)&&(t=i.some(c=>rr(c,Ye)&&cr(c)&&Array.isArray(c.hooks)&&c.hooks.some(l=>cr(l)&&fc(l.command,Ye))))}}catch{e="unreadable"}let r,o=!0,a=Cc();if(!await x(a))r="missing";else try{let s=await B(a);if(s.mcpServers===void 0)r="missing";else if(!cr(s.mcpServers))r="unreadable";else{let i=s.mcpServers[On];r=i===void 0?"missing":_t(i,"claude")?"owned":"foreign",r==="owned"&&(o=mc(i,"claude"))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Gr()?"owned":"missing",beacon_target:await bc().catch(()=>"unreadable")}},async inferenceAuthLanes(){try{let e=await B(ir()),t=cr(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=ir();if(!await x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray keys from ${t}`]};let n=await B(t),r=n.env,o=Pw(n),a=Kr(n);a&&delete n.apiKeyHelper;let s=r?await OT(t,r):[],i=ww(typeof n.model=="string"?n.model:void 0,(await Ur(t)).model);i!==void 0&&(n.model=i),r&&Object.keys(r).length===0&&delete n.env,(r||o||a||i!==void 0)&&await X(t,n,{backup:!1});let c=[`removed Anyray keys from ${t}`];i!==void 0&&c.push(`Put model back to ${i} \u2014 dropped the [1m] alias Anyray added for your context window.`),o&&c.push("Removed the Anyray PostToolUse, UserPromptSubmit, and SessionStart hooks."),a&&c.push("Removed the Anyray apiKeyHelper."),s.length&&c.push(`Put back the ${s.join(" and ")} you had set before Anyray.`);let l=Cc();try{let d=await B(l);_w(d)&&(await X(l,d,{backup:!1}),c.push("Removed the Anyray retrieval MCP server (anyray_retrieve)."))}catch{}return await ie(t),{status:"reverted",messages:c,changedFiles:[t]}}};import{delimiter as _T,dirname as PT}from"node:path";var dr=e=>{let{command:t,args:n}=an([e]);return{command:t,args:n}},jr=()=>nr(),gt=(e="",t=process.env.PATH??"",n=dc(),r=nr())=>{let a=t.split(_T).filter(Boolean).some(s=>s===n)||PT(r)!==n?"anyray-connect":r;return e?`${a} ${e}`:a};import{rm as DT,stat as LT}from"node:fs/promises";import{homedir as $w,platform as NT}from"node:os";import{join as $T}from"node:path";var fp="Anyray",MT=(e=$w())=>$T(e,"Applications",`${fp}.app`),mp=async(e={})=>{if((e.os??NT())!=="darwin")return{ok:!0,messages:[]};let n=MT(e.home??$w());try{return await LT(n).then(()=>!0,()=>!1)?(await DT(n,{recursive:!0,force:!0}),{ok:!0,messages:[`Removed the legacy ${fp}.app background item from ~/Applications.`]}):{ok:!0,messages:[]}}catch(r){return{ok:!1,messages:[`Could not remove the legacy ${fp}.app background item (${r?.name??"Error"}).`]}}};import{homedir as Mw,userInfo as BT}from"node:os";var Bw=()=>{try{return Mw()!==BT().homedir}catch{return!1}},hp=e=>[`Skipped ${e} \u2014 HOME (${Mw()}) 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 cn=(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,Zr=(e=process.env)=>cn(e)!==null,Tn=e=>e==="codespaces"||e==="devcontainer",Ko=e=>{switch(e){case"codespaces":return"a GitHub Codespace";case"devcontainer":return"a dev container";case"ssh":return"an SSH session"}};var Fw=()=>Jr(xc(),".anyray","logs"),wp=()=>Jr(Fw(),"connect-refresh.log"),Ic=1800,Rc="ai.anyray.connect.refresh",ys="anyray-refresh",Ap="\\AnyrayConnectKeyRefresh",Oc=Rc,gs=ys,hs=Ap,HT=String(Ic/60),Cp=(e,t)=>{let n=UT(e,t,{stdio:"ignore"});return{ok:!n.error&&n.status===0}},kp=()=>Jr(xc(),"Library","LaunchAgents",`${Oc}.plist`),vp=()=>Jr(xc(),".config","systemd","user"),Ww=()=>Jr(vp(),`${gs}.service`),Ec=()=>Jr(vp(),`${gs}.timer`),gp=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Tc=()=>dr(ar),GT=(e=Tc())=>{let{command:t,args:n}=e,r=[t,...n].map(o=>` <string>${gp(o)}</string>`).join(`
|
|
9
9
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
10
10
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
11
11
|
<plist version="1.0">
|
|
@@ -23,14 +23,14 @@ ${r}
|
|
|
23
23
|
<key>StandardErrorPath</key><string>${gp(wp())}</string>
|
|
24
24
|
</dict>
|
|
25
25
|
</plist>
|
|
26
|
-
`},
|
|
26
|
+
`},VT=(e=Tc())=>{let{command:t,args:n}=e;return`[Unit]
|
|
27
27
|
Description=Anyray connect gateway key refresh
|
|
28
28
|
After=network-online.target
|
|
29
29
|
|
|
30
30
|
[Service]
|
|
31
31
|
Type=oneshot
|
|
32
32
|
ExecStart=${[t,...n].map(o=>/\s/.test(o)?JSON.stringify(o):o).join(" ")}
|
|
33
|
-
`},
|
|
33
|
+
`},KT=()=>`[Unit]
|
|
34
34
|
Description=Anyray connect gateway key refresh (every ${Ic/60}m)
|
|
35
35
|
|
|
36
36
|
[Timer]
|
|
@@ -40,13 +40,13 @@ Persistent=true
|
|
|
40
40
|
|
|
41
41
|
[Install]
|
|
42
42
|
WantedBy=timers.target
|
|
43
|
-
`,
|
|
44
|
-
${t.stderr??""}`}},t_=async e=>{try{return(await JT(e)).isDirectory()}catch{return!1}},n_=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},Sp=async(e,t={})=>{if((t.os??YT())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??t_)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??e_;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?n_(a.output):void 0;return s?zT.has(s)?QT(a.output)!==qT?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},jo=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await Sp(n,t)).ok?"healthy":"gone"},Ep=async(e={})=>{try{let t=e.load??P,n=await t(),r=await jo(n,e);if(r!=="gone")return r;let o=e.installScheduler??ur;return n.refreshSchedulerEnabled&&Je(n)&&await o().catch(()=>{}),await(e.save??ce)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var r_={"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."},o_=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},a_=async(e,t)=>{let n=t.stderr??console.error,r=o_(e,"--app-path")??Vw,o=await Sp(r,t);if(!o.ok)return n(r_[o.reason]),1;let s=await(t.load??P)();return await(t.save??ce)({...s,persistenceOwner:"tray",trayAppPath:r}),await(t.uninstallScheduler??_n)().catch(()=>{}),0},s_=async e=>{let t=e.load??P,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??ur;return n.refreshSchedulerEnabled&&Je(n)&&await r().catch(()=>{}),await(e.save??ce)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},Kw=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await a_(e,t):e.includes("--release-tray")?await s_(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 i_}from"node:fs/promises";import{homedir as Tp,platform as _c}from"node:os";import{join as Jt}from"node:path";import{basename as jw,dirname as Ip,join as Zo}from"node:path";var pr="https://github.com/anyrayHQ/install/releases",Xr="connect-v",xp="release-assets.githubusercontent.com",Rp=".anyray",zr="__anyray-refresh-desktop-helpers",fr=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",Dn=(e,t=process.platform)=>({launcher:Zo(e,"bin",fr(t)),binDir:Zo(e,"bin"),versionsDir:Zo(e,"versions"),lock:Zo(e,"update.lock"),state:Zo(e,"update-state.json")}),bs=(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"}},Op=(e,t,n=process.platform)=>jw(e)===fr(n)&&jw(Ip(e))==="bin"?Ip(Ip(e)):Zo(t,Rp);var Pc=(e=_c(),t=Tp())=>{if(e==="darwin")return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:Rc,paths:[Jt(t,"Library","LaunchAgents",`${Rc}.plist`)],dataPaths:[Jt(t,".anyray","logs","connect-refresh.log")]}];if(e==="linux"){let n=Jt(t,".config","systemd","user");return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:`${ys}.timer`,paths:[Jt(n,`${ys}.timer`),Jt(n,`${ys}.service`)]}]}return e==="win32"?[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:Ap,paths:[]}]:[]},Zw=async e=>{try{return await i_(e),!0}catch{return!1}},Dc=async(e={})=>{let t=e.os??_c(),n=e.exists??Zw;for(let r of Pc(t,e.home)){if(r.paths.length===0){if(await(e.supervisorHolds??(async a=>{try{return await Pn(a)}catch{return!1}}))(t))return!0;continue}for(let o of r.paths)if(await n(o))return!0}return!1},Yw=async e=>{let t={suspected:!1,missingPaths:[],kinds:[],removed:!1};if(!e.binaryDurable||!e.schedulerEnabled||e.schedulerInstalled||e.trayManaged===!0)return t;let n=e.exists??Zw;for(let r of Pc(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.removed=t.suspected&&e.schedulerInstalledOnce===!0,t},Jw=e=>{let t=e.os??_c(),n=e.home??Tp(),r=e.binaryPath??jr(),o=e.arch??process.arch,a=Dn(Op(r,n,t),t),s=fr(t);return{schema:"anyray.connect.security-exclusions/v1",connectVersion:e.connectVersion,platform:t,arch:o,binary:{path:r,...e.binarySha256?{sha256:e.binarySha256}:{}},services:Pc(t,n).map(i=>({kind:i.kind,title:i.title,supervisorName:i.supervisorName,unitPaths:i.paths,logPaths:i.dataPaths??[]})),writePaths:[Jt(a.versionsDir,"<version>",s),a.launcher,a.lock,a.state],network:{outboundHosts:[...e.gatewayHost?[e.gatewayHost]:[],"github.com",xp],inboundListeners:[]},notes:["Match on binary.path and services[].supervisorName. Do not match on binary.sha256: connect self-updates, so a hash-scoped exclusion stops matching at the next release.","The scheduler is unprivileged and runs as the logged-in user. It renews the seat gateway key so a long AI-coding session does not lose access.","A seat whose key cannot lapse between sessions installs no scheduler at all, and connect retires one it no longer needs.","No inbound listener, no proxy, no CA certificate, no DNS change."]}},Xw=(e=_c(),t=Tp(),n=jr(),r=process.arch)=>{let o=Dn(Op(n,t,e),e),a=fr(e),s=bs(e,r),i=s?[` ${pr}/download/${Xr}<version>/${s}`]:[" (no binary is published for this OS/architecture \u2014 nothing here"," downloads a release asset)"],c=["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 l of Pc(e,t)){c.push(`${l.title} \u2014 supervisor name: ${l.supervisorName}`);for(let d of l.paths)c.push(` ${d}`);l.paths.length===0&&c.push(" (no unit file \u2014 held in the Task Scheduler store)");for(let d of l.dataPaths??[])c.push(` ${d} (captured stdout/stderr \u2014 error names only)`);c.push("")}return c.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."," - Outbound: github.com, for the self-update below. Asset downloads",` redirect to ${xp}.`," - No inbound listener, no proxy, no CA certificate, no DNS change.","","Self-update:"," The installed binary keeps itself on the published version, on the same"," tick as key renewal. Every file it downloads is SHA-256 verified against"," the release's published SHA256SUMS before anything is activated; a"," mismatch is deleted and the running version stays.",""," Fetches over HTTPS, unauthenticated, no request body:",` ${pr}/latest`," (the redirect target alone names the published version)",` ${pr}/download/${Xr}<version>/connect-update.json`,` ${pr}/download/${Xr}<version>/SHA256SUMS`,...i,""," Writes:",` ${Jt(o.versionsDir,"<version>",a)}`," (the downloaded binary; the version it replaces is kept for rollback)",` ${o.launcher}`," (the stable path above, pointed at the new version)",` ${o.lock}`,` ${o.state}`,` ${Jt(o.versionsDir,"<version>",`${a}.part-<pid>`)}`,...e==="win32"?[` ${Jt(o.binDir,`${a}.old-<pid>`)}`,` ${Jt(o.binDir,`${a}.rollback-<pid>`)}`]:[` ${Jt(o.binDir,`${a}.new-<pid>`)}`]," (transient: a partial download and the staged swap, removed as the"," swap completes or on the next run)",...e==="win32"?[""," Windows cannot overwrite a running .exe, so activation renames the"," live copy aside, copies the new one into place, and records the",` active version in \`${a}.source\` beside it.`]:[],""," Runs the newly downloaded binary directly, around the swap:"," - `--version`, as a smoke test when it replaces a non-managed runtime;"," a failure puts the previous version back.",` - \`anyray-connect ${zr}\`, which rewrites an`," already-installed Anyray credential-helper script to name the new"," path. It writes nothing where no such helper exists.","","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."),c};import{homedir as h_}from"node:os";import{join as Uc}from"node:path";import{chmod as y_,readFile as As,rm as nb,copyFile as g_}from"node:fs/promises";var qr="# >>> anyray connect >>>",$c="# <<< anyray connect <<<",_p="# restore: ",zw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Mc=e=>{let t=new RegExp(`\\n*${zw(qr)}[\\s\\S]*?${zw($c)}\\n?`,"g");return e.replace(t,"")},Pp=e=>{let t="",n=!1,r="";for(let o=0;o<e.length;o++){let a=e[o];if(n){if(a==="\\"&&r==='"'){o++;continue}a===r&&(n=!1);continue}if(a==='"'||a==="'"){n=!0,r=a;continue}if(a==="#")break;t+=a}return t},Lc=(e,t)=>e.split(t).length-1,qw=e=>Lc(e,"[")-Lc(e,"]"),c_=e=>e.replace(/^['"]|['"]$/g,""),Nc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Lc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+qw(Pp(a))),t.push({kind:"other"});continue}let s=a.trim();if(s===""||s.startsWith("#")){t.push({kind:"other"});continue}if(s.startsWith("[")){t.push({kind:"table"});continue}let i=a.indexOf("="),c=i>=0?c_(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=Pp(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Lc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+qw(l)))}return t},Dp=e=>e.findIndex(t=>t.kind==="table"),Lp=e=>e.includes(qr),Qw=(e,t)=>{let n=`[${t}]`;return e.split(`
|
|
43
|
+
`,jT=(e=Tc())=>[e.command,...e.args].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),ms=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(" ")}`],Uw=e=>!e.run&&Bw(),ZT=async(e,t)=>await FT(kp(),"utf-8").catch(()=>null)!==e?!1:t("launchctl",["list",Oc]).ok,ur=async(e={})=>{let t=e.os??bp(),n=e.invocation??Tc(),r=e.run??Cp,o=e.binaryPath??jr();if(tt(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(Uw(e))return{ok:!1,messages:hp("auto-refresh scheduling")};let a=cn(e.env??(e.run?{}:process.env));if(Tn(a))return{ok:!1,messages:[`Skipped the OS auto-refresh schedule \u2014 ${Ko(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=kp(),i=GT(n),c=await mp({os:t});if(await ZT(i,r))return{ok:!0,messages:[`Auto-refresh already scheduled via launchd (${s}).`,...c.messages]};await yp(Fw(),{recursive:!0,mode:448}),await yp(Jr(xc(),"Library","LaunchAgents"),{recursive:!0});let l=String(process.getuid?.()??""),d=`${s}.new-${process.pid}`;await Yr(d,{force:!0}).catch(()=>{}),await Sc(d,i),r("launchctl",["bootout",`gui/${l}`,s]),await Yr(s,{force:!0}).catch(()=>{});try{await WT(d,s)}catch{await Sc(s,i),await Yr(d,{force:!0}).catch(()=>{})}return r("launchctl",["bootstrap",`gui/${l}`,s]).ok||r("launchctl",["load","-w",s]).ok?{ok:!0,messages:[`Scheduled auto-refresh via launchd (${s}).`,...c.messages]}:{ok:!1,messages:[`Wrote ${s} but launchd would not load the agent.`,...ms(n)]}}if(t==="linux")return await yp(vp(),{recursive:!0}),await Sc(Ww(),VT(n)),await Sc(Ec(),KT()),r("systemctl",["--user","daemon-reload"]),r("systemctl",["--user","enable","--now",`${gs}.timer`]).ok?{ok:!0,messages:[`Scheduled auto-refresh via systemd (${Ec()}).`]}:{ok:!1,messages:[`Wrote ${Ec()} but \`systemctl --user enable --now\` failed.`,...ms(n)]};if(t==="win32"){let s=jT(n);return r("schtasks",["/Create","/TN",hs,"/TR",s,"/SC","MINUTE","/MO",HT,"/F","/RL","LIMITED"]).ok?(r("schtasks",["/Run","/TN",hs]),{ok:!0,messages:[`Scheduled auto-refresh via Task Scheduler (${hs}).`]}):{ok:!1,messages:["Could not register the Task Scheduler auto-refresh task.",...ms(n)]}}return{ok:!1,messages:ms(n)}}catch(s){return{ok:!1,messages:[`Could not schedule auto-refresh: ${s instanceof Error?s.message:String(s)}`,...ms(n)]}}},_n=async(e={})=>{await Yr(wp(),{force:!0}).catch(()=>{});let t=e.os??bp(),n=e.run??Cp,r=[];if(Uw(e))return{ok:!0,messages:hp("scheduler teardown")};try{if(t==="darwin"){let o=kp(),a=String(process.getuid?.()??"");n("launchctl",["bootout",`gui/${a}`,o]),n("launchctl",["unload",o]),await Yr(o,{force:!0}),r.push("Removed the launchd auto-refresh schedule.");let s=await mp({os:t});r.push(...s.messages)}else t==="linux"?(n("systemctl",["--user","disable","--now",`${gs}.timer`]),await Yr(Ec(),{force:!0}),await Yr(Ww(),{force:!0}),n("systemctl",["--user","daemon-reload"]),r.push("Removed the systemd auto-refresh schedule.")):t==="win32"&&(n("schtasks",["/Delete","/TN",hs,"/F"]),r.push("Removed the Task Scheduler auto-refresh schedule."))}catch{}return{ok:!0,messages:r}},Pn=async(e=bp(),t=Cp)=>e==="win32"?t("schtasks",["/Query","/TN",hs]).ok:e==="darwin"?t("launchctl",["list",Oc]).ok:e==="linux"?t("systemctl",["--user","is-enabled",`${gs}.timer`]).ok:!1;import{platform as JT}from"node:os";import{stat as XT}from"node:fs/promises";import{spawnSync as zT}from"node:child_process";var ws=e=>{let t=e.enrolledCert?.payload.keyTtlSeconds;return typeof t=="number"&&Number.isFinite(t)&&t>0?t*1e3:void 0},Hw=new Set(["claude-code","codex","opencode","cursor","copilot","copilot-cli","claude-desktop","jetbrains","windsurf"]),YT=10080*60*1e3,Gw=(e,t,n=Date.now())=>{let r=[],o=ws(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)<=YT},Je=(e,t={},n=Date.now())=>{if(!e.enrolledCert)return!1;let o=(t.toolIds??e.managedTools??[]).some(a=>Hw.has(a));return Gw(e,t.keyExpiresAt,n)||!o};var Vw="/Applications/Anyray Connect Tray.app",qT=new Set(["V53XMA78UF"]),QT="ai.anyray.connect-tray",e_=e=>e.match(/^Identifier=(.+)$/m)?.[1]?.trim()||void 0,t_=e=>{let t=zT("codesign",e,{encoding:"utf8"});return{ok:t.status===0,output:`${t.stdout??""}
|
|
44
|
+
${t.stderr??""}`}},n_=async e=>{try{return(await XT(e)).isDirectory()}catch{return!1}},r_=e=>{if(/^Signature=adhoc$/m.test(e))return;let n=/^TeamIdentifier=(.+)$/m.exec(e)?.[1]?.trim();if(!(!n||n==="not set"))return n},Sp=async(e,t={})=>{if((t.os??JT())!=="darwin")return{ok:!1,reason:"not-macos"};if(!e.endsWith(".app"))return{ok:!1,reason:"bad-path"};if(!await(t.pathExists??n_)(e))return{ok:!1,reason:"missing"};let o=t.runCodesign??t_;if(!o(["--verify","--deep","--strict",e]).ok)return{ok:!1,reason:"unsigned"};let a=o(["-dv",e]),s=a.ok?r_(a.output):void 0;return s?qT.has(s)?e_(a.output)!==QT?{ok:!1,reason:"untrusted-bundle-id"}:{ok:!0,teamIdentifier:s}:{ok:!1,reason:"untrusted-team"}:{ok:!1,reason:"no-team-identifier"}},jo=async(e,t={})=>{if(e.persistenceOwner!=="tray")return"not-tray-owned";let n=e.trayAppPath;return n&&(await Sp(n,t)).ok?"healthy":"gone"},Ep=async(e={})=>{try{let t=e.load??P,n=await t(),r=await jo(n,e);if(r!=="gone")return r;let o=e.installScheduler??ur;return n.refreshSchedulerEnabled&&Je(n)&&await o().catch(()=>{}),await(e.save??ce)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),"healed"}catch{return"not-tray-owned"}};var o_={"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."},a_=(e,t)=>{let n=e.indexOf(t);return n>=0?e[n+1]:void 0},s_=async(e,t)=>{let n=t.stderr??console.error,r=a_(e,"--app-path")??Vw,o=await Sp(r,t);if(!o.ok)return n(o_[o.reason]),1;let s=await(t.load??P)();return await(t.save??ce)({...s,persistenceOwner:"tray",trayAppPath:r}),await(t.uninstallScheduler??_n)().catch(()=>{}),0},i_=async e=>{let t=e.load??P,n=await t();if(n.persistenceOwner!=="tray")return 0;let r=e.installScheduler??ur;return n.refreshSchedulerEnabled&&Je(n)&&await r().catch(()=>{}),await(e.save??ce)({...await t(),persistenceOwner:void 0,trayAppPath:void 0}),0},Kw=async(e,t={})=>{let n=t.stderr??console.error;try{return e.includes("--adopt-tray")?await s_(e,t):e.includes("--release-tray")?await i_(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 c_}from"node:fs/promises";import{homedir as Tp,platform as _c}from"node:os";import{join as Jt}from"node:path";import{basename as jw,dirname as Ip,join as Zo}from"node:path";var pr="https://github.com/anyrayHQ/install/releases",Xr="connect-v",xp="release-assets.githubusercontent.com",Rp=".anyray",zr="__anyray-refresh-desktop-helpers",fr=(e=process.platform)=>e==="win32"?"anyray-connect.exe":"anyray-connect",Dn=(e,t=process.platform)=>({launcher:Zo(e,"bin",fr(t)),binDir:Zo(e,"bin"),versionsDir:Zo(e,"versions"),lock:Zo(e,"update.lock"),state:Zo(e,"update-state.json")}),bs=(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"}},Op=(e,t,n=process.platform)=>jw(e)===fr(n)&&jw(Ip(e))==="bin"?Ip(Ip(e)):Zo(t,Rp);var Pc=(e=_c(),t=Tp())=>{if(e==="darwin")return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:Rc,paths:[Jt(t,"Library","LaunchAgents",`${Rc}.plist`)],dataPaths:[Jt(t,".anyray","logs","connect-refresh.log")]}];if(e==="linux"){let n=Jt(t,".config","systemd","user");return[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:`${ys}.timer`,paths:[Jt(n,`${ys}.timer`),Jt(n,`${ys}.service`)]}]}return e==="win32"?[{kind:"scheduler",title:"key-renewal scheduler",supervisorName:Ap,paths:[]}]:[]},Zw=async e=>{try{return await c_(e),!0}catch{return!1}},Dc=async(e={})=>{let t=e.os??_c(),n=e.exists??Zw;for(let r of Pc(t,e.home)){if(r.paths.length===0){if(await(e.supervisorHolds??(async a=>{try{return await Pn(a)}catch{return!1}}))(t))return!0;continue}for(let o of r.paths)if(await n(o))return!0}return!1},Yw=async e=>{let t={suspected:!1,missingPaths:[],kinds:[],removed:!1};if(!e.binaryDurable||!e.schedulerEnabled||e.schedulerInstalled||e.trayManaged===!0)return t;let n=e.exists??Zw;for(let r of Pc(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.removed=t.suspected&&e.schedulerInstalledOnce===!0,t},Jw=e=>{let t=e.os??_c(),n=e.home??Tp(),r=e.binaryPath??jr(),o=e.arch??process.arch,a=Dn(Op(r,n,t),t),s=fr(t);return{schema:"anyray.connect.security-exclusions/v1",connectVersion:e.connectVersion,platform:t,arch:o,binary:{path:r,...e.binarySha256?{sha256:e.binarySha256}:{}},services:Pc(t,n).map(i=>({kind:i.kind,title:i.title,supervisorName:i.supervisorName,unitPaths:i.paths,logPaths:i.dataPaths??[]})),writePaths:[Jt(a.versionsDir,"<version>",s),a.launcher,a.lock,a.state],network:{outboundHosts:[...e.gatewayHost?[e.gatewayHost]:[],"github.com",xp],inboundListeners:[]},notes:["Match on binary.path and services[].supervisorName. Do not match on binary.sha256: connect self-updates, so a hash-scoped exclusion stops matching at the next release.","The scheduler is unprivileged and runs as the logged-in user. It renews the seat gateway key so a long AI-coding session does not lose access.","A seat whose key cannot lapse between sessions installs no scheduler at all, and connect retires one it no longer needs.","No inbound listener, no proxy, no CA certificate, no DNS change."]}},Xw=(e=_c(),t=Tp(),n=jr(),r=process.arch)=>{let o=Dn(Op(n,t,e),e),a=fr(e),s=bs(e,r),i=s?[` ${pr}/download/${Xr}<version>/${s}`]:[" (no binary is published for this OS/architecture \u2014 nothing here"," downloads a release asset)"],c=["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 l of Pc(e,t)){c.push(`${l.title} \u2014 supervisor name: ${l.supervisorName}`);for(let d of l.paths)c.push(` ${d}`);l.paths.length===0&&c.push(" (no unit file \u2014 held in the Task Scheduler store)");for(let d of l.dataPaths??[])c.push(` ${d} (captured stdout/stderr \u2014 error names only)`);c.push("")}return c.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."," - Outbound: github.com, for the self-update below. Asset downloads",` redirect to ${xp}.`," - No inbound listener, no proxy, no CA certificate, no DNS change.","","Self-update:"," The installed binary keeps itself on the published version, on the same"," tick as key renewal. Every file it downloads is SHA-256 verified against"," the release's published SHA256SUMS before anything is activated; a"," mismatch is deleted and the running version stays.",""," Fetches over HTTPS, unauthenticated, no request body:",` ${pr}/latest`," (the redirect target alone names the published version)",` ${pr}/download/${Xr}<version>/connect-update.json`,` ${pr}/download/${Xr}<version>/SHA256SUMS`,...i,""," Writes:",` ${Jt(o.versionsDir,"<version>",a)}`," (the downloaded binary; the version it replaces is kept for rollback)",` ${o.launcher}`," (the stable path above, pointed at the new version)",` ${o.lock}`,` ${o.state}`,` ${Jt(o.versionsDir,"<version>",`${a}.part-<pid>`)}`,...e==="win32"?[` ${Jt(o.binDir,`${a}.old-<pid>`)}`,` ${Jt(o.binDir,`${a}.rollback-<pid>`)}`]:[` ${Jt(o.binDir,`${a}.new-<pid>`)}`]," (transient: a partial download and the staged swap, removed as the"," swap completes or on the next run)",...e==="win32"?[""," Windows cannot overwrite a running .exe, so activation renames the"," live copy aside, copies the new one into place, and records the",` active version in \`${a}.source\` beside it.`]:[],""," Runs the newly downloaded binary directly, around the swap:"," - `--version`, as a smoke test when it replaces a non-managed runtime;"," a failure puts the previous version back.",` - \`anyray-connect ${zr}\`, which rewrites an`," already-installed Anyray credential-helper script to name the new"," path. It writes nothing where no such helper exists.","","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."),c};import{homedir as y_}from"node:os";import{join as Uc}from"node:path";import{chmod as g_,readFile as As,rm as nb,copyFile as w_}from"node:fs/promises";var qr="# >>> anyray connect >>>",$c="# <<< anyray connect <<<",_p="# restore: ",zw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Mc=e=>{let t=new RegExp(`\\n*${zw(qr)}[\\s\\S]*?${zw($c)}\\n?`,"g");return e.replace(t,"")},Pp=e=>{let t="",n=!1,r="";for(let o=0;o<e.length;o++){let a=e[o];if(n){if(a==="\\"&&r==='"'){o++;continue}a===r&&(n=!1);continue}if(a==='"'||a==="'"){n=!0,r=a;continue}if(a==="#")break;t+=a}return t},Lc=(e,t)=>e.split(t).length-1,qw=e=>Lc(e,"[")-Lc(e,"]"),l_=e=>e.replace(/^['"]|['"]$/g,""),Nc=e=>{let t=[],n=0,r=!1,o="";for(let a of e){if(r){Lc(a,o)%2===1&&(r=!1),t.push({kind:"other"});continue}if(n>0){n=Math.max(0,n+qw(Pp(a))),t.push({kind:"other"});continue}let s=a.trim();if(s===""||s.startsWith("#")){t.push({kind:"other"});continue}if(s.startsWith("[")){t.push({kind:"table"});continue}let i=a.indexOf("="),c=i>=0?l_(a.slice(0,i).trim()):"";t.push({kind:"key",key:c});let l=Pp(i>=0?a.slice(i+1):a);for(let d of['"""',"'''"])Lc(l,d)%2===1&&(r=!0,o=d);r||(n=Math.max(0,n+qw(l)))}return t},Dp=e=>e.findIndex(t=>t.kind==="table"),Lp=e=>e.includes(qr),Qw=(e,t)=>{let n=`[${t}]`;return e.split(`
|
|
45
45
|
`).some(r=>{let o=r.trim();if(!o.startsWith(n))return!1;let a=o.slice(n.length).trimStart();return a===""||a.startsWith("#")})},Np=(e,t)=>Qw(Mc(e),t),$p=e=>{let t=e.indexOf(qr);if(t<0)return;let n=e.indexOf($c,t+qr.length);if(!(n<0))return e.slice(t,n)},eb=(e,t)=>{let n=e.indexOf(qr);if(n<0)return!1;let r=e.indexOf($c,n+qr.length);return r<0?!1:Qw(e.slice(n,r),t)},Mp=(e,t)=>{let r=Mc(e).split(`
|
|
46
46
|
`),o=Nc(r),a=Dp(o),s=a<0?r.length:a;for(let i=0;i<s;i++){let c=o[i];if(c.kind!=="key"||c.key!==t)continue;let l=r[i].indexOf("="),d=Pp(r[i].slice(l+1)).trim();if(!/^\d[\d_]*$/.test(d))return;let u=Number(d.replaceAll("_",""));return Number.isSafeInteger(u)&&u>0?u:void 0}},Bc=(e,t,n)=>{let r=tb(e),a=Mc(e).split(`
|
|
47
47
|
`),s=Nc(a),i=Dp(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 f=Nc(d),m=Dp(f),p=(m===-1?d:d.slice(0,m)).join(`
|
|
48
48
|
`),h=m===-1?"":d.slice(m).join(`
|
|
49
|
-
`),
|
|
49
|
+
`),g=[...u.entries()].sort(([b],[k])=>b.localeCompare(k)).map(([,b])=>`${_p}${b}`),y=[qr,...g,...t,$c].join(`
|
|
50
50
|
`);return[p.replace(/\s*$/,""),y,h.replace(/^\s*/,"")].filter(b=>b.length>0).join(`
|
|
51
51
|
|
|
52
52
|
`).replace(/\s*$/,"")+`
|
|
@@ -55,7 +55,7 @@ ${t.stderr??""}`}},t_=async e=>{try{return(await JT(e)).isDirectory()}catch{retu
|
|
|
55
55
|
`),n].filter(a=>a.length>0).join(`
|
|
56
56
|
|
|
57
57
|
`);return o.length>0?o+`
|
|
58
|
-
`:""};import{randomUUID as
|
|
58
|
+
`:""};import{randomUUID as d_}from"node:crypto";import{chmod as u_,mkdir as p_,rm as f_,writeFile as m_}from"node:fs/promises";import{dirname as h_}from"node:path";var we=async(e,t)=>{await p_(h_(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${d_()}`;try{await m_(n,t,{flag:"wx",mode:384}),await ye(n,e),await u_(e,384)}finally{await f_(n,{force:!0}).catch(()=>{})}};var b_="codex",A_="Codex app / CLI / IDE",C_="https://chatgpt.com/backend-api/codex",k_="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",v_="x-anyray-client-context-window",S_="x-anyray-client-auto-compact-limit",Hc=()=>process.env.CODEX_HOME?.trim()||Uc(y_(),".codex"),Qr=()=>Uc(Hc(),"config.toml"),Wc=()=>`${Qr()}.anyray-bak`,Bp=()=>Uc(Hc(),"hooks.json"),Ln=()=>Uc(Hc(),"anyray.config.toml"),rb=e=>Vo(e,"PostToolUse",dw),ob=(e,t=!1)=>me({...e.metadata,tool:e.metadata.tool??"codex",intent:(t?void 0:process.env.ANYRAY_CODEX_INTENT?.trim())||e.metadata.intent||b_,intentLabel:(t?void 0:process.env.ANYRAY_CODEX_INTENT_LABEL?.trim())||e.metadata.intentLabel||A_}),rt=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Fp=()=>process.env.ANYRAY_CODEX_MODEL?.trim()||void 0,Cs=(e,t={})=>{let n=ob(e,t.ignoreEnv),r=te(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:Fp(),i=e.clientKey,c=r?['"x-anyray-auth-mode" = "passthrough"',`"x-anyray-custom-host" = ${rt(C_)}`,`"x-anyray-forward-headers" = ${rt(k_)}`,...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(`"${v_}" = ${rt(String(t.modelContextWindow))}`),t.modelAutoCompactTokenLimit&&c.push(`"${S_}" = ${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(", ")}]`]:[]]},E_=()=>Fp()?["model_provider","model"]:["model_provider"],ab={id:"codex",title:"Codex app / CLI / IDE",automatic:!0,async detect(){let e=Hc(),t=await x(e);return{installed:t,detail:t?Qr():`no ${e} directory`}},async apply(e,t){let n=Qr(),r=Bp(),o=ob(e),a=te(e,"openai"),s=Fp(),i=oe(),c={},l=await x(r);try{l&&(c=await B(r))}catch(k){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${r} (${k instanceof Error?k.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run Connect so the retired Anyray PostToolUse entry can be removed safely.`]}}let d=rb(c),u=await x(n),f=u?await As(n,"utf-8"):"";if(Np(f,"model_providers.anyray"))return{status:"manual",messages:[`Refused to replace the existing model provider in ${n}: model_providers.anyray is not owned by Anyray Connect. Rename that provider or route it manually; the file was left unchanged.`]};let m=Np(f,"mcp_servers.anyray"),p=Mp(f,"model_context_window"),h=Mp(f,"model_auto_compact_token_limit"),g=[`${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}.`:p?`Context budget: follows model_context_window=${p}.`:"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 g.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:g};let y=[];d?(await X(r,c,{backup:!1}),await ie(r),y.push(r),g.push(`Removed the retired Anyray Codex PostToolUse hook from ${r}; Codex does not expose a safe pre-transcript replacement seam for side-effecting tools.`)):g.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(Wc())&&(await w_(n,Wc()),await g_(Wc(),384),g.push(`Backed up your original config to ${Wc()}.`));let w=i&&!m?Ge("profile"):void 0;g.push(m?`MCP name conflict in ${n}: mcp_servers.anyray is not owned by Anyray Connect, so it was left untouched.`:w?"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 (${De()}). Re-run via the installer or a global install to enable retrieval.`);let b=Bc(f,Cs(e,{mcpServer:w,modelContextWindow:p,modelAutoCompactTokenLimit:h}),E_());return await we(n,b),y.push(n),await x(Ln())&&(await nb(Ln(),{force:!0}),y.push(Ln()),g.push(`Removed the old opt-in profile ${Ln()} (the default route replaces it).`)),{status:"configured",messages:g,changedFiles:y}},async pointsAt(e){let t=Qr();if(!await x(t))return!1;try{let n=await As(t,"utf-8"),r=`base_url = ${rt(`${e}/v1`)}`;return n.includes("[model_providers.anyray]")&&n.includes(r)}catch{return!1}},async mcpStatus(){if(!oe())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=Qr();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await As(e,"utf-8");if(!eb(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 As(Qr(),"utf-8"),t=$p(e);if(!t||!t.includes("[model_providers.anyray]"))return["unknown"];if(/^requires_openai_auth = true$/m.test(t)||t.includes('"x-anyray-auth-mode" = "passthrough"'))return["subscription"];if(t.includes('"Authorization" = "Bearer ')||t.includes("[model_providers.anyray.auth]"))return["api_key"]}catch{}return["unknown"]},async revert(e){let t=Qr(),n=await x(t),r=await x(Ln()),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 B(i)}catch(l){return{status:"manual",messages:[`Could not inspect the Codex hooks file ${i} (${l instanceof Error?l.name:"unknown error"}); routing was left unchanged. Repair the JSON and re-run --revert.`]}}rb(c)&&(e.dryRun||(await X(i,c,{backup:!1}),await ie(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=Fc(await As(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 nb(Ln(),{force:!0}),s.push(Ln()),a.push(e.dryRun?`would remove the old opt-in profile ${Ln()}`:`removed the old opt-in profile ${Ln()}`)),s.length===0?{status:"not-found",messages:["nothing to revert"]}:(!e.dryRun&&s.includes(t)&&await ie(t),{status:"reverted",messages:a,changedFiles:s})}};import{homedir as __}from"node:os";import{join as P_}from"node:path";import{readFile as lb,rm as Up}from"node:fs/promises";import{readFile as I_,writeFile as sb,access as x_}from"node:fs/promises";import{homedir as R_}from"node:os";import{join as Wp}from"node:path";var O_="# >>> anyray connect >>>",T_="# <<< anyray connect <<<",ks=e=>e?{begin:`# >>> anyray connect (${e}) >>>`,end:`# <<< anyray connect (${e}) <<<`}:{begin:O_,end:T_},wt=()=>{let e=R_(),t=process.env.SHELL||"";return t.includes("zsh")?Wp(e,".zshrc"):t.includes("bash")?Wp(e,".bashrc"):Wp(e,".profile")},Gc=async e=>{try{return await x_(e),await I_(e,"utf-8")}catch{return""}},ib=(e,t)=>{let{begin:n,end:r}=ks(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]===`
|
|
59
59
|
`;)s-=1;let i=a+r.length;return e[i]===`
|
|
60
60
|
`&&(i+=1),e.slice(0,s)+e.slice(i)},Vc=async(e,t,n)=>{let r=await Gc(e),{begin:o,end:a}=ks(n),s=ib(r,n).replace(/\s*$/,""),i=[o,...t,a].join(`
|
|
61
61
|
`),c=s?`${s}
|
|
@@ -64,41 +64,41 @@ ${i}
|
|
|
64
64
|
`:`${i}
|
|
65
65
|
`;return await sb(e,c),e},Kc=async(e,t)=>{let n=await Gc(e),{begin:r,end:o}=ks(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(`
|
|
66
66
|
`).filter(c=>c.trim().length>0)},cb=async(e,t)=>(await Gc(e)).includes(ks(t).begin),vs=async(e,t)=>{let n=await Gc(e);return n.includes(ks(t).begin)?(await sb(e,ib(n,t).replace(/\s*$/,"")+`
|
|
67
|
-
`),!0):!1};var Dt=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 Oe=e=>`'${e.replace(/'/g,"'\\''")}'`,
|
|
68
|
-
`)):w&&
|
|
67
|
+
`),!0):!1};var Dt=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 Oe=e=>`'${e.replace(/'/g,"'\\''")}'`,D_=e=>{let t=Oe(e);return`case ":$PATH:" in *:${t}:*) ;; *) export PATH=${t}:"$PATH" ;; esac`},db=(e,t,n,r)=>[`export OPENAI_BASE_URL=${Oe(e.openaiBaseUrl)}`,...n?[]:[`export OPENAI_API_KEY=${Oe(t)}`],`export ANTHROPIC_BASE_URL=${Oe(e.anthropicBaseUrl)}`,...r?[]:[`export ANTHROPIC_AUTH_TOKEN=${Oe(t)}`],...e.byoUpstream?[]:["export ENABLE_TOOL_SEARCH='true'"],...e.byoUpstream?[]:["export _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL='1'"]],L_=["OPENAI_BASE_URL","OPENAI_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","ENABLE_TOOL_SEARCH","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL"],N_=["OPENAI_API_KEY","ANTHROPIC_AUTH_TOKEN"],Hp=()=>P_(__(),".anyray","shell-env.sh"),pb="# Managed by anyray-connect. Do not source this file anywhere else.",ub=e=>e.split(/\r?\n/,1)[0]===pb,Gp=e=>N_.some(t=>e.startsWith(`export ${t}=`)),jc=(e,t=process.env)=>t.ANTHROPIC_BASE_URL===e.anthropicBaseUrl||t.OPENAI_BASE_URL===e.openaiBaseUrl?L_.filter(r=>(t[r]??"")!==""):[],fb={id:"shell-env",title:"Shell environment (SDKs, scripts, Codex)",automatic:!0,async detect(){let e=wt();return{installed:!0,detail:await x(e)?e:`${e} (will be created)`}},async inferenceAuthLanes(){try{let e=await Kc(wt());return e?e.some(n=>Gp(n)||n.includes(Hp()))?["api_key"]:["subscription"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){let n=wt(),r=te(e,"openai"),o=te(e,"anthropic"),a=r||o,s=e.clientKey??e.placeholderKey,i=db(e,s,r,o),c=i.filter(Gp),l=i.filter(b=>!Gp(b)),d=Hp(),u=dc(),f=[D_(u),...l,...c.length>0?[`[ -r ${Oe(d)} ] && . ${Oe(d)}`]:[]],m=e.clientKey?db(e,Dt(e.clientKey),r,o):i,p=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)`,...m.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 ${p} \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."]],g=await x(d),y=g?await lb(d,"utf8"):void 0,w=y===void 0||ub(y);if(c.length>0&&!w)return{status:"manual",messages:[`Refused to overwrite user-managed ${d}; move or rename that file, then run Connect again.`]};if(w||h.push(`Preserved unrelated existing ${d}.`),t.dryRun)return{status:"configured",messages:h};try{c.length>0?await we(d,[pb,...c,""].join(`
|
|
68
|
+
`)):g&&w&&await Up(d,{force:!0}),await Vc(n,f)}catch(b){try{y!==void 0&&w?await we(d,y):w&&await Up(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||g&&w?[d]:[]]}},async revert(e){let t=wt(),n=Hp(),r=await x(n),o=r?ub(await lb(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 vs(t);o&&await Up(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 wP}from"node:child_process";import{closeSync as bP,copyFileSync as AP,existsSync as Se,mkdirSync as CP,openSync as kP,readFileSync as Kb,readSync as vP,renameSync as SP,rmSync as ln,writeFileSync as rf}from"node:fs";import{homedir as jb,platform as EP}from"node:os";import{dirname as Zb,join as zo,resolve as IP}from"node:path";import{isIP as zp}from"node:net";import{homedir as $_,platform as M_}from"node:os";import{join as Zc}from"node:path";var Ne=e=>{let t=$_();switch(M_()){case"darwin":return Zc(t,"Library","Application Support",e);case"win32":return Zc(process.env.APPDATA??Zc(t,"AppData","Roaming"),e);default:return Zc(t,".config",e)}};import{execFileSync as Xc}from"node:child_process";import{mkdtempSync as B_,rmSync as F_,writeFileSync as W_}from"node:fs";import{createRequire as U_}from"node:module";import{tmpdir as H_}from"node:os";import{join as mb}from"node:path";var Ss=class extends Error{},Es=e=>e instanceof Ss?`: ${e.message}`:"",hb=e=>{if(e?.length!==3||!e.every(Number.isSafeInteger))throw new Ss("WAL checkpoint returned an unexpected status");let[t,n,r]=e;if(t!==0)throw new Ss(`WAL checkpoint incomplete (busy=${t}, logFrames=${n}, checkpointedFrames=${r})`)},yb=()=>{try{return Xc("sqlite3",["--version"],{stdio:"ignore"}),!0}catch{return!1}},Kp=64*1024*1024,G_=Kp*2+64,Jc=e=>`'${e.replace(/'/g,"''")}'`,V_=(e,t)=>Xc("sqlite3",[e,t],{encoding:"utf-8",maxBuffer:G_,stdio:["ignore","pipe","pipe"]}),K_=(e,t)=>Xc("sqlite3",[e],{input:t,encoding:"utf-8",maxBuffer:Kp,stdio:["pipe","pipe","pipe"]}),gb=(e,t,n=V_)=>{let r=Jc(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
|
|
69
69
|
`)?a.slice(0,-2):a.endsWith(`
|
|
70
|
-
`)?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")},wb=(e,t=
|
|
70
|
+
`)?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")},wb=(e,t=K_)=>{let r=t(e,`.bail on
|
|
71
71
|
.timeout 5000
|
|
72
72
|
PRAGMA wal_checkpoint(TRUNCATE);
|
|
73
|
-
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");hb(o?.slice(1).map(Number))},
|
|
74
|
-
`);Xc("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Kp,stdio:["pipe","ignore","pipe"]})}finally{try{
|
|
75
|
-
`,{mode:384}),await ye(n,t)},
|
|
76
|
-
`),
|
|
73
|
+
`).trim().split(/\r?\n/).at(-1),o=/^([01])\|(-?\d+)\|(-?\d+)$/.exec(r??"");hb(o?.slice(1).map(Number))},j_=(e,t)=>{let n=B_(mb(H_(),"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=${Jc(a.key)};`;let i=mb(n,`value-${s}`);return W_(i,a.value,{encoding:"utf-8",mode:384}),`INSERT INTO ItemTable(key, value) VALUES (${Jc(a.key)}, CAST(readfile(${Jc(i)}) AS TEXT)) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`}),"COMMIT;",""].join(`
|
|
74
|
+
`);Xc("sqlite3",[e],{input:o,encoding:"utf-8",maxBuffer:Kp,stdio:["pipe","ignore","pipe"]})}finally{try{F_(n,{recursive:!0,force:!0})}catch{}}},Z_={kind:"sqlite3-cli",readItem:(e,t)=>gb(e,t),checkpointWal:e=>wb(e),mutateRows:j_},Y_=()=>{try{let t=U_(import.meta.url)("node:sqlite");return typeof t.DatabaseSync=="function"?t:void 0}catch{return}},Vp=(e,t,n)=>{let r=new e.DatabaseSync(t);try{return r.exec("PRAGMA busy_timeout = 5000;"),n(r)}finally{try{r.close()}catch{}}},J_=e=>e==null?"":typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf-8"):String(e),X_=e=>({kind:"node-sqlite",readItem:(t,n)=>Vp(e,t,r=>{let o=r.prepare("SELECT value FROM ItemTable WHERE key = ?").get(n);return o===void 0?void 0:J_(o.value)}),checkpointWal:t=>Vp(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);hb(o)}),mutateRows:(t,n)=>Vp(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}})}),Yc,mr=()=>{if(Yc!==void 0)return Yc;let e=Y_();return Yc=e?X_(e):yb()?Z_:null,Yc};import{spawn as z_}from"node:child_process";import{randomUUID as bb}from"node:crypto";import{constants as Ab}from"node:fs";import{chmod as q_,copyFile as Cb,mkdir as Q_,readdir as eP,readFile as tP,rename as nP,rm as Is,writeFile as rP}from"node:fs/promises";import{join as jp}from"node:path";var Zp=/^[a-z0-9][a-z0-9-]{0,31}$/,oP=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/,kb=/^[a-z0-9][a-z0-9-]{0,31}$/,aP=/^[0-9TZ:.+-]{1,40}$/,Yp=()=>jp(ee(),"pending"),qc=e=>{if(!Zp.test(e)||oP.test(e))throw new Error(`Invalid adapter id for a pending operation: ${e}`);return jp(Yp(),`${e}.json`)},vb=()=>jp(ee(),"cursor-pending.json"),sP=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),iP=(e,t)=>{if(!sP(e)||e.version!==1)return;let n=typeof e.adapter=="string"&&e.adapter?e.adapter:t;if(!(!Zp.test(n)||typeof e.op!="string"||!kb.test(e.op)||typeof e.requestedAt!="string"||!aP.test(e.requestedAt)||Number.isNaN(Date.parse(e.requestedAt))))return{version:1,adapter:n,op:e.op,requestedAt:e.requestedAt,watcherPid:typeof e.watcherPid=="number"&&Number.isSafeInteger(e.watcherPid)&&e.watcherPid>0?e.watcherPid:void 0,...typeof e.generation=="string"&&e.generation?{generation:e.generation}:{}}},Jp=async(e,t)=>{try{return iP(JSON.parse(await tP(e,"utf-8")),t)}catch{return}},Sb=async()=>{let e=vb(),t=await Jp(e,"cursor");if(!t)return;let n=!1;try{await Eb(),await Cb(e,qc("cursor"),Ab.COPYFILE_EXCL),n=!0}catch(r){n=r.code==="EEXIST"}if(n)try{await Is(e,{force:!0})}catch{}return t},Qc=async e=>{let t=await Jp(qc(e),e);return t||(e==="cursor"?Sb():void 0)},hr=async()=>{let e;try{e=await eP(Yp())}catch{e=[]}let t=[];for(let n of e){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);if(!Zp.test(r))continue;let o=await Qc(r);o&&t.push(o)}if(!t.some(n=>n.adapter==="cursor")){let n=await Sb();n&&t.push(n)}return t},Eb=async()=>{await et();let e=Yp();await Q_(e,{recursive:!0,mode:448});try{await q_(e,448)}catch{}},zc=async e=>{await Eb();let t=qc(e.adapter),n=`${t}.${process.pid}.tmp`;await rP(n,`${JSON.stringify(e)}
|
|
75
|
+
`,{mode:384}),await ye(n,t)},cP=(e,t)=>e.generation||t.generation?!!(e.generation&&e.generation===t.generation):e.op===t.op&&e.requestedAt===t.requestedAt&&e.watcherPid===t.watcherPid,yr=async(e,t)=>await Xp(e,t)==="claimed",Xp=async(e,t)=>{let n=qc(e);if(t){let o=`${n}.${process.pid}.${bb()}.claimed`;try{await nP(n,o)}catch(i){let c=i.code;if(c==="ENOENT"||c==="ENOTDIR")return"absent";throw i}let a=await Jp(o,e);if(a&&cP(a,t))return await Is(o,{force:!0}),"claimed";let s=!1;try{await Cb(o,n,Ab.COPYFILE_EXCL),s=!0}catch(i){if(i.code!=="EEXIST")throw i;s=!0}finally{s&&await Is(o,{force:!0})}return"superseded"}let r=!1;try{await Is(n,{force:!0}),r=!0}catch(o){let a=o.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw o}if(e==="cursor")try{await Is(vb(),{force:!0})}catch{}return r?"claimed":"absent"},gr=e=>{if(!e)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},lP=e=>{let{command:t,args:n}=dr("__anyray-quit-watch");return{exe:t,args:[...n,e]}},dP=e=>{let{exe:t,args:n}=lP(e),r=z_(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),r.pid},Ib=dP;var xb=async()=>{let e=[],t;try{t=await hr()}catch{return e}for(let n of t)if(!gr(n.watcherPid))try{let r=Ib(n.adapter);if(!r)continue;await zc({...n,watcherPid:r}),e.push(n.adapter)}catch{}return e},xs=async(e,t)=>{if(!kb.test(t))throw new Error(`Invalid pending operation kind: ${t}`);let n=await Qc(e),r=new Date().toISOString(),o=bb();if(n&&gr(n.watcherPid))return await zc({...n,adapter:e,op:t,requestedAt:r,generation:o}),{watcherPid:n.watcherPid,alreadyWatching:!0};await zc({version:1,adapter:e,op:t,requestedAt:r,generation:o});let a;try{a=Ib(e)}catch{a=void 0}return a&&await zc({version:1,adapter:e,op:t,requestedAt:r,watcherPid:a,generation:o}),{watcherPid:a,alreadyWatching:!1}};import{spawn as uP,spawnSync as Ob}from"node:child_process";import{existsSync as el}from"node:fs";import{homedir as pP,platform as wr}from"node:os";import{join as Tb,win32 as Rb}from"node:path";var _b=(e,t={})=>{let n=t.env??process.env,r=t.exists??el,o=(t.home??pP)(),a={localAppData:n.LOCALAPPDATA??Rb.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=Rb.join(i,s.path);if(r(c))return c}},eo=/^[A-Za-z0-9 ._-]{1,64}$/,fP=/^[A-Za-z0-9.-]{1,128}$/,tl=e=>e.darwinBundleId&&fP.test(e.darwinBundleId)?e.darwinBundleId:void 0,Pb=(e,t=wr())=>t==="darwin"?tl(e)??e.darwinAppName??"":t==="win32"?(e.win32Image??"").toLowerCase():e.linuxProcess??"",Db=e=>e.darwinAppName??e.win32Image?.replace(/\.exe$/i,"")??e.linuxProcess??"the app",Lb=(e,t=wr(),n=process.env.PATH??"",r={})=>{if(t==="darwin")return!0;if(t==="win32")return _b(e,r)!==void 0;let o=e.linuxProcess;return!o||!eo.test(o)?!1:n.split(":").filter(Boolean).some(a=>el(Tb(a,o)))},Nb=(e,t=wr())=>{if(t==="darwin"&&tl(e))return!0;let n=t==="darwin"?e.darwinAppName:t==="win32"?e.win32Image:e.linuxProcess;return!!(n&&eo.test(n))},$b=1e4,Rs=e=>{let t=process.env.SystemRoot??process.env.SYSTEMROOT;if(!t)return e;let n=Tb(t,"System32",e);return el(n)?n:e},mP=e=>{let t=`/usr/bin/${e}`;return el(t)?t:e},hP=(e,t)=>{try{let n=Ob(e,t,{encoding:"utf-8",timeout:$b,windowsHide:!0,...wr()==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return n.error?!1:wr()==="win32"?/^SUCCESS/im.test(n.stdout??""):n.status===0}catch{return!1}},yP=e=>new Promise(t=>setTimeout(t,e)),Mb=(e,t={})=>{let n=t.runtimePlatform??wr(),r=t.run??hP;if(n==="darwin"){let a=tl(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||!eo.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||!eo.test(a)?!1:r(Rs("taskkill.exe"),["/IM",a])}let o=e.linuxProcess;return!o||!eo.test(o)?!1:r(mP("pkill"),["-TERM","-o","-x",o])},Bb=async(e,t=2e4,n={})=>{let r=n.sleep??yP,o=n.now??Date.now,a=o();for(;;){if(!e())return!0;if(o()-a>=t)return!1;await r(500)}},gP=(e,t,n={})=>{let r=wr();try{if(!n.detach&&(r==="darwin"||r==="win32")){let a=Ob(e,t,{stdio:"ignore",timeout:$b,windowsHide:!0,...r==="win32"?{cwd:process.env.SystemRoot??"C:\\Windows"}:{}});return!a.error&&a.status===0}let o=uP(e,t,{detached:!0,stdio:"ignore",windowsHide:!1});return o.on("error",()=>{}),o.unref(),o.pid!==void 0}catch{return!1}},Fb=(e,t={})=>{let n=t.runtimePlatform??wr(),r=t.launch??gP;if(n==="darwin"){let a=tl(e);if(a&&r("/usr/bin/open",["-b",a]))return!0;let s=e.darwinAppName;return!s||!eo.test(s)?!1:r("/usr/bin/open",["-a",s])}if(n==="win32"){let a=_b(e,t.windows);return a?r(a,[],{detach:!0}):!1}let o=e.linuxProcess;return!o||!eo.test(o)?!1:r(o,[])};var xP={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"}]},RP=e=>e==="apply"||e==="native"||e==="revert",Yb=()=>Ne("Cursor"),br=()=>zo(Yb(),"User","globalStorage","state.vscdb"),Ts=()=>`${br()}.anyray-bak.json`,Xo=()=>`${br()}.anyray-bak`,Ve="src.vs.platform.reactivestorage.browser.reactiveStorageServiceImpl.persistentStorage.applicationUser",at="cursorAuth/openAIKey";var Jb="/seat/cursor",of="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.",Os=zo(".cursor","rules","anyray.mdc"),Xb="<!-- anyray:managed \u2014 regenerated by `anyray-connect --tools cursor` -->",OP=()=>["---","description: Use Anyray's context tools for code search and file reads.","alwaysApply: true","---","",Xb,"",of,""].join(`
|
|
76
|
+
`),TP=e=>{let t=IP(e);for(;;){if(Se(zo(t,".git")))return t;let n=Zb(t);if(n===t)return null;t=n}},_P=e=>e.authMode!=="placeholder",dn=()=>zo(jb(),".cursor","hooks.json"),un=()=>zo(jb(),".cursor","mcp.json"),Lt="anyray",zb="--anyray-owner=cursor-v1",PP="postToolUse",DP="beforeSubmitPrompt",Wb="preToolUse",LP="^MCP:",NP="UserPromptSubmit",$P="Shell",MP="^(Read|Grep)$",sl="--anyray-owner=cursor-hook-v1",to=[{event:PP,flag:Ye,trailingArgs:["cursor"],matcher:LP},{event:DP,flag:or,trailingArgs:[],matcher:NP},{event:Wb,flag:uw,trailingArgs:[],matcher:$P},{event:Wb,flag:pw,trailingArgs:[],matcher:MP}];var Ub={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},BP=(e,t,n)=>wP(e,t,n),Hb=BP,FP,WP=()=>{let e=FP??EP();if(e==="win32"){let t=Hb(Rs("tasklist.exe"),["/FI","IMAGENAME eq Cursor.exe","/FO","CSV","/NH"],Ub);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=Hb("pgrep",["-x",t],Ub);if(n.error||n.signal||n.status===null||n.status===0)return!0}return!1},UP=WP,ol=()=>UP();var HP=(e,t,n,r)=>{let o={applicationUser:e.readItem(n,Ve)??null,openAIKey:e.readItem(n,at)??null,lastWritten:r};rf(t,`${JSON.stringify(o,null,2)}
|
|
77
77
|
`,{encoding:"utf-8",flag:"wx",mode:384})},qb=(e,t)=>{let n=`${e}.${process.pid}.tmp`;rf(n,`${JSON.stringify(t,null,2)}
|
|
78
|
-
`,{encoding:"utf-8",flag:"wx",mode:384});try{vP(n,e)}catch(r){throw ln(n,{force:!0}),r}},HP=(e,t)=>{let n=Yo(e);qb(e,{...n,lastWritten:t})},se=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Gb=e=>se(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Yo=e=>{let t=Kb(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(se(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||se(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(!se(n)||n.version!==1||!se(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Ve],o=n.rows[at];if(!Gb(r)||!Gb(o))throw new Error("Cursor value backup is missing an exact managed row");return{applicationUser:r.exists?r.value:null,openAIKey:o.exists?o.value:null}},Vb=e=>{let t=Buffer.alloc(16),n=CP(e,"r");try{return kP(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{wP(n)}},GP=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return se(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Qb=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(".")&&zp(t)===0||t==="0.0.0.0")return!0;if(zp(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(zp(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 Qb(`${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},eA=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Qb(t.hostname)}catch{return!1}},VP=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${Jb}`}catch{}return{...e,openaiBaseUrl:t}},Jo=["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."],Qp=()=>{let e=br();if(!Se(e))return"clear";let t=mr();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ve)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return se(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},KP=(e,t)=>{if(!eA(e))return{routed:!1,problem:"gateway-not-public-https"};let n=br();if(!Se(n))return{routed:!1,problem:"state-db-missing"};let r=mr();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Ve),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(!se(s))return{routed:!1,problem:"settings-malformed"};let i=`${Kt(e)}/v1${Jb}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Ae(a)||!Ae(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},jP=()=>{let e=br();if(!Se(e))return"unverifiable";let t=mr();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ve)}catch{return"unverifiable"}if(n===void 0)return"unverifiable";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}if(!se(r))return"unverifiable";let o=r.availableAPIKeyModels;return Array.isArray(o)?o.length>0?"registered":"none":"unverifiable"},ZP=(e,t=[])=>({command:Tt(e,[...t,sl])}),af=(e,t,n)=>{if(!se(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Tt(t,[...n,sl])||r===Tt(t,n)||r.endsWith(` ${sl}`)&&r.includes(` ${t} `)},YP=(e,t)=>se(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),tA=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(af(a,t,n)){r=!0;continue}if(!se(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!YP(c,t));if(s.length===a.hooks.length){o.push(a);continue}r=!0;let i=Object.keys(a).every(c=>c==="matcher"||c==="hooks");s.length===0&&i||o.push({...a,hooks:s})}return{entries:o,changed:r}},sf=(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},nA=(e,t,n,r,o)=>se(e.hooks)&&sf(e.hooks,t).some(a=>se(a)&&a.matcher===o&&af(a,n,r)),JP=(e,t,n,r,o)=>se(e.hooks)&&sf(e.hooks,t).some(a=>se(a)&&a.matcher===o&&af(a,n,r)&&fc(a.command,n,[...r,sl])),rA=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!se(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=se(e.hooks)?{...e.hooks}:{},{entries:s}=tA(sf(a,t),n,r);return s.push({...ZP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},XP=(e,t,n,r=[])=>{if(!se(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=tA(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},zP=async()=>{let e=dn();if(!oe()){let t=await aA();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${De()}). Re-run via the installer or a global install to enable cache-safe trimming and paste-savings beacons.`],complete:t.complete}}try{let t=await B(e);for(let n of to)t=rA(t,n.event,n.flag,n.trailingArgs,n.matcher);return await X(e,t),{changedFiles:[e],messages:[`Installed Cursor global hooks in ${e} (postToolUse trims oversized MCP tool outputs; preToolUse trims recognized Shell command output and redirects bulky built-in Read/Grep to Anyray's context tools; beforeSubmitPrompt beacons oversized pasted-data prompts). Cursor hook cache/tee persistence is disabled; gateway request logs and savings/spend rows remain metadata-only, while trace decision content follows the deployment's ANYRAY_CONTENT_MODE.`],complete:!0}}catch{return{changedFiles:[],messages:[`Could not install Cursor hooks in ${e}. Chat can still route through Anyray, but hook-based trimming/beacons are unavailable until this is fixed.`],complete:!1}}},al=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,zb]}},ef=e=>se(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===al().command&&e.args.length===al().args.length&&e.args.every((t,n)=>t===al().args[n]),qP=e=>{if(!se(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")||tt(e.command))return!1;let t=e.args;if(t.at(-2)!==sr||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!tt(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},il=e=>se(e)&&Array.isArray(e.args)&&e.args.at(-1)===zb||qP(e),QP=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,eD=async()=>{if(!oe())return oA();let e=un();try{let t=await B(e);if(t.mcpServers!==void 0&&!se(t.mcpServers))throw new Error("mcpServers is not an object");let n=se(t.mcpServers)?{...t.mcpServers}:{},r=n[Lt];return r!==void 0&&!il(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Lt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Lt]=al(),await X(e,{...t,mcpServers:n}),{changedFiles:[e],messages:[`Registered the Anyray retrieval MCP server (anyray_retrieve) in ${e} for explicit recovery of stashed context.`],complete:!0})}catch{return{changedFiles:[],messages:[`Could not register the Anyray MCP server in ${e}; retrieval via anyray_retrieve is unavailable until this is fixed.`],complete:!1}}},oA=async()=>{let e=un();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await B(e);if(!se(t.mcpServers)||!(Lt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!il(t.mcpServers[Lt]))return{changedFiles:[],messages:[`Preserved the foreign ${Lt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Lt];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await X(e,r,{backup:!1}),{changedFiles:[e],messages:["Removed the Anyray retrieval MCP server (anyray_retrieve)."],complete:!0}}catch{return{changedFiles:[],messages:[`Could not remove the Anyray MCP server from ${e}; the registration was left in place.`],complete:!1}}},aA=async()=>{let e=dn();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await B(e),n=t;for(let r of to)n=XP(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await X(e,n,{backup:!1}),{changedFiles:[e],messages:["Removed Cursor global Anyray hooks."],complete:!0})}catch{return{changedFiles:[],messages:[`Could not remove Cursor hooks from ${e}; the hooks were left in place.`],complete:!1}}},tD=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=OP(e);if(!n)return t;let r=zo(n,Os),o=RP();try{if(Se(r)){let a=Kb(r,"utf8");if(a===o)return t;if(!a.includes(Xb))return{...t,messages:[`Left ${Os} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${of}"`]}}return AP(Zb(r),{recursive:!0}),rf(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Os} 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 ${Os} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},sA=async()=>{let e=await zP(),t=await eD(),n=await tD();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},tf=async()=>{let e=await aA(),t=await oA();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},iA=async()=>{if(!oe()){let e=await tf();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${De()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await B(dn());for(let r of to)e=rA(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await B(un());if(t.mcpServers!==void 0&&!se(t.mcpServers))throw new Error("mcpServers is not an object");let n=se(t.mcpServers)?t.mcpServers[Lt]:void 0;return n!==void 0&&!il(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${un()} already contains a foreign ${Lt} 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 ${dn()} and ${un()}, then re-run Connect.`],complete:!1}}},nD=async()=>{if(!oe())return!1;try{let e=await B(dn());if(!se(e.hooks)||!to.every(r=>nA(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await B(un()),n=se(t.mcpServers)?t.mcpServers[Lt]:void 0;return ef(n)}catch{return!1}},cA=["openAIBaseUrl","useOpenAIKey"],_s=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!se(t))throw new Error("Cursor application-user settings are not an object");return t},rD=(e,t,n)=>{let r=_s(e),o=_s(t??void 0),a=n===void 0?void 0:_s(n),s={...r},i=[];for(let c of cA){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:Ve}:{key:Ve,value:JSON.stringify(s)},conflicts:i}},qp=(e,t)=>{let n=_s(e),r=_s(t??void 0),o={...n};for(let a of cA)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Ve}:{key:Ve,value:JSON.stringify(o)}},nl=e=>typeof e=="string"&&e.startsWith("ark_"),rl=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);se(o)&&(n=o)}catch{}let r=nl(t)||n!==null&&(nl(n.useOpenAIKey)||nl(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,nl(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.",...Jo];let n=me(e.metadata);return[...t?[t]:[],"Configure Cursor by hand: Cursor \u2192 Settings \u2192 Models \u2192 OpenAI API Key:",` \u2022 Override OpenAI Base URL: ${e.openaiBaseUrl}`," \u2022 API key: run `anyray-connect print-key` and paste the returned personal gateway key (the key is not shown here).",n?` \u2022 Cursor has no custom-header field, so attribution rides your per-user key, not ${n}.`:" \u2022 (No attribution metadata resolved; set --user, or use --enroll for a per-user key.)","This is Cursor's OpenAI-BYOK lane: usage counts toward your Anyray subscription seat, but the upstream still needs a provider API key. It does not consume the native Cursor Team entitlement; exact custom-model Agent compatibility varies by Cursor release.",...Jo]},nf=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!oe())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 xs("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]}},oD=async(e,t)=>{if(!Ae(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 yr("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 iA();if(!n.complete)return{status:"manual",messages:n.messages};let r=Se(Ts())||Se(Xo());if(r&&ol())return nf("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=Qp();if(c!=="clear")return{status:"manual",messages:[c==="active"?"Cursor still has an OpenAI BYOK override enabled, and Connect has no recovery journal proving it owns those values.":"Cursor's OpenAI override state could not be verified safely, and Connect has no recovery journal for it.","In Cursor \u2192 Settings \u2192 Models, disable the OpenAI API-key/base-URL override, keep your Cursor Team login, then re-run Connect. No app-state value or credential was guessed or overwritten."]}}if(t.dryRun)return{status:"configured",messages:[r?`Would restore Cursor's journaled OpenAI override from ${Se(Xo())?Xo():Ts()}, 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 ${dn()}, and register the Anyray retrieval MCP server in ${un()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Ps.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 sA(),s=[];if(!t.preservePendingOp)try{await yr("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 -- "${of}" (connect already writes ${Os} 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."]}},Ps={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>ol(),quitTarget:IP,needsTarget:e=>e!=="revert",async complete(e,t,n){return xP(e)?e!=="revert"&&t?Ps.apply(t,n):Ps.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=Yb(),t=Se(e);return{installed:t,detail:t?br():"Cursor user dir not found"}},async mcpStatus(){if(!oe())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=un();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await B(e),n=se(t.mcpServers)?t.mcpServers[Lt]:void 0;return ef(n)?{registered:!0,command:QP(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=dn();if(!await x(n))e="missing";else try{let s=await B(n);if(s.hooks===void 0)e="missing";else if(!se(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(to.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=to.every(c=>nA(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=to.every(c=>JP(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=un();if(!await x(a))r="missing";else try{let s=await B(a);if(s.mcpServers===void 0)r="missing";else if(!se(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Lt];r=i===void 0?"missing":il(i)?"owned":"foreign",r==="owned"&&(o=ef(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Gr()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await P();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(TP(e))return oD(e,t);let n=VP(e),r=br(),o=Ts(),a=Xo();if(!Ae(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(!eA(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.",...Jo]});let c=await iA();if(!c.complete)return{status:"manual",messages:c.messages};let l=mr();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(!Se(r))return i({status:"manual",messages:ot(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(Se(a)){if(Se(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{Vb(a)?d="sqlite":(Yo(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 f;if(Se(o))try{f=Yo(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(ol())return i(await nf("apply",t,{status:"manual",messages:ot(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Jo,...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}, ${Se(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 ${dn()}, and register the Anyray retrieval MCP server in ${un()}.`,...Jo]};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}${Es(g)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(d==="sqlite")y=rl(l.readItem(a,Ve)??null,l.readItem(a,at)??null);else{let g=Yo(a);y=rl(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,[qp(l.readItem(r,Ve),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{ln(a,{force:!0}),ln(`${a}-wal`,{force:!0}),ln(`${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}${Es(y)} \u2014 refusing to write; set it by hand:`)})}let m;try{m=l.readItem(r,Ve)}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 p=GP(m,n);if(!p)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:p.value,openAIKey:e.clientKey};if(Se(o))try{HP(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{UP(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:Ve,value:p.value},{key:at,value:e.clientKey}])}catch{let y=!0;if(f)try{qb(o,f)}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 sA();let w=[];if(!t.preservePendingOp)try{await yr("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,...Jo,"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await P().catch(()=>{}),n=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Se(Ts())||Se(Xo())||Qp()!=="clear"?!1:nD():KP(e,n).routed},async routingOverrides(){return Qp()!=="active"?[]:jP()!=="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=br(),n=Ts(),r=Xo(),o=Se(n),a=Se(r);if(e.dryRun)return{status:"reverted",messages:[o||a?`Would restore Cursor from ${a?r:n}, remove its recovery sidecar(s), remove Anyray Cursor hooks from ${dn()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${dn()} and unregister its owned retrieval MCP server.`]};if((o||a)&&ol()){if(e.fullRevert){let p=await tf(),h=!0;try{await yr("cursor")}catch{h=!1}return{status:"manual",changedFiles:p.changedFiles,messages:[...p.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 nf("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=mr(),i=!1,c=!1,l,d=[];if(a)try{if(Vb(r))if(Se(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let p=rl(s.readItem(r,Ve)??null,s.readItem(r,at)??null);s.mutateRows(t,[qp(s.readItem(t,Ve),p.applicationUser),p.openAIKey===null?{key:at}:{key:at,value:p.openAIKey}]),c=!0}else i=!0,bP(r,t),ln(`${t}-wal`,{force:!0}),ln(`${t}-shm`,{force:!0});else{let p=Yo(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Se(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let h=rl(p.applicationUser,p.openAIKey);s.mutateRows(t,[qp(s.readItem(t,Ve),h.applicationUser),h.openAIKey===null?{key:at}:{key:at,value:h.openAIKey}]),c=!0}}catch(p){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${Es(p)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Yo(n)}catch{return{status:"manual",messages:[`Couldn't read a supported Cursor value backup from ${n}; the backup was retained.`]}}if(l){if(!l.lastWritten)return{status:"manual",messages:[`The Cursor backup at ${n} predates three-way ownership, so Connect cannot prove which current values are still its own. The backup was retained and no hook or MCP cleanup was attempted.`]};if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Se(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let p=rD(s.readItem(t,Ve),l.applicationUser,l.lastWritten?.applicationUser);d.push(...p.conflicts);let h=[p.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(p){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${Es(p)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{ln(r,{force:!0}),ln(`${r}-wal`,{force:!0}),ln(`${r}-shm`,{force:!0}),ln(n,{force:!0})}catch{f=!1,u.push("Cursor values were restored, but a recovery sidecar could not be removed; retain it until a later revert can finish cleanup.")}if(!e.preservePendingOp)try{await yr("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let m=await tf();return f=f&&m.complete,{status:f?"reverted":"manual",changedFiles:[...o||a?[t]:[],...m.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(", ")}.`]:[],...m.messages,"Restart Cursor."]}}};import{chmod as iL,mkdir as cL,readFile as jA,rm as lL,writeFile as dL}from"node:fs/promises";import{randomUUID as uL}from"node:crypto";import{dirname as pL,join as ZA}from"node:path";import{constants as iD,chmod as cD,copyFile as lD,readFile as lA}from"node:fs/promises";import{applyEdits as dD,modify as uD}from"jsonc-parser";var aD=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]!==`
|
|
79
|
-
`;)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},
|
|
80
|
-
`,r=n.trim()?bt(n):{};if(!cl(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},dA=(e,t,n=[])=>{if(cl(e)&&cl(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...dA(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}]},pn=async(e,t,n,r)=>{let o=dA(t.data,n);if(o.length===0)return!1;if(r&&!await x(`${e}.anyray-bak`))if(t.existed)try{await
|
|
78
|
+
`,{encoding:"utf-8",flag:"wx",mode:384});try{SP(n,e)}catch(r){throw ln(n,{force:!0}),r}},GP=(e,t)=>{let n=Yo(e);qb(e,{...n,lastWritten:t})},se=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Gb=e=>se(e)&&typeof e.exists=="boolean"&&(typeof e.value=="string"||e.value===null)&&(e.exists?typeof e.value=="string":e.value===null),Yo=e=>{let t=Kb(e),n;try{n=JSON.parse(t.toString("utf-8"))}catch{throw new Error("Cursor value backup is not JSON")}if(se(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||se(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(!se(n)||n.version!==1||!se(n.rows))throw new Error("Cursor value backup has an unsupported shape");let r=n.rows[Ve],o=n.rows[at];if(!Gb(r)||!Gb(o))throw new Error("Cursor value backup is missing an exact managed row");return{applicationUser:r.exists?r.value:null,openAIKey:o.exists?o.value:null}},Vb=e=>{let t=Buffer.alloc(16),n=kP(e,"r");try{return vP(n,t,0,t.length,0)===t.length&&t.toString("utf-8")==="SQLite format 3\0"}finally{bP(n)}},VP=(e,t)=>{let n={};if(e!==void 0)try{n=JSON.parse(e)}catch{return null}return se(n)?(n.openAIBaseUrl=t.openaiBaseUrl,n.useOpenAIKey=!0,{value:JSON.stringify(n)}):null};var Qb=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(".")&&zp(t)===0||t==="0.0.0.0")return!0;if(zp(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(zp(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 Qb(`${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},eA=e=>{try{let t=new URL(e);return t.protocol==="https:"&&!Qb(t.hostname)}catch{return!1}},KP=e=>{let t=e.openaiBaseUrl;try{new URL(t),t=`${t.replace(/\/+$/,"")}${Jb}`}catch{}return{...e,openaiBaseUrl:t}},Jo=["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."],Qp=()=>{let e=br();if(!Se(e))return"clear";let t=mr();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ve)}catch{return"unverifiable"}if(n===void 0)return"clear";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}return se(r)?r.useOpenAIKey===!0?"active":"clear":"unverifiable"},jP=(e,t)=>{if(!eA(e))return{routed:!1,problem:"gateway-not-public-https"};let n=br();if(!Se(n))return{routed:!1,problem:"state-db-missing"};let r=mr();if(!r)return{routed:!1,problem:"state-db-unreadable"};let o,a;try{o=r.readItem(n,Ve),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(!se(s))return{routed:!1,problem:"settings-malformed"};let i=`${Kt(e)}/v1${Jb}`;return typeof s.openAIBaseUrl!="string"||s.openAIBaseUrl.replace(/\/+$/,"")!==i?{routed:!1,problem:"base-url-mismatch"}:s.useOpenAIKey!==!0?{routed:!1,problem:"override-disabled"}:!Ae(a)||!Ae(t)?{routed:!1,problem:"credential-missing-or-invalid"}:a!==t?{routed:!1,problem:"credential-mismatch"}:{routed:!0,problem:null}},ZP=()=>{let e=br();if(!Se(e))return"unverifiable";let t=mr();if(!t)return"unverifiable";let n;try{n=t.readItem(e,Ve)}catch{return"unverifiable"}if(n===void 0)return"unverifiable";let r;try{r=JSON.parse(n)}catch{return"unverifiable"}if(!se(r))return"unverifiable";let o=r.availableAPIKeyModels;return Array.isArray(o)?o.length>0?"registered":"none":"unverifiable"},YP=(e,t=[])=>({command:Tt(e,[...t,sl])}),af=(e,t,n)=>{if(!se(e)||typeof e.command!="string")return!1;let r=e.command.trim();return r===Tt(t,[...n,sl])||r===Tt(t,n)||r.endsWith(` ${sl}`)&&r.includes(` ${t} `)},JP=(e,t)=>se(e)&&e.type==="command"&&typeof e.command=="string"&&e.command.includes(t),tA=(e,t,n=[])=>{let r=!1,o=[];for(let a of e){if(af(a,t,n)){r=!0;continue}if(!se(a)||!Array.isArray(a.hooks)){o.push(a);continue}let s=a.hooks.filter(c=>!JP(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}},sf=(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},nA=(e,t,n,r,o)=>se(e.hooks)&&sf(e.hooks,t).some(a=>se(a)&&a.matcher===o&&af(a,n,r)),XP=(e,t,n,r,o)=>se(e.hooks)&&sf(e.hooks,t).some(a=>se(a)&&a.matcher===o&&af(a,n,r)&&fc(a.command,n,[...r,sl])),rA=(e,t,n,r=[],o)=>{if(e.hooks!==void 0&&!se(e.hooks))throw new Error("Cursor hooks config has a non-object hooks field");let a=se(e.hooks)?{...e.hooks}:{},{entries:s}=tA(sf(a,t),n,r);return s.push({...YP(n,r),...o?{matcher:o}:{}}),a[t]=s,{...e,version:e.version??1,hooks:a}},zP=(e,t,n,r=[])=>{if(!se(e.hooks))return e;let o={...e.hooks},a=o[t];if(!Array.isArray(a))return e;let{entries:s,changed:i}=tA(a,n,r);return i?(s.length===0?delete o[t]:o[t]=s,{...e,hooks:o}):e},qP=async()=>{let e=dn();if(!oe()){let t=await aA();return{changedFiles:t.changedFiles,messages:[...t.messages,`Skipped Cursor hooks \u2014 anyray-connect is running from a temporary path (${De()}). Re-run via the installer or a global install to enable cache-safe trimming and paste-savings beacons.`],complete:t.complete}}try{let t=await B(e);for(let n of to)t=rA(t,n.event,n.flag,n.trailingArgs,n.matcher);return await X(e,t),{changedFiles:[e],messages:[`Installed Cursor global hooks in ${e} (postToolUse trims oversized MCP tool outputs; preToolUse trims recognized Shell command output and redirects bulky built-in Read/Grep to Anyray's context tools; beforeSubmitPrompt beacons oversized pasted-data prompts). Cursor hook cache/tee persistence is disabled; gateway request logs and savings/spend rows remain metadata-only, while trace decision content follows the deployment's ANYRAY_CONTENT_MODE.`],complete:!0}}catch{return{changedFiles:[],messages:[`Could not install Cursor hooks in ${e}. Chat can still route through Anyray, but hook-based trimming/beacons are unavailable until this is fixed.`],complete:!1}}},al=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,zb]}},ef=e=>se(e)&&Object.keys(e).length===2&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")&&e.command===al().command&&e.args.length===al().args.length&&e.args.every((t,n)=>t===al().args[n]),QP=e=>{if(!se(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")||tt(e.command))return!1;let t=e.args;if(t.at(-2)!==sr||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!tt(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(r)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(r))},il=e=>se(e)&&Array.isArray(e.args)&&e.args.at(-1)===zb||QP(e),eD=e=>/[\\/](node|node\.exe)$/i.test(e.command)&&typeof e.args[0]=="string"?e.args[0]:e.command,tD=async()=>{if(!oe())return oA();let e=un();try{let t=await B(e);if(t.mcpServers!==void 0&&!se(t.mcpServers))throw new Error("mcpServers is not an object");let n=se(t.mcpServers)?{...t.mcpServers}:{},r=n[Lt];return r!==void 0&&!il(r)?{changedFiles:[],messages:[`Preserved the existing foreign ${Lt} MCP registration in ${e}; choose another name or remove it explicitly before Connect can register anyray_retrieve.`],complete:!1}:(n[Lt]=al(),await X(e,{...t,mcpServers:n}),{changedFiles:[e],messages:[`Registered the Anyray retrieval MCP server (anyray_retrieve) in ${e} for explicit recovery of stashed context.`],complete:!0})}catch{return{changedFiles:[],messages:[`Could not register the Anyray MCP server in ${e}; retrieval via anyray_retrieve is unavailable until this is fixed.`],complete:!1}}},oA=async()=>{let e=un();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await B(e);if(!se(t.mcpServers)||!(Lt in t.mcpServers))return{changedFiles:[],messages:[],complete:!0};if(!il(t.mcpServers[Lt]))return{changedFiles:[],messages:[`Preserved the foreign ${Lt} MCP registration in ${e}.`],complete:!0};let n={...t.mcpServers};delete n[Lt];let r={...t};return Object.keys(n).length===0?delete r.mcpServers:r.mcpServers=n,await X(e,r,{backup:!1}),{changedFiles:[e],messages:["Removed the Anyray retrieval MCP server (anyray_retrieve)."],complete:!0}}catch{return{changedFiles:[],messages:[`Could not remove the Anyray MCP server from ${e}; the registration was left in place.`],complete:!1}}},aA=async()=>{let e=dn();if(!await x(e))return{changedFiles:[],messages:[],complete:!0};try{let t=await B(e),n=t;for(let r of to)n=zP(n,r.event,r.flag,r.trailingArgs);return JSON.stringify(n)===JSON.stringify(t)?{changedFiles:[],messages:[],complete:!0}:(await X(e,n,{backup:!1}),{changedFiles:[e],messages:["Removed Cursor global Anyray hooks."],complete:!0})}catch{return{changedFiles:[],messages:[`Could not remove Cursor hooks from ${e}; the hooks were left in place.`],complete:!1}}},nD=async(e=process.cwd())=>{let t={changedFiles:[],messages:[],complete:!0},n=TP(e);if(!n)return t;let r=zo(n,Os),o=OP();try{if(Se(r)){let a=Kb(r,"utf8");if(a===o)return t;if(!a.includes(Xb))return{...t,messages:[`Left ${Os} alone \u2014 it exists but was not written by Anyray. Delete it to have connect manage the steering rule, or merge in: "${of}"`]}}return CP(Zb(r),{recursive:!0}),rf(r,o,{encoding:"utf8",mode:420}),{changedFiles:[r],messages:[`Wrote ${Os} 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 ${Os} in ${n}. Add it by hand, or use Cursor's dashboard Team Rules instead.`]}}},sA=async()=>{let e=await qP(),t=await tD(),n=await nD();return{changedFiles:[...e.changedFiles,...t.changedFiles,...n.changedFiles],messages:[...e.messages,...t.messages,...n.messages],complete:e.complete&&t.complete}},tf=async()=>{let e=await aA(),t=await oA();return{changedFiles:[...e.changedFiles,...t.changedFiles],messages:[...e.messages,...t.messages],complete:e.complete&&t.complete}},iA=async()=>{if(!oe()){let e=await tf();return{changedFiles:e.changedFiles,messages:[...e.messages,`Cursor's supported retrieval and MCP-trim setup requires a durable anyray-connect runtime (${De()} is temporary). Re-run via the installer or a global install before routing is changed.`],complete:!1}}try{let e=await B(dn());for(let r of to)e=rA(e,r.event,r.flag,r.trailingArgs,r.matcher);let t=await B(un());if(t.mcpServers!==void 0&&!se(t.mcpServers))throw new Error("mcpServers is not an object");let n=se(t.mcpServers)?t.mcpServers[Lt]:void 0;return n!==void 0&&!il(n)?{changedFiles:[],messages:[`Cursor routing was not changed because ${un()} already contains a foreign ${Lt} 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 ${dn()} and ${un()}, then re-run Connect.`],complete:!1}}},rD=async()=>{if(!oe())return!1;try{let e=await B(dn());if(!se(e.hooks)||!to.every(r=>nA(e,r.event,r.flag,r.trailingArgs,r.matcher)))return!1;let t=await B(un()),n=se(t.mcpServers)?t.mcpServers[Lt]:void 0;return ef(n)}catch{return!1}},cA=["openAIBaseUrl","useOpenAIKey"],_s=e=>{if(e===void 0)return{};let t;try{t=JSON.parse(e)}catch{throw new Error("Cursor application-user settings are malformed")}if(!se(t))throw new Error("Cursor application-user settings are not an object");return t},oD=(e,t,n)=>{let r=_s(e),o=_s(t??void 0),a=n===void 0?void 0:_s(n),s={...r},i=[];for(let c of cA){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:Ve}:{key:Ve,value:JSON.stringify(s)},conflicts:i}},qp=(e,t)=>{let n=_s(e),r=_s(t??void 0),o={...n};for(let a of cA)Object.prototype.hasOwnProperty.call(r,a)?o[a]=r[a]:delete o[a];return Object.keys(o).length===0?{key:Ve}:{key:Ve,value:JSON.stringify(o)}},nl=e=>typeof e=="string"&&e.startsWith("ark_"),rl=(e,t)=>{let n=null;if(e!==null)try{let o=JSON.parse(e);se(o)&&(n=o)}catch{}let r=nl(t)||n!==null&&(nl(n.useOpenAIKey)||nl(n.openAIKey));if(n===null)return{applicationUser:null,openAIKey:r?null:t};if(r){let o={...n};return delete o.openAIBaseUrl,delete o.useOpenAIKey,nl(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.",...Jo];let n=me(e.metadata);return[...t?[t]:[],"Configure Cursor by hand: Cursor \u2192 Settings \u2192 Models \u2192 OpenAI API Key:",` \u2022 Override OpenAI Base URL: ${e.openaiBaseUrl}`," \u2022 API key: run `anyray-connect print-key` and paste the returned personal gateway key (the key is not shown here).",n?` \u2022 Cursor has no custom-header field, so attribution rides your per-user key, not ${n}.`:" \u2022 (No attribution metadata resolved; set --user, or use --enroll for a per-user key.)","This is Cursor's OpenAI-BYOK lane: usage counts toward your Anyray subscription seat, but the upstream still needs a provider API key. It does not consume the native Cursor Team entitlement; exact custom-model Agent compatibility varies by Cursor release.",...Jo]},nf=async(e,t,n,r=[])=>{let o=e==="native"?"native-subscription convergence":e;if(!oe())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 xs("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]}},aD=async(e,t)=>{if(!Ae(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 yr("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 iA();if(!n.complete)return{status:"manual",messages:n.messages};let r=Se(Ts())||Se(Xo());if(r&&ol())return nf("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=Qp();if(c!=="clear")return{status:"manual",messages:[c==="active"?"Cursor still has an OpenAI BYOK override enabled, and Connect has no recovery journal proving it owns those values.":"Cursor's OpenAI override state could not be verified safely, and Connect has no recovery journal for it.","In Cursor \u2192 Settings \u2192 Models, disable the OpenAI API-key/base-URL override, keep your Cursor Team login, then re-run Connect. No app-state value or credential was guessed or overwritten."]}}if(t.dryRun)return{status:"configured",messages:[r?`Would restore Cursor's journaled OpenAI override from ${Se(Xo())?Xo():Ts()}, 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 ${dn()}, and register the Anyray retrieval MCP server in ${un()}.`,"Claude/Opus inference would remain Cursor-hosted; only supported local Shell/MCP context would be optimized by Anyray."]};let o;if(r&&(o=await Ps.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 sA(),s=[];if(!t.preservePendingOp)try{await yr("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 -- "${of}" (connect already writes ${Os} 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."]}},Ps={id:"cursor",title:"Cursor",automatic:!0,quitGated:{isRunning:()=>ol(),quitTarget:xP,needsTarget:e=>e!=="revert",async complete(e,t,n){return RP(e)?e!=="revert"&&t?Ps.apply(t,n):Ps.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=Yb(),t=Se(e);return{installed:t,detail:t?br():"Cursor user dir not found"}},async mcpStatus(){if(!oe())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=un();if(!await x(e))return{registered:!1,command:null,reason:"no-config"};try{let t=await B(e),n=se(t.mcpServers)?t.mcpServers[Lt]:void 0;return ef(n)?{registered:!0,command:eD(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=dn();if(!await x(n))e="missing";else try{let s=await B(n);if(s.hooks===void 0)e="missing";else if(!se(s.hooks))e="unreadable";else{let i=s.hooks;[...new Set(to.map(c=>c.event))].some(c=>i[c]!==void 0&&!Array.isArray(i[c]))?e="unreadable":(e=to.every(c=>nA(s,c.event,c.flag,c.trailingArgs,c.matcher))?"owned":"missing",e==="owned"&&(t=to.every(c=>XP(s,c.event,c.flag,c.trailingArgs,c.matcher))))}}catch{e="unreadable"}let r,o=!0,a=un();if(!await x(a))r="missing";else try{let s=await B(a);if(s.mcpServers===void 0)r="missing";else if(!se(s.mcpServers))r="unreadable";else{let i=s.mcpServers[Lt];r=i===void 0?"missing":il(i)?"owned":"foreign",r==="owned"&&(o=ef(i))}}catch{r="unreadable"}return{hook_registration:e,mcp_registration:r,hook_binary:t&&o&&await Gr()?"owned":"missing"}},async inferenceAuthLanes(){try{let e=await P();return e.authMode==="auto"||e.authMode==="subscription"?["native"]:e.authMode==="placeholder"?["api_key"]:["unknown"]}catch{return["unknown"]}},async apply(e,t){if(_P(e))return aD(e,t);let n=KP(e),r=br(),o=Ts(),a=Xo();if(!Ae(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 w=y.status==="configured"&&!s.complete;return{...y,status:w?"manual":y.status,changedFiles:[...y.changedFiles??[],...s.changedFiles],messages:[...y.messages,...s.messages,...w?["Cursor routing landed, but trim/retrieval did not fully converge. Re-run Connect after resolving the reported integration error."]:[]]}};if(!eA(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.",...Jo]});let c=await iA();if(!c.complete)return{status:"manual",messages:c.messages};let l=mr();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(!Se(r))return i({status:"manual",messages:ot(n,`No Cursor state DB at ${r} (open Cursor once first).`)});let d=null,u;if(Se(a)){if(Se(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{Vb(a)?d="sqlite":(Yo(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 f;if(Se(o))try{f=Yo(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(ol())return i(await nf("apply",t,{status:"manual",messages:ot(n,"Cursor is running \u2014 quit it and re-run, or set it by hand:")},[...Jo,...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}, ${Se(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 ${dn()}, and register the Anyray retrieval MCP server in ${un()}.`,...Jo]};if(d){try{l.checkpointWal(r)}catch(w){return i({status:"manual",messages:ot(n,`Couldn't checkpoint Cursor's state DB at ${r} while migrating the legacy Anyray backup at ${a}${Es(w)} \u2014 refusing to migrate; the legacy backup was retained. Run --revert or resolve it by hand:`)})}let y;try{if(d==="sqlite")y=rl(l.readItem(a,Ve)??null,l.readItem(a,at)??null);else{let w=Yo(a);y=rl(w.applicationUser,w.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,[qp(l.readItem(r,Ve),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{ln(a,{force:!0}),ln(`${a}-wal`,{force:!0}),ln(`${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}${Es(y)} \u2014 refusing to write; set it by hand:`)})}let m;try{m=l.readItem(r,Ve)}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 p=VP(m,n);if(!p)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:p.value,openAIKey:e.clientKey};if(Se(o))try{GP(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:Ve,value:p.value},{key:at,value:e.clientKey}])}catch{let y=!0;if(f)try{qb(o,f)}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 sA();let g=[];if(!t.preservePendingOp)try{await yr("cursor")}catch{g.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).",...g,...Jo,"Restart Cursor to pick it up."]})},async pointsAt(e){let t=await P().catch(()=>{}),n=process.env.ANYRAY_CLIENT_KEY?.trim()||t?.clientKey;return t&&(t.authMode==="auto"||t.authMode==="subscription")?Se(Ts())||Se(Xo())||Qp()!=="clear"?!1:rD():jP(e,n).routed},async routingOverrides(){return Qp()!=="active"?[]:ZP()!=="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=br(),n=Ts(),r=Xo(),o=Se(n),a=Se(r);if(e.dryRun)return{status:"reverted",messages:[o||a?`Would restore Cursor from ${a?r:n}, remove its recovery sidecar(s), remove Anyray Cursor hooks from ${dn()}, and unregister its owned retrieval MCP server.`:`No Cursor row backup is present; would still remove Anyray Cursor hooks from ${dn()} and unregister its owned retrieval MCP server.`]};if((o||a)&&ol()){if(e.fullRevert){let p=await tf(),h=!0;try{await yr("cursor")}catch{h=!1}return{status:"manual",changedFiles:p.changedFiles,messages:[...p.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 nf("revert",e,{status:"manual",messages:["Cursor is running \u2014 quit it and re-run --revert to restore the backup."]})}let s=mr(),i=!1,c=!1,l,d=[];if(a)try{if(Vb(r))if(Se(t)){if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to checkpoint the current Cursor DB before restoring its legacy backup."]};s.checkpointWal(t);let p=rl(s.readItem(r,Ve)??null,s.readItem(r,at)??null);s.mutateRows(t,[qp(s.readItem(t,Ve),p.applicationUser),p.openAIKey===null?{key:at}:{key:at,value:p.openAIKey}]),c=!0}else i=!0,AP(r,t),ln(`${t}-wal`,{force:!0}),ln(`${t}-shm`,{force:!0});else{let p=Yo(r);if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Se(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};s.checkpointWal(t);let h=rl(p.applicationUser,p.openAIKey);s.mutateRows(t,[qp(s.readItem(t,Ve),h.applicationUser),h.openAIKey===null?{key:at}:{key:at,value:h.openAIKey}]),c=!0}}catch(p){return{status:"manual",messages:[`Couldn't read or restore Cursor safely from ${r}${Es(p)}; all backups were retained and no hook cleanup was attempted.`]}}else if(o)try{l=Yo(n)}catch{return{status:"manual",messages:[`Couldn't read a supported Cursor value backup from ${n}; the backup was retained.`]}}if(l){if(!l.lastWritten)return{status:"manual",messages:[`The Cursor backup at ${n} predates three-way ownership, so Connect cannot prove which current values are still its own. The backup was retained and no hook or MCP cleanup was attempted.`]};if(!s)return{status:"manual",messages:["No SQLite backend available \u2014 one is required to restore the Cursor value backup safely."]};if(!Se(t))return{status:"manual",messages:[`No Cursor state DB at ${t} \u2014 refusing to create an incomplete database from a value backup.`]};try{s.checkpointWal(t);let p=oD(s.readItem(t,Ve),l.applicationUser,l.lastWritten?.applicationUser);d.push(...p.conflicts);let h=[p.mutation],g=s.readItem(t,at);l.lastWritten&&g===l.lastWritten.openAIKey?h.push(l.openAIKey===null?{key:at}:{key:at,value:l.openAIKey}):d.push("OpenAI credential"),s.mutateRows(t,h)}catch(p){return{status:"manual",messages:[`Couldn't restore Cursor safely from ${n}${Es(p)}; all backups were retained and no hook cleanup was attempted.`]}}}let u=[],f=!0;try{ln(r,{force:!0}),ln(`${r}-wal`,{force:!0}),ln(`${r}-shm`,{force:!0}),ln(n,{force:!0})}catch{f=!1,u.push("Cursor values were restored, but a recovery sidecar could not be removed; retain it until a later revert can finish cleanup.")}if(!e.preservePendingOp)try{await yr("cursor")}catch{f=!1,u.push("Could not clear Cursor's stale queue marker.")}let m=await tf();return f=f&&m.complete,{status:f?"reverted":"manual",changedFiles:[...o||a?[t]:[],...m.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(", ")}.`]:[],...m.messages,"Restart Cursor."]}}};import{chmod as cL,mkdir as lL,readFile as jA,rm as dL,writeFile as uL}from"node:fs/promises";import{randomUUID as pL}from"node:crypto";import{dirname as fL,join as ZA}from"node:path";import{constants as cD,chmod as lD,copyFile as dD,readFile as lA}from"node:fs/promises";import{applyEdits as uD,modify as pD}from"jsonc-parser";var sD=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]!==`
|
|
79
|
+
`;)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},iD=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},bt=e=>JSON.parse(iD(sD(e)));var cl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ke=async e=>{let t=await x(e),n=t?await lA(e,"utf8"):`{}
|
|
80
|
+
`,r=n.trim()?bt(n):{};if(!cl(r))throw new Error(`${e} is not a JSON object`);return{data:r,raw:n,existed:t}},dA=(e,t,n=[])=>{if(cl(e)&&cl(t)){let r=[];for(let o of new Set([...Object.keys(e),...Object.keys(t)]))o in t?o in e?r.push(...dA(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}]},pn=async(e,t,n,r)=>{let o=dA(t.data,n);if(o.length===0)return!1;if(r&&!await x(`${e}.anyray-bak`))if(t.existed)try{await dD(e,`${e}.anyray-bak`,cD.COPYFILE_EXCL),await lD(`${e}.anyray-bak`,384)}catch(i){if(i.code!=="EEXIST")throw i}else await we(`${e}.anyray-bak`,`{}
|
|
81
81
|
`);let a={insertSpaces:!0,tabSize:2,eol:t.raw.includes(`\r
|
|
82
82
|
`)?`\r
|
|
83
83
|
`:`
|
|
84
|
-
`},s=t.raw;for(let i of o)s=
|
|
84
|
+
`},s=t.raw;for(let i of o)s=uD(s,pD(s,i.path,i.value,{formattingOptions:a}));return await we(e,s.endsWith(`
|
|
85
85
|
`)?s:`${s}
|
|
86
|
-
`),!0},qo=async e=>{try{let t=bt(await lA(`${e}.anyray-bak`,"utf8"));return cl(t)?t:void 0}catch{return}};import{readFile as
|
|
87
|
-
`;)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},
|
|
86
|
+
`),!0},qo=async e=>{try{let t=bt(await lA(`${e}.anyray-bak`,"utf8"));return cl(t)?t:void 0}catch{return}};import{readFile as XD,writeFile as zD}from"node:fs/promises";import{dirname as qD,join as QD}from"node:path";import{mkdir as eL}from"node:fs/promises";var uA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fD=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]!==`
|
|
87
|
+
`;)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},mD=(e,t)=>{let n=/\n([ \t]+)"/.exec(e.slice(t));return n?n[1]:" "},hD=(e,t)=>{let n=e.slice(t+1),r=n.indexOf("}");return r===-1?!1:n.slice(0,r).trim()===""},cf=(e,t,n)=>{let r;try{r=bt(e)}catch{return{ok:!1,reason:"unsupported"}}if(!uA(r))return{ok:!1,reason:"unsupported"};if(t in r)return{ok:!1,reason:"key-present"};let o=fD(e);if(o===-1)return{ok:!1,reason:"unsupported"};let a=mD(e,o),s=`${JSON.stringify(t)}: ${JSON.stringify(n)}`,i=e.slice(0,o+1),c=e.slice(o+1),l=hD(e,o)?`
|
|
88
88
|
${a}${s}
|
|
89
89
|
`:`
|
|
90
|
-
${a}${s},`,d=`${i}${l}${c}`;try{let u=bt(d);if(!uA(u))return{ok:!1,reason:"unsupported"};for(let[f,m]of Object.entries(r))if(JSON.stringify(u[f])!==JSON.stringify(m))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 CD}from"node:child_process";import{readdirSync as kD,statSync as vD}from"node:fs";import{createHash as IA,randomBytes as SD,randomUUID as xA}from"node:crypto";import{chmod as ED,lstat as yf,mkdir as gf,readdir as RA,readFile as mn,rm as OA,unlink as pl,writeFile as wf}from"node:fs/promises";import{homedir as na,platform as bf}from"node:os";import{dirname as ff,join as At,posix as vA,win32 as ID}from"node:path";import{promisify as xD}from"node:util";var fn="0.1.29";var Ar="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3d8f3",ll="c341829c0dacfc512fa49fb951be4864ca3e7d6b46d6befbee84e663daa8e9a7",pA="UEsDBBQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAZXh0ZW5zaW9uLnZzaXhtYW5pZmVzdL1WTW8bNxA927+CYIGeItLyqXVXGwiynQiVAhVyfSwwIkcr1lyS4HBlKb++2F19WXGSSg5y2+XMvMf54COz96vSsiVGMt71eFdccYZOeW1c0eNVmnd+4+/zy4tsAuoJChyDM3OkxB63Idfiqg5aldZRjy9SCjdSklpgCSRKo6InP09C+VJqXKL1AaNc0qrT+sjrq253E36jzwDoaCRTuBYnv7y4yMaYQEOC+uciG2p0yaQ1G4ErKiiwx9F1/p5yNtQ9Dm4dYd1ZkvIa+T6rK9EV179zNqlm1tAC49aVM9ni3hoKFtafoMS835jY3Ef2OGUDrzGTh/Y2AElFE5Lxrk73hgIo7PEQkTAuked9rRmugjXKJLaB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lwbgDJwWwIyWZlPhXgXLjJY2u+xUZ9HulXS/XCjvQrsvNiYKL9o7GdJRIvwpit/5KLHjNQ4Gnk4icM5e7UEod154b48TrS7Vgu8iMxOLIlc6j1tasslSoUZwug+XxDgEtrsxlOZe1YiOaspCVDvSwESIVjUk8JsJSB4U0Y/6cutVmkl2m0qKc2ofazT8y/8FUEsHCKcyHPQDOQAAI6kAAFBLAQI/AxQAAAgIABdaGF0E7sw5NAMAAK4KAAAWAAAAAAAAAAAAAAC0gQAAAABleHRlbnNpb24udnNpeG1hbmlmZXN0UEsBAj8DFAAACAgAF1oYXVr3VFTSAAAAzgEAABMAAAAAAAAAAAAAALSBaAMAAFtDb250ZW50X1R5cGVzXS54bWxQSwECPwMUAAgICAAKWhhdcQ3Z86YCAAC7BQAAFgAAAAAAAAAAAAAApIFrBAAAZXh0ZW5zaW9uL3BhY2thZ2UuanNvblBLAQI/AxQACAgIAARaGF0wVq3AThEAACgTAAASAAAAAAAAAAAAAACkgVUHAABleHRlbnNpb24vaWNvbi5wbmdQSwECPwMUAAAICAAXWhhdC7fjr0sCAAB9BAAAEwAAAAAAAAAAAAAAtIHjGAAAZXh0ZW5zaW9uL3JlYWRtZS5tZFBLAQI/AxQACAgIAMtZGF2yhnqNeQIAACcEAAAVAAAAAAAAAAAAAACkgV8bAABleHRlbnNpb24vTElDRU5TRS50eHRQSwECPwMUAAgICAAXWhhdpzIc9AM5AAAjqQAAGwAAAAAAAAAAAAAApIEbHgAAZXh0ZW5zaW9uL2Rpc3QvZXh0ZW5zaW9uLmpzUEsFBgAAAAAHAAcA1gEAAGdXAAAAAA==";import{readFile as hA}from"node:fs/promises";import{homedir as no,platform as Qo}from"node:os";import{join as Nn,posix as hD,win32 as yD}from"node:path";var ro=["Code","Code - Insiders","VSCodium"],lf="1.121.0",fA=1,gD=121,yA="1.102.0",mA=1,wD=102,bD={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},dl=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},df=e=>{let t=dl(e);return t?t.major!==fA?t.major>fA:t.minor>=gD:!1},gA=e=>{let t=dl(e);return t?t.major!==mA?t.major>mA:t.minor>=wD:!1},AD=async e=>{if(Qo()!=="darwin")return;let t=Nn("/Applications",`${bD[e]}.app`,"Contents","Resources","app","package.json");if(await x(t))try{let n=JSON.parse(await hA(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},ul=(e,t=Qo(),n=no(),r=process.env)=>{switch(t){case"darwin":return Nn(n,"Library","Application Support",e);case"win32":return Nn(r.APPDATA??Nn(n,"AppData","Roaming"),e);default:return Nn(n,".config",e)}},uf=(e,t)=>e?t==="win32"?yD.join:hD.join:Nn,ea=(e,t=!1,n=Qo(),r=no(),o=process.env)=>t?uf(t,n)(r,Ds[e],"data","User"):Nn(ul(e,n,r,o),"User"),wA=async(e,t=!1,n=Qo(),r=no(),o=process.env)=>{try{let a=uf(t,n)(ea(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await hA(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[]}},bA=async(e,t=Qo(),n=no(),r=process.env)=>{let a=(await wA(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},AA=async(e,t=!1,n=Qo(),r=no(),o=process.env)=>{let a=uf(t,n),s=ea(e,t,n,r,o),i=await wA(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},ta=async()=>{for(let e of ro)if(await x(ul(e)))return e},Ds={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},CA=(e,t=no())=>Nn(t,Ds[e],"extensions"),pf=async(e=no())=>{for(let t of ro)if(await x(Nn(e,Ds[t])))return t},kA=async e=>{let t=e??await ta();if(!t)return{status:"unknown"};let n=await AD(t);return n?{variant:t,version:n,status:df(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var q="anyray.anyray-vscode",Af="vscode-handoffs",TA="vscode-receipts",Ls=2,RD=xD(CD),$n={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"]}},OD={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"}},TD=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),_A=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&TD(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Ns=e=>{if(_A(e))try{return new URL(e.trim()).origin}catch{return}},_D=(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)},PD=e=>{try{return kD(e)}catch{return[]}},DD=e=>{try{return vD(e).mtimeMs}catch{return}},LD=(e,t,n,r,o)=>{if(!Zr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=$n[e].commands[0],s=At(t,Ds[e]),i=[];for(let{directory:c,suffix:l}of[{directory:At(s,"bin"),suffix:["bin","remote-cli"]},{directory:At(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=At(c,d,...l,a),f=o(u);f!==void 0&&i.push({path:u,mtime:f})}return i.sort((c,l)=>l.mtime-c.mtime).map(({path:c})=>c)},ND=(e,t,n)=>{let{macAppName:r,commands:o}=$n[e],a=o[0],s=[];for(let i of["/Applications",vA.join(t,"Applications")])for(let c of n(i))_D(c,r)&&s.push(vA.join(i,c,"Contents/Resources/app/bin",a));return s},$D=(e,t=bf(),n=na(),r=process.env,o=PD,a=DD)=>{let s=LD(e,n,r,o,a);if(t==="darwin")return[...new Set([...$n[e].commands,...ND(e,n,o),...s])];if(t!=="win32"){let u=$n[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=OD[e],c=ID.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)),$n[e].commands[0],...s])]},PA={run:async(e,t)=>({stdout:(await RD(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>SD(24).toString("base64url"),home:"",commandCandidates:e=>$D(e)},oo=(e,t)=>At(e,".anyray",TA,`${t}.json`),Cf=(e,t)=>At(e,".anyray",TA,`${t}.applied.json`),DA=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&dl(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},mf=async(e,t,n)=>{try{let r=await t.run(e,[...n===void 0?[]:["--profile",n],"--list-extensions","--show-versions"]);if(typeof r?.stdout!="string")return;let o=r.stdout.split(/\r?\n/).map(a=>a.trim()).flatMap(a=>{let s=a.lastIndexOf("@");return s<=0?[]:a.slice(0,s).toLowerCase()===q.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===fn}catch{return}},LA=async(e,t)=>{let n=await DA(e,t);if(n)return mf(n.command,t)},MD=async(e,t,n)=>{let r=At(e,".anyray",Af);for(let o of n){if(!o.endsWith(".json"))continue;let a=At(r,o);try{if(!(await yf(a)).isFile()||JSON.parse(await mn(a,"utf8")).variant!==t)continue;await pl(a)}catch{}}},BD=async(e,t)=>{let n=At(e,".anyray",Af),r;try{r=await RA(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=At(n,o);try{if(!(await yf(a)).isFile()||JSON.parse(await mn(a,"utf8")).variant!==t)continue;await pl(a)}catch{}}},FD=async(e,t)=>{try{let n=JSON.parse(await mn(oo(e,t),"utf8"));return n.extensionVersion===fn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==Ar}catch{return!1}},NA=250,WD=9e4,UD=WD/NA,HD=async(e,t,n,r)=>{for(let o=0;o<UD;o++){try{let a=JSON.parse(await mn(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Ls&&a.action===n?"confirmed":a.extensionVersion!==fn||a.extensionDistSha256!==Ar?"reload-required":a.version===Ls&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(NA)}return"timeout"},GD=200,SA=(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(": ")},VD=async e=>{try{let t=await yf(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},EA=e=>IA("sha256").update(e).digest("hex"),KD=async(e=na())=>{let t=Buffer.from(pA,"base64");if(t.length<4||t[0]!==80||t[1]!==75||EA(t)!==ll)throw new Error("bundled VS Code extension failed integrity validation");let n=At(e,".anyray","vscode-extension"),r=At(n,`anyray-vscode-${fn}-${ll.slice(0,12)}.vsix`);try{if(EA(await mn(r))===ll)return r}catch{}await gf(n,{recursive:!0,mode:448});let o=`${r}.${xA()}.tmp`;try{await wf(o,t,{mode:384}),await ye(o,r),bf()!=="win32"&&await ED(r,384)}finally{await OA(o,{force:!0})}return r},hf=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=>hf(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${hf(t[n])}`).join(",")}}`},$A=(e,t,n)=>IA("sha256").update(hf({gatewayUrl:Ns(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:fn,extensionDistSha256:Ar,profiles:[...n].sort()})).digest("hex"),jD=async(e,t,n,r,o,a)=>{let s=JSON.parse(await mn(Cf(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==$A(t,n,r))return!1;let i=JSON.parse(await mn(oo(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===fn&&i.extensionDistSha256===Ar&&i.gatewayUrl===Ns(t.origin)?await LA(e,a)===!0:!1},ZD=async(e,t,n,r)=>{let o=Cf(e,t),a=`${o}.${xA()}.tmp`;try{await gf(ff(o),{recursive:!0,mode:448}),await wf(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
91
|
-
`,{mode:384}),await ye(a,o)}catch{}finally{await OA(a,{force:!0})}},
|
|
92
|
-
`,{mode:384}),await
|
|
93
|
-
`,{flag:"wx",mode:384}),await ye(n,e),await iL(e,384)}finally{await lL(n,{force:!0}).catch(()=>{})}},vf=e=>{if(!Ct(e))return!1;let t=e,n=Object.keys(t).sort(),r=["apiType",...t.apiKey===void 0?[]:["apiKey"],"models","name","vendor"].sort();return n.length!==r.length||!n.every((o,a)=>o===r[a])||t.name!==Cr||t.vendor!=="customendpoint"||t.apiType!=="chat-completions"||!(t.apiKey===void 0||typeof t.apiKey=="string"&&t.apiKey.length>0&&t.apiKey.length<=512&&!/[\u0000-\u001f\u007f]/.test(t.apiKey))||!Array.isArray(t.models)||t.models.length===0||t.models.length>64?!1:t.models.every(o=>{if(!Ct(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!==XA(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!Ct(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}})},Sf=e=>{let t=e.filter(n=>!vf(n));return{next:t,removed:t.length!==e.length}},hL=async(e,t)=>{let n=Bs(e),r=await yl(n);if(r.kind==="missing")return{changedFiles:[],messages:[],manual:!1};if(r.kind==="unrecognized")return{changedFiles:[],manual:!0,messages:[`Could not recognize ${n}; left it untouched. Remove the legacy "${Cr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=Sf(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${Cr}" Custom Endpoint from ${n}.`]};try{return await zA(n,o),await ie(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${Cr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${Cr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},yL=async e=>{try{let t=bt(await jA(e,"utf-8"));if(Ct(t))return JA(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Fs}.${gl} 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 ${Fs}.${gl} value manually if present.`]}},qA=async(e,t)=>{let n=fL(e),r;try{r=await B(n)}catch{return yL(n)}let{next:o,removed:a}=JA(r);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the retired Anyray Copilot debug override from ${n}.`]};try{return await X(n,o,{backup:!1}),await ie(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.`]}}},gL=async(e,t)=>{let n=await hL(e,t),r=await qA(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},QA=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,YA]}},eC=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},tC=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),wL=e=>Array.isArray(e.args)&&e.args.at(-1)===YA,nC=(e,t)=>{if(!t.hookBinaryIsDurable()||!Ct(e)||!eC(e,["type","command","args"]))return!1;let n=QA(t);return e.type==="stdio"&&e.command===n.command&&tC(e.args,n.args)},bL=(e,t)=>{if(!Ct(e)||!eC(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&&tC(e.args,n.args))return!0;if(tt(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===sr&&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!tt(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},wl=(e,t)=>nC(e,t)?"exact":Ct(e)&&wL(e)||bL(e,t)?"stale-owned":"foreign",GA=e=>`MCP name conflict in ${e}: servers.${gn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,AL=async(e,t,n,r,o)=>{let a=await o.vscodeUserMcpConfigPaths(e,r),s=o.hookBinaryIsDurable(),i=n&&s,c=[],l=[],d=0,u=!1,f=[];for(let m of a)try{let p=await Ke(m),h=p.data;if(i){if("servers"in h&&!Ct(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${m} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let b=Ct(h.servers)?{...h.servers}:{},k=QA(o),C=b[gn],S=C===void 0?void 0:wl(C,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(GA(m));continue}if(t){d+=1;continue}b[gn]=k,f.push({path:m,document:p,next:{...h,servers:b},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!Ct(h.servers)||!(gn in h.servers))continue;if(wl(h.servers[gn],o)==="foreign"){u=!0,l.push(GA(m));continue}if(t)continue;let y={...h.servers};delete y[gn];let g={...h};Object.keys(y).length===0?delete g.servers:g.servers=y,f.push({path:m,document:p,next:g,backup:!1,clearBackupAfter:!0})}catch(p){u=!0,l.push(`Could not update the Anyray MCP server in ${m} (${p instanceof Error?p.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let m of f)try{await pn(m.path,m.document,m.next,m.backup),m.clearBackupAfter&&await ie(m.path),c.push(m.path),i&&(d+=1)}catch(p){u=!0,l.push(`Could not update the Anyray MCP server in ${m.path} (${p instanceof Error?p.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 (${yA}+).`),{changedFiles:c,messages:l,manual:u}},CL=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await x(c))try{let l=await Ke(c),d=l.data;if(!Ct(d.servers)||!(gn in d.servers)||wl(d.servers[gn],r)==="foreign"||(i+=1,t))continue;let u={...d.servers};delete u[gn];let f={...d};Object.keys(u).length===0?delete f.servers:f.servers=u,await pn(c,l,f,!1),await ie(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}},rC=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.`]:[]],oC=()=>`${q} is already installed and configured for this gateway \u2014 skipped the VSIX reinstall and the VS Code URI confirmation prompt. (Run --revert first to force re-delivery.)`,VA=e=>[`${q} mirrors the GitHub Copilot models available to this VS Code install.`,`Gateway: ${e.origin} (client key stored by VS Code SecretStorage).`,"Mode: SUBSCRIPTION \u2014 requests use your existing Copilot sign-in and model; Anyray supplies a supported before-request optimization provider.","Inline completions remain native GitHub Copilot traffic. Choose an \u201CAnyray \xB7 \u2026\u201D model in Chat for optimized requests.",'Copilot\u2019s internal utility models (chat titles, summaries) keep working with an Anyray main model: the extension sets VS Code\u2019s chat.byokUtilityModelDefault to "copilot" unless you already set it yourself.',"VS Code profiles scope extensions; Connect installs the provider into every profile registered at apply time. A profile created later needs a Connect re-run (or VS Code\u2019s \u201CApply Extension to all Profiles\u201D action).","Copilot Business/Enterprise administrators must allow language-model providers in GitHub\u2019s Bring Your Own Language Model Key policy."],aC=(e,t,n,r)=>({runMcp:o=>AL(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):gL(e,o)}),sC=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${q} VSIX${a}. Nothing was configured. Run \`${n?"code":t.toLowerCase()} --install-extension\` by hand on that VSIX to see the full error.`;case"handoff-undeliverable":return n?`Installed ${q} and staged its configuration, but could not hand it over${a}. A remote VS Code server's command-line launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\`. Reload the VS Code window attached to this machine (Developer: Reload Window): the extension applies the staged configuration as it loads, so there is nothing to re-run.`:`Installed ${q} and staged its configuration, but could not hand it to ${t}${a}. Reload ${t} (quit and reopen): the extension applies the staged configuration as it loads, so there is nothing to re-run.`;case"reload-required":return`A newer ${q} build was installed, but ${t} is still running the previous build. Reload VS Code completely \u2014 the new build applies the staged configuration as it loads, so there is nothing to re-run.`;case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher on this machine. Run anyray-connect from the integrated terminal of the VS Code window attached here (Terminal \u2192 New Terminal in that window) \u2014 a plain SSH shell has no "code" on PATH and cannot hand the key to a running window. No VS Code configuration was written.`:`The ${t} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`;case"unsupported-version":return`The Anyray language-model provider requires VS Code ${lf} or newer. Upgrade ${t}, then re-run anyray-connect; no extension configuration was written.`;case"unsafe-gateway":return"The Anyray VS Code provider requires HTTPS for a remote gateway because it sends a personal key and prompt content. Publish a trusted TLS gateway URL (or use literal loopback HTTP), then re-run anyray-connect.";case"extension-missing":return`This anyray-connect installation is missing its bundled ${q} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${q} installed and VS Code accepted the ${r}, but its extension host never confirmed. Reload the VS Code window attached to this machine (Developer: Reload Window): the staged configuration applies as it loads.`:`${q} installed and ${t} accepted the ${r}, but its extension host never confirmed. Reload ${t} completely (quit and reopen): the staged configuration applies as it loads.`;default:return n?`VS Code did not confirm the one-time ${q} ${r}${a}. The configuration is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension applies it as it loads.`:`VS Code did not confirm the one-time ${q} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},kL=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${q} still holds its SecretStorage configuration`;switch(e){case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher, so Anyray could not ask ${q} to clear its SecretStorage configuration. Re-run revert from the integrated terminal of the VS Code window attached to this machine.`:`The ${t} command-line launcher was not found, so Anyray could not ask ${q} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${q} reset to VS Code${o}, so ${a} until it reloads. A remote VS Code server's launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\` \u2014 but the reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`Could not hand the ${q} reset to ${t}${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;case"activation-timeout":return n?`VS Code accepted the ${q} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`${t} accepted the ${q} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;default:return n?`VS Code did not confirm the ${q} reset${o}, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`VS Code did not confirm the ${q} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},vL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=aC(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required for the authenticated Anyray VS Code provider. Re-run anyray-connect with --enroll, then apply Copilot again."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${q} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...VA(t),a?kf({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,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${q}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"copilot-seat"});if(!d.ok)return{status:"manual",messages:[sC(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),f=await i(!1),m=a?void 0:await WA(e).catch(()=>({status:"manual",reason:"the settings file could not be read"}));return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles,...m?.status==="enabled"&&m.changed?[$s(e)]:[]],messages:[...d.alreadyCurrent?[oC()]:[],...VA(t),kf(m??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:rC(d.profiles),...f.messages,...u.messages]}},KA=e=>[`${q} exposes the configured Anyray gateway models without writing a key to chatLanguageModels.json.`,`Gateway: ${e.origin} (personal client key and attribution stored together in VS Code SecretStorage).`,"Mode: API KEY \u2014 the extension streams normal /v1/chat/completions requests through Anyray. Text chat only: the models register without tool calling (the OpenAI bridge cannot carry VS Code's structured tool results).",`Models in the picker: ${Us().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."],SL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=aC(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let m=await c(!0),p=await i(!0);return{status:m.manual||p.manual?"manual":"configured",messages:[`Would install the bundled ${q} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...KA(t),...p.messages,...m.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${q}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Us().map(m=>({id:m,name:XA(m)}))});if(!d.ok)return{status:"manual",messages:[sC(d.reason,e,a,"gateway API configuration",d.detail)]};let u=await c(!1),f=await i(!1);return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[oC()]:[],...KA(t),...d.alreadyCurrent?[]:rC(d.profiles),...f.messages,...u.messages]}},EL=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 Ke(s),c=Ct(i.servers)?i.servers[gn]:void 0;if(!nC(c,n))return{registered:!1,command:null,reason:c===void 0?"absent":wl(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 IL=async(e={installedVariant:ta,remoteServerVariant:pf,isRemoteDevContext:Zr})=>{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}},xL={installedVariant:ta,remoteServerVariant:pf,detectVscodeLmProviderEligibility:kA,configureVscodeExtension:MA,vscodeExtensionPointsAt:BA,vscodeExtensionAwaitingReload:fl,vscodeExtensionReceiptMode:ml,hookBinaryIsDurable:oe,hookBinaryPath:De,mcpServerCommand:Ge,vscodeUserMcpConfigPaths:AA,isRemoteDevContext:Zr},RL=(e={})=>{let t={...xL,...e},n=()=>IL(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Ms,quitTarget:hl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${ea(r,!0)}`:Bs(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Ae(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 ${lf} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||gA(i.version);return te(r,"copilot")?vL(a,r,o,t.configureVscodeExtension,c,s,t):SL(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?EL(r,o,t):{registered:!1,command:null,reason:"no-config"}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Ns(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await yl(Bs(o));if(s.kind==="array"){let c=s.entries.find(vf)?.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 yl(Bs(r));if(o.kind==="array"&&o.entries.some(vf))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 CL(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await qA(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${q} to clear its global configuration and SecretStorage key`);else{let g=await t.configureVscodeExtension(o,void 0,"reset");g.ok?(c=!0,d=g.receipt,u.push(`Cleared ${q} gateway configuration and secret.`)):(l=!0,u.push(kL(g.reason,o,a,g.detail)))}let f=Bs(o),m=await yl(f),p=m.kind==="missing"||m.kind==="array"&&!Sf(m.entries).removed,h=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),p)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(m.kind==="unrecognized")return{status:"manual",changedFiles:h.length?h:void 0,messages:[...u,`Couldn't recognize ${f} \u2014 remove the "${Cr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:w}=Sf(m.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${Cr} Custom Endpoint from ${f}`]};await zA(f,w);let y=[...u,`Removed the ${Cr} Custom Endpoint from ${f}.`];return await ie(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...h,f],messages:y}}}},iC=RL();import{accessSync as oN,constants as CC,statSync as aN}from"node:fs";import{readFile as kC,rm as Gs}from"node:fs/promises";import{homedir as Lf,platform as TC}from"node:os";import{delimiter as sN,join as Nf,resolve as iN}from"node:path";import{execFile as DL}from"node:child_process";import{readFile as LL}from"node:fs/promises";import{homedir as xf,platform as NL}from"node:os";import{join as Hs}from"node:path";import{join as OL}from"node:path";var Ef="Iv1.b507a08c87ecfe98",TL="https://github.com/login/device/code",_L="https://github.com/login/oauth/access_token",PL="read:user",cC=1e4,ra=()=>OL(ee(),"copilot-seat-login.json"),lC={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},If=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),dC=async(e={})=>{let t={...lC,...e};try{let n=await t.fetch(TL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:Ef,scope:PL}),signal:AbortSignal.timeout(cC)});if(!n.ok)return;let r=await n.json();if(!If(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}},uC=async(e,t={})=>{let n={...lC,...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(_L,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:Ef,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(cC)})).json();if(!If(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"}},pC=async(e,t)=>{let n=ra();return await we(n,`${JSON.stringify({token:e,clientId:Ef,mintedAtIso:t},null,2)}
|
|
94
|
-
`),n},bl=async()=>{try{let e=await B(ra());if(!If(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var
|
|
95
|
-
`))}`]:[],`export ${El}=${Oe(n)}`]},Pf=(e,t,n)=>{let r=me({...e.metadata,tool:io});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${Oe(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Bn(t)}'`,`export COPILOT_MODEL=${Oe(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${Oe(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${El}=${Oe(n)}`]:[]]},
|
|
96
|
-
`).map(
|
|
97
|
-
`)):G&&z&&await Gs(W,{force:!0}),await Vc(c,Q,bn)}catch(re){try{ne!==void 0&&z?await we(W,ne):z&&await Gs(W,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw re}return{status:"configured",messages:U,changedFiles:[c,..._.length>0||G&&z?[W]:[],...Y?[Mn()]:[]]}},d=await r(),u=d!==void 0&&!_f(d),f=s.authMode==="placeholder",m=u,p=u&&(!m||!te(s,"copilot")),h=f?void 0:await t.readDeviceLoginToken().catch(()=>{}),
|
|
90
|
+
${a}${s},`,d=`${i}${l}${c}`;try{let u=bt(d);if(!uA(u))return{ok:!1,reason:"unsupported"};for(let[f,m]of Object.entries(r))if(JSON.stringify(u[f])!==JSON.stringify(m))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 kD}from"node:child_process";import{readdirSync as vD,statSync as SD}from"node:fs";import{createHash as IA,randomBytes as ED,randomUUID as xA}from"node:crypto";import{chmod as ID,lstat as yf,mkdir as gf,readdir as RA,readFile as mn,rm as OA,unlink as pl,writeFile as wf}from"node:fs/promises";import{homedir as na,platform as bf}from"node:os";import{dirname as ff,join as At,posix as vA,win32 as xD}from"node:path";import{promisify as RD}from"node:util";var fn="0.1.29";var Ar="cfb6d7a1bd56464b8f6b12d6a60ff41a7a43b626acbef399a137cdb6f1b3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C7fjr0sCAAB9BAAAEwAAAAAAAAAAAAAAtIHjGAAAZXh0ZW5zaW9uL3JlYWRtZS5tZFBLAQI/AxQACAgIAMtZGF2yhnqNeQIAACcEAAAVAAAAAAAAAAAAAACkgV8bAABleHRlbnNpb24vTElDRU5TRS50eHRQSwECPwMUAAgICAAXWhhdpzIc9AM5AAAjqQAAGwAAAAAAAAAAAAAApIEbHgAAZXh0ZW5zaW9uL2Rpc3QvZXh0ZW5zaW9uLmpzUEsFBgAAAAAHAAcA1gEAAGdXAAAAAA==";import{readFile as hA}from"node:fs/promises";import{homedir as no,platform as Qo}from"node:os";import{join as Nn,posix as yD,win32 as gD}from"node:path";var ro=["Code","Code - Insiders","VSCodium"],lf="1.121.0",fA=1,wD=121,yA="1.102.0",mA=1,bD=102,AD={Code:"Visual Studio Code","Code - Insiders":"Visual Studio Code - Insiders",VSCodium:"VSCodium"},dl=e=>{let t=/^(\d+)\.(\d+)/.exec(e.trim());if(t)return{major:Number(t[1]),minor:Number(t[2])}},df=e=>{let t=dl(e);return t?t.major!==fA?t.major>fA:t.minor>=wD:!1},gA=e=>{let t=dl(e);return t?t.major!==mA?t.major>mA:t.minor>=bD:!1},CD=async e=>{if(Qo()!=="darwin")return;let t=Nn("/Applications",`${AD[e]}.app`,"Contents","Resources","app","package.json");if(await x(t))try{let n=JSON.parse(await hA(t,"utf8"));return typeof n.version=="string"?n.version:void 0}catch{return}},ul=(e,t=Qo(),n=no(),r=process.env)=>{switch(t){case"darwin":return Nn(n,"Library","Application Support",e);case"win32":return Nn(r.APPDATA??Nn(n,"AppData","Roaming"),e);default:return Nn(n,".config",e)}},uf=(e,t)=>e?t==="win32"?gD.join:yD.join:Nn,ea=(e,t=!1,n=Qo(),r=no(),o=process.env)=>t?uf(t,n)(r,Ds[e],"data","User"):Nn(ul(e,n,r,o),"User"),wA=async(e,t=!1,n=Qo(),r=no(),o=process.env)=>{try{let a=uf(t,n)(ea(e,t,n,r,o),"globalStorage","storage.json"),i=JSON.parse(await hA(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[]}},bA=async(e,t=Qo(),n=no(),r=process.env)=>{let a=(await wA(e,!1,t,n,r)).map(({name:s})=>s);return a.filter((s,i)=>a.indexOf(s)===i)},AA=async(e,t=!1,n=Qo(),r=no(),o=process.env)=>{let a=uf(t,n),s=ea(e,t,n,r,o),i=await wA(e,t,n,r,o);return[a(s,"mcp.json"),...i.map(({location:c})=>a(s,"profiles",c,"mcp.json"))]},ta=async()=>{for(let e of ro)if(await x(ul(e)))return e},Ds={Code:".vscode-server","Code - Insiders":".vscode-server-insiders",VSCodium:".vscodium-server"},CA=(e,t=no())=>Nn(t,Ds[e],"extensions"),pf=async(e=no())=>{for(let t of ro)if(await x(Nn(e,Ds[t])))return t},kA=async e=>{let t=e??await ta();if(!t)return{status:"unknown"};let n=await CD(t);return n?{variant:t,version:n,status:df(n)?"available":"needs-update"}:{variant:t,status:"unknown"}};var q="anyray.anyray-vscode",Af="vscode-handoffs",TA="vscode-receipts",Ls=2,OD=RD(kD),$n={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"]}},TD={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"}},_D=e=>e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e),_A=e=>{if(typeof e!="string")return!1;try{let t=new URL(e.trim());return(t.protocol==="https:"||t.protocol==="http:"&&_D(t.hostname))&&!t.username&&!t.password&&t.pathname==="/"&&!t.search&&!t.hash}catch{return!1}},Ns=e=>{if(_A(e))try{return new URL(e.trim()).origin}catch{return}},PD=(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)},DD=e=>{try{return vD(e)}catch{return[]}},LD=e=>{try{return SD(e).mtimeMs}catch{return}},ND=(e,t,n,r,o)=>{if(!Zr(n)||!n.VSCODE_IPC_HOOK_CLI)return[];let a=$n[e].commands[0],s=At(t,Ds[e]),i=[];for(let{directory:c,suffix:l}of[{directory:At(s,"bin"),suffix:["bin","remote-cli"]},{directory:At(s,"cli","servers"),suffix:["server","bin","remote-cli"]}])for(let d of r(c)){let u=At(c,d,...l,a),f=o(u);f!==void 0&&i.push({path:u,mtime:f})}return i.sort((c,l)=>l.mtime-c.mtime).map(({path:c})=>c)},$D=(e,t,n)=>{let{macAppName:r,commands:o}=$n[e],a=o[0],s=[];for(let i of["/Applications",vA.join(t,"Applications")])for(let c of n(i))PD(c,r)&&s.push(vA.join(i,c,"Contents/Resources/app/bin",a));return s},MD=(e,t=bf(),n=na(),r=process.env,o=DD,a=LD)=>{let s=ND(e,n,r,o,a);if(t==="darwin")return[...new Set([...$n[e].commands,...$D(e,n,o),...s])];if(t!=="win32"){let u=$n[e].commands[0];return[...new Set([u,`/usr/bin/${u}`,`/usr/local/bin/${u}`,...s])]}let i=TD[e],c=xD.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)),$n[e].commands[0],...s])]},PA={run:async(e,t)=>({stdout:(await OD(e,t,{timeout:3e4,windowsHide:!0,maxBuffer:1048576})).stdout}),sleep:e=>new Promise(t=>setTimeout(t,e)),nonce:()=>ED(24).toString("base64url"),home:"",commandCandidates:e=>MD(e)},oo=(e,t)=>At(e,".anyray",TA,`${t}.json`),Cf=(e,t)=>At(e,".anyray",TA,`${t}.applied.json`),DA=async(e,t)=>{for(let n of t.commandCandidates(e))try{let o=(await t.run(n,["--version"]))?.stdout?.trim(),a=o&&dl(o)?o.split(/\r?\n/,1)[0]:void 0;return{command:n,version:a}}catch{}},mf=async(e,t,n)=>{try{let r=await t.run(e,[...n===void 0?[]:["--profile",n],"--list-extensions","--show-versions"]);if(typeof r?.stdout!="string")return;let o=r.stdout.split(/\r?\n/).map(a=>a.trim()).flatMap(a=>{let s=a.lastIndexOf("@");return s<=0?[]:a.slice(0,s).toLowerCase()===q.toLowerCase()?[a.slice(s+1)]:[]});return o.length===1&&o[0]===fn}catch{return}},LA=async(e,t)=>{let n=await DA(e,t);if(n)return mf(n.command,t)},BD=async(e,t,n)=>{let r=At(e,".anyray",Af);for(let o of n){if(!o.endsWith(".json"))continue;let a=At(r,o);try{if(!(await yf(a)).isFile()||JSON.parse(await mn(a,"utf8")).variant!==t)continue;await pl(a)}catch{}}},FD=async(e,t)=>{let n=At(e,".anyray",Af),r;try{r=await RA(n)}catch{return}for(let o of r){if(!o.endsWith(".json"))continue;let a=At(n,o);try{if(!(await yf(a)).isFile()||JSON.parse(await mn(a,"utf8")).variant!==t)continue;await pl(a)}catch{}}},WD=async(e,t)=>{try{let n=JSON.parse(await mn(oo(e,t),"utf8"));return n.extensionVersion===fn&&typeof n.extensionDistSha256=="string"&&n.extensionDistSha256!==Ar}catch{return!1}},NA=250,UD=9e4,HD=UD/NA,GD=async(e,t,n,r)=>{for(let o=0;o<HD;o++){try{let a=JSON.parse(await mn(e,"utf8"));if(a.nonce===t)return n==="reset"&&a.version===Ls&&a.action===n?"confirmed":a.extensionVersion!==fn||a.extensionDistSha256!==Ar?"reload-required":a.version===Ls&&a.action===n?"confirmed":"reload-required"}catch{}await r.sleep(NA)}return"timeout"},VD=200,SA=(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,VD))}return r.join(": ")},KD=async e=>{try{let t=await yf(e);return t.isFile()&&t.size>0&&t.size<=10*1024*1024}catch{return!1}},EA=e=>IA("sha256").update(e).digest("hex"),jD=async(e=na())=>{let t=Buffer.from(pA,"base64");if(t.length<4||t[0]!==80||t[1]!==75||EA(t)!==ll)throw new Error("bundled VS Code extension failed integrity validation");let n=At(e,".anyray","vscode-extension"),r=At(n,`anyray-vscode-${fn}-${ll.slice(0,12)}.vsix`);try{if(EA(await mn(r))===ll)return r}catch{}await gf(n,{recursive:!0,mode:448});let o=`${r}.${xA()}.tmp`;try{await wf(o,t,{mode:384}),await ye(o,r),bf()!=="win32"&&await ID(r,384)}finally{await OA(o,{force:!0})}return r},hf=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=>hf(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${hf(t[n])}`).join(",")}}`},$A=(e,t,n)=>IA("sha256").update(hf({gatewayUrl:Ns(e.origin),clientKey:e.clientKey,metadata:e.metadata,mode:t.mode,gatewayModels:t.gatewayModels??[],extensionVersion:fn,extensionDistSha256:Ar,profiles:[...n].sort()})).digest("hex"),ZD=async(e,t,n,r,o,a)=>{let s=JSON.parse(await mn(Cf(a.home,o),"utf8"));if(s.version!==1||typeof s.fingerprint!="string"||typeof s.nonce!="string"||s.fingerprint!==$A(t,n,r))return!1;let i=JSON.parse(await mn(oo(a.home,o),"utf8"));return i.action==="configure"&&i.nonce===s.nonce&&i.extensionVersion===fn&&i.extensionDistSha256===Ar&&i.gatewayUrl===Ns(t.origin)?await LA(e,a)===!0:!1},YD=async(e,t,n,r)=>{let o=Cf(e,t),a=`${o}.${xA()}.tmp`;try{await gf(ff(o),{recursive:!0,mode:448}),await wf(a,`${JSON.stringify({version:1,fingerprint:n,nonce:r,confirmedAt:new Date().toISOString()})}
|
|
91
|
+
`,{mode:384}),await ye(a,o)}catch{}finally{await OA(a,{force:!0})}},JD=async(e,t)=>{await pl(Cf(e,t)).catch(()=>{})},MA=async(e,t,n,r={},o={mode:"copilot-seat"})=>{let a={...PA,...r,home:r.home??na()},s=$n[e];if(n==="configure"&&!t?.clientKey)return{ok:!1,reason:"failed"};if(n==="configure"&&!_A(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 DA(e,a);if(!c)return{ok:!1,reason:"cli-not-found"};if(n==="configure"&&c.version&&!df(c.version))return{ok:!1,reason:"unsupported-version"};let{command:l}=c,u=await(a.listProfiles??(b=>bA(b,bf(),a.home)))(e).catch(()=>[]);if(n==="configure"&&await ZD(e,t,o,u,s.slug,a).catch(()=>!1))return{ok:!0,receipt:oo(a.home,s.slug),profiles:{installed:[],failed:[]},alreadyCurrent:!0};let f=a.extensionPath;if(n==="configure"){try{f??=await jD(a.home)}catch{return{ok:!1,reason:"extension-missing"}}if(!await KD(f))return{ok:!1,reason:"extension-missing"}}let m=a.nonce(),p=At(a.home,".anyray",Af,`${m}.json`),h=oo(a.home,s.slug);await gf(ff(p),{recursive:!0,mode:448});let g=await RA(ff(p)).catch(()=>[]);await wf(p,`${JSON.stringify({version:Ls,action:n,nonce:m,variant:s.slug,...n==="configure"&&{gatewayUrl:t.origin,clientKey:t.clientKey,metadata:t.metadata,mode:o.mode,gatewayModels:i},expectedExtensionVersion:fn,expectedExtensionDistSha256:Ar})}
|
|
92
|
+
`,{mode:384}),await BD(a.home,s.slug,g).catch(()=>{});let y={installed:[],failed:[]},w=!1;try{if(n==="configure"){let k=await WD(a.home,s.slug);if(k||await mf(l,a)!==!0)try{await a.run(l,["--install-extension",f,"--force"])}catch(C){return w=!0,{ok:!1,reason:"install-failed",detail:SA(C,m)}}for(let C of u)try{(k||await mf(l,a,C)!==!0)&&await a.run(l,["--profile",C,"--install-extension",f,"--force"]),y.installed.push(C)}catch{y.failed.push(C)}}try{await a.run(l,["--open-url",`${s.scheme}://${q}/configure?nonce=${encodeURIComponent(m)}`])}catch(k){return{ok:!1,reason:"handoff-undeliverable",detail:SA(k,m)}}let b=await GD(h,m,n,a);if(b!=="confirmed")return{ok:!1,reason:b==="reload-required"?"reload-required":"activation-timeout"};if(w=!0,n==="configure")y.failed.length===0&&await YD(a.home,s.slug,$A(t,o,u),m);else{await JD(a.home,s.slug),await FD(a.home,s.slug).catch(()=>{});for(let k of[void 0,...u])try{await a.run(l,[...k?["--profile",k]:[],"--uninstall-extension",q])}catch{}}return{ok:!0,receipt:h,profiles:y}}catch{return{ok:!1,reason:"failed"}}finally{w&&await pl(p).catch(()=>{})}},fl=async(e,t=na())=>{try{let n=JSON.parse(await mn(oo(t,$n[e].slug),"utf8"));return n.action==="reload-required"?!0:n.action==="configure"&&(n.extensionVersion!==fn||n.extensionDistSha256!==Ar)}catch{return!1}},ml=async(e,t=na())=>{try{let n=JSON.parse(await mn(oo(t,$n[e].slug),"utf8"));return n.version!==Ls||n.action!=="configure"?void 0:n.mode==="copilot-seat"||n.mode==="gateway-api"?n.mode:void 0}catch{return}},BA=async(e,t,n=na(),r={})=>{try{let o=Ns(t);if(!o)return!1;let a=JSON.parse(await mn(oo(n,$n[e].slug),"utf8"));if(!(a.version===Ls&&a.action==="configure"&&a.gatewayUrl===o&&a.extensionVersion===fn&&a.extensionDistSha256===Ar))return!1;let i={...PA,...r,home:n};return await LA(e,i)===!0}catch{return!1}};var hn="extensions.supportAgentsWindow",yn="chat.agentHost.byokModels.enabled",$s=e=>QD(Ne(e),"User","settings.json"),FA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tL=e=>FA(e)&&e[q]===!0,WA=async(e,t={})=>{let n=$s(e),r=t.read??(m=>XD(m,"utf-8")),o=t.exists??x,a=t.write??(async(m,p)=>{await eL(qD(m),{recursive:!0}),await zD(m,p,"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=bt(s)}catch{return{status:"manual",reason:`${n} is not valid JSON/JSONC, so it was left untouched`}}if(!FA(i))return{status:"manual",reason:`${n} is not a JSON object`};let c=s,l=!1;if(!(hn in i)){let m=cf(c,hn,{[q]:!0});if(!m.ok)return{status:"manual",reason:`could not add ${hn} to ${n} without rewriting it`};c=m.text,l=!0}if(!(yn in i)){let m=cf(c,yn,!0);if(!m.ok)return{status:"manual",reason:`could not add ${yn} to ${n} without rewriting it`};c=m.text,l=!0}l&&await a(n,c);let d=l?bt(c):i,u=tL(d[hn]),f=d[yn]===!0;return!u||!f?{status:"manual",reason:`${n} already sets ${u?yn:hn} to something else; left as it is`}:{status:"enabled",changed:l}},kf=(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 "${hn}": {"${q}": true} and "${yn}": 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 nL}from"node:child_process";import{platform as rL}from"node:os";var UA={encoding:"utf-8",windowsHide:!0,timeout:2e3,maxBuffer:64*1024},oL=(e,t,n)=>nL(e,t,n),HA=oL,aL,sL=()=>{let e=aL??rL();if(e==="win32"){let n=HA(Rs("tasklist.exe"),["/FI","IMAGENAME eq Code.exe","/FO","CSV","/NH"],UA);return n.error||n.signal||n.status!==0?!0:/(?:^|\r?\n)"Code\.exe",/iu.test(n.stdout??"")}let t=e==="linux"?[["-f","Visual Studio Code"],["-x","code"]]:[["-f","Visual Studio Code"]];for(let[n,r]of t){let o=HA("pgrep",[n,r],UA);if(o.error||o.signal||o.status===null||o.status===0)return!0}return!1},iL=sL,Ms=()=>iL();var hl={darwinAppName:"Visual Studio Code",darwinBundleId:"com.microsoft.VSCode",win32Image:"Code.exe",linuxProcess:"code",win32Install:[{root:"localAppData",path:"Programs\\Microsoft VS Code\\Code.exe"},{root:"programFiles",path:"Microsoft VS Code\\Code.exe"},{root:"programFilesX86",path:"Microsoft VS Code\\Code.exe"}]};var Cr="Anyray",gn="anyray",YA="--anyray-owner=vscode-profile-v1",Bs=e=>ZA(Ne(e),"User","chatLanguageModels.json"),mL=e=>ZA(Ne(e),"User","settings.json"),Fs="github.copilot.advanced",gl="debug.overrideCapiUrl",Ct=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hL=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}},JA=e=>{let t=e[Fs];if(!Ct(t)||!hL(t[gl]))return{next:e,removed:!1};let n={...t};delete n[gl];let r={...e};return Object.keys(n).length>0?r[Fs]=n:delete r[Fs],{next:r,removed:!0}},Ws="anyray-default",Us=()=>{let e=(process.env.ANYRAY_COPILOT_MODEL??"").split(",").map(t=>t.trim()).filter(t=>t.length>0&&t.length<=200&&!/[\u0000-\u001f\u007f]/.test(t)).filter((t,n,r)=>r.indexOf(t)===n).slice(0,64);return e.length?e:[Ws]},XA=e=>e===Ws?"Anyray Gateway":`Anyray \xB7 ${e}`.slice(0,200),yl=async e=>{if(!await x(e))return{kind:"missing"};try{let t=await jA(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"}}},zA=async(e,t)=>{await lL(fL(e),{recursive:!0});let n=`${e}.anyray-tmp-${process.pid}-${pL()}`;try{await uL(n,`${JSON.stringify(t,null,2)}
|
|
93
|
+
`,{flag:"wx",mode:384}),await ye(n,e),await cL(e,384)}finally{await dL(n,{force:!0}).catch(()=>{})}},vf=e=>{if(!Ct(e))return!1;let t=e,n=Object.keys(t).sort(),r=["apiType",...t.apiKey===void 0?[]:["apiKey"],"models","name","vendor"].sort();return n.length!==r.length||!n.every((o,a)=>o===r[a])||t.name!==Cr||t.vendor!=="customendpoint"||t.apiType!=="chat-completions"||!(t.apiKey===void 0||typeof t.apiKey=="string"&&t.apiKey.length>0&&t.apiKey.length<=512&&!/[\u0000-\u001f\u007f]/.test(t.apiKey))||!Array.isArray(t.models)||t.models.length===0||t.models.length>64?!1:t.models.every(o=>{if(!Ct(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!==XA(o.id)||typeof o.url!="string"||o.toolCalling!==!0||o.vision!==!0||o.maxInputTokens!==128e3||o.maxOutputTokens!==16e3||o.requestHeaders!==void 0&&(!Ct(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}})},Sf=e=>{let t=e.filter(n=>!vf(n));return{next:t,removed:t.length!==e.length}},yL=async(e,t)=>{let n=Bs(e),r=await yl(n);if(r.kind==="missing")return{changedFiles:[],messages:[],manual:!1};if(r.kind==="unrecognized")return{changedFiles:[],manual:!0,messages:[`Could not recognize ${n}; left it untouched. Remove the legacy "${Cr}" Custom Endpoint manually if it is still listed.`]};let{next:o,removed:a}=Sf(r.entries);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the obsolete "${Cr}" Custom Endpoint from ${n}.`]};try{return await zA(n,o),await ie(n),{changedFiles:[n],manual:!1,messages:[`Removed the obsolete "${Cr}" Custom Endpoint from ${n}.`]}}catch{return{changedFiles:[],manual:!0,messages:[`Could not remove the obsolete "${Cr}" Custom Endpoint from ${n}; remove it manually from Manage Language Models.`]}}},gL=async e=>{try{let t=bt(await jA(e,"utf-8"));if(Ct(t))return JA(t).removed?{changedFiles:[],manual:!0,messages:[`Found the retired Anyray ${Fs}.${gl} 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 ${Fs}.${gl} value manually if present.`]}},qA=async(e,t)=>{let n=mL(e),r;try{r=await B(n)}catch{return gL(n)}let{next:o,removed:a}=JA(r);if(!a)return{changedFiles:[],messages:[],manual:!1};if(t)return{changedFiles:[],manual:!1,messages:[`Would remove the retired Anyray Copilot debug override from ${n}.`]};try{return await X(n,o,{backup:!1}),await ie(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.`]}}},wL=async(e,t)=>{let n=await yL(e,t),r=await qA(e,t);return{changedFiles:[...n.changedFiles,...r.changedFiles],messages:[...n.messages,...r.messages],manual:n.manual||r.manual}},QA=e=>{let t=e.mcpServerCommand("profile");return{type:"stdio",command:t.command,args:[...t.args,YA]}},eC=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},tC=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),bL=e=>Array.isArray(e.args)&&e.args.at(-1)===YA,nC=(e,t)=>{if(!t.hookBinaryIsDurable()||!Ct(e)||!eC(e,["type","command","args"]))return!1;let n=QA(t);return e.type==="stdio"&&e.command===n.command&&tC(e.args,n.args)},AL=(e,t)=>{if(!Ct(e)||!eC(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&&tC(e.args,n.args))return!0;if(tt(e.command))return!1;let r=e.args;if(!((r.length===2||r.length===3)&&r.at(-2)===sr&&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!tt(s)&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(s)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(s))},wl=(e,t)=>nC(e,t)?"exact":Ct(e)&&bL(e)||AL(e,t)?"stale-owned":"foreign",GA=e=>`MCP name conflict in ${e}: servers.${gn} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run anyray-connect to register Anyray retrieval.`,CL=async(e,t,n,r,o)=>{let a=await o.vscodeUserMcpConfigPaths(e,r),s=o.hookBinaryIsDurable(),i=n&&s,c=[],l=[],d=0,u=!1,f=[];for(let m of a)try{let p=await Ke(m),h=p.data;if(i){if("servers"in h&&!Ct(h.servers)){u=!0,l.push(`Could not register Anyray retrieval in ${m} because its servers value is not an object; left the file untouched. Repair that value, then re-run anyray-connect.`);continue}let b=Ct(h.servers)?{...h.servers}:{},k=QA(o),C=b[gn],S=C===void 0?void 0:wl(C,o);if(S==="exact"){d+=1;continue}if(S==="foreign"){u=!0,l.push(GA(m));continue}if(t){d+=1;continue}b[gn]=k,f.push({path:m,document:p,next:{...h,servers:b},backup:S!=="stale-owned",clearBackupAfter:!1});continue}if(!Ct(h.servers)||!(gn in h.servers))continue;if(wl(h.servers[gn],o)==="foreign"){u=!0,l.push(GA(m));continue}if(t)continue;let y={...h.servers};delete y[gn];let w={...h};Object.keys(y).length===0?delete w.servers:w.servers=y,f.push({path:m,document:p,next:w,backup:!1,clearBackupAfter:!0})}catch(p){u=!0,l.push(`Could not update the Anyray MCP server in ${m} (${p instanceof Error?p.name:"unknown error"}); retrieval via anyray_retrieve is unavailable in that profile.`)}if(!u&&!t)for(let m of f)try{await pn(m.path,m.document,m.next,m.backup),m.clearBackupAfter&&await ie(m.path),c.push(m.path),i&&(d+=1)}catch(p){u=!0,l.push(`Could not update the Anyray MCP server in ${m.path} (${p instanceof Error?p.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 (${yA}+).`),{changedFiles:c,messages:l,manual:u}},kL=async(e,t,n,r)=>{let o=await r.vscodeUserMcpConfigPaths(e,n),a=[],s=[],i=0;for(let c of o)if(await x(c))try{let l=await Ke(c),d=l.data;if(!Ct(d.servers)||!(gn in d.servers)||wl(d.servers[gn],r)==="foreign"||(i+=1,t))continue;let u={...d.servers};delete u[gn];let f={...d};Object.keys(u).length===0?delete f.servers:f.servers=u,await pn(c,l,f,!1),await ie(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}},rC=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.`]:[]],oC=()=>`${q} is already installed and configured for this gateway \u2014 skipped the VSIX reinstall and the VS Code URI confirmation prompt. (Run --revert first to force re-delivery.)`,VA=e=>[`${q} mirrors the GitHub Copilot models available to this VS Code install.`,`Gateway: ${e.origin} (client key stored by VS Code SecretStorage).`,"Mode: SUBSCRIPTION \u2014 requests use your existing Copilot sign-in and model; Anyray supplies a supported before-request optimization provider.","Inline completions remain native GitHub Copilot traffic. Choose an \u201CAnyray \xB7 \u2026\u201D model in Chat for optimized requests.",'Copilot\u2019s internal utility models (chat titles, summaries) keep working with an Anyray main model: the extension sets VS Code\u2019s chat.byokUtilityModelDefault to "copilot" unless you already set it yourself.',"VS Code profiles scope extensions; Connect installs the provider into every profile registered at apply time. A profile created later needs a Connect re-run (or VS Code\u2019s \u201CApply Extension to all Profiles\u201D action).","Copilot Business/Enterprise administrators must allow language-model providers in GitHub\u2019s Bring Your Own Language Model Key policy."],aC=(e,t,n,r)=>({runMcp:o=>CL(e,o,t,n,r),runLegacy:o=>n?Promise.resolve({changedFiles:[],messages:[],manual:!1}):wL(e,o)}),sC=(e,t,n,r,o)=>{let a=o?` (${o})`:"";switch(e){case"install-failed":return`${t} refused to install the bundled ${q} VSIX${a}. Nothing was configured. Run \`${n?"code":t.toLowerCase()} --install-extension\` by hand on that VSIX to see the full error.`;case"handoff-undeliverable":return n?`Installed ${q} and staged its configuration, but could not hand it over${a}. A remote VS Code server's command-line launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\`. Reload the VS Code window attached to this machine (Developer: Reload Window): the extension applies the staged configuration as it loads, so there is nothing to re-run.`:`Installed ${q} and staged its configuration, but could not hand it to ${t}${a}. Reload ${t} (quit and reopen): the extension applies the staged configuration as it loads, so there is nothing to re-run.`;case"reload-required":return`A newer ${q} build was installed, but ${t} is still running the previous build. Reload VS Code completely \u2014 the new build applies the staged configuration as it loads, so there is nothing to re-run.`;case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher on this machine. Run anyray-connect from the integrated terminal of the VS Code window attached here (Terminal \u2192 New Terminal in that window) \u2014 a plain SSH shell has no "code" on PATH and cannot hand the key to a running window. No VS Code configuration was written.`:`The ${t} data directory exists, but its command-line launcher was not found. Install the \u201Ccode\u201D command in PATH and re-run anyray-connect.`;case"unsupported-version":return`The Anyray language-model provider requires VS Code ${lf} or newer. Upgrade ${t}, then re-run anyray-connect; no extension configuration was written.`;case"unsafe-gateway":return"The Anyray VS Code provider requires HTTPS for a remote gateway because it sends a personal key and prompt content. Publish a trusted TLS gateway URL (or use literal loopback HTTP), then re-run anyray-connect.";case"extension-missing":return`This anyray-connect installation is missing its bundled ${q} VSIX. Reinstall a complete anyray-connect release; no Marketplace fallback was attempted.`;case"activation-timeout":return n?`${q} installed and VS Code accepted the ${r}, but its extension host never confirmed. Reload the VS Code window attached to this machine (Developer: Reload Window): the staged configuration applies as it loads.`:`${q} installed and ${t} accepted the ${r}, but its extension host never confirmed. Reload ${t} completely (quit and reopen): the staged configuration applies as it loads.`;default:return n?`VS Code did not confirm the one-time ${q} ${r}${a}. The configuration is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension applies it as it loads.`:`VS Code did not confirm the one-time ${q} ${r}${a}. The configuration is staged: reload ${t} (quit and reopen) and the extension applies it as it loads.`}},vL=(e,t,n,r)=>{let o=r?` (${r})`:"",a=`${q} still holds its SecretStorage configuration`;switch(e){case"cli-not-found":return n?`Could not reach the VS Code server's command-line launcher, so Anyray could not ask ${q} to clear its SecretStorage configuration. Re-run revert from the integrated terminal of the VS Code window attached to this machine.`:`The ${t} command-line launcher was not found, so Anyray could not ask ${q} to clear its SecretStorage configuration. Install the launcher and re-run revert.`;case"handoff-undeliverable":return n?`Could not hand the ${q} reset to VS Code${o}, so ${a} until it reloads. A remote VS Code server's launcher exposes only a subset of the desktop flags, and this step needs \`--open-url\` \u2014 but the reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`Could not hand the ${q} reset to ${t}${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;case"activation-timeout":return n?`VS Code accepted the ${q} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`${t} accepted the ${q} reset but its extension host never confirmed, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`;default:return n?`VS Code did not confirm the ${q} reset${o}, so ${a} until it reloads. The reset is staged: reload the VS Code window attached to this machine (Developer: Reload Window) and the extension clears the configuration as it loads.`:`VS Code did not confirm the ${q} reset${o}, so ${a} until it reloads. The reset is staged: quit and reopen ${t} and the extension clears the configuration as it loads.`}},SL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=aC(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required for the authenticated Anyray VS Code provider. Re-run anyray-connect with --enroll, then apply Copilot again."]};if(n.dryRun){let p=await c(!0),h=await i(!0);return{status:p.manual||h.manual?"manual":"configured",messages:[`Would install the bundled ${q} VSIX with the ${e} CLI and configure it through VS Code SecretStorage.`,...VA(t),a?kf({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,...p.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${q}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"copilot-seat"});if(!d.ok)return{status:"manual",messages:[sC(d.reason,e,a,"configuration",d.detail)]};let u=await c(!1),f=await i(!1),m=a?void 0:await WA(e).catch(()=>({status:"manual",reason:"the settings file could not be read"}));return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles,...m?.status==="enabled"&&m.changed?[$s(e)]:[]],messages:[...d.alreadyCurrent?[oC()]:[],...VA(t),kf(m??{status:"enabled",changed:!1},a),...d.alreadyCurrent?[]:rC(d.profiles),...f.messages,...u.messages]}},KA=e=>[`${q} exposes the configured Anyray gateway models without writing a key to chatLanguageModels.json.`,`Gateway: ${e.origin} (personal client key and attribution stored together in VS Code SecretStorage).`,"Mode: API KEY \u2014 the extension streams normal /v1/chat/completions requests through Anyray. Text chat only: the models register without tool calling (the OpenAI bridge cannot carry VS Code's structured tool results).",`Models in the picker: ${Us().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."],EL=async(e,t,n,r,o,a,s)=>{let{runMcp:i,runLegacy:c}=aC(e,o,a,s);if(!t.clientKey)return{status:"manual",messages:["A personal gateway key is required."]};if(n.dryRun){let m=await c(!0),p=await i(!0);return{status:m.manual||p.manual?"manual":"configured",messages:[`Would install the bundled ${q} VSIX with the ${e} CLI and configure gateway API mode through VS Code SecretStorage.`,...KA(t),...p.messages,...m.messages]}}let l=await i(!0);if(l.manual)return{status:"manual",messages:[`Did not configure ${q}; resolve the retrieval MCP profile conflicts first.`,...l.messages]};let d=await r(e,t,"configure",{},{mode:"gateway-api",gatewayModels:Us().map(m=>({id:m,name:XA(m)}))});if(!d.ok)return{status:"manual",messages:[sC(d.reason,e,a,"gateway API configuration",d.detail)]};let u=await c(!1),f=await i(!1);return{status:u.manual||f.manual?"manual":"configured",changedFiles:[d.receipt,...f.changedFiles,...u.changedFiles],messages:[...d.alreadyCurrent?[oC()]:[],...KA(t),...d.alreadyCurrent?[]:rC(d.profiles),...f.messages,...u.messages]}},IL=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 Ke(s),c=Ct(i.servers)?i.servers[gn]:void 0;if(!nC(c,n))return{registered:!1,command:null,reason:c===void 0?"absent":wl(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 xL=async(e={installedVariant:ta,remoteServerVariant:pf,isRemoteDevContext:Zr})=>{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}},RL={installedVariant:ta,remoteServerVariant:pf,detectVscodeLmProviderEligibility:kA,configureVscodeExtension:MA,vscodeExtensionPointsAt:BA,vscodeExtensionAwaitingReload:fl,vscodeExtensionReceiptMode:ml,hookBinaryIsDurable:oe,hookBinaryPath:De,mcpServerCommand:Ge,vscodeUserMcpConfigPaths:AA,isRemoteDevContext:Zr},OL=(e={})=>{let t={...RL,...e},n=()=>xL(t);return{id:"copilot",title:"GitHub Copilot Chat",automatic:!0,quitGated:{isRunning:Ms,quitTarget:hl},async detect(){let{variant:r,remote:o}=await n();return r?{installed:!0,detail:o?`remote server at ${ea(r,!0)}`:Bs(r)}:{installed:!1,detail:"no VS Code install found"}},async apply(r,o){if(!Ae(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 ${lf} or newer, then re-run anyray-connect; no extension configuration was written.`]};let c=i.version===void 0||gA(i.version);return te(r,"copilot")?SL(a,r,o,t.configureVscodeExtension,c,s,t):EL(a,r,o,t.configureVscodeExtension,c,s,t)},async mcpStatus(){let{variant:r,remote:o}=await n();return r?IL(r,o,t):{registered:!1,command:null,reason:"no-config"}},async pointsAt(r){let{variant:o}=await n();if(!o)return!1;let a=Ns(r);if(!a)return!1;if(await t.vscodeExtensionPointsAt(o,a))return!0;let s=await yl(Bs(o));if(s.kind==="array"){let c=s.entries.find(vf)?.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 yl(Bs(r));if(o.kind==="array"&&o.entries.some(vf))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 kL(o,r.dryRun,a,t),i=a?{changedFiles:[],messages:[],manual:!1}:await qA(o,r.dryRun),c=!1,l=!1,d,u=[...i.messages];if(r.dryRun)u.push(`would ask ${q} to clear its global configuration and SecretStorage key`);else{let w=await t.configureVscodeExtension(o,void 0,"reset");w.ok?(c=!0,d=w.receipt,u.push(`Cleared ${q} gateway configuration and secret.`)):(l=!0,u.push(vL(w.reason,o,a,w.detail)))}let f=Bs(o),m=await yl(f),p=m.kind==="missing"||m.kind==="array"&&!Sf(m.entries).removed,h=[...s.changedFiles,...i.changedFiles,...d?[d]:[]];if(u.push(...s.messages),p)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(m.kind==="unrecognized")return{status:"manual",changedFiles:h.length?h:void 0,messages:[...u,`Couldn't recognize ${f} \u2014 remove the "${Cr}" Custom Endpoint by hand: Chat model picker \u2192 "Manage Language Models\u2026".`]};let{next:g}=Sf(m.entries);if(r.dryRun)return{status:"reverted",messages:[...u,`would remove the ${Cr} Custom Endpoint from ${f}`]};await zA(f,g);let y=[...u,`Removed the ${Cr} Custom Endpoint from ${f}.`];return await ie(f),{status:l||i.manual?"manual":"reverted",changedFiles:[...h,f],messages:y}}}},iC=OL();import{accessSync as aN,constants as CC,statSync as sN}from"node:fs";import{readFile as kC,rm as Gs}from"node:fs/promises";import{homedir as Lf,platform as TC}from"node:os";import{delimiter as iN,join as Nf,resolve as cN}from"node:path";import{execFile as LL}from"node:child_process";import{readFile as NL}from"node:fs/promises";import{homedir as xf,platform as $L}from"node:os";import{join as Hs}from"node:path";import{join as TL}from"node:path";var Ef="Iv1.b507a08c87ecfe98",_L="https://github.com/login/device/code",PL="https://github.com/login/oauth/access_token",DL="read:user",cC=1e4,ra=()=>TL(ee(),"copilot-seat-login.json"),lC={fetch:(...e)=>fetch(...e),now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},If=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),dC=async(e={})=>{let t={...lC,...e};try{let n=await t.fetch(_L,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:Ef,scope:DL}),signal:AbortSignal.timeout(cC)});if(!n.ok)return;let r=await n.json();if(!If(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}},uC=async(e,t={})=>{let n={...lC,...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(PL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({client_id:Ef,device_code:e.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:AbortSignal.timeout(cC)})).json();if(!If(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"}},pC=async(e,t)=>{let n=ra();return await we(n,`${JSON.stringify({token:e,clientId:Ef,mintedAtIso:t},null,2)}
|
|
94
|
+
`),n},bl=async()=>{try{let e=await B(ra());if(!If(e))return;let t=e.token;return typeof t=="string"&&t.length>0?t:void 0}catch{return}};var ML=5e3,Rf=5e3,BL=["copilot-cli","CopilotCLI"],FL="https://api.github.com/copilot_internal/user",mC="~/.copilot/config.json",hC="macOS Keychain (Copilot CLI)",yC=e=>e===mC||e===hC,oa=e=>typeof e=="string"&&/^[\x21-\x7e]{20,255}$/.test(e),Xt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),WL=()=>process.env.XDG_CONFIG_HOME?.trim()||Hs(xf(),".config"),UL=()=>process.env.XDG_DATA_HOME?.trim()||Hs(xf(),".local","share"),HL=async()=>{try{let e=await NL(Hs(xf(),".copilot","config.json"),"utf-8"),t=/\bgh[ou]_[A-Za-z0-9_]{16,251}/.exec(e)?.[0];return oa(t)?t:void 0}catch{}},GL=async e=>{try{let t=await B(Hs(WL(),"github-copilot",e));if(!Xt(t))return;for(let n of Object.values(t))if(Xt(n)&&oa(n.oauth_token))return n.oauth_token}catch{}},VL=async()=>{try{let e=await B(Hs(UL(),"opencode","auth.json")),t=Xt(e)?e["github-copilot"]:void 0;if(!Xt(t)||t.type!=="oauth")return;if(oa(t.access))return t.access;if(oa(t.refresh))return t.refresh}catch{}},KL=(e,t)=>new Promise((n,r)=>{try{LL(e,[...t],{timeout:ML},(a,s)=>{a?r(a):n({stdout:s})}).on("error",r)}catch(o){r(o)}}),jL=async(e,t)=>{try{let{stdout:n}=await t("security",["find-generic-password","-s",e,"-w"]),r=n?.trim();return oa(r)?r:void 0}catch{return}},ZL=async(e=KL)=>{for(let t of BL){let n=await jL(t,e);if(n)return n}};var Al={env:process.env,platform:$L,tokenFromDeviceLogin:bl,tokenFromCopilotCliConfig:HL,tokenFromSharedConfig:GL,tokenFromOpenCode:VL,tokenFromKeychain:ZL,fetch:(...e)=>fetch(...e)},YL=new Set([401,403,404]),Cl=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,gC=e=>{let t=e?.trim().toLowerCase()??"";return t&&t!=="default"&&Cl.test(t)?t:"default"},JL=e=>e!=="default"&&Cl.test(e)?`https://api.${e}.githubcopilot.com`:"https://api.githubcopilot.com",XL=e=>{if(typeof e!="string")return"default";let t=e.trim().match(/^https:\/\/api\.([a-z0-9-]{1,63})\.githubcopilot\.com\/?$/)?.[1];return t&&Cl.test(t)?t:"default"},Of=async(e,t={})=>{let n={...Al,...t},r=new AbortController,o=setTimeout(()=>r.abort(),Rf);try{let a=await n.fetch(FL,{headers:{authorization:`Bearer ${e}`},signal:r.signal});if(a.ok){let s;try{let i=await a.json();s=Xt(i)&&Xt(i.endpoints)?i.endpoints.api:void 0}catch{}return{verdict:"valid",capiSegment:XL(s)}}return{verdict:YL.has(a.status)?"no-copilot":"unreachable",capiSegment:"default"}}catch{return{verdict:"unreachable",capiSegment:"default"}}finally{clearTimeout(o)}};var aa=async(e,t={},n="default",r)=>{if(r){let o=`${r.laneOrigin.replace(/\/+$/,"")}/v1/copilot/${Cl.test(n)?n:"default"}/header/models`,a=await fC(o,e,r.clientKey,t);if(a.length>0)return a}return fC(`${JL(n)}/models`,e,void 0,t)},fC=async(e,t,n,r={})=>{let o={...Al,...r},a=new AbortController,s=setTimeout(()=>a.abort(),Rf);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=Xt(c)?c.data:void 0;if(!Array.isArray(l))return[];let d=[];for(let u of l){if(!Xt(u))continue;let f=u.id;if(typeof f!="string"||f.length===0||u.model_picker_enabled!==!0)continue;let m=u.policy;if(Xt(m)&&m.state!=="enabled")continue;let p=u.supported_endpoints,h=Array.isArray(p)?p.filter(S=>typeof S=="string"):[],g=u.capabilities,y=Xt(g)?g.limits:void 0,w=S=>{let E=Xt(y)?y[S]:void 0;return typeof E=="number"&&Number.isFinite(E)&&E>0?Math.floor(E):void 0},b={id:f,endpoints:h},k=w("max_prompt_tokens"),C=w("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)}},kl=async(e,t,n,r={})=>{let o={...Al,...r},a=new AbortController,s=setTimeout(()=>a.abort(),Rf);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)}},vl=async(e={},t={})=>{let n={...Al,...t},r=[{source:"COPILOT_GITHUB_TOKEN",read:async()=>{let a=n.env.COPILOT_GITHUB_TOKEN?.trim();return oa(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:hC,read:()=>n.tokenFromKeychain()}]:[],{source:mC,read:()=>n.tokenFromCopilotCliConfig()}],o=[];for(let a of r){let s=await a.read();if(!s)continue;let i=await Of(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 Sl,platform as bC}from"node:os";import{join as st}from"node:path";import{execFile as zL}from"node:child_process";import{readFile as qL,readdir as QL}from"node:fs/promises";var eN=3e3,tN="Claude Code-credentials",nN=["copilot-cli","CopilotCLI"],AC=e=>new Promise(t=>{try{zL("security",["find-generic-password","-s",e],{timeout:eN},r=>t(!r)).on("error",()=>t(!1))}catch{t(!1)}}),rN=async()=>{if(process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim())return!0;let e=st(Sl(),".claude");return!!(await x(st(e,".oauth_token"))||await x(st(e,".credentials.json"))||bC()==="darwin"&&await AC(tN))},oN=async()=>{let e=st(process.env.CODEX_HOME?.trim()||st(Sl(),".codex"),"auth.json");if(!await x(e))return!1;try{let t=JSON.parse(await qL(e,"utf-8"));return typeof t.tokens?.access_token=="string"&&t.tokens.access_token.trim()!==""}catch{return!1}},wC=async e=>{try{return(await QL(e)).some(n=>n.startsWith("github.copilot-chat-"))}catch{return!1}},Tf=async()=>{if(process.env.COPILOT_GITHUB_TOKEN?.trim())return!0;for(let t of ro){let n=st(Ne(t),"User","globalStorage");if(await x(st(n,"github.copilot-chat"))||await x(st(n,"github.copilot")))return!0}let e=st(Sl(),".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 wC(st(Sl(),t,"extensions")))return!0;for(let t of ro){if(await wC(CA(t)))return!0;let n=st(ea(t,!0),"globalStorage");if(await x(st(n,"github.copilot-chat"))||await x(st(n,"github.copilot")))return!0}if(bC()==="darwin"){for(let t of nN)if(await AC(t))return!0}return!1},wn=async()=>{let[e,t,n]=await Promise.all([rN(),oN(),Tf()]);return{anthropic:e,openai:t,copilot:n}};var io="copilot-cli",bn="copilot-cli",lN=Ms,dN=()=>lN()?["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."]:[],_C=["Editor-Version: vscode/1.99.0","Editor-Plugin-Version: copilot-chat/0.26.7","Copilot-Integration-Id: vscode-chat"],$f=()=>Object.fromEntries(_C.map(e=>{let t=e.indexOf(": ");return[e.slice(0,t).toLowerCase(),e.slice(t+2)]})),vC=()=>Nf(Lf(),".anyray","copilot-cli.sh"),PC="# Managed by anyray-connect. Do not source this file anywhere else.",SC=e=>e.split(/\r?\n/,1)[0]===PC,uN=["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"],El="COPILOT_PROVIDER_API_KEY",EC=e=>e.startsWith(`export ${El}=`)||e.startsWith("export COPILOT_PROVIDER_HEADERS=")&&e.includes("x-anyray-api-key:"),Bn=e=>/(^|\/)(gpt-5|o[1-9])[\w.-]*$/.test(e)?"responses":"completions",pN=()=>Us()[0],Vs=(e="default")=>`/copilot/${e}/header`,d6=Vs(),ao=e=>e.replace(/\/+$/,""),fN=(e,t="default")=>`${ao(e.openaiBaseUrl)}${Vs(t)}`,_f=e=>/\/v1\/copilot\/[^/]+\/header\/?$/.test(e),Df="claude-sonnet-5",mN=()=>{let e=Us()[0];return e===Ws?Df:e},DC=e=>e.endpoints.includes(Bn(e.id)==="responses"?"/responses":"/chat/completions"),Mf=e=>{let t=e.filter(DC),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)=>IC(a.version,s.version)?-1:IC(s.version,a.version)?1:0).map(a=>a.m),o=t.filter(a=>!n(a.id));return[...r,...o]};var IC=(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},xC=(e,t,n,r,o,a="default")=>{let s=me({...e.metadata,tool:io}),i=[...r?[`x-anyray-api-key: ${r}`]:[],...s?[`x-anyray-metadata: ${s}`]:[],..._C];return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${Oe(fN(e,a))}`,`export COPILOT_PROVIDER_WIRE_API='${Bn(t)}'`,`export COPILOT_MODEL=${Oe(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=${Oe(i.join(`
|
|
95
|
+
`))}`]:[],`export ${El}=${Oe(n)}`]},Pf=(e,t,n)=>{let r=me({...e.metadata,tool:io});return["export COPILOT_PROVIDER_TYPE='openai'",`export COPILOT_PROVIDER_BASE_URL=${Oe(e.openaiBaseUrl)}`,`export COPILOT_PROVIDER_WIRE_API='${Bn(t)}'`,`export COPILOT_MODEL=${Oe(t)}`,...r?[`export COPILOT_PROVIDER_HEADERS=${Oe(`x-anyray-metadata: ${r}`)}`]:[],...n?[`export ${El}=${Oe(n)}`]:[]]},hN=(e,t)=>t||!te(e,"copilot"),RC=()=>{let e=uN.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).`]},OC=(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 ${io}\`), 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`."],yN=(e=process.env.PATH,t=TC())=>{if(!e)return;let n=t==="win32"?"copilot.exe":"copilot";for(let r of e.split(iN)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=cN(o,n);try{if(!sN(a).isFile())continue;return aN(a,t==="win32"?CC.F_OK:CC.X_OK),a}catch{}}},gN=()=>Nf(Lf(),".copilot","config.json"),Mn=()=>Nf(Lf(),".copilot","mcp-config.json"),so="anyray",wN=()=>({type:"local",...Ge("profile"),tools:["*"]}),kr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bN=async()=>{let e=Mn(),t;try{t=await B(e)}catch{return{status:"skipped",message:`Skipped the Anyray retrieval MCP server because ${e} could not be parsed; it was left unchanged.`}}if("mcpServers"in t&&!kr(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=(kr(t.mcpServers)?t.mcpServers:{})[so];return r!==void 0&&!_t(r,"profile")?{status:"skipped",message:`MCP name conflict in ${e}: mcpServers.${so} is not owned by Anyray Connect, so retrieval was skipped and the existing server was left untouched.`}:{status:"installable",json:t}},AN=async e=>{let t=Mn(),n=e.json,r=kr(n.mcpServers)?n.mcpServers:{};r[so]=wN(),n.mcpServers=r,await X(t,n)},CN=async()=>{let e=Mn(),t;try{let r=await B(e);if(!kr(r))return!1;t=r}catch{return!1}let n=t.mcpServers;return!kr(n)||!(so in n)||!_t(n[so],"profile")?!1:(delete n[so],Object.keys(n).length===0&&delete t.mcpServers,Object.keys(t).length===0?await Gs(e,{force:!0}):await X(e,t,{backup:!1}),await ie(e),!0)},kN={resolveCopilotCommand:yN,platform:TC,detectCopilotSeat:Tf,discoverSeatToken:vl,readDeviceLoginToken:bl,fetchSeatModelCatalog:aa,probeSeatChatModel:kl},vN=e=>`'${e.replace(/'/g,"''")}'`,SN=e=>e.split(`
|
|
96
|
+
`).map(vN).join(" + [Environment]::NewLine + "),EN=(e={})=>{let t={...kN,...e},n=()=>t.platform()==="win32",r=async()=>{let i=(await Kc(wt(),bn))?.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&&ao(s)===`${ao(i)}/v1`,a=(s,i)=>s!==void 0&&_f(s)&&ao(s).startsWith(`${ao(i)}/v1/copilot/`);return{id:io,title:"GitHub Copilot CLI",automatic:!0,changesBilling:!1,quitGated:{isRunning:Ms,quitTarget:hl},async detect(){let s=t.resolveCopilotCommand();if(s)return{installed:!0,detail:s};let i=gN();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=wt(),l=async(S,E,I)=>{let _=S.filter(EC),T=S.filter(re=>!EC(re)),W=vC(),Q=[...T,..._.length>0?[`[ -r ${Oe(W)} ] && . ${Oe(W)}`]:[]],G=await x(W),ne=G?await kC(W,"utf8"):void 0,z=ne===void 0||SC(ne);if(_.length>0&&!z)return{status:"manual",messages:[`Refused to overwrite user-managed ${W}; move or rename that file, then run Connect again.`]};let Z=oe(),le=Z?await bN():void 0,U=[`${c} \u2190 managed Anyray block (${bn})`,...E.map(re=>` ${re}`),..._.length>0?[`${W} \u2190 owner-only credential (mode 0600)`]:[],...I,le?.status==="skipped"?le.message:Z?`${Mn()} \u2190 Anyray retrieval MCP server (anyray_retrieve / anyray_recall)`:`Skipped the Anyray MCP server \u2014 anyray-connect is running from a temporary path (${De()}). 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.`,...dN()];if(i.dryRun)return{status:"configured",messages:U};let Y=!1;le?.status==="installable"&&(await AN(le),Y=!0);try{_.length>0?await we(W,[PC,..._,""].join(`
|
|
97
|
+
`)):G&&z&&await Gs(W,{force:!0}),await Vc(c,Q,bn)}catch(re){try{ne!==void 0&&z?await we(W,ne):z&&await Gs(W,{force:!0})}catch{throw new Error("Copilot CLI environment update failed and credential rollback could not be completed")}throw re}return{status:"configured",messages:U,changedFiles:[c,..._.length>0||G&&z?[W]:[],...Y?[Mn()]:[]]}},d=await r(),u=d!==void 0&&!_f(d),f=s.authMode==="placeholder",m=u,p=u&&(!m||!te(s,"copilot")),h=f?void 0:await t.readDeviceLoginToken().catch(()=>{}),g=f||p&&!h?{rejected:[]}:await t.discoverSeatToken({allowKeychainPrompt:i.explicit===!0&&!i.dryRun}),y=g.token,w=g.rejected;if(y){let S=g.capiSegment??"default",E=mN(),I=E!==Df||!!process.env.ANYRAY_COPILOT_MODEL,_=await t.fetchSeatModelCatalog(y.token,{},S,{laneOrigin:ao(s.origin),...s.clientKey?{clientKey:s.clientKey}:{}}),T=_.find(U=>U.id===E);if(!I){let U=Mf(_);if(T=U[0],!i.dryRun&&U.length>0){let Y=ke=>`${ao(s.origin)}/v1${Vs(S)}/${Bn(ke)==="responses"?"responses":"chat/completions"}`,re={...$f(),authorization:`Bearer ${y.token}`,...s.clientKey?{"x-anyray-api-key":s.clientKey}:{}},Qe=new Set,Ie;for(let ke of U.slice(0,4)){let Rt=await t.probeSeatChatModel(Y(ke.id),re,ke.id);if(Rt==="ok"){Ie=ke;break}if(Rt==="unreachable")break;Qe.add(ke.id)}T=Ie??U.find(ke=>!Qe.has(ke.id))??U[0]}E=T?.id??Df}let W=s.clientKey??s.placeholderKey,Q=W&&s.clientKey?Dt(W):W,G=xC(s,E,y.token,W,T,S),ne=xC(s,E,Dt(y.token),Q,T,S),z=Bn(E),Z=_.filter(U=>DC(U)&&Bn(U.id)===z).map(U=>U.id).filter(U=>U!==E),le=[`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: ${E}${I?" (pinned via ANYRAY_COPILOT_MODEL)":_.length>0?" (your plan's default class; pin via ANYRAY_COPILOT_MODEL)":" (seat-lane fallback; pin via ANYRAY_COPILOT_MODEL)"}.`,..._.length===0&&yC(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."]:[],...Z.length>0?[`Your plan also serves: ${Z.slice(0,8).join(", ")}${Z.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",...ne.map(U=>{let Y=U.indexOf("="),re=U.slice(7,Y),Qe=U.slice(Y+1).replace(/^'|'$/g,"");return` [Environment]::SetEnvironmentVariable('${re}', ${SN(Qe)}, 'User')`}),`(secrets are shown masked \u2014 substitute the Copilot token from ${y.source}, and the gateway key from \`anyray-connect print-key\`.)`,...le]}:l(G,ne,le)}if(!hN(s,p)){if(m&&!i.dryRun){let S=wt();if(await vs(S,bn))return{status:"reverted",changedFiles:[S],messages:[`removed a stale Anyray ${bn} 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:",...OC(t.platform(),w),...RC()]}}return{status:"held",messages:[...m&&i.dryRun?[`would remove a stale Anyray ${bn} block from ${wt()} (org lane, not chosen)`]:[],...OC(t.platform(),w)]}}let b=pN(),k=s.clientKey??s.placeholderKey,C=k&&s.clientKey?Dt(k):k;return n()?{status:"manual",messages:["Windows: set these for your user, then restart your terminal \u2014",...Pf(s,b,C).map(S=>{let[E,...I]=S.replace(/^export /,"").split("=");return` setx ${E} "${I.join("=").replace(/^'|'$/g,"")}"`}),...s.clientKey?[`(${El} is shown masked \u2014 substitute the real one from \`anyray-connect print-key\`.)`]:[]]}:l(Pf(s,b,k),Pf(s,b,C),["Mode: BYOK \u2014 Copilot CLI requests are billed as org API usage through the gateway, not against your Copilot subscription.",`Model: ${b}${b===Ws?" (the gateway resolves the org default)":" (pinned via ANYRAY_COPILOT_MODEL)"}.`])},async revert(s){let i=wt(),c=vC(),l=await x(c),d=l?SC(await kC(c,"utf8")):!1;if(s.dryRun)return{status:"reverted",messages:[`would remove the Anyray ${bn} block from ${i}`,...d?[`would remove owner-only credential ${c}`]:l?[`would preserve user-managed ${c}`]:[],`would remove the Anyray MCP server from ${Mn()} if registered`,...await x(ra())?[`would remove the Copilot sign-in Connect minted (${ra()})`]:[]]};let u=await vs(i,bn);d&&await Gs(c,{force:!0});let f=await CN(),m=ra(),p=await x(m);p&&await Gs(m,{force:!0});let h=[...u?[i]:[],...d?[c]:[],...f?[Mn()]:[],...p?[m]:[]];return{status:h.length>0?"reverted":"not-found",messages:[u?`removed the Anyray ${bn} block from ${i}`:`no Anyray ${bn} block found in ${i}`,...d?[`removed owner-only credential ${c}`]:l?[`preserved user-managed ${c}`]:[],...p?[`removed the Copilot sign-in Connect minted (${m})`]:[],...f?[`removed the Anyray MCP server from ${Mn()}`]:[],...RC()],changedFiles:h.length>0?h:void 0}},async pointsAt(s){let i=await r();return o(i,s)||a(i,s)},async mcpStatus(){if(!oe())return{registered:!1,command:null,reason:"ephemeral-runtime"};let s=Mn();if(!await x(s))return{registered:!1,command:null,reason:"no-config"};try{let i=await B(s),c=kr(i)?i.mcpServers:void 0,l=kr(c)?c[so]:void 0;return!kr(l)||!_t(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"]:_f(s)?["subscription"]:["api_key"]}catch{return["unknown"]}},async routingExpected(s){return s.includes(io)?!0:!await t.detectCopilotSeat()}}},LC=EN();import{homedir as UC}from"node:os";import{join as Sr}from"node:path";import{readFile as HC}from"node:fs/promises";import{readFile as NC,rm as IN}from"node:fs/promises";var $C="// Managed by anyray-connect: OpenCode trim carrier v1",xN=5e3,Bf=e=>`${$C}
|
|
98
98
|
import { spawn } from "node:child_process"
|
|
99
99
|
|
|
100
100
|
const hookCommand = ${JSON.stringify([e.command,...e.args])}
|
|
101
|
-
const hookTimeoutMs = ${
|
|
101
|
+
const hookTimeoutMs = ${xN}
|
|
102
102
|
|
|
103
103
|
const invokeHook = (payload) =>
|
|
104
104
|
new Promise((resolve) => {
|
|
@@ -166,23 +166,23 @@ export const AnyrayTrimPlugin = async () => ({
|
|
|
166
166
|
},
|
|
167
167
|
})
|
|
168
168
|
`,Ks=async e=>await x(e)?(await NC(e,"utf-8")).startsWith(`${$C}
|
|
169
|
-
`)?"owned":"foreign":"absent",MC=async(e,t)=>{let n=Bf(t),r=await Ks(e);return r==="foreign"?"foreign":r==="owned"&&await NC(e,"utf-8")===n?"unchanged":(await we(e,n),"installed")},Ff=async e=>{let t=await Ks(e);return t!=="owned"?t:(await EN(e,{force:!0}),"removed")};var Wf="https://opencode.ai/config.json",Un="x-anyray-metadata",Nt="x-anyray-api-key",Uf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Fn="Authorization",vr=["anthropic","openai"],Hn="github-copilot",xN="header",Wn="anyray",RN=()=>process.env.XDG_CONFIG_HOME?.trim()||Sr(UC(),".config"),ON=()=>process.env.XDG_DATA_HOME?.trim()||Sr(UC(),".local","share"),Rl=()=>Sr(RN(),"opencode"),Il=()=>Sr(Rl(),"plugins","anyrayTrim.js"),GC=()=>Sr(ON(),"opencode"),VC=async()=>{try{let e=await HC(Sr(GC(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return F(t)?{chatGptOAuth:F(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}}},BC=async()=>(await VC()).chatGptOAuth,TN=["opencode.jsonc","opencode.json","config.json"],sa=async()=>{let e=Rl(),t=[];for(let n of TN){let r=Sr(e,n);await x(r)&&t.push(r)}return t},FC=async()=>(await sa())[0]??Sr(Rl(),"opencode.json"),Hf=()=>gC(process.env.ANYRAY_COPILOT_PLAN),Gf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${Hf()}/${xN}`,F=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},_N=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===vr[0]||n===vr[1]||n===Hn?[]:F(r)&&F(r.options)&&Yf(r.options.baseURL,t)?[n]:[]),Vf=/claude/i,Jf=["model","small_model"],KC=(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)||!Vf.test(o)))return`${vr[0]}/${o}`},Kf=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Kf(n,t);return t}if(!F(e))return t;for(let[n,r]of Object.entries(e))Jf.includes(n)&&typeof r=="string"?t.push(r):Kf(r,t);return t},PN=(e,t,n)=>{if(!F(e)||!F(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>Vf.test(a)))return!1;let o=`${n}/`;return Kf(t).filter(a=>a.startsWith(o)).every(a=>Vf.test(a.slice(o.length)))},jf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>jf(o,t,n));if(!F(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Jf.includes(o)?KC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=jf(a,t,n)}return r},Zf=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Zf(o,t[a],n));if(!F(e)||!F(t))return e;let r={};for(let[o,a]of Object.entries(e))Jf.includes(o)&&typeof a=="string"&&KC(t[o],n)===a?r[o]=t[o]:r[o]=Zf(a,t[o],n);return r},DN=e=>{if(F(e))for(let t of vr){let n=e[t];if(F(n)&&F(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},js=e=>{if(!F(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&_t({command:t,args:n},"profile")},xl=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),LN=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return F(t)&&t.tool==="opencode"}catch{return!1}},Xf=e=>te(e,"copilot")&&!!e.clientKey,NN=e=>e.byoUpstream?[]:te(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".`]:[],$N=(e,t)=>te(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.`]:[],MN=e=>Xf(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."]:[],BN=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Wf);let o=!1;if(n)if("mcp"in r&&!F(r.mcp))o=!0;else{let g=F(r.mcp)?{...r.mcp}:{},b=g[Wn];b!==void 0&&!js(b)?o=!0:(g[Wn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=g)}else if(F(r.mcp)&&js(r.mcp[Wn])){let g={...r.mcp};delete g[Wn],Object.keys(g).length===0?delete r.mcp:r.mcp=g}let a=F(r.provider)?{...r.provider}:{},s=_N(a,t.origin),i=s.every(g=>PN(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=jf(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,m=t.clientKey??t.placeholderKey,p=me({...t.metadata,tool:"opencode"});for(let g of c){let b={...a[g]},k={...b.options};if("headers"in k&&!F(k.headers)){u.push(g);continue}let C=F(k.headers)?{...k.headers}:{},S=!1;for(let[E,I]of[[Nt,m],...p?[[Un,p]]:[]])E in C?(typeof C[E]!="string"||C[E].trim()==="")&&u.push(`${g}.${E}`):(C[E]=I,d.push(`${g}.${E}`),S=!0);S&&(k.headers=C,b.options=k,a[g]=b)}let h=c.length>0?[]:vr.filter(g=>g!=="openai"||!te(t,"openai")),w=t.byoUpstream;for(let g of h){let b=F(a[g])?{...a[g]}:{},k=F(b.options)?{...b.options}:{};k.baseURL=f;let C=F(k.headers)?{...k.headers}:{};if(g==="anthropic"&&w)k.apiKey=w.key,C[Fn]=`Bearer ${w.key}`,C["x-anyray-provider"]="anthropic",C["x-anyray-auth-mode"]="passthrough",C["x-anyray-custom-host"]=w.url;else{k.apiKey=m,"x-anyray-custom-host"in C&&delete C[Fn];for(let S of Uf)delete C[S]}C[Nt]=m,p&&(C[Un]=p),k.headers=C,b.options=k,a[g]=b}let y=c.length===0&&Xf(t);if(y){let g=F(a[Hn])?{...a[Hn]}:{},b=F(g.options)?{...g.options}:{};b.baseURL=Gf(t);let k=F(b.headers)?{...b.headers}:{};k[Nt]=t.clientKey,p&&(k[Un]=p),b.headers=k,g.options=b,a[Hn]=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"],WC=(e,t,n,r,o=!1,a=!1)=>{let s=e[t];if(!F(s)||!F(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=F(c.headers)?{...c.headers}:void 0,f=u?.[Nt],m=xl(f);if(d&&(delete c.baseURL,l=!0),u&&(d||m)){let p=u,h=F(r)?r.options:void 0,w=F(h)&&F(h.headers)?h.headers:void 0;for(let y of[Nt,Un])w&&y in w?p[y]!==w[y]&&(p[y]=w[y],l=!0):y in p&&(delete p[y],l=!0);Object.keys(p).length===0?delete c.headers:c.headers=p}}else{let d=F(r)?r.options:void 0,u=F(d)?d:{},f=F(c.headers)?c.headers:{},m=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof f[Nt]=="string"||typeof f[Un]=="string"||Uf.some(p=>p in f);if(!o&&!m)return!1;for(let p of FN)p in u?c[p]!==u[p]&&(c[p]=u[p],l=!0):p in c&&(delete c[p],l=!0);if(F(c.headers)){let p={...c.headers},h=F(u.headers)?u.headers:{};"x-anyray-custom-host"in p&&Fn in p&&(Fn in h?p[Fn]!==h[Fn]&&(p[Fn]=h[Fn],l=!0):(delete p[Fn],l=!0));for(let w of[Nt,Un,...Uf])w in h?p[w]!==h[w]&&(p[w]=h[w],l=!0):w in p&&(delete p[w],l=!0);Object.keys(p).length===0?delete c.headers:c.headers=p}}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},WN=(e,t,n)=>{let r=e[t];if(!F(r)||!F(r.options)||!F(n)||!F(n.options))return!1;let o={...r.options};if(!F(o.headers)||"headers"in n.options&&!F(n.options.headers))return!1;let a={...o.headers},s=F(n.options.headers)?n.options.headers:{},i=!1;return!(Nt in s)&&xl(a[Nt])&&(delete a[Nt],i=!0),!(Un in s)&&LN(a[Un])&&(delete a[Un],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},UN=(e,t)=>{let n={...e},r=!1,o=DN(e.provider);if(F(n.mcp)&&js(n.mcp[Wn])){let c={...n.mcp};delete c[Wn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!F(n.provider))return{next:n,removed:r};let a={...n.provider},s=F(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===Wf&&vr.every(c=>{let l=a[c];return F(l)&&F(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of vr)WC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...vr,Hn]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;WN(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&F(u)&&F(u.options)&&Yf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Zf(n,t,l))}return WC(a,Hn,!0,s[Hn])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===Wf&&(delete n.$schema,r=!0),{next:n,removed:r}},jC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=Rl(),t=GC(),n=await x(e)||await x(t),r=n&&await BC();return{installed:n,detail:n?`${await FC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await FC(),r=e.openaiBaseUrl,o=me({...e.metadata,tool:"opencode"}),a=Xf(e),s=te(e,"openai"),i=await BC(),c;try{c=await Ke(n)}catch{return e.clientKey?{status:"manual",messages:[`Couldn't parse ${n} \u2014 set it by hand. Under "provider", add:`,e.byoUpstream?` "anthropic": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your upstream key>", "headers": { "Authorization": "Bearer <your upstream key>", "x-anyray-auth-mode": "passthrough", "x-anyray-provider": "anthropic", "x-anyray-custom-host": ${JSON.stringify(e.byoUpstream.url)}, "x-anyray-api-key": "<your personal ark_ key>" } } }`:` "anthropic": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your personal ark_ key>" } }`,...s?[]:[` "openai": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your personal ark_ key>" } }`],...a?[` "github-copilot": { "options": { "baseURL": ${JSON.stringify(Gf(e))}, "headers": { "${Nt}": "<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 Gr()?Ge("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:m,customHeadersAdded:p,customHeaderConflicts:h,mcpConflict:w}=BN(c.data,e,l),y=u.length>0,g=f.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${f.map(I=>`provider.${I}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...m.length>0?[`Updated model references: ${m.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=y?[`${n} already routes through ${e.origin} via ${u.map(I=>`provider.${I}`).join(", ")}; existing provider values were preserved.`,p.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${p.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)"}`,...NN(e),...$N(e,i),a?`provider.github-copilot options.baseURL \u2192 ${Gf(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. ${Hf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${Hf()} 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).",...MN(e),"Restart OpenCode (or start a new session) to pick up the change."];w?b.push(`MCP name conflict in ${n}: mcp.${Wn} is not owned by Anyray Connect, so it was left untouched.`):l&&b.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.");let k=h.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let S=await pn(n,c,d,!0)?[n]:[],E=Il();if(oe())try{let I=await MC(E,ps(Ye,["opencode"]));I==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${E} already exists and is not owned by Anyray.`):(I==="installed"&&S.push(E),b.push(`The OpenCode tool.execute.after carrier is active in ${E}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${E}. Gateway-side optimization remains active.`)}else{try{await Ff(E)==="removed"&&S.push(E)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${De()}). 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 sa())try{let{data:n}=await Ke(t);if(!F(n.provider))continue;for(let r of Object.values(n.provider))if(!(!F(r)||!F(r.options))&&Yf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){if(!oe())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=await sa();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 Ke(r);if(!F(o.mcp))continue;let a=o.mcp[Wn];if(!js(a)||!F(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 Ks(Il());e=i==="absent"?"missing":i,e==="owned"&&(t=await HC(Il(),"utf-8")===Bf(ps(Ye,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await sa()){let c;try{c=await Ke(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!F(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Wn];if(l!==void 0)if(js(l))if(n=!0,!F(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;mc({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 Gr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await VC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await sa()){let{data:o}=await Ke(r);if(F(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!F(s)||!F(s.options)){e.add("unknown");continue}let i=s.options,c=F(i.headers)?i.headers:{};if(a===Hn&&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===Hn&&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(xl(c[Nt])||xl(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 sa(),n=Il(),r="absent";try{r=await Ks(n)}catch{}if(t.length===0&&r!=="owned")return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[...t.map(i=>`would remove Anyray provider settings from ${i}`),...r==="owned"?[`would remove the Anyray OpenCode trim carrier from ${n}`]:[]]};let o=[],a=[],s=[];for(let i of t){let c;try{c=await Ke(i)}catch{s.push(i);continue}let{next:l,removed:d}=UN(c.data,await qo(i));d&&(await pn(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await ie(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 Ff(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 rm}from"node:os";import{join as Ll}from"node:path";import{homedir as HN}from"node:os";import{dirname as GN,join as Er}from"node:path";import{mkdir as VN,readdir as KN,readFile as YC,rm as JC}from"node:fs/promises";var zf="48ff8bb9a7afde1d9e8468d632f84b46f199e6a28657833b113de93698d9ac63",ZC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyNTYwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0KICAgICAgICBdCiAgICAgIH0KICAgIH0KICB9LAogICJjb25maWdTY2hlbWEiOiB7CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogZmFsc2UsCiAgICAicmVxdWlyZWQiOiBbImdhdGV3YXlVcmwiXSwKICAgICJwcm9wZXJ0aWVzIjogewogICAgICAiZ2F0ZXdheVVybCI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBbnlyYXkgZ2F0ZXdheSBvcmlnaW4sIGUuZy4gaHR0cHM6Ly9nYXRld2F5LmV4YW1wbGUuYW55cmF5LmFpIChubyAvdjEgc3VmZml4KS4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiUGVyc29uYWwgQW55cmF5IGNsaWVudCBrZXkgKGFya1/igKYpLiBTdXBwb3J0cyAke0VOVl9WQVJ9IHN1YnN0aXR1dGlvbjsgZGVmYXVsdHMgdG8gJHtBTllSQVlfQ0xJRU5UX0tFWX0uIgogICAgICB9LAogICAgICAidXNlciI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB1c2VyIChjb250ZW50LWZyZWU7IHVzdWFsbHkgYW4gZW1haWwpLiBPcHRpb25hbCDigJQgdGhlIGNsaWVudCBrZXkgYWxyZWFkeSBhdHRyaWJ1dGVzIHRoZSBlbnJvbGxlZCB1c2VyLiIKICAgICAgfSwKICAgICAgInRlYW0iOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiQXR0cmlidXRpb24gdGVhbSAoY29udGVudC1mcmVlKS4gT3B0aW9uYWwuIgogICAgICB9CiAgICB9LAogICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIjIwMjYuNy4xIgogICAgfQogIH0sCiAgInBlZXJEZXBlbmRlbmNpZXMiOiB7CiAgICAib3BlbmNsYXciOiAiPj0yMDI2LjcuMSIKICB9LAogICJkZXZEZXBlbmRlbmNpZXMiOiB7CiAgICAidHN4IjogIl40LjIzLjEyIiwKICAgICJ0eXBlc2NyaXB0IjogIl41LjYuMyIKICB9Cn0K"},{path:"src/index.ts",contentBase64:"LyoqCiA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yICYmIGhlYWRlcnNbJ3gtYW55cmF5LXByb3ZpZGVyJ10gPT09IHVuZGVmaW5lZCkgewogICAgICBoZWFkZXJzWyd4LWFueXJheS1wcm92aWRlciddID0gZ2F0ZXdheVByb3ZpZGVyOwogICAgfQogICAgb3B0cy5oZWFkZXJzID0gaGVhZGVyczsKICAgIGNvbnN0IHNlc3Npb25JZCA9CiAgICAgIHR5cGVvZiBvcHRzLnNlc3Npb25JZCA9PT0gJ3N0cmluZycgPyBvcHRzLnNlc3Npb25JZCA6IHVuZGVmaW5lZDsKICAgIGNvbnN0IGNhbGxlck9uUGF5bG9hZCA9IG9wdHMub25QYXlsb2FkOwogICAgb3B0cy5vblBheWxvYWQgPSBhc3luYyAocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA9PiB7CiAgICAgIGlmIChwYXlsb2FkICYmIHR5cGVvZiBwYXlsb2FkID09PSAnb2JqZWN0JyAmJiAhQXJyYXkuaXNBcnJheShwYXlsb2FkKSkgewogICAgICAgIHBhdGNoUGF5bG9hZFNlc3Npb25JZGVudGl0eSgKICAgICAgICAgIHBheWxvYWQgYXMgUmVjb3JkPHN0cmluZywgdW5rbm93bj4sCiAgICAgICAgICBzZXNzaW9uSWQKICAgICAgICApOwogICAgICB9CiAgICAgIHJldHVybiBjYWxsZXJPblBheWxvYWQgPyBjYWxsZXJPblBheWxvYWQocGF5bG9hZCwgcGF5bG9hZE1vZGVsKSA6IHBheWxvYWQ7CiAgICB9OwogICAgcmV0dXJuIGlubmVyKG1vZGVsLCBjb250ZXh0LCBvcHRzKTsKICB9OwogIHJldHVybiB3cmFwcGVkOwp9Owo="}];var qf=".anyray-source-sha",An=()=>Er(HN(),".anyray","openclaw-plugin"),XC=async(e=An())=>{try{if((await YC(Er(e,qf),"utf8")).trim()===zf)return"current"}catch{}for(let t of ZC){let n=Er(e,t.path);await VN(GN(n),{recursive:!0,mode:448}),await we(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await we(Er(e,qf),`${zf}
|
|
170
|
-
`),"installed"},Zs=async(e,t=[])=>{let n=[],r=async a=>{let s=Er(a,"plugins","anyray","catalog.json");try{await JC(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await KN(Er(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(Er(e,"agents",a,"agent"));return n},Ol=async(e=An())=>{try{await YC(Er(e,qf),"utf8")}catch{return!1}return await JC(e,{recursive:!0,force:!0}),!0};var em="x-anyray-metadata",la="x-anyray-api-key",tm=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],co="Authorization",lo="anthropic-beta",_l="interleaved-thinking-2025-05-14",Pl=["anthropic","openai"],qC="short",om="anthropic-messages",am=32e3,Dl="anthropic/claude-sonnet-4-5",sm=["anthropic/claude-haiku-4-5"],im="anyray/claude-sonnet-4-5",cm=["anyray/claude-haiku-4-5"],jN=[Dl,im],ZN=[sm,cm],Xe="anyray",Ir="ANYRAY_API_KEY",Ys="openclaw",ca=()=>process.env.OPENCLAW_STATE_DIR?.trim()||Ll(rm(),".openclaw"),ia=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||Ll(ca(),"openclaw.json"),$=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},nm=e=>{if(!$(e))return{};let t=e.models;return!$(t)||!$(t.providers)?{}:t.providers},YN=e=>e==="~"||e.startsWith("~/")?Ll(rm(),e.slice(1)):e,Tl=e=>{if(!$(e))return[];let t=e.agents;if(!$(t)||!Array.isArray(t.list))return[];let n=[];for(let r of t.list){if(!$(r))continue;let o=typeof r.agentDir=="string"?r.agentDir.trim():"";o&&n.push(YN(o))}return n},JN=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=me({...t.metadata,tool:Ys}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!$(l.models)&&d.push("models");let u=$(l.models)?{...l.models}:{};if("providers"in u&&!$(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let f=$(u.providers)?{...u.providers}:{},m=!1;if(n){let C=$(l.plugins)?{...l.plugins}:{},S=$(C.load)?{...C.load}:{},E=$(C.entries)?{...C.entries}:{},I=$(E[Xe])?{...E[Xe]}:{},_=$(I.config)?{...I.config}:{};if("plugins"in l&&!$(l.plugins)||"load"in C&&!$(C.load)||"paths"in S&&!Array.isArray(S.paths)||"entries"in C&&!$(C.entries)||Xe in E&&!$(E[Xe])||"config"in I&&!$(I.config)||"env"in l&&!$(l.env))d.push("plugins");else{let T=Array.isArray(S.paths)?[...S.paths]:[];T.includes(n)||T.push(n),S.paths=T,C.load=S,I.enabled=!0,_.gatewayUrl=t.anthropicBaseUrl,_.apiKey=r;let W=t.metadata.user,Q=t.metadata.team;W&&(_.user=W),Q&&(_.team=Q),I.config=_,E[Xe]=I,C.entries=E,l.plugins=C;let G=$(l.env)?{...l.env}:{};G[Ir]=r,l.env=G,m=!0}}let p=Pl.filter(C=>C!=="openai"||!te(t,"openai"));for(let C of p){if(C in f&&!$(f[C])){d.push(`models.providers.${C}`);continue}let S=$(f[C])?{...f[C]}:{};if("headers"in S&&!$(S.headers)){i.push(C);continue}let E=$(S.headers)?{...S.headers}:{};if(S.baseUrl=C==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,C==="anthropic"&&(S.api=om,(typeof S.maxTokens!="number"||S.maxTokens<=0)&&(S.maxTokens=am)),C==="anthropic"&&a)S.apiKey=a.key,E[co]=`Bearer ${a.key}`,E["x-anyray-provider"]="anthropic",E["x-anyray-auth-mode"]="passthrough",E["x-anyray-custom-host"]=a.url;else{S.apiKey=r,"x-anyray-custom-host"in E&&delete E[co];for(let I of tm)delete E[I]}E[la]=r,o&&(E[em]=o),C==="anthropic"&&(lo in E?c=E[lo]!==_l:E[lo]=_l),S.headers=E,f[C]=S,s.push(C)}u.providers=f,l.models=u;let h=!1,w=!1,y=!1,g,b=[],k="agents"in l&&!$(l.agents)||$(l.agents)&&"defaults"in l.agents&&!$(l.agents.defaults)||$(l.agents)&&$(l.agents.defaults)&&("params"in l.agents.defaults&&!$(l.agents.defaults.params)||"model"in l.agents.defaults&&!$(l.agents.defaults.model));if(k&&d.push("agents.defaults"),s.includes("anthropic")&&!k){let C=$(l.agents)?{...l.agents}:{},S=$(C.defaults)?{...C.defaults}:{},E=$(S.params)?{...S.params}:{};"cacheRetention"in E||(E.cacheRetention=qC,h=!0,S.params=E);let I=$(S.model)?{...S.model}:{},_=m?[...s,Xe]:s,T=W=>typeof W=="string"&&_.some(Q=>W.startsWith(`${Q}/`));typeof I.primary!="string"||I.primary.trim()===""?(I.primary=m?im:Dl,w=!0,S.model=I,"fallbacks"in I||(I.fallbacks=m?[...cm]:[...sm],y=!0)):T(I.primary)||(g=I.primary),b=(Array.isArray(I.fallbacks)?I.fallbacks:[]).filter(W=>typeof W=="string"&&!T(W)),(h||w)&&(C.defaults=S,l.agents=C)}return{next:l,routed:s,cacheRetentionSeeded:h,betaPreserved:c,headerConflicts:i,primarySeeded:w,fallbacksSeeded:y,unroutedPrimary:g,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:m}},XN=["baseUrl","apiKey","api","maxTokens"],Qf=(e,t,n=Pl,r)=>{let o={...e},a=!("models"in o)||$(o.models)&&(!("providers"in o.models)||$(o.models.providers)),s=$(o.models)?{...o.models}:{},i=$(s.providers)?{...s.providers}:{},c=nm(t),l=!1;for(let u of a?n:[]){let f=i[u];if(!$(f))continue;let m={...f},p=$(m.headers)?{...m.headers}:{};if(!(t!==void 0||typeof p[la]=="string"||typeof p[em]=="string"||typeof m.apiKey=="string"&&m.apiKey.startsWith("ark_")||tm.some(C=>C in p)))continue;let w=$(c[u])?c[u]:{},y=$(w.headers)?w.headers:{},g="x-anyray-custom-host"in p,b=C=>C==="api"?m.api===om:C==="maxTokens"?m.maxTokens===am:C==="apiKey"?g||typeof m.apiKey=="string"&&m.apiKey.startsWith("ark_"):!0;for(let C of XN)b(C)&&(C in w?m[C]!==w[C]&&(m[C]=w[C],l=!0):C in m&&(delete m[C],l=!0));let k=[la,em,...tm,..."x-anyray-custom-host"in p?[co]:[]];p[lo]===_l&&k.push(lo);for(let C of k)C in y?p[C]!==y[C]&&(p[C]=y[C],l=!0):C in p&&(delete p[C],l=!0);co in y&&!(co in p)&&(p[co]=y[co],l=!0),Object.keys(p).length===0?delete m.headers:m.headers=p,Object.keys(m).length===0?delete i[u]:i[u]=m}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=$(o.plugins)?{...o.plugins}:{},f=$(u.load)?{...u.load}:{},m=$(u.entries)?{...u.entries}:{};if((!("plugins"in o)||$(o.plugins))&&(!("load"in u)||$(u.load))&&(!("paths"in f)||Array.isArray(f.paths))&&(!("entries"in u)||$(u.entries))){if(Array.isArray(f.paths)&&f.paths.includes(r)){let w=f.paths.filter(y=>y!==r);w.length===0?delete f.paths:f.paths=w,l=!0}let h=m[Xe];if($(h)){let w=$(h.config)?h.config:{};if(t!==void 0||typeof w.apiKey=="string"&&w.apiKey.startsWith("ark_")){let g=$(t?.plugins)?t.plugins:{},b=$(g.entries)?g.entries:{};Xe in b?JSON.stringify(m[Xe])!==JSON.stringify(b[Xe])&&(m[Xe]=b[Xe],l=!0):(delete m[Xe],l=!0)}}if(Object.keys(f).length===0?delete u.load:u.load=f,Object.keys(m).length===0?delete u.entries:u.entries=m,Object.keys(u).length===0?delete o.plugins:o.plugins=u,$(o.env)){let w={...o.env},y=w[Ir];if(typeof y=="string"&&y.startsWith("ark_")){let g=$(t?.env)?t.env:{};Ir in g?w[Ir]!==g[Ir]&&(w[Ir]=g[Ir],l=!0):(delete w[Ir],l=!0),Object.keys(w).length===0?delete o.env:o.env=w}}}}let d=!("agents"in o)||$(o.agents)&&(!("defaults"in o.agents)||$(o.agents.defaults)&&(!("params"in o.agents.defaults)||$(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||$(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=$(o.agents)?{...o.agents}:{},f=$(u.defaults)?{...u.defaults}:{},m=$(f.params)?{...f.params}:{},p=$(t.agents)?t.agents:{},h=$(p.defaults)?p.defaults:{},w=$(h.params)?h.params:{};m.cacheRetention===qC&&("cacheRetention"in w?m.cacheRetention!==w.cacheRetention&&(m.cacheRetention=w.cacheRetention,l=!0):(delete m.cacheRetention,l=!0));let y=$(f.model)?{...f.model}:{},g=$(h.model)?h.model:{};jN.includes(y.primary)&&("primary"in g?y.primary!==g.primary&&(y.primary=g.primary,l=!0):(delete y.primary,l=!0)),ZN.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 f.model:f.model=y,Object.keys(m).length===0?delete f.params:f.params=m,Object.keys(f).length===0?delete u.defaults:u.defaults=f,Object.keys(u).length===0?delete o.agents:o.agents=u}return{next:o,removed:l}},QC={id:Ys,title:"OpenClaw",automatic:!0,async detect(){let e=await x(ia())||await x(ca());return{installed:e,detail:e?ia():`no ${Ll(rm(),".openclaw")} state dir`}},async apply(e,t){let n=ia();if(!e.byoUpstream&&te(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 ${Ys}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],E;try{E=await Ke(n)}catch{return{status:"held",messages:S}}let{next:I,removed:_}=Qf(E.data,await qo(n),Pl,An());return _?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 pn(n,E,I,!1),await ie(n),await Ol(),await Zs(ca(),Tl(I)),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...S]}):(t.dryRun||(await Ol(),await Zs(ca(),Tl(I))),{status:"held",messages:S})}let r=An(),o=!1;if(!t.dryRun)try{await XC(r)}catch{r=void 0,o=!0}let a;try{a=await Ke(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${om}", "maxTokens": ${am}, "apiKey": "<your personal ark_ key>", "headers": { "${la}": "<your personal ark_ key>", "${lo}": "${_l}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${la}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${Dl}") if none is set,`,'and under "agents.defaults.params" set "cacheRetention": "short" \u2014',"custom Anthropic-compatible hosts get no prompt-cache auto-seed, and","an unset value would leave the provider cache permanently cold.","Then run `openclaw config validate`."]}}let{next:s,routed:i,cacheRetentionSeeded:c,betaPreserved:l,headerConflicts:d,primarySeeded:u,fallbacksSeeded:f,unroutedPrimary:m,unroutedFallbacks:p,structureConflicts:h,pluginConfigured:w}=JN(a.data,e,r),y=s,g=!1;if(!i.includes("openai")){let S=Qf(y,await qo(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: ${me({...e.metadata,tool:Ys})??"(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 ${lo} 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?im:Dl} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(w?cm:sm).join(", ")}] so failover stays on a routed provider.`]:[]]:[],...m!==void 0?[`Your primary model (${m}) 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.`]:[],...p.length>0?[`Fallback model(s) ${p.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 (${An()}) and registered it under plugins.entries.${Xe}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${An()}; 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 pn(n,a,y,!0);return w&&await Zs(ca(),Tl(y)),{status:k,messages:b,changedFiles:C?[n]:[]}},async pointsAt(e){try{let{data:t}=await Ke(ia());for(let a of Object.values(nm(t)))if($(a)&&zC(a.baseUrl,e))return!0;let n=$(t.plugins)?t.plugins:{},o=($(n.entries)?n.entries:{})[Xe];if($(o)&&$(o.config)&&zC(o.config.gatewayUrl,e))return!0}catch{}return!1},async routingExpected(e){return e.includes(Ys)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Ke(ia());for(let a of Object.values(nm(t))){if(!$(a))continue;let s=$(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[la]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=$(t.plugins)?t.plugins:{},o=($(n.entries)?n.entries:{})[Xe];if($(o)&&$(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=ia();if(!await x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await Ke(t)}catch{return{status:"manual",messages:[`Couldn't parse ${t} \u2014 if you added Anyray settings there by hand, remove baseUrl/apiKey and the x-anyray-* headers from models.providers.anthropic and models.providers.openai yourself.`]}}let{next:r,removed:o}=Qf(n.data,await qo(t),Pl,An()),a=await Ol();return await Zs(ca(),Tl(r)),o?(await pn(t,n,r,!1),await ie(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${An()}`]:[]],changedFiles:[t]}):(await ie(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${An()}`]:[]]})}};import{execFile as UB}from"node:child_process";import{readFile as HB}from"node:fs/promises";import{homedir as fi,platform as Tr}from"node:os";import{join as Sn}from"node:path";import{isDeepStrictEqual as Ym,promisify as GB}from"node:util";var Js=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},Nl=(e,t)=>{let n=Js(e),r=Js(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 oB}from"node:crypto";import{promises as uv}from"node:fs";import{platform as aB,tmpdir as sB}from"node:os";import{join as Ql}from"node:path";import{execFile as zN}from"node:child_process";import{promises as Xs}from"node:fs";import{homedir as qN,platform as QN}from"node:os";import{delimiter as e$,join as $l}from"node:path";import{promisify as t$}from"node:util";var n$=t$(zN),r$=15*6e4,o$=64*1024*1024,a$=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],ek=async(e={})=>{let t=(e.home??qN)(),n=e.env??process.env,r=a$(e.runtimePlatform??QN()),o=[$l(t,".local","bin"),$l(t,".claude","local"),...(n.PATH??"").split(e$).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=$l(a,`claude${s}`);try{return await Xs.access(i),i}catch{}}return null},s$=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},i$=async e=>{let t=$l(e,"projects"),n;try{n=(await Xs.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return[]}let r=[];for(let o of n){let a=o.slice(-36);if(!d$.test(a))continue;let s=o.slice(0,-37).split("-").filter(i=>i.length>0).map(i=>i[0].toUpperCase()+i.slice(1)).join(" ");r.push({uuid:a,name:s.length>0?s:"Project",dirName:o})}return r},c$=e=>{if(!e||!e.startsWith("{"))return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t,r=n.sessionIds,o=n.jsonlPaths;if(!Array.isArray(r)||!Array.isArray(o))return null;let a=Array.isArray(n.titles)?n.titles:[],s=Array.isArray(n.createdAts)?n.createdAts:[],i=Array.isArray(n.updatedAts)?n.updatedAts:[],c=d=>typeof d=="number"&&Number.isFinite(d)?d:void 0,l=[];for(let d=0;d<r.length;d+=1){let u=r[d],f=o[d];if(typeof u!="string"||typeof f!="string"||u.length===0||f.length===0)continue;let m=a[d];l.push({sessionId:u,transcriptPath:f,title:typeof m=="string"&&m.length>0?m:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:s$(n.projectList)}},l$=async e=>{let t,n;try{let r=await Xs.readFile(e,"utf8");for(let o of r.split(`
|
|
171
|
-
`)){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}},
|
|
172
|
-
`).filter(d=>d.trim().length>0),i=c$(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 l$(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await i$(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as f$}from"node:crypto";import{promises as Gn}from"node:fs";import{homedir as m$,platform as h$}from"node:os";import{join as kt}from"node:path";var nk=448,Vn="local_",y$="local-agent-mode-sessions",lm="-3p",g$="cowork_account_settings.json",uo=(e={})=>{let t=(e.home??m$)(),n=e.runtimePlatform??h$(),r=e.env??process.env;if(n==="darwin")return kt(t,"Library","Application Support",`Claude${lm}`);if(n==="win32"){let o=r.LOCALAPPDATA??kt(t,"AppData","Local");return kt(o,`Claude${lm}`)}return null},zs=(e={})=>{let t=uo(e);return t?t.slice(0,-lm.length):null},dm=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)}`},Ml=async e=>{let t=kt(e,y$),n;try{n=(await Gn.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return{ok:!1,reason:"no-profile",found:[]}}let r=[];for(let o of n){let a;try{a=(await Gn.readdir(kt(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=kt(t,o,s);try{await Gn.access(kt(i,g$)),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]}},um=async e=>{try{let t=await Gn.readdir(e);return new Set(t.filter(n=>n.startsWith(Vn)&&n.endsWith(".json")).map(n=>n.slice(Vn.length,-5)))}catch{return new Set}},da=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),w$=async(e,t)=>{let n=`${Vn}${t.sessionId}`,r=kt(e,n),o=kt(r,"outputs"),a=kt(r,".claude"),s=kt(a,"projects",dm(o));await Gn.mkdir(o,{recursive:!0,mode:nk}),await Gn.mkdir(s,{recursive:!0,mode:nk});let i=kt(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${f$()}`;await Gn.copyFile(t.transcriptPath,c),await Gn.chmod(c,384),await Gn.rename(c,i);let l=t.createdAt??Date.now();await X(kt(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})},rk=async(e,t)=>{let n=await um(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!da(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await w$(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as ua}from"node:fs";import{homedir as b$}from"node:os";import{dirname as A$,join as qs}from"node:path";var C$=448,k$=["Documents","Claude","Projects"],v$="spaces.json",S$=(e={})=>qs((e.home??b$)(),...k$),E$=async e=>{try{let t=JSON.parse(await ua.readFile(e,"utf8"));if(!t||typeof t!="object")return{spaces:[],readable:!1};let n=t.spaces;return Array.isArray(n)?{spaces:n.filter(r=>!!r&&typeof r=="object"&&typeof r.id=="string"),readable:!0}:{spaces:[],readable:!1}}catch(t){return t.code==="ENOENT"?{spaces:[],readable:!0}:{spaces:[],readable:!1}}},I$=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},pm=async e=>{try{return await ua.access(e),!0}catch{return!1}},x$=async(e,t,n)=>{let r=qs(t,I$(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await pm(r)?o:r;return a===o&&await pm(o)?null:(await ua.mkdir(A$(a),{recursive:!0}),await ua.cp(e,a,{recursive:!0}),a)},R$=async e=>{try{let t=(await ua.readFile(qs(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},ok=async e=>{let t=S$({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=qs(e.storageDir,v$),{spaces:a,readable:s}=await E$(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=qs(e.stagedProjectsDir,l.dirName);try{if(!await pm(d)){n.failed+=1;continue}let u=await x$(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await R$(u);c.push({id:l.uuid,name:l.name,folders:[{path:u}],projects:[],links:[],...f?{instructions:f}:{},origin:"user",createdAt:e.now,updatedAt:e.now}),n.imported+=1}catch{n.failed+=1}}return c.length>0&&(await ua.mkdir(e.storageDir,{recursive:!0,mode:C$}),await X(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as P$}from"node:crypto";import{execFile as D$,spawnSync as hk}from"node:child_process";import{constants as yk}from"node:fs";import{access as Gl,chmod as L$,mkdir as N$,readdir as $$,readFile as mm,rename as M$,rm as pa,stat as gk,writeFile as B$}from"node:fs/promises";import{homedir as F$,platform as W$,userInfo as U$}from"node:os";import{basename as H$,dirname as wk,isAbsolute as fa,join as $t,resolve as lk}from"node:path";import{isDeepStrictEqual as ei,promisify as G$}from"node:util";var xr="__anyray-claude-desktop-credential",Qs="__anyray-claude-desktop-bootstrap-headers";var Bl=(e="anyray-connect migrate")=>["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: \`${e} --export <file.zip>\`.`],Fl=["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."],ak=(e="anyray-connect migrate",t="anyray-connect desktop")=>`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 \`${e} --export <file.zip>\`, and \`${t} disconnect\` restores the first-party profile.`;var Wl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],sk=["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"],O$=new Set(sk),T$=new Set(sk.map(e=>e.toLowerCase())),_$=new Set(Wl.map(e=>e.toLowerCase())),Ul=(e,t=!1)=>(t?T$:O$).has(t?e.toLowerCase():e),ik=(e,t=!1)=>t?_$.has(e.toLowerCase()):Wl.some(n=>n===e),ck=["*"],po=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...ck]}),Rr=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var ti=/^[a-f0-9-]{36}$/,bk="Anyray",hm=4,oi=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],ai=["deploymentMode","awaitingSignIn"],V$=["inferenceGatewayApiKey","awaitingSignIn"],Ak=[...[...oi,...ai].filter(e=>!V$.includes(e)),"configLibrary","_meta.json"],Cn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),it=e=>structuredClone(e),ni=async e=>{try{return await Gl(e),!0}catch{return!1}},K$=async e=>{try{let t=await $$(wk(e)),n=H$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},j$=async e=>{try{return await Gl(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":K$(e)}},zt=(e={})=>{let t=(e.home??F$)(),n=(e.username??(()=>U$().username))(),r=$t(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",$t("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:$t(r,"configLibrary"),meta:$t(r,"configLibrary","_meta.json"),appConfig:$t(r,"claude_desktop_config.json"),helper:$t(t,".anyray","bin","claude-desktop-credential-helper"),journal:$t(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Vl=()=>{let e=hk("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},Ck=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],Z$=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...Ck(t)]}},ym=(e="json")=>{let t=an(Ck(e)),n=lk(t.command),r=lk(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:oe()&&(!o||r!==n)}},Y$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,gm=e=>[e.command,...e.args].map(Y$).join(" "),J$=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!fa(e.command))throw new Error("the credential helper executable is not absolute")},kk=(e,t)=>{J$(e);let n=Kl(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!fa(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},vk=e=>(kk(e,"--json"),`#!/bin/sh
|
|
169
|
+
`)?"owned":"foreign":"absent",MC=async(e,t)=>{let n=Bf(t),r=await Ks(e);return r==="foreign"?"foreign":r==="owned"&&await NC(e,"utf-8")===n?"unchanged":(await we(e,n),"installed")},Ff=async e=>{let t=await Ks(e);return t!=="owned"?t:(await IN(e,{force:!0}),"removed")};var Wf="https://opencode.ai/config.json",Un="x-anyray-metadata",Nt="x-anyray-api-key",Uf=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],Fn="Authorization",vr=["anthropic","openai"],Hn="github-copilot",RN="header",Wn="anyray",ON=()=>process.env.XDG_CONFIG_HOME?.trim()||Sr(UC(),".config"),TN=()=>process.env.XDG_DATA_HOME?.trim()||Sr(UC(),".local","share"),Rl=()=>Sr(ON(),"opencode"),Il=()=>Sr(Rl(),"plugins","anyrayTrim.js"),GC=()=>Sr(TN(),"opencode"),VC=async()=>{try{let e=await HC(Sr(GC(),"auth.json"),"utf-8"),t=e.trim()?JSON.parse(e):{};return F(t)?{chatGptOAuth:F(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}}},BC=async()=>(await VC()).chatGptOAuth,_N=["opencode.jsonc","opencode.json","config.json"],sa=async()=>{let e=Rl(),t=[];for(let n of _N){let r=Sr(e,n);await x(r)&&t.push(r)}return t},FC=async()=>(await sa())[0]??Sr(Rl(),"opencode.json"),Hf=()=>gC(process.env.ANYRAY_COPILOT_PLAN),Gf=e=>`${e.origin.replace(/\/+$/,"")}/v1/copilot/${Hf()}/${RN}`,F=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yf=(e,t)=>{if(typeof e!="string")return!1;let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)},PN=(e,t)=>Object.entries(e).flatMap(([n,r])=>n===vr[0]||n===vr[1]||n===Hn?[]:F(r)&&F(r.options)&&Yf(r.options.baseURL,t)?[n]:[]),Vf=/claude/i,Jf=["model","small_model"],KC=(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)||!Vf.test(o)))return`${vr[0]}/${o}`},Kf=(e,t=[])=>{if(Array.isArray(e)){for(let n of e)Kf(n,t);return t}if(!F(e))return t;for(let[n,r]of Object.entries(e))Jf.includes(n)&&typeof r=="string"?t.push(r):Kf(r,t);return t},DN=(e,t,n)=>{if(!F(e)||!F(e.models))return!1;let r=Object.keys(e.models);if(r.length===0||!r.every(a=>Vf.test(a)))return!1;let o=`${n}/`;return Kf(t).filter(a=>a.startsWith(o)).every(a=>Vf.test(a.slice(o.length)))},jf=(e,t,n)=>{if(Array.isArray(e))return e.map(o=>jf(o,t,n));if(!F(e))return e;let r={};for(let[o,a]of Object.entries(e)){let s=Jf.includes(o)?KC(a,t):void 0;s!==void 0?(r[o]=s,n.push(`${String(a)} \u2192 ${s}`)):r[o]=jf(a,t,n)}return r},Zf=(e,t,n)=>{if(Array.isArray(e)&&Array.isArray(t))return e.map((o,a)=>Zf(o,t[a],n));if(!F(e)||!F(t))return e;let r={};for(let[o,a]of Object.entries(e))Jf.includes(o)&&typeof a=="string"&&KC(t[o],n)===a?r[o]=t[o]:r[o]=Zf(a,t[o],n);return r},LN=e=>{if(F(e))for(let t of vr){let n=e[t];if(F(n)&&F(n.options)&&typeof n.options.baseURL=="string")return n.options.baseURL.replace(/\/+$/,"").replace(/\/v1$/,"")}},js=e=>{if(!F(e)||!Array.isArray(e.command))return!1;let[t,...n]=e.command;return typeof t=="string"&&_t({command:t,args:n},"profile")},xl=e=>typeof e=="string"&&(e.startsWith("ark_")||e==="anyray-placeholder"),NN=e=>{if(typeof e!="string")return!1;try{let t=JSON.parse(e);return F(t)&&t.tool==="opencode"}catch{return!1}},Xf=e=>te(e,"copilot")&&!!e.clientKey,$N=e=>e.byoUpstream?[]:te(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".`]:[],MN=(e,t)=>te(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.`]:[],BN=e=>Xf(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."]:[],FN=(e,t,n)=>{let r={...e};Object.keys(e).length===0&&(r.$schema=Wf);let o=!1;if(n)if("mcp"in r&&!F(r.mcp))o=!0;else{let w=F(r.mcp)?{...r.mcp}:{},b=w[Wn];b!==void 0&&!js(b)?o=!0:(w[Wn]={type:"local",command:[n.command,...n.args],enabled:!0},r.mcp=w)}else if(F(r.mcp)&&js(r.mcp[Wn])){let w={...r.mcp};delete w[Wn],Object.keys(w).length===0?delete r.mcp:r.mcp=w}let a=F(r.provider)?{...r.provider}:{},s=PN(a,t.origin),i=s.every(w=>DN(a[w],e,w))?s:[],c=s.filter(w=>!i.includes(w)),l=[];if(i.length>0){for(let w of i)delete a[w];r=jf(r,i,l)}let d=[],u=[],f=t.openaiBaseUrl,m=t.clientKey??t.placeholderKey,p=me({...t.metadata,tool:"opencode"});for(let w of c){let b={...a[w]},k={...b.options};if("headers"in k&&!F(k.headers)){u.push(w);continue}let C=F(k.headers)?{...k.headers}:{},S=!1;for(let[E,I]of[[Nt,m],...p?[[Un,p]]:[]])E in C?(typeof C[E]!="string"||C[E].trim()==="")&&u.push(`${w}.${E}`):(C[E]=I,d.push(`${w}.${E}`),S=!0);S&&(k.headers=C,b.options=k,a[w]=b)}let h=c.length>0?[]:vr.filter(w=>w!=="openai"||!te(t,"openai")),g=t.byoUpstream;for(let w of h){let b=F(a[w])?{...a[w]}:{},k=F(b.options)?{...b.options}:{};k.baseURL=f;let C=F(k.headers)?{...k.headers}:{};if(w==="anthropic"&&g)k.apiKey=g.key,C[Fn]=`Bearer ${g.key}`,C["x-anyray-provider"]="anthropic",C["x-anyray-auth-mode"]="passthrough",C["x-anyray-custom-host"]=g.url;else{k.apiKey=m,"x-anyray-custom-host"in C&&delete C[Fn];for(let S of Uf)delete C[S]}C[Nt]=m,p&&(C[Un]=p),k.headers=C,b.options=k,a[w]=b}let y=c.length===0&&Xf(t);if(y){let w=F(a[Hn])?{...a[Hn]}:{},b=F(w.options)?{...w.options}:{};b.baseURL=Gf(t);let k=F(b.headers)?{...b.headers}:{};k[Nt]=t.clientKey,p&&(k[Un]=p),b.headers=k,w.options=b,a[Hn]=w}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(!F(s)||!F(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=F(c.headers)?{...c.headers}:void 0,f=u?.[Nt],m=xl(f);if(d&&(delete c.baseURL,l=!0),u&&(d||m)){let p=u,h=F(r)?r.options:void 0,g=F(h)&&F(h.headers)?h.headers:void 0;for(let y of[Nt,Un])g&&y in g?p[y]!==g[y]&&(p[y]=g[y],l=!0):y in p&&(delete p[y],l=!0);Object.keys(p).length===0?delete c.headers:c.headers=p}}else{let d=F(r)?r.options:void 0,u=F(d)?d:{},f=F(c.headers)?c.headers:{},m=c.apiKey==="anyray-placeholder"||a&&typeof c.apiKey=="string"&&c.apiKey.startsWith("ark_")||typeof f[Nt]=="string"||typeof f[Un]=="string"||Uf.some(p=>p in f);if(!o&&!m)return!1;for(let p of WN)p in u?c[p]!==u[p]&&(c[p]=u[p],l=!0):p in c&&(delete c[p],l=!0);if(F(c.headers)){let p={...c.headers},h=F(u.headers)?u.headers:{};"x-anyray-custom-host"in p&&Fn in p&&(Fn in h?p[Fn]!==h[Fn]&&(p[Fn]=h[Fn],l=!0):(delete p[Fn],l=!0));for(let g of[Nt,Un,...Uf])g in h?p[g]!==h[g]&&(p[g]=h[g],l=!0):g in p&&(delete p[g],l=!0);Object.keys(p).length===0?delete c.headers:c.headers=p}}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},UN=(e,t,n)=>{let r=e[t];if(!F(r)||!F(r.options)||!F(n)||!F(n.options))return!1;let o={...r.options};if(!F(o.headers)||"headers"in n.options&&!F(n.options.headers))return!1;let a={...o.headers},s=F(n.options.headers)?n.options.headers:{},i=!1;return!(Nt in s)&&xl(a[Nt])&&(delete a[Nt],i=!0),!(Un in s)&&NN(a[Un])&&(delete a[Un],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=LN(e.provider);if(F(n.mcp)&&js(n.mcp[Wn])){let c={...n.mcp};delete c[Wn],Object.keys(c).length===0?delete n.mcp:n.mcp=c,r=!0}if(!F(n.provider))return{next:n,removed:r};let a={...n.provider},s=F(t?.provider)?t.provider:{},i=t===void 0&&n.$schema===Wf&&vr.every(c=>{let l=a[c];return F(l)&&F(l.options)&&typeof l.options.baseURL=="string"&&typeof l.options.apiKey=="string"&&l.options.apiKey.startsWith("ark_")});for(let c of vr)WC(a,c,!1,s[c],t!==void 0,i)&&(r=!0);if(t!==void 0){let c=new Set([...vr,Hn]),l=[];for(let d of Object.keys(s)){if(c.has(d))continue;UN(a,d,s[d])&&(r=!0);let u=s[d];!(d in a)&&o!==void 0&&F(u)&&F(u.options)&&Yf(u.options.baseURL,o)&&(a[d]=u,l.push(d),r=!0)}l.length>0&&(n=Zf(n,t,l))}return WC(a,Hn,!0,s[Hn])&&(r=!0),Object.keys(a).length===0?delete n.provider:n.provider=a,t!==void 0&&!("$schema"in t)&&n.$schema===Wf&&(delete n.$schema,r=!0),{next:n,removed:r}},jC={id:"opencode",title:"OpenCode",automatic:!0,async detect(){let e=Rl(),t=GC(),n=await x(e)||await x(t),r=n&&await BC();return{installed:n,detail:n?`${await FC()}${r?" (ChatGPT Pro/Plus OAuth detected)":""}`:"no ~/.config/opencode or ~/.local/share/opencode"}},async apply(e,t){let n=await FC(),r=e.openaiBaseUrl,o=me({...e.metadata,tool:"opencode"}),a=Xf(e),s=te(e,"openai"),i=await BC(),c;try{c=await Ke(n)}catch{return e.clientKey?{status:"manual",messages:[`Couldn't parse ${n} \u2014 set it by hand. Under "provider", add:`,e.byoUpstream?` "anthropic": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your upstream key>", "headers": { "Authorization": "Bearer <your upstream key>", "x-anyray-auth-mode": "passthrough", "x-anyray-provider": "anthropic", "x-anyray-custom-host": ${JSON.stringify(e.byoUpstream.url)}, "x-anyray-api-key": "<your personal ark_ key>" } } }`:` "anthropic": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your personal ark_ key>" } }`,...s?[]:[` "openai": { "options": { "baseURL": ${JSON.stringify(r)}, "apiKey": "<your personal ark_ key>" } }`],...a?[` "github-copilot": { "options": { "baseURL": ${JSON.stringify(Gf(e))}, "headers": { "${Nt}": "<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 Gr()?Ge("profile"):void 0,{next:d,customProviders:u,migratedProviders:f,modelRefsRemapped:m,customHeadersAdded:p,customHeaderConflicts:h,mcpConflict:g}=FN(c.data,e,l),y=u.length>0,w=f.length>0?[`${t.dryRun?"Would migrate":"Migrated"} ${f.map(I=>`provider.${I}`).join(", ")} \u2014 a hand-rolled ${e.origin} route serving only Claude models \u2014 onto the managed anthropic lane; pick models under anthropic/* from now on.`,...m.length>0?[`Updated model references: ${m.join(", ")}.`]:[],"The original block is kept in the .anyray-bak backup; `anyray-connect revert` restores it."]:[],b=y?[`${n} already routes through ${e.origin} via ${u.map(I=>`provider.${I}`).join(", ")}; existing provider values were preserved.`,p.length>0?`${t.dryRun?"Would add":"Added"} only the missing Anyray authentication/attribution headers: ${p.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."]:[...w,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)"}`,...$N(e),...MN(e,i),a?`provider.github-copilot options.baseURL \u2192 ${Gf(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. ${Hf()==="default"?"Uses GitHub\u2019s documented all-plan Copilot API host automatically.":`Uses the ${Hf()} 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).",...BN(e),"Restart OpenCode (or start a new session) to pick up the change."];g?b.push(`MCP name conflict in ${n}: mcp.${Wn} is not owned by Anyray Connect, so it was left untouched.`):l&&b.push("Registered the Anyray retrieval MCP server (anyray_retrieve) for explicit recovery of stashed context.");let k=h.length>0?"manual":"configured";if(t.dryRun)return{status:k,messages:b};let S=await pn(n,c,d,!0)?[n]:[],E=Il();if(oe())try{let I=await MC(E,ps(Ye,["opencode"]));I==="foreign"?b.push(`Skipped the OpenCode trim carrier because ${E} already exists and is not owned by Anyray.`):(I==="installed"&&S.push(E),b.push(`The OpenCode tool.execute.after carrier is active in ${E}; oversized string tool outputs run through the shared __anyray-hook before OpenCode stores them.`))}catch{b.push(`Could not install the OpenCode trim carrier in ${E}. Gateway-side optimization remains active.`)}else{try{await Ff(E)==="removed"&&S.push(E)}catch{}b.push(`Skipped the OpenCode trim carrier \u2014 anyray-connect is running from a temporary path (${De()}). 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 sa())try{let{data:n}=await Ke(t);if(!F(n.provider))continue;for(let r of Object.values(n.provider))if(!(!F(r)||!F(r.options))&&Yf(r.options.baseURL,e))return!0}catch{}return!1},async mcpStatus(){if(!oe())return{registered:!1,command:null,reason:"ephemeral-runtime"};let e=await sa();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 Ke(r);if(!F(o.mcp))continue;let a=o.mcp[Wn];if(!js(a)||!F(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 Ks(Il());e=i==="absent"?"missing":i,e==="owned"&&(t=await HC(Il(),"utf-8")===Bf(ps(Ye,["opencode"])))}catch{e="unreadable"}let n=!1,r=!1,o=!1,a=!0;for(let i of await sa()){let c;try{c=await Ke(i)}catch{o=!0;continue}if(c.data.mcp===void 0)continue;if(!F(c.data.mcp)){o=!0;continue}let l=c.data.mcp[Wn];if(l!==void 0)if(js(l))if(n=!0,!F(l)||!Array.isArray(l.command))a=!1;else{let[d,...u]=l.command;mc({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 Gr()?"owned":"missing"}},async inferenceAuthLanes(){let e=new Set;try{let t=await VC(),n=t.chatGptOAuth;t.readable||e.add("unknown"),n&&e.add("native");for(let r of await sa()){let{data:o}=await Ke(r);if(F(o.provider))for(let[a,s]of Object.entries(o.provider)){if(!F(s)||!F(s.options)){e.add("unknown");continue}let i=s.options,c=F(i.headers)?i.headers:{};if(a===Hn&&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===Hn&&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(xl(c[Nt])||xl(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 sa(),n=Il(),r="absent";try{r=await Ks(n)}catch{}if(t.length===0&&r!=="owned")return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[...t.map(i=>`would remove Anyray provider settings from ${i}`),...r==="owned"?[`would remove the Anyray OpenCode trim carrier from ${n}`]:[]]};let o=[],a=[],s=[];for(let i of t){let c;try{c=await Ke(i)}catch{s.push(i);continue}let{next:l,removed:d}=HN(c.data,await qo(i));d&&(await pn(i,c,l,!1),a.push(i),o.push(`removed Anyray provider settings from ${i}`)),await ie(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 Ff(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 rm}from"node:os";import{join as Ll}from"node:path";import{homedir as GN}from"node:os";import{dirname as VN,join as Er}from"node:path";import{mkdir as KN,readdir as jN,readFile as YC,rm as JC}from"node:fs/promises";var zf="48ff8bb9a7afde1d9e8468d632f84b46f199e6a28657833b113de93698d9ac63",ZC=[{path:"openclaw.plugin.json",contentBase64:"ewogICJpZCI6ICJhbnlyYXkiLAogICJuYW1lIjogIkFueXJheSIsCiAgImRlc2NyaXB0aW9uIjogIlJvdXRlIE9wZW5DbGF3J3MgbW9kZWwgY2FsbHMgdGhyb3VnaCB5b3VyIG9yZ2FuaXphdGlvbidzIEFueXJheSBnYXRld2F5IHdpdGggcGVyLXNlc3Npb24gaWRlbnRpdHkgYW5kIGNvbnRlbnQtZnJlZSBhdHRyaWJ1dGlvbi4iLAogICJhY3RpdmF0aW9uIjogewogICAgIm9uU3RhcnR1cCI6IHRydWUKICB9LAogICJwcm92aWRlcnMiOiBbImFueXJheSJdLAogICJzZXR1cCI6IHsKICAgICJwcm92aWRlcnMiOiBbCiAgICAgIHsKICAgICAgICAiaWQiOiAiYW55cmF5IiwKICAgICAgICAiZW52VmFycyI6IFsiQU5ZUkFZX0FQSV9LRVkiLCAiQU5ZUkFZX0NMSUVOVF9LRVkiXQogICAgICB9CiAgICBdCiAgfSwKICAicHJvdmlkZXJBdXRoQ2hvaWNlcyI6IFsKICAgIHsKICAgICAgInByb3ZpZGVyIjogImFueXJheSIsCiAgICAgICJtZXRob2QiOiAiYXBpLWtleSIsCiAgICAgICJjaG9pY2VJZCI6ICJhbnlyYXktYXBpLWtleSIsCiAgICAgICJjaG9pY2VMYWJlbCI6ICJBbnlyYXkgY2xpZW50IGtleSIsCiAgICAgICJjaG9pY2VIaW50IjogIlBlcnNvbmFsIGFya18ga2V5IGZyb20gYW55cmF5LWNvbm5lY3QgZW5yb2xsbWVudCIsCiAgICAgICJncm91cElkIjogImFueXJheSIsCiAgICAgICJncm91cExhYmVsIjogIkFueXJheSIsCiAgICAgICJvcHRpb25LZXkiOiAiYW55cmF5QXBpS2V5IiwKICAgICAgImNsaUZsYWciOiAiLS1hbnlyYXktYXBpLWtleSIKICAgIH0KICBdLAogICJtb2RlbENhdGFsb2ciOiB7CiAgICAiZGlzY292ZXJ5IjogewogICAgICAiYW55cmF5IjogInJlZnJlc2hhYmxlIgogICAgfSwKICAgICJwcm92aWRlcnMiOiB7CiAgICAgICJhbnlyYXkiOiB7CiAgICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly91bmNvbmZpZ3VyZWQuZ2F0ZXdheS5pbnZhbGlkIiwKICAgICAgICAiYXBpIjogImFudGhyb3BpYy1tZXNzYWdlcyIsCiAgICAgICAgImRlZmF1bHRNb2RlbCI6ICJjbGF1ZGUtc29ubmV0LTQtNSIsCiAgICAgICAgIm1vZGVscyI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1zb25uZXQtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIFNvbm5ldCA0LjUgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogMjAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogNjQwMDAKICAgICAgICAgIH0sCiAgICAgICAgICB7CiAgICAgICAgICAgICJpZCI6ICJjbGF1ZGUtaGFpa3UtNC01IiwKICAgICAgICAgICAgIm5hbWUiOiAiQ2xhdWRlIEhhaWt1IDQuNSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiA2NDAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImNsYXVkZS1vcHVzLTQtOCIsCiAgICAgICAgICAgICJuYW1lIjogIkNsYXVkZSBPcHVzIDQuOCAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyMDAwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAzMjAwMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgImlkIjogImdyb2stNC42IiwKICAgICAgICAgICAgIm5hbWUiOiAiR3JvayA0LjYgKEFueXJheSkiLAogICAgICAgICAgICAicmVhc29uaW5nIjogdHJ1ZSwKICAgICAgICAgICAgImlucHV0IjogWyJ0ZXh0IiwgImltYWdlIl0sCiAgICAgICAgICAgICJjb250ZXh0V2luZG93IjogNTAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay00LjMiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIDQuMyAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAxMDAwMDAwLAogICAgICAgICAgICAibWF4VG9rZW5zIjogMTI4MDAwCiAgICAgICAgICB9LAogICAgICAgICAgewogICAgICAgICAgICAiaWQiOiAiZ3Jvay1idWlsZC0wLjEiLAogICAgICAgICAgICAibmFtZSI6ICJHcm9rIEJ1aWxkIDAuMSAoQW55cmF5KSIsCiAgICAgICAgICAgICJyZWFzb25pbmciOiB0cnVlLAogICAgICAgICAgICAiaW5wdXQiOiBbInRleHQiLCAiaW1hZ2UiXSwKICAgICAgICAgICAgImNvbnRleHRXaW5kb3ciOiAyNTYwMDAsCiAgICAgICAgICAgICJtYXhUb2tlbnMiOiAxMjgwMDAKICAgICAgICAgIH0KICAgICAgICBdCiAgICAgIH0KICAgIH0KICB9LAogICJjb25maWdTY2hlbWEiOiB7CiAgICAidHlwZSI6ICJvYmplY3QiLAogICAgImFkZGl0aW9uYWxQcm9wZXJ0aWVzIjogZmFsc2UsCiAgICAicmVxdWlyZWQiOiBbImdhdGV3YXlVcmwiXSwKICAgICJwcm9wZXJ0aWVzIjogewogICAgICAiZ2F0ZXdheVVybCI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBbnlyYXkgZ2F0ZXdheSBvcmlnaW4sIGUuZy4gaHR0cHM6Ly9nYXRld2F5LmV4YW1wbGUuYW55cmF5LmFpIChubyAvdjEgc3VmZml4KS4iCiAgICAgIH0sCiAgICAgICJhcGlLZXkiOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiUGVyc29uYWwgQW55cmF5IGNsaWVudCBrZXkgKGFya1/igKYpLiBTdXBwb3J0cyAke0VOVl9WQVJ9IHN1YnN0aXR1dGlvbjsgZGVmYXVsdHMgdG8gJHtBTllSQVlfQ0xJRU5UX0tFWX0uIgogICAgICB9LAogICAgICAidXNlciI6IHsKICAgICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJBdHRyaWJ1dGlvbiB1c2VyIChjb250ZW50LWZyZWU7IHVzdWFsbHkgYW4gZW1haWwpLiBPcHRpb25hbCDigJQgdGhlIGNsaWVudCBrZXkgYWxyZWFkeSBhdHRyaWJ1dGVzIHRoZSBlbnJvbGxlZCB1c2VyLiIKICAgICAgfSwKICAgICAgInRlYW0iOiB7CiAgICAgICAgInR5cGUiOiAic3RyaW5nIiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiQXR0cmlidXRpb24gdGVhbSAoY29udGVudC1mcmVlKS4gT3B0aW9uYWwuIgogICAgICB9CiAgICB9LAogICAgInVpSGludHMiOiB7CiAgICAgICJnYXRld2F5VXJsIjogewogICAgICAgICJsYWJlbCI6ICJHYXRld2F5IFVSTCIsCiAgICAgICAgImhlbHAiOiAiWW91ciBvcmdhbml6YXRpb24ncyBBbnlyYXkgZ2F0ZXdheSBvcmlnaW4uIgogICAgICB9LAogICAgICAiYXBpS2V5IjogewogICAgICAgICJsYWJlbCI6ICJDbGllbnQga2V5IiwKICAgICAgICAiaGVscCI6ICJQZXJzb25hbCBhcmtfIGtleSBmcm9tIGFueXJheS1jb25uZWN0IGVucm9sbG1lbnQuIExlYXZlIHVuc2V0IHRvIHJlYWQgJEFOWVJBWV9DTElFTlRfS0VZLiIKICAgICAgfQogICAgfQogIH0KfQo="},{path:"package.json",contentBase64:"ewogICJuYW1lIjogIkBhbnlyYXkvb3BlbmNsYXctcGx1Z2luIiwKICAidmVyc2lvbiI6ICIwLjMuMCIsCiAgInByaXZhdGUiOiB0cnVlLAogICJkZXNjcmlwdGlvbiI6ICJPcGVuQ2xhdyBwcm92aWRlciBwbHVnaW4gZm9yIHRoZSBBbnlyYXkgZ2F0ZXdheSDigJQgcGVyLXNlc3Npb24gaWRlbnRpdHksIGF0dHJpYnV0aW9uLCBhbmQgY2FjaGUtc2FmZSBkZWZhdWx0cyBvbiBldmVyeSBtb2RlbCBjYWxsLiIsCiAgInR5cGUiOiAibW9kdWxlIiwKICAibWFpbiI6ICIuL3NyYy9pbmRleC50cyIsCiAgInNjcmlwdHMiOiB7CiAgICAiYnVpbGQiOiAidHNjIC1wIHRzY29uZmlnLmpzb24iLAogICAgInRlc3QiOiAibm9kZSAtLXRlc3QgLS1pbXBvcnQgdHN4ICdzcmMvKi50ZXN0LnRzJyIKICB9LAogICJvcGVuY2xhdyI6IHsKICAgICJleHRlbnNpb25zIjogWyIuL3NyYy9pbmRleC50cyJdLAogICAgImNvbXBhdCI6IHsKICAgICAgIm1pbkdhdGV3YXlWZXJzaW9uIjogIjIwMjYuNy4xIgogICAgfQogIH0sCiAgInBlZXJE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ICAgLy8gQmFyZSBvcmlnaW46IHRoZSBhbnRocm9waWMtbWVzc2FnZXMgdHJhbnNwb3J0IGFwcGVuZHMgL3YxL21lc3NhZ2VzLgogICAgYmFzZVVybDogZ2F0ZXdheVVybC5yZXBsYWNlKC9cLyskLywgJycpLAogICAgYXBpOiAnYW50aHJvcGljLW1lc3NhZ2VzJywKICAgIC4uLihhcGlLZXkgPyB7IGFwaUtleSB9IDoge30pLAogICAgaGVhZGVyczogewogICAgICAnYW50aHJvcGljLWJldGEnOiBBTlRIUk9QSUNfQkVUQSwKICAgICAgLi4uKGFwaUtleSA/IHsgJ3gtYW55cmF5LWFwaS1rZXknOiBhcGlLZXkgfSA6IHt9KSwKICAgICAgLi4uKGF0dHJpYnV0aW9uID8geyAneC1hbnlyYXktbWV0YWRhdGEnOiBhdHRyaWJ1dGlvbiB9IDoge30pLAogICAgfSwKICAgIG1vZGVsczogTU9ERUxTLAogIH07Cn07Cg=="},{path:"src/sessionIdentity.ts",contentBase64:"LyoqCiAqIFBlci1zZXNzaW9uIGlkZW50aXR5IGZvciB0aGUgQW55cmF5IGdhdGV3YXksIGluamVjdGVkIGludG8gdGhlIEFudGhyb3BpYwogKiBNZXNzYWdlcyBib2R5IGFzIGBtZXRhZGF0YS51c2VyX2lkYC4KICoKICogVGhlIGdhdGV3YXkgZGVyaXZlcyBpdHMgb3B0aW1pemVyIHNlc3Npb24gZnJvbSBhIGBfc2Vzc2lvbl88dXVpZD5gIHN1ZmZpeCBvbgogKiBgbWV0YWRhdGEudXNlcl9pZGAgKHRoZSBDbGF1ZGUgQ29kZSBjb252ZW50aW9uOyBnYXRld2F5CiAqIGBjbGllbnRTZXNzaW9uLnRzI21ldGFkYXRhU2Vzc2lvblV1aWRgKS4gV2l0aG91dCBpdCwgT3BlbkNsYXcgdHJhZmZpYyBmYWxscwogKiB0byBhIGNvbnZlcnNhdGlvbi1hbmNob3IgZmluZ2VycHJpbnQsIGFuZCBjb25jdXJyZW50IGNvbnZlcnNhdG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];var qf=".anyray-source-sha",An=()=>Er(GN(),".anyray","openclaw-plugin"),XC=async(e=An())=>{try{if((await YC(Er(e,qf),"utf8")).trim()===zf)return"current"}catch{}for(let t of ZC){let n=Er(e,t.path);await KN(VN(n),{recursive:!0,mode:448}),await we(n,Buffer.from(t.contentBase64,"base64").toString("utf8"))}return await we(Er(e,qf),`${zf}
|
|
170
|
+
`),"installed"},Zs=async(e,t=[])=>{let n=[],r=async a=>{let s=Er(a,"plugins","anyray","catalog.json");try{await JC(s),n.push(s)}catch{}};for(let a of t)await r(a);let o=[];try{o=(await jN(Er(e,"agents"),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name)}catch{}for(let a of o)await r(Er(e,"agents",a,"agent"));return n},Ol=async(e=An())=>{try{await YC(Er(e,qf),"utf8")}catch{return!1}return await JC(e,{recursive:!0,force:!0}),!0};var em="x-anyray-metadata",la="x-anyray-api-key",tm=["x-anyray-provider","x-anyray-auth-mode","x-anyray-custom-host"],co="Authorization",lo="anthropic-beta",_l="interleaved-thinking-2025-05-14",Pl=["anthropic","openai"],qC="short",om="anthropic-messages",am=32e3,Dl="anthropic/claude-sonnet-4-5",sm=["anthropic/claude-haiku-4-5"],im="anyray/claude-sonnet-4-5",cm=["anyray/claude-haiku-4-5"],ZN=[Dl,im],YN=[sm,cm],Xe="anyray",Ir="ANYRAY_API_KEY",Ys="openclaw",ca=()=>process.env.OPENCLAW_STATE_DIR?.trim()||Ll(rm(),".openclaw"),ia=()=>process.env.OPENCLAW_CONFIG_PATH?.trim()||Ll(ca(),"openclaw.json"),$=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zC=(e,t)=>{if(typeof e!="string")return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}},nm=e=>{if(!$(e))return{};let t=e.models;return!$(t)||!$(t.providers)?{}:t.providers},JN=e=>e==="~"||e.startsWith("~/")?Ll(rm(),e.slice(1)):e,Tl=e=>{if(!$(e))return[];let t=e.agents;if(!$(t)||!Array.isArray(t.list))return[];let n=[];for(let r of t.list){if(!$(r))continue;let o=typeof r.agentDir=="string"?r.agentDir.trim():"";o&&n.push(JN(o))}return n},XN=(e,t,n)=>{let r=t.clientKey??t.placeholderKey,o=me({...t.metadata,tool:Ys}),a=t.byoUpstream,s=[],i=[],c=!1,l={...e},d=[];"models"in l&&!$(l.models)&&d.push("models");let u=$(l.models)?{...l.models}:{};if("providers"in u&&!$(u.providers)&&d.push("models.providers"),d.length>0)return{next:e,routed:[],cacheRetentionSeeded:!1,betaPreserved:!1,headerConflicts:[],primarySeeded:!1,fallbacksSeeded:!1,unroutedFallbacks:[],structureConflicts:d,pluginConfigured:!1};let f=$(u.providers)?{...u.providers}:{},m=!1;if(n){let C=$(l.plugins)?{...l.plugins}:{},S=$(C.load)?{...C.load}:{},E=$(C.entries)?{...C.entries}:{},I=$(E[Xe])?{...E[Xe]}:{},_=$(I.config)?{...I.config}:{};if("plugins"in l&&!$(l.plugins)||"load"in C&&!$(C.load)||"paths"in S&&!Array.isArray(S.paths)||"entries"in C&&!$(C.entries)||Xe in E&&!$(E[Xe])||"config"in I&&!$(I.config)||"env"in l&&!$(l.env))d.push("plugins");else{let T=Array.isArray(S.paths)?[...S.paths]:[];T.includes(n)||T.push(n),S.paths=T,C.load=S,I.enabled=!0,_.gatewayUrl=t.anthropicBaseUrl,_.apiKey=r;let W=t.metadata.user,Q=t.metadata.team;W&&(_.user=W),Q&&(_.team=Q),I.config=_,E[Xe]=I,C.entries=E,l.plugins=C;let G=$(l.env)?{...l.env}:{};G[Ir]=r,l.env=G,m=!0}}let p=Pl.filter(C=>C!=="openai"||!te(t,"openai"));for(let C of p){if(C in f&&!$(f[C])){d.push(`models.providers.${C}`);continue}let S=$(f[C])?{...f[C]}:{};if("headers"in S&&!$(S.headers)){i.push(C);continue}let E=$(S.headers)?{...S.headers}:{};if(S.baseUrl=C==="anthropic"?t.anthropicBaseUrl:t.openaiBaseUrl,C==="anthropic"&&(S.api=om,(typeof S.maxTokens!="number"||S.maxTokens<=0)&&(S.maxTokens=am)),C==="anthropic"&&a)S.apiKey=a.key,E[co]=`Bearer ${a.key}`,E["x-anyray-provider"]="anthropic",E["x-anyray-auth-mode"]="passthrough",E["x-anyray-custom-host"]=a.url;else{S.apiKey=r,"x-anyray-custom-host"in E&&delete E[co];for(let I of tm)delete E[I]}E[la]=r,o&&(E[em]=o),C==="anthropic"&&(lo in E?c=E[lo]!==_l:E[lo]=_l),S.headers=E,f[C]=S,s.push(C)}u.providers=f,l.models=u;let h=!1,g=!1,y=!1,w,b=[],k="agents"in l&&!$(l.agents)||$(l.agents)&&"defaults"in l.agents&&!$(l.agents.defaults)||$(l.agents)&&$(l.agents.defaults)&&("params"in l.agents.defaults&&!$(l.agents.defaults.params)||"model"in l.agents.defaults&&!$(l.agents.defaults.model));if(k&&d.push("agents.defaults"),s.includes("anthropic")&&!k){let C=$(l.agents)?{...l.agents}:{},S=$(C.defaults)?{...C.defaults}:{},E=$(S.params)?{...S.params}:{};"cacheRetention"in E||(E.cacheRetention=qC,h=!0,S.params=E);let I=$(S.model)?{...S.model}:{},_=m?[...s,Xe]:s,T=W=>typeof W=="string"&&_.some(Q=>W.startsWith(`${Q}/`));typeof I.primary!="string"||I.primary.trim()===""?(I.primary=m?im:Dl,g=!0,S.model=I,"fallbacks"in I||(I.fallbacks=m?[...cm]:[...sm],y=!0)):T(I.primary)||(w=I.primary),b=(Array.isArray(I.fallbacks)?I.fallbacks:[]).filter(W=>typeof W=="string"&&!T(W)),(h||g)&&(C.defaults=S,l.agents=C)}return{next:l,routed:s,cacheRetentionSeeded:h,betaPreserved:c,headerConflicts:i,primarySeeded:g,fallbacksSeeded:y,unroutedPrimary:w,unroutedFallbacks:b,structureConflicts:d,pluginConfigured:m}},zN=["baseUrl","apiKey","api","maxTokens"],Qf=(e,t,n=Pl,r)=>{let o={...e},a=!("models"in o)||$(o.models)&&(!("providers"in o.models)||$(o.models.providers)),s=$(o.models)?{...o.models}:{},i=$(s.providers)?{...s.providers}:{},c=nm(t),l=!1;for(let u of a?n:[]){let f=i[u];if(!$(f))continue;let m={...f},p=$(m.headers)?{...m.headers}:{};if(!(t!==void 0||typeof p[la]=="string"||typeof p[em]=="string"||typeof m.apiKey=="string"&&m.apiKey.startsWith("ark_")||tm.some(C=>C in p)))continue;let g=$(c[u])?c[u]:{},y=$(g.headers)?g.headers:{},w="x-anyray-custom-host"in p,b=C=>C==="api"?m.api===om:C==="maxTokens"?m.maxTokens===am:C==="apiKey"?w||typeof m.apiKey=="string"&&m.apiKey.startsWith("ark_"):!0;for(let C of zN)b(C)&&(C in g?m[C]!==g[C]&&(m[C]=g[C],l=!0):C in m&&(delete m[C],l=!0));let k=[la,em,...tm,..."x-anyray-custom-host"in p?[co]:[]];p[lo]===_l&&k.push(lo);for(let C of k)C in y?p[C]!==y[C]&&(p[C]=y[C],l=!0):C in p&&(delete p[C],l=!0);co in y&&!(co in p)&&(p[co]=y[co],l=!0),Object.keys(p).length===0?delete m.headers:m.headers=p,Object.keys(m).length===0?delete i[u]:i[u]=m}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=$(o.plugins)?{...o.plugins}:{},f=$(u.load)?{...u.load}:{},m=$(u.entries)?{...u.entries}:{};if((!("plugins"in o)||$(o.plugins))&&(!("load"in u)||$(u.load))&&(!("paths"in f)||Array.isArray(f.paths))&&(!("entries"in u)||$(u.entries))){if(Array.isArray(f.paths)&&f.paths.includes(r)){let g=f.paths.filter(y=>y!==r);g.length===0?delete f.paths:f.paths=g,l=!0}let h=m[Xe];if($(h)){let g=$(h.config)?h.config:{};if(t!==void 0||typeof g.apiKey=="string"&&g.apiKey.startsWith("ark_")){let w=$(t?.plugins)?t.plugins:{},b=$(w.entries)?w.entries:{};Xe in b?JSON.stringify(m[Xe])!==JSON.stringify(b[Xe])&&(m[Xe]=b[Xe],l=!0):(delete m[Xe],l=!0)}}if(Object.keys(f).length===0?delete u.load:u.load=f,Object.keys(m).length===0?delete u.entries:u.entries=m,Object.keys(u).length===0?delete o.plugins:o.plugins=u,$(o.env)){let g={...o.env},y=g[Ir];if(typeof y=="string"&&y.startsWith("ark_")){let w=$(t?.env)?t.env:{};Ir in w?g[Ir]!==w[Ir]&&(g[Ir]=w[Ir],l=!0):(delete g[Ir],l=!0),Object.keys(g).length===0?delete o.env:o.env=g}}}}let d=!("agents"in o)||$(o.agents)&&(!("defaults"in o.agents)||$(o.agents.defaults)&&(!("params"in o.agents.defaults)||$(o.agents.defaults.params))&&(!("model"in o.agents.defaults)||$(o.agents.defaults.model)));if(t!==void 0&&n.includes("anthropic")&&d){let u=$(o.agents)?{...o.agents}:{},f=$(u.defaults)?{...u.defaults}:{},m=$(f.params)?{...f.params}:{},p=$(t.agents)?t.agents:{},h=$(p.defaults)?p.defaults:{},g=$(h.params)?h.params:{};m.cacheRetention===qC&&("cacheRetention"in g?m.cacheRetention!==g.cacheRetention&&(m.cacheRetention=g.cacheRetention,l=!0):(delete m.cacheRetention,l=!0));let y=$(f.model)?{...f.model}:{},w=$(h.model)?h.model:{};ZN.includes(y.primary)&&("primary"in w?y.primary!==w.primary&&(y.primary=w.primary,l=!0):(delete y.primary,l=!0)),YN.some(b=>JSON.stringify(y.fallbacks)===JSON.stringify(b))&&("fallbacks"in w?JSON.stringify(y.fallbacks)!==JSON.stringify(w.fallbacks)&&(y.fallbacks=w.fallbacks,l=!0):(delete y.fallbacks,l=!0)),Object.keys(y).length===0?delete f.model:f.model=y,Object.keys(m).length===0?delete f.params:f.params=m,Object.keys(f).length===0?delete u.defaults:u.defaults=f,Object.keys(u).length===0?delete o.agents:o.agents=u}return{next:o,removed:l}},QC={id:Ys,title:"OpenClaw",automatic:!0,async detect(){let e=await x(ia())||await x(ca());return{installed:e,detail:e?ia():`no ${Ll(rm(),".openclaw")} state dir`}},async apply(e,t){let n=ia();if(!e.byoUpstream&&te(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 ${Ys}\` if that is intended.`,"Agents on the claude-cli runtime already follow the machine's","Claude Code settings, which Connect manages separately."],E;try{E=await Ke(n)}catch{return{status:"held",messages:S}}let{next:I,removed:_}=Qf(E.data,await qo(n),Pl,An());return _?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 pn(n,E,I,!1),await ie(n),await Ol(),await Zs(ca(),Tl(I)),{status:"reverted",changedFiles:[n],messages:[`removed a stale Anyray route from ${n} \u2014 it routed OpenClaw on org API billing, which is not the lane in effect for this seat.`,...S]}):(t.dryRun||(await Ol(),await Zs(ca(),Tl(I))),{status:"held",messages:S})}let r=An(),o=!1;if(!t.dryRun)try{await XC(r)}catch{r=void 0,o=!0}let a;try{a=await Ke(n)}catch{return{status:"manual",messages:[`Couldn't parse ${n}; left it untouched. Under "models.providers", add:`,` "anthropic": { "baseUrl": ${JSON.stringify(e.anthropicBaseUrl)}, "api": "${om}", "maxTokens": ${am}, "apiKey": "<your personal ark_ key>", "headers": { "${la}": "<your personal ark_ key>", "${lo}": "${_l}" } }`,` "openai": { "baseUrl": ${JSON.stringify(e.openaiBaseUrl)}, "apiKey": "<your personal ark_ key>", "headers": { "${la}": "<your personal ark_ key>" } }`,`Set "agents.defaults.model.primary" to a routed model (e.g. "${Dl}") if none is set,`,'and under "agents.defaults.params" set "cacheRetention": "short" \u2014',"custom Anthropic-compatible hosts get no prompt-cache auto-seed, and","an unset value would leave the provider cache permanently cold.","Then run `openclaw config validate`."]}}let{next:s,routed:i,cacheRetentionSeeded:c,betaPreserved:l,headerConflicts:d,primarySeeded:u,fallbacksSeeded:f,unroutedPrimary:m,unroutedFallbacks:p,structureConflicts:h,pluginConfigured:g}=XN(a.data,e,r),y=s,w=!1;if(!i.includes("openai")){let S=Qf(y,await qo(n),["openai"]);S.removed&&(y=S.next,w=!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: ${me({...e.metadata,tool:Ys})??"(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 ${lo} 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 = ${g?im:Dl} (none was set; routing is inert until the primary resolves to a routed provider).`,...f?[`Seeded agents.defaults.model.fallbacks = [${(g?cm:sm).join(", ")}] so failover stays on a routed provider.`]:[]]:[],...m!==void 0?[`Your primary model (${m}) 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.`]:[],...p.length>0?[`Fallback model(s) ${p.join(", ")} resolve to unrouted providers: a failover would bypass the gateway. Your settings were kept.`]:[],...w?["Removed the earlier Anyray route from models.providers.openai \u2014 your ChatGPT sign-in keeps that lane native now."]:[],...g?[`${t.dryRun?"Would install":"Installed"} the Anyray OpenClaw plugin (${An()}) and registered it under plugins.entries.${Xe}: anyray/* models get per-conversation optimization sessions. Restart the OpenClaw gateway once to load it.`]:[],...o?[`Could not write the Anyray OpenClaw plugin to ${An()}; 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 pn(n,a,y,!0);return g&&await Zs(ca(),Tl(y)),{status:k,messages:b,changedFiles:C?[n]:[]}},async pointsAt(e){try{let{data:t}=await Ke(ia());for(let a of Object.values(nm(t)))if($(a)&&zC(a.baseUrl,e))return!0;let n=$(t.plugins)?t.plugins:{},o=($(n.entries)?n.entries:{})[Xe];if($(o)&&$(o.config)&&zC(o.config.gatewayUrl,e))return!0}catch{}return!1},async routingExpected(e){return e.includes(Ys)},async inferenceAuthLanes(){let e=new Set;try{let{data:t}=await Ke(ia());for(let a of Object.values(nm(t))){if(!$(a))continue;let s=$(a.headers)?a.headers:{};typeof s["x-anyray-custom-host"]=="string"?e.add("byo"):(typeof s[la]=="string"||typeof a.apiKey=="string"&&a.apiKey.startsWith("ark_"))&&e.add("api_key")}let n=$(t.plugins)?t.plugins:{},o=($(n.entries)?n.entries:{})[Xe];if($(o)&&$(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=ia();if(!await x(t))return{status:"not-found",messages:["nothing to revert"]};if(e.dryRun)return{status:"reverted",messages:[`would remove Anyray provider settings from ${t}`]};let n;try{n=await Ke(t)}catch{return{status:"manual",messages:[`Couldn't parse ${t} \u2014 if you added Anyray settings there by hand, remove baseUrl/apiKey and the x-anyray-* headers from models.providers.anthropic and models.providers.openai yourself.`]}}let{next:r,removed:o}=Qf(n.data,await qo(t),Pl,An()),a=await Ol();return await Zs(ca(),Tl(r)),o?(await pn(t,n,r,!1),await ie(t),{status:"reverted",messages:[`removed Anyray provider settings from ${t}`,...a?[`removed the Anyray OpenClaw plugin from ${An()}`]:[]],changedFiles:[t]}):(await ie(t),{status:"reverted",messages:["no Anyray provider settings found",...a?[`removed the Anyray OpenClaw plugin from ${An()}`]:[]]})}};import{execFile as HB}from"node:child_process";import{readFile as GB}from"node:fs/promises";import{homedir as fi,platform as Tr}from"node:os";import{join as Sn}from"node:path";import{isDeepStrictEqual as Ym,promisify as VB}from"node:util";var Js=e=>{if(!/^\d+(?:\.\d+)+$/.test(e))return;let t=e.split(".").map(Number);return t.every(Number.isSafeInteger)?t:void 0},Nl=(e,t)=>{let n=Js(e),r=Js(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 aB}from"node:crypto";import{promises as uv}from"node:fs";import{platform as sB,tmpdir as iB}from"node:os";import{join as Ql}from"node:path";import{execFile as qN}from"node:child_process";import{promises as Xs}from"node:fs";import{homedir as QN,platform as e$}from"node:os";import{delimiter as t$,join as $l}from"node:path";import{promisify as n$}from"node:util";var r$=n$(qN),o$=15*6e4,a$=64*1024*1024,s$=e=>e==="win32"?[".exe",".cmd",".bat"]:[""],ek=async(e={})=>{let t=(e.home??QN)(),n=e.env??process.env,r=s$(e.runtimePlatform??e$()),o=[$l(t,".local","bin"),$l(t,".claude","local"),...(n.PATH??"").split(t$).filter(a=>a.length>0)];for(let a of o)for(let s of r){let i=$l(a,`claude${s}`);try{return await Xs.access(i),i}catch{}}return null},i$=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},c$=async e=>{let t=$l(e,"projects"),n;try{n=(await Xs.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(!u$.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},l$=e=>{if(!e||!e.startsWith("{"))return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t,r=n.sessionIds,o=n.jsonlPaths;if(!Array.isArray(r)||!Array.isArray(o))return null;let a=Array.isArray(n.titles)?n.titles:[],s=Array.isArray(n.createdAts)?n.createdAts:[],i=Array.isArray(n.updatedAts)?n.updatedAts:[],c=d=>typeof d=="number"&&Number.isFinite(d)?d:void 0,l=[];for(let d=0;d<r.length;d+=1){let u=r[d],f=o[d];if(typeof u!="string"||typeof f!="string"||u.length===0||f.length===0)continue;let m=a[d];l.push({sessionId:u,transcriptPath:f,title:typeof m=="string"&&m.length>0?m:"Imported conversation",createdAt:c(s[d]),lastActivityAt:c(i[d])})}return{conversations:l,projects:i$(n.projectList)}},d$=async e=>{let t,n;try{let r=await Xs.readFile(e,"utf8");for(let o of r.split(`
|
|
171
|
+
`)){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}},u$=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,p$=/\.(?:cmd|bat)$/i,f$=(e,t)=>p$.test(e)?{file:"cmd.exe",args:["/d","/s","/c",`"${[e,...t].map(r=>`"${r}"`).join(" ")}"`],verbatim:!0}:{file:e,args:[...t],verbatim:!1},tk=async(e,t={})=>{let n=t.exec??r$,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 Xs.mkdir(e.configDir,{recursive:!0,mode:448}),await Xs.mkdir(e.workDir,{recursive:!0,mode:448});let o=f$(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:o$,maxBuffer:a$,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(`
|
|
172
|
+
`).filter(d=>d.trim().length>0),i=l$(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 d$(d.transcriptPath);return{...d,...u}})),l=i.projects.length>0?i.projects:await c$(e.workDir);return{ok:!0,conversations:c,projects:l}};import{randomUUID as m$}from"node:crypto";import{promises as Gn}from"node:fs";import{homedir as h$,platform as y$}from"node:os";import{join as kt}from"node:path";var nk=448,Vn="local_",g$="local-agent-mode-sessions",lm="-3p",w$="cowork_account_settings.json",uo=(e={})=>{let t=(e.home??h$)(),n=e.runtimePlatform??y$(),r=e.env??process.env;if(n==="darwin")return kt(t,"Library","Application Support",`Claude${lm}`);if(n==="win32"){let o=r.LOCALAPPDATA??kt(t,"AppData","Local");return kt(o,`Claude${lm}`)}return null},zs=(e={})=>{let t=uo(e);return t?t.slice(0,-lm.length):null},dm=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)}`},Ml=async e=>{let t=kt(e,g$),n;try{n=(await Gn.readdir(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return{ok:!1,reason:"no-profile",found:[]}}let r=[];for(let o of n){let a;try{a=(await Gn.readdir(kt(t,o),{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{continue}for(let s of a){let i=kt(t,o,s);try{await Gn.access(kt(i,w$)),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]}},um=async e=>{try{let t=await Gn.readdir(e);return new Set(t.filter(n=>n.startsWith(Vn)&&n.endsWith(".json")).map(n=>n.slice(Vn.length,-5)))}catch{return new Set}},da=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),b$=async(e,t)=>{let n=`${Vn}${t.sessionId}`,r=kt(e,n),o=kt(r,"outputs"),a=kt(r,".claude"),s=kt(a,"projects",dm(o));await Gn.mkdir(o,{recursive:!0,mode:nk}),await Gn.mkdir(s,{recursive:!0,mode:nk});let i=kt(s,`${t.sessionId}.jsonl`),c=`${i}.anyray-tmp-${process.pid}-${m$()}`;await Gn.copyFile(t.transcriptPath,c),await Gn.chmod(c,384),await Gn.rename(c,i);let l=t.createdAt??Date.now();await X(kt(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})},rk=async(e,t)=>{let n=await um(e),r={registered:0,skipped:0,failed:0};for(let o of t){if(!da(o.sessionId)){r.failed+=1;continue}if(n.has(o.sessionId)){r.skipped+=1;continue}try{await b$(e,o),n.add(o.sessionId),r.registered+=1}catch{r.failed+=1}}return r};import{promises as ua}from"node:fs";import{homedir as A$}from"node:os";import{dirname as C$,join as qs}from"node:path";var k$=448,v$=["Documents","Claude","Projects"],S$="spaces.json",E$=(e={})=>qs((e.home??A$)(),...v$),I$=async e=>{try{let t=JSON.parse(await ua.readFile(e,"utf8"));if(!t||typeof t!="object")return{spaces:[],readable:!1};let n=t.spaces;return Array.isArray(n)?{spaces:n.filter(r=>!!r&&typeof r=="object"&&typeof r.id=="string"),readable:!0}:{spaces:[],readable:!1}}catch(t){return t.code==="ENOENT"?{spaces:[],readable:!0}:{spaces:[],readable:!1}}},x$=e=>{let t=e.replace(/[/\\:*?"<>|\x00-\x1f]/g," ").replace(/\s+/g," ").replace(/^[.\s]+/,"").slice(0,60).trim();return t.length>0?t:"Project"},pm=async e=>{try{return await ua.access(e),!0}catch{return!1}},R$=async(e,t,n)=>{let r=qs(t,x$(n.name)),o=`${r} (${n.uuid.slice(0,8)})`,a=await pm(r)?o:r;return a===o&&await pm(o)?null:(await ua.mkdir(C$(a),{recursive:!0}),await ua.cp(e,a,{recursive:!0}),a)},O$=async e=>{try{let t=(await ua.readFile(qs(e,"CLAUDE.md"),"utf8")).trim();return t.length>0?t:void 0}catch{return}},ok=async e=>{let t=E$({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=qs(e.storageDir,S$),{spaces:a,readable:s}=await I$(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=qs(e.stagedProjectsDir,l.dirName);try{if(!await pm(d)){n.failed+=1;continue}let u=await R$(d,t,l);if(!u){n.skippedCollision+=1;continue}let f=await O$(u);c.push({id:l.uuid,name:l.name,folders:[{path:u}],projects:[],links:[],...f?{instructions:f}:{},origin:"user",createdAt:e.now,updatedAt:e.now}),n.imported+=1}catch{n.failed+=1}}return c.length>0&&(await ua.mkdir(e.storageDir,{recursive:!0,mode:k$}),await X(o,{spaces:[...a,...c]},{backup:!1})),n};import{randomUUID as D$}from"node:crypto";import{execFile as L$,spawnSync as hk}from"node:child_process";import{constants as yk}from"node:fs";import{access as Gl,chmod as N$,mkdir as $$,readdir as M$,readFile as mm,rename as B$,rm as pa,stat as gk,writeFile as F$}from"node:fs/promises";import{homedir as W$,platform as U$,userInfo as H$}from"node:os";import{basename as G$,dirname as wk,isAbsolute as fa,join as $t,resolve as lk}from"node:path";import{isDeepStrictEqual as ei,promisify as V$}from"node:util";var xr="__anyray-claude-desktop-credential",Qs="__anyray-claude-desktop-bootstrap-headers";var Bl=(e="anyray-connect migrate")=>["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: \`${e} --export <file.zip>\`.`],Fl=["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."],ak=(e="anyray-connect migrate",t="anyray-connect desktop")=>`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 \`${e} --export <file.zip>\`, and \`${t} disconnect\` restores the first-party profile.`;var Wl=["disableAutoUpdates","autoUpdaterEnforcementHours","disableWslSessions"],sk=["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"],T$=new Set(sk),_$=new Set(sk.map(e=>e.toLowerCase())),P$=new Set(Wl.map(e=>e.toLowerCase())),Ul=(e,t=!1)=>(t?_$:T$).has(t?e.toLowerCase():e),ik=(e,t=!1)=>t?P$.has(e.toLowerCase()):Wl.some(n=>n===e),ck=["*"],po=(e,t)=>({inferenceProvider:"gateway",inferenceGatewayBaseUrl:e.anthropicBaseUrl,inferenceGatewayAuthScheme:"bearer",inferenceCredentialKind:"helper-script",inferenceCredentialHelper:t,chatTabEnabled:!0,coworkEgressAllowedHosts:[...ck]}),Rr=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,typeof n=="object"?JSON.stringify(n):String(n)]));var ti=/^[a-f0-9-]{36}$/,bk="Anyray",hm=4,oi=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts","inferenceGatewayApiKey"],ai=["deploymentMode","awaitingSignIn"],K$=["inferenceGatewayApiKey","awaitingSignIn"],Ak=[...[...oi,...ai].filter(e=>!K$.includes(e)),"configLibrary","_meta.json"],Cn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),it=e=>structuredClone(e),ni=async e=>{try{return await Gl(e),!0}catch{return!1}},j$=async e=>{try{let t=await M$(wk(e)),n=G$(e).toLowerCase();return t.some(r=>r.toLowerCase()===n)?"unreadable":"absent"}catch{return"unreadable"}},Z$=async e=>{try{return await Gl(e),"present"}catch(t){return(t instanceof Error&&"code"in t?t.code:void 0)==="ENOENT"?"absent":j$(e)}},zt=(e={})=>{let t=(e.home??W$)(),n=(e.username??(()=>H$().username))(),r=$t(t,"Library","Application Support","Claude-3p"),o=e.managedPolicyPaths?e.managedPolicyPaths():["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",$t("/Library/Managed Preferences",n,"com.anthropic.claudefordesktop.plist")];return{root:r,library:$t(r,"configLibrary"),meta:$t(r,"configLibrary","_meta.json"),appConfig:$t(r,"claude_desktop_config.json"),helper:$t(t,".anyray","bin","claude-desktop-credential-helper"),journal:$t(t,".anyray","claude-desktop-native.json"),managedPolicies:o}},Vl=()=>{let e=hk("pgrep",["-x","Claude"],{stdio:"ignore",timeout:2e3,windowsHide:!0});return!!e.error||e.status!==1},Ck=e=>["print-key",e==="passthrough"?"--passthrough-headers":"--json"],Y$=(e,t)=>{let n=e.args.lastIndexOf("print-key"),r=n>=0?e.args.slice(0,n):e.args;return{...e,args:[...r,...Ck(t)]}},ym=(e="json")=>{let t=an(Ck(e)),n=lk(t.command),r=lk(t.entryPath),o=/[\\/](node|node\.exe)$/i.test(n);return{command:n,args:o&&r!==n?[r,...t.args.slice(1)]:t.args,durable:oe()&&(!o||r!==n)}},J$=e=>`'${e.replace(/'/g,`'"'"'`)}'`,gm=e=>[e.command,...e.args].map(J$).join(" "),X$=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!fa(e.command))throw new Error("the credential helper executable is not absolute")},kk=(e,t)=>{X$(e);let n=Kl(e.command);if(e.args.at(-2)!=="print-key"||e.args.at(-1)!==t||(n?e.args.length!==3||!fa(e.args[0]):e.args.length!==2))throw new Error(`the credential helper does not use print-key ${t}`)},vk=e=>(kk(e,"--json"),`#!/bin/sh
|
|
173
173
|
exec ${gm(e)}
|
|
174
|
-
`),
|
|
174
|
+
`),z$=`#!/bin/sh
|
|
175
175
|
# Anyray subscription pass-through credential helper v2 for Claude Desktop`,Sk=e=>{kk(e,"--passthrough-headers");let t={...e,args:[...e.args.slice(0,-2),xr]};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 ${gm(t)}`,""].join(`
|
|
176
|
-
`)},
|
|
176
|
+
`)},q$=e=>e.args.at(-1)==="--passthrough-headers"?Sk(e):vk(e),Kl=e=>/[\\/](node|node\.exe)$/i.test(e),wm=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++}},Q$=e=>{let t=`#!/bin/sh
|
|
177
177
|
exec `;if(!e.startsWith(t)||!e.endsWith(`
|
|
178
178
|
`))return;let n=e.slice(t.length,-1);if(n.includes(`
|
|
179
|
-
`)||n.includes("\r"))return;let r=wm(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Kl(o);if(!fa(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!fa(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return vk(i)===e?i:void 0}catch{return}},
|
|
180
|
-
# Anyray subscription pass-through credential helper`,
|
|
181
|
-
`)},
|
|
182
|
-
`,384)},kn=async e=>{if(!await ni(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await mm(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!Cn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},si=async e=>{if(!await ni(e))return{present:!1};let t=await gk(e);return{present:!0,content:await mm(e,"utf-8"),mode:t.mode&511}},Ik=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:it(e[t])}:{present:!1},fm=(e,t,n)=>{n.present?e[t]=it(n.value):delete e[t]},dk=e=>Cn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),
|
|
183
|
-
`,384)},ri=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!ti.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(!Cn(o)||typeof o.id!="string"||!ti.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},mM=async(e,t,n)=>{let r=await kn(e.meta);if(t){if(!r.present){if(t.metaFileExisted)throw new Error("Claude config-library metadata disappeared after apply");return{configId:t.configId,meta:r,metaFileExisted:!1,metaEntry:it(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[it(t.metaEntry)]}}}let c=ri(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!ei(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=ri(r.value);let c=$t(e.library,`${o}.json`);if(!await ni(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=it(r.value.entries)}let s=n();if(!ti.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await ni($t(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:bk};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?it(r.value):{},appliedId:s,entries:[...a,i]}}},hM=(e,t)=>{let n=po(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},xk=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),yM=async(e,t,n,r,o,a,s)=>{let i=xk(),c=Object.fromEntries(oi.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(ai.map(d=>[d,{original:s?.deployment[d].original??Ik(r.value,d),lastWritten:i[d]}]));return{version:hm,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 si(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Hl=e=>({status:"manual",messages:[e]}),gM=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}`)]}},wM=G$(D$),bM=new Set(Wl),AM=async e=>{try{let{stdout:t}=await wM("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return Cn(n)?Object.keys(n):void 0}catch{return}},fo=async(e,t={})=>{let n=t.readManagedPolicyKeys??AM;for(let r of e.managedPolicies){let o=await j$(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=>Ul(i)&&!bM.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},Cm=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.`},km=e=>(e.platform??W$)()==="darwin",Rk=async(e,t,n={})=>{if(!km(n))return Hl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Vl)()&&r.push({audience:"user",message:"Claude Desktop is running. Fully quit it, then re-run connect so its cached state cannot overwrite the change."});let o=zt(n),a=await fo(o,n);if(a&&r.push({audience:"admin",message:Cm(a)}),r.length>0)return gM(r);let s=!1,i=!1,c=[o.journal];try{let l=te(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??rM)())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=Z$((n.credentialCommand??(()=>ym(d)))(),d),f=z$(u),m=await Am(o),p=await si(o.helper);if(m&&p.present&&p.content!==m.helper.lastWritten&&p.content!==m.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!m&&p.present&&p.content!==f)throw new Error("the Claude Desktop credential helper path contains a foreign file");let h=await mM(o,m,n.randomUUID??P$),w=$t(o.library,`${h.configId}.json`);c=[o.journal,o.helper,w,...h.metaToWrite?[o.meta]:[],o.appConfig];let y=await kn(w),g=await kn(o.appConfig),b=hM(e,o.helper),k=await yM(o,h,y,g,f,b,m);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 fk(o.journal,k),i=!0,await jl(o.helper,f,448),k.helper.previousWritten!==void 0&&(delete k.helper.previousWritten,await fk(o.journal,k));let C=it(y.value);for(let I of oi)fm(C,I,b[I]);await Kn(w,C),h.metaToWrite&&await Kn(o.meta,h.metaToWrite);let S=it(g.value),E=xk();for(let I of ai)fm(S,I,E[I]);return await Kn(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.",...Bl(gt("migrate"))]}}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.`]}:Hl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},mk=(e,t,n,r)=>{let o=it(e);for(let a of n){let s=t[a];ei(Ik(e,a),s.lastWritten)?fm(o,a,s.original):r.push(a)}return o},Ok=async(e,t={})=>{if(!km(t))return{status:"not-found",messages:[]};if((t.appRunning??Vl)())return Hl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=zt(t);try{let r=await Am(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=$t(n.library,`${r.configId}.json`);if(e.dryRun)return{status:"reverted",messages:[`Would restore Anyray-owned Claude Desktop fields from ${n.journal}, preserving user changes.`]};let a=[],s=await kn(o),i=s.value;s.present&&(i=mk(s.value,r.config,oi,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await kn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let p=ri(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&&ei(y,r.metaEntry);if(y!==void 0&&!g&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=it(l.value),p===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=ei(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&p!==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 pa(o,{force:!0}):await Kn(o,i)),l.present&&(u?await pa(n.meta,{force:!0}):ei(l.value,d)||await Kn(n.meta,d));let f=await kn(n.appConfig);if(f.present){let p=mk(f.value,r.deployment,ai,a);!r.deploymentFileExisted&&Object.keys(p).length===0?await pa(n.appConfig,{force:!0}):await Kn(n.appConfig,p)}else r.deploymentFileExisted&&a.push("deployment config file");let m=await si(n.helper);return m.present&&(m.content===r.helper.lastWritten||m.content===r.helper.previousWritten)?r.helper.original.present?await jl(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await pa(n.helper,{force:!0}):(m.present||r.helper.original.present)&&a.push("credential helper"),await pa(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?[]:Fl]}}catch(r){return Hl(`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.`)}},vm=async(e,t={})=>{if(!km(t))return!1;let n=zt(t);if(await fo(n,t))return!1;try{let r=await kn(n.meta);if(!r.present)return!1;let o=ri(r.value),a=await kn($t(n.library,`${o}.json`)),s=await kn(n.appConfig);if(!a.present||!s.present)return!1;await Gl(n.helper,yk.X_OK);let i=Kt(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}},Tk=async(e={})=>{try{let t=zt(e),n=await si(t.helper);if(!n.present||typeof n.content!="string")return;let r=Ek(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},_k=async(e,t={})=>{if(!await vm(e,t))return!1;let n=zt(t);try{let r=await Am(n);if(!r)return!1;let o=await kn(n.meta);if(!o.present||ri(o.value)!==r.configId)return!1;let a=await si(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=Ek(a.content??"");return s?await(t.helperLauncherAvailable??oM)(s):!1}catch{return!1}};import{createHash as Zk,randomUUID as Yk}from"node:crypto";import{spawn as CM,spawnSync as kM}from"node:child_process";import{link as Tm,mkdir as Sm,open as Jk,readFile as Em,readdir as Xk,rename as zk,rm as qt,stat as qk}from"node:fs/promises";import{homedir as _m}from"node:os";import{basename as Qk,dirname as ci,join as Aa,win32 as vM}from"node:path";import{isDeepStrictEqual as ma}from"node:util";var Le="HKCU\\SOFTWARE\\Policies\\Claude",ii="HKLM\\SOFTWARE\\Policies\\Claude",Xl=5,Ca="inferenceGatewayApiKey",$e=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",Ca],Pk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",Ca],Dk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",Ca],Lk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",Ca],ev="Managed by anyray-connect; dynamic credential only.",SM=e=>/^[A-Za-z]:[\\/]/.test(e)&&vM.isAbsolute(e),Nk=e=>{if(!SM(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)},tv=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!Nk(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&&!Nk(e.args[0]))throw new Error("the credential helper does not use print-key --json")},Pm=(e={})=>Aa((e.home??_m)(),".anyray","bin","claude-desktop-credential-helper.cmd"),EM=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},IM=e=>(tv(e),["@echo off",`REM ${ev}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(EM).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
184
|
-
`)),
|
|
185
|
-
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${ev}`||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(
|
|
179
|
+
`)||n.includes("\r"))return;let r=wm(n);if(!r||r.length!==3&&r.length!==4)return;let[o,...a]=r,s=Kl(o);if(!fa(o)||a.at(-2)!=="print-key"||a.at(-1)!=="--json"||(s?a.length!==3||!fa(a[0]):a.length!==2))return;let i={command:o,args:a,durable:!0};try{return vk(i)===e?i:void 0}catch{return}},eM=e=>{if(!e.startsWith(z$))return;let t=e.match(/^exec (.*)$/m);if(!t)return;let n=wm(t[1]);if(!n)return;let[r,...o]=n;if(o.at(-1)!==xr)return;let a={command:r,args:[...o.slice(0,-1),"print-key","--passthrough-headers"],durable:!0};try{return Sk(a)===e?a:void 0}catch{return}},tM=`#!/bin/sh
|
|
180
|
+
# Anyray subscription pass-through credential helper`,nM=e=>{let t=Kl(e.command);if(!(!fa(e.command)||e.args.at(-2)!=="print-key"||e.args.at(-1)!=="--passthrough-headers"||(t?e.args.length!==3||!fa(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=$(${gm(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(`
|
|
181
|
+
`)},rM=e=>{if(!e.startsWith(tM))return;let t=e.match(/^headers=\$\((.*)\)$/m);if(!t)return;let n=wm(t[1]);if(!n)return;let[r,...o]=n,a={command:r,args:o,durable:!0};return nM(a)===e?a:void 0},Ek=e=>Q$(e)??eM(e)??rM(e),oM=async()=>{let e=hk("/usr/bin/security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:3e3});return!e.error&&e.status===0},aM=async e=>{let t=[e.command,...Kl(e.command)?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>gk(r)))).every(r=>r.isFile())?(await Gl(e.command,yk.X_OK),!0):!1}catch{return!1}},sM=0,jl=async(e,t,n)=>{await $$(wk(e),{recursive:!0,mode:448});let r=`${e}.anyray-${process.pid}-${sM++}.tmp`;try{await F$(r,t,{mode:n}),await N$(r,n),await B$(r,e)}catch(o){throw await pa(r,{force:!0}).catch(()=>{}),o}},Kn=async(e,t)=>{await jl(e,`${JSON.stringify(t,null,2)}
|
|
182
|
+
`,384)},kn=async e=>{if(!await ni(e))return{present:!1,value:{}};let t;try{t=JSON.parse(await mm(e,"utf-8"))}catch{throw new Error(`${e} is not valid JSON`)}if(!Cn(t))throw new Error(`${e} is not a JSON object`);return{present:!0,value:t}},si=async e=>{if(!await ni(e))return{present:!1};let t=await gk(e);return{present:!0,content:await mm(e,"utf-8"),mode:t.mode&511}},Ik=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?{present:!0,value:it(e[t])}:{present:!1},fm=(e,t,n)=>{n.present?e[t]=it(n.value):delete e[t]},dk=e=>Cn(e)&&typeof e.present=="boolean"&&(!e.present||Object.prototype.hasOwnProperty.call(e,"value")),iM=e=>Cn(e)&&dk(e.original)&&dk(e.lastWritten),cM=e=>Cn(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),uk=(e,t)=>Cn(e)&&t.every(n=>iM(e[n])),lM=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","inferenceGatewayApiKey"],dM=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","inferenceGatewayApiKey"],bm=(e,t,n,r)=>!(!Cn(e)||e.version!==n||typeof e.configId!="string"||!ti.test(e.configId)||typeof e.metaFileExisted!="boolean"||e.originalAppliedId!==void 0&&(typeof e.originalAppliedId!="string"||!ti.test(e.originalAppliedId))||e.metaFileExisted!==(e.originalAppliedId!==void 0)||!Cn(e.metaEntry)||e.metaEntry.id!==e.configId||e.metaEntry.name!==bk||Object.keys(e.metaEntry).length!==2||typeof e.configFileExisted!="boolean"||e.configFileExisted||typeof e.deploymentFileExisted!="boolean"||!uk(e.config,r)||r.some(o=>e.config[o].original.present)||!uk(e.deployment,ai)||!Cn(e.helper)||e.helper.path!==t.helper||!cM(e.helper.original)||typeof e.helper.lastWritten!="string"||e.helper.previousWritten!==void 0&&typeof e.helper.previousWritten!="string"),uM=(e,t)=>bm(e,t,hm,oi),pM=(e,t)=>bm(e,t,2,lM),fM=(e,t)=>bm(e,t,3,dM),mM=e=>({...e,version:3,config:{...e.config,chatTabEnabled:{original:{present:!1},lastWritten:{present:!1}}}}),pk=e=>({...e,version:hm,config:{...e.config,coworkEgressAllowedHosts:{original:{present:!1},lastWritten:{present:!1}}}}),Am=async e=>{if(!await ni(e.journal))return;let t;try{t=JSON.parse(await mm(e.journal,"utf-8"))}catch{throw new Error(`${e.journal} is not valid JSON`)}if(uM(t,e))return t;if(fM(t,e))return pk(t);if(pM(t,e))return pk(mM(t));throw new Error(`${e.journal} is not a valid ownership journal`)},fk=async(e,t)=>{await jl(e,`${JSON.stringify(t,null,2)}
|
|
183
|
+
`,384)},ri=e=>{let{appliedId:t,entries:n}=e;if(typeof t!="string"||!ti.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(!Cn(o)||typeof o.id!="string"||!ti.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},hM=async(e,t,n)=>{let r=await kn(e.meta);if(t){if(!r.present){if(t.metaFileExisted)throw new Error("Claude config-library metadata disappeared after apply");return{configId:t.configId,meta:r,metaFileExisted:!1,metaEntry:it(t.metaEntry),metaToWrite:{appliedId:t.configId,entries:[it(t.metaEntry)]}}}let c=ri(r.value),d=r.value.entries.find(u=>u.id===t.configId);if(!d||!ei(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=ri(r.value);let c=$t(e.library,`${o}.json`);if(!await ni(c))throw new Error(`Claude's applied configuration ${o} is missing`);a=it(r.value.entries)}let s=n();if(!ti.test(s))throw new Error("could not create a valid config id");if(a.some(c=>c.id===s)||await ni($t(e.library,`${s}.json`)))throw new Error("could not create a unique Anyray config id");let i={id:s,name:bk};return{configId:s,meta:r,metaFileExisted:r.present,originalAppliedId:o,metaEntry:i,metaToWrite:{...r.present?it(r.value):{},appliedId:s,entries:[...a,i]}}},yM=(e,t)=>{let n=po(e,t);return{...Object.fromEntries(Object.entries(n).map(([r,o])=>[r,{present:!0,value:o}])),inferenceGatewayApiKey:{present:!1}}},xk=()=>({deploymentMode:{present:!0,value:"3p"},awaitingSignIn:{present:!1}}),gM=async(e,t,n,r,o,a,s)=>{let i=xk(),c=Object.fromEntries(oi.map(d=>[d,{original:s?.config[d].original??{present:!1},lastWritten:a[d]}])),l=Object.fromEntries(ai.map(d=>[d,{original:s?.deployment[d].original??Ik(r.value,d),lastWritten:i[d]}]));return{version:hm,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 si(e.helper),lastWritten:o,...s?.helper.previousWritten!==void 0?{previousWritten:s.helper.previousWritten}:s&&s.helper.lastWritten!==o?{previousWritten:s.helper.lastWritten}:{}}}},Hl=e=>({status:"manual",messages:[e]}),wM=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}`)]}},bM=V$(L$),AM=new Set(Wl),CM=async e=>{try{let{stdout:t}=await bM("/usr/bin/plutil",["-convert","json","-o","-",e],{timeout:2e3,maxBuffer:262144}),n=JSON.parse(t);return Cn(n)?Object.keys(n):void 0}catch{return}},fo=async(e,t={})=>{let n=t.readManagedPolicyKeys??CM;for(let r of e.managedPolicies){let o=await Z$(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=>Ul(i)&&!AM.has(i));if(s.length>0)return{path:r,keys:s,unreadable:!1}}},Cm=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.`},km=e=>(e.platform??U$)()==="darwin",Rk=async(e,t,n={})=>{if(!km(n))return Hl("Automatic Claude Desktop local setup is available on macOS.");let r=[];(n.appRunning??Vl)()&&r.push({audience:"user",message:"Claude Desktop is running. Fully quit it, then re-run connect so its cached state cannot overwrite the change."});let o=zt(n),a=await fo(o,n);if(a&&r.push({audience:"admin",message:Cm(a)}),r.length>0)return wM(r);let s=!1,i=!1,c=[o.journal];try{let l=te(e,"anthropic");if(l&&!await(n.subscriptionCredentialAvailable??oM)())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=Y$((n.credentialCommand??(()=>ym(d)))(),d),f=q$(u),m=await Am(o),p=await si(o.helper);if(m&&p.present&&p.content!==m.helper.lastWritten&&p.content!==m.helper.previousWritten)throw new Error("Claude Desktop credential helper changed after Connect configured it");if(!m&&p.present&&p.content!==f)throw new Error("the Claude Desktop credential helper path contains a foreign file");let h=await hM(o,m,n.randomUUID??D$),g=$t(o.library,`${h.configId}.json`);c=[o.journal,o.helper,g,...h.metaToWrite?[o.meta]:[],o.appConfig];let y=await kn(g),w=await kn(o.appConfig),b=yM(e,o.helper),k=await gM(o,h,y,w,f,b,m);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 fk(o.journal,k),i=!0,await jl(o.helper,f,448),k.helper.previousWritten!==void 0&&(delete k.helper.previousWritten,await fk(o.journal,k));let C=it(y.value);for(let I of oi)fm(C,I,b[I]);await Kn(g,C),h.metaToWrite&&await Kn(o.meta,h.metaToWrite);let S=it(w.value),E=xk();for(let I of ai)fm(S,I,E[I]);return await Kn(o.appConfig,S),{status:"configured",changedFiles:[o.journal,o.helper,g,...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.",...Bl(gt("migrate"))]}}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.`]}:Hl(`Could not safely configure Claude Desktop (${d}). Claude Desktop configuration was unchanged.`)}},mk=(e,t,n,r)=>{let o=it(e);for(let a of n){let s=t[a];ei(Ik(e,a),s.lastWritten)?fm(o,a,s.original):r.push(a)}return o},Ok=async(e,t={})=>{if(!km(t))return{status:"not-found",messages:[]};if((t.appRunning??Vl)())return Hl("Claude Desktop is running. Fully quit it, then re-run --revert.");let n=zt(t);try{let r=await Am(n);if(!r)return{status:"not-found",messages:["No native Claude Desktop setup to revert."]};let o=$t(n.library,`${r.configId}.json`);if(e.dryRun)return{status:"reverted",messages:[`Would restore Anyray-owned Claude Desktop fields from ${n.journal}, preserving user changes.`]};let a=[],s=await kn(o),i=s.value;s.present&&(i=mk(s.value,r.config,oi,a));let c=!r.configFileExisted&&Object.keys(i).length===0,l=await kn(n.meta),d=l.value,u=!1;if(!l.present)r.metaFileExisted&&(a.push("config-library metadata"),c=!1);else{let p=ri(l.value),h=it(l.value.entries),g=h.findIndex(b=>b.id===r.configId),y=g>=0?h[g]:void 0,w=y!==void 0&&ei(y,r.metaEntry);if(y!==void 0&&!w&&(a.push("Anyray config-library entry"),c=!1),r.metaFileExisted){if(d=it(l.value),p===r.configId){let b=r.originalAppliedId;b&&h.some(k=>k.id===b)?d.appliedId=b:(a.push("applied profile"),c=!1)}c&&w?(h.splice(g,1),d.entries=h):c&&y===void 0&&(d.entries=h)}else{let b=ei(l.value,{appliedId:r.configId,entries:[r.metaEntry]});c&&b?u=!0:c&&p!==r.configId?(w&&h.splice(g,1),d={...it(l.value),entries:h}):(c&&a.push("config-library metadata"),c=!1)}}s.present&&(c?await pa(o,{force:!0}):await Kn(o,i)),l.present&&(u?await pa(n.meta,{force:!0}):ei(l.value,d)||await Kn(n.meta,d));let f=await kn(n.appConfig);if(f.present){let p=mk(f.value,r.deployment,ai,a);!r.deploymentFileExisted&&Object.keys(p).length===0?await pa(n.appConfig,{force:!0}):await Kn(n.appConfig,p)}else r.deploymentFileExisted&&a.push("deployment config file");let m=await si(n.helper);return m.present&&(m.content===r.helper.lastWritten||m.content===r.helper.previousWritten)?r.helper.original.present?await jl(n.helper,r.helper.original.content??"",r.helper.original.mode??448):await pa(n.helper,{force:!0}):(m.present||r.helper.original.present)&&a.push("credential helper"),await pa(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?[]:Fl]}}catch(r){return Hl(`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.`)}},vm=async(e,t={})=>{if(!km(t))return!1;let n=zt(t);if(await fo(n,t))return!1;try{let r=await kn(n.meta);if(!r.present)return!1;let o=ri(r.value),a=await kn($t(n.library,`${o}.json`)),s=await kn(n.appConfig);if(!a.present||!s.present)return!1;await Gl(n.helper,yk.X_OK);let i=Kt(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}},Tk=async(e={})=>{try{let t=zt(e),n=await si(t.helper);if(!n.present||typeof n.content!="string")return;let r=Ek(n.content);return r?r.args.at(-1)==="--passthrough-headers"?"subscription":"api_key":void 0}catch{return}},_k=async(e,t={})=>{if(!await vm(e,t))return!1;let n=zt(t);try{let r=await Am(n);if(!r)return!1;let o=await kn(n.meta);if(!o.present||ri(o.value)!==r.configId)return!1;let a=await si(n.helper);if(!a.present||a.content!==r.helper.lastWritten)return!1;let s=Ek(a.content??"");return s?await(t.helperLauncherAvailable??aM)(s):!1}catch{return!1}};import{createHash as Zk,randomUUID as Yk}from"node:crypto";import{spawn as kM,spawnSync as vM}from"node:child_process";import{link as Tm,mkdir as Sm,open as Jk,readFile as Em,readdir as Xk,rename as zk,rm as qt,stat as qk}from"node:fs/promises";import{homedir as _m}from"node:os";import{basename as Qk,dirname as ci,join as Aa,win32 as SM}from"node:path";import{isDeepStrictEqual as ma}from"node:util";var Le="HKCU\\SOFTWARE\\Policies\\Claude",ii="HKLM\\SOFTWARE\\Policies\\Claude",Xl=5,Ca="inferenceGatewayApiKey",$e=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled","coworkEgressAllowedHosts",Ca],Pk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme",Ca],Dk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper",Ca],Lk=["inferenceProvider","inferenceGatewayBaseUrl","inferenceGatewayAuthScheme","inferenceCredentialKind","inferenceCredentialHelper","chatTabEnabled",Ca],ev="Managed by anyray-connect; dynamic credential only.",EM=e=>/^[A-Za-z]:[\\/]/.test(e)&&SM.isAbsolute(e),Nk=e=>{if(!EM(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)},tv=e=>{if(!e.durable)throw new Error("the anyray-connect runtime is temporary");if(!Nk(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&&!Nk(e.args[0]))throw new Error("the credential helper does not use print-key --json")},Pm=(e={})=>Aa((e.home??_m)(),".anyray","bin","claude-desktop-credential-helper.cmd"),IM=e=>{if(/[\0\r\n"]/.test(e))throw new Error("the credential helper command contains unsafe characters");return`"${e.replace(/%/g,"%%")}"`},xM=e=>(tv(e),["@echo off",`REM ${ev}`,"setlocal DisableDelayedExpansion",[e.command,...e.args].map(IM).join(" "),"exit /b %ERRORLEVEL%",""].join(`\r
|
|
184
|
+
`)),RM=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},nv=e=>{let t=e.split(`\r
|
|
185
|
+
`);if(t.length!==6||t[0]!=="@echo off"||t[1]!==`REM ${ev}`||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(RM);if(r.some(i=>i===void 0))return;let[o,...a]=r,s={command:o,args:a,durable:!0};try{return tv(s),s}catch{return}},OM=async e=>{let t=[e.command,...e.args.length===3?[e.args[0]]:[]];try{return(await Promise.all(t.map(r=>qk(r)))).every(r=>r.isFile())}catch{return!1}},TM=async(e,t)=>{let n=nv(e.content);if(!n)return!1;try{return await(t.helperLauncherAvailable??OM)(n)}catch{return!1}},Im=e=>({sha256:mo(e),content:e}),$k=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Mt(t,["sha256","content"])&&BM(t.sha256)&&typeof t.content=="string"&&mo(t.content)===t.sha256&&nv(t.content)!==void 0},Dm=()=>{let e=vM("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??"")},_M=async(e,t)=>{await Sm(ci(e),{recursive:!0,mode:448});let n=`${e}.anyray-tmp-${process.pid}-${Date.now()}`;try{let r=await Jk(n,"wx",384);try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await Tm(n,e)}finally{await qt(n,{force:!0}).catch(()=>{})}},PM=e=>`${Qk(e)}.anyray-old-`,DM=e=>`${e}.anyray-old-${process.pid}-${Yk()}`,rv=async(e,t)=>{try{await Tm(t,e)}catch(n){if(n.code==="EEXIST")return!1;throw n}return await qt(t,{force:!0}),!0},Yl=async(e,t,n,r,o)=>{let a=DM(e),s=n===void 0?void 0:mo(n),i=n===void 0?void 0:`${e}.anyray-tmp-${process.pid}-${Yk()}`,c=!1;try{if(i&&n!==void 0){let d=await Jk(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 zk(e,a),c=!0,await o.helperFileOperationHook?.({operation:r,phase:"after-move",path:e,recoveryPath:a});let l=await wa(a);if(!l||l.sha256!==t)throw new Error("credential helper changed during operation");if(i&&n!==void 0&&(await Tm(i,e),await o.helperFileOperationHook?.({operation:r,phase:"after-publish",path:e,recoveryPath:a}),await ba(e)!==s))throw new Error("credential helper publication verification failed");await qt(a,{force:!0}),c=!1}catch(l){throw c&&await rv(e,a).catch(()=>!1),l}finally{i&&await qt(i,{force:!0}).catch(()=>{})}},xm=e=>`reg failed to spawn (${e.code??e.signal??e.name??"unknown"})`,LM=String.raw`
|
|
186
186
|
$ErrorActionPreference = 'Stop'
|
|
187
187
|
try {
|
|
188
188
|
$request = ConvertFrom-Json ([Console]::In.ReadToEnd())
|
|
@@ -251,16 +251,16 @@ try {
|
|
|
251
251
|
exit 5
|
|
252
252
|
} catch {
|
|
253
253
|
exit 6
|
|
254
|
-
}`,Zn=async e=>new Promise((t,n)=>{let r=
|
|
255
|
-
`)}catch(a){if(a.code!=="EEXIST")throw await qt(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await Em(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0
|
|
256
|
-
`;t.writeJournalFile?await t.writeJournalFile(n,r):await we(n,r)},KM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,jM=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),ZM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),YM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),JM=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===YM(t).toUpperCase(),Kk=(e,t,n,r,o)=>{let a=$e.find(i=>i.toLowerCase()===t.toLowerCase());if(!a)return!1;let s=n==="String"?"REG_SZ":n==="ExpandString"?"REG_EXPAND_SZ":n;if(s!=="REG_SZ"&&s!=="REG_EXPAND_SZ"){if(o)throw new Error("an owned Claude policy value has an unsupported type");return!1}if(e[a].present)throw new Error("a Claude policy value was returned more than once");return e[a]={present:!0,type:s,value:r},!0},XM=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,zM=(e,t)=>{if(!Ul(e,!0))return!1;let n=XM(t);if(ZM.has(n))return!1;if(jM.has(n))return n==="REG_EXPAND_SZ"?!0:!ik(e,!0)},qM=(e,t)=>{let n=ov(),r=!1,o=!1,a=!1,s=t.toUpperCase()===ii.toUpperCase(),i=(l,d)=>{if(!s)return;let u=zM(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),Kk(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||JM(d,t))continue;let u=KM.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),Kk(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},jn=async(e,t=Le)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:ov(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return qM(n.stdout,t)},Or=async e=>{let t=await jn(e,ii);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...$e.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},Bm=e=>e.unparsed?`This machine may have a Claude policy under ${ii} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${ii} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${ii} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var ql=(e,t)=>Rr(po(e,t)),av=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],QM=(e,t)=>{let n=ql(e,t);return Object.fromEntries($e.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},eB=(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}}),tB=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,Rm=e=>Object.fromEntries($e.map(t=>[t,$M(t,e[t])])),jk=(e,t,n,r)=>({version:Xl,registryKey:Le,keyExisted:e,lastWritten:Rm(t),helper:{path:n,lastWritten:Im(r)}}),nB=(e,t,n,r,o,a)=>({version:Xl,registryKey:Le,keyExisted:e,lastWritten:Rm(t),pending:Rm(n),helper:{path:r,...o?{lastWritten:Im(o)}:{},pending:Im(a)}}),Om=(e,t,n)=>ha(n,e.lastWritten[t])||e.pending!==void 0&&ha(n,e.pending[t]),wa=async e=>{try{let t=await Em(e,"utf8");return{content:t,sha256:mo(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},ba=async e=>(await wa(e))?.sha256,ya=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Jl=async(e,t)=>{let n=_M(e),r;try{r=await Xk(ci(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>Aa(ci(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([wa(e),wa(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!ya(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await rv(e,a))throw new Error("credential helper changed during recovery");return}if(t&&ya(t,s.sha256)&&ya(t,i.sha256)){await qt(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},Fm=async(e,t,n)=>(n.present?await e(av(Le,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Le,"/v",t,"/f"])).code===0,rB=async(e,t,n)=>{let r=!0,o=await jn(e);for(let a of $e)if(!ma(o.values[a],t[a])){if(!ma(o.values[a],n[a])){r=!1;continue}await Fm(e,a,t[a])||(r=!1),o=await jn(e)}return r&&$e.every(a=>ma(o.values[a],t[a]))},ze=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Bt(n)]}}),sv=async(e,t,n,r={})=>{if(!Ae(t))return ze("A valid personal ark_ gateway key is required.",!1,r);let o=Pm(r),a;try{a=IM((r.credentialCommand??ym)())}catch{return ze("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=mo(a),i=r.runReg??Zn,c=Bt(r),l;if(!n.dryRun)try{l=await Lm(r)}catch(h){return ze(h instanceof ga?"Another Claude Desktop policy operation is already in progress; retry shortly.":"Could not acquire the owner-only Claude Desktop policy lock; the registry was left unchanged.",!1,r)}let d,u,f,m,p=!1;try{let h=await Or(i);if(h)return ze(Bm(h),!1,r);let w=await Mm(r,!n.dryRun);n.dryRun||await Jl(o,w);let y=await jn(i),g=QM(e,o),b=await wa(o),k=b?.sha256,C=!1;if(d=w,u=y,f=g,w){let I=$e.find(_=>!Om(w,_,y.values[_]));if(I)return ze(`Claude's ${I} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(k!==void 0&&!ya(w,k))return ze(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);C=tB(w)}else{if(k!==void 0&&k!==s)return ze(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let I=y.foreignState||$e.some(W=>y.values[W].present),_=$e.every(W=>ma(y.values[W],g[W])),T=$e.every(W=>ma(y.values[W],eB(e,t.trim())[W]));if(I&&!_&&!T)return ze(`Existing Claude third-party-inference policy values under ${Le} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(C=T,_&&k===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Le} into an owner-only journal without rewriting them.`]}:(await Zl(jk(y.keyPresent,g,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Le} into the ownership journal.`]})}if(C){let I=!0;try{I=(r.appRunning??Dm)()}catch{}if(I)return ze("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let S=nB(w?.keyExisted??y.keyPresent,y.values,g,o,b?.content,a);if(m=S,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${Le}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Zl(S,r),p=!0;for(let I of $e){let _=await jn(i);if(!ha(_.values[I],S.lastWritten[I])&&!ha(_.values[I],S.pending[I]))throw new Error("registry value changed during apply");if(!ma(_.values[I],g[I])&&!await Fm(i,I,g[I]))throw new Error("registry write failed")}let E=await jn(i);if(!$e.every(I=>ha(E.values[I],S.pending[I])))throw new Error("registry verification failed");if(k!==s&&(k===void 0?await TM(o,a):await Yl(o,k,a,"apply",r)),await ba(o)!==s)throw new Error("credential helper verification failed");return await Zl(jk(S.keyExisted,g,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Le}.`,`Installed or updated the dynamic credential helper at ${o}; no personal key is stored in policy or the ownership journal.`,"Fully quit and reopen Claude Desktop to load the policy.",...Bl(gt("migrate"))]}}catch{if(!p||!u||!f||!m)return ze("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Jl(o,m);let h=!0,w=await wa(o),y=m.helper.pending;if(w?.sha256!==m.helper.lastWritten?.sha256&&(y!==void 0&&w?.sha256===y.sha256?m.helper.lastWritten?(await Yl(o,y.sha256,m.helper.lastWritten.content,"rollback",r),h=await ba(o)===m.helper.lastWritten.sha256):await Yl(o,y.sha256,void 0,"rollback",r):h=w===void 0&&m.helper.lastWritten===void 0),h&&await rB(i,u.values,f))return d?await Zl(d,r):await qt(c,{force:!0}),ze("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return ze("Could not complete or fully roll back Claude Desktop's HKCU policy transaction. The owner-only journal was preserved; run `anyray-connect desktop disconnect` to recover safely.",!0,r)}finally{await l?.()}},iv=async(e,t={})=>{let n=t.runReg??Zn,r=Bt(t),o;if(!e.dryRun)try{o=await Lm(t)}catch(a){return ze(a instanceof ga?"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 Mm(t,!e.dryRun);a&&!e.dryRun&&await Jl(a.helper.path,a);let s=await jn(n);if(!a)return $e.filter(p=>s.values[p].present).length>0?ze(`Claude policy values exist under ${Le}, but Anyray has no ownership journal. Remove them manually only if you know they came from an older Connect run.`,!1,t):{status:"not-found",messages:["No Windows Claude setup to revert."]};let i=$e.filter(m=>s.values[m].present&&!Om(a,m,s.values[m])),c=await ba(a.helper.path),l=c!==void 0&&!ya(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Le}.`,`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 m of $e){let h=(await jn(n)).values[m];if(h.present){if(!Om(a,m,h)){u.add(m);continue}await Fm(n,m,{present:!1})||(d=!0)}}let f=await ba(a.helper.path);if(f!==void 0)if(ya(a,f))try{await Yl(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?ze(`Could not remove every Anyray-owned Claude policy value or credential-helper file. The ownership journal remains at ${r}; re-run revert.`,!0,t):(await qt(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Le}.`,"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?[]:Fl]})}catch{return ze(`Could not safely inspect or revert ${Le}; no unproven value was removed.`,!1,t)}finally{await o?.()}},cv=async(e,t={})=>{let n=t.runReg??Zn;if(!await x(Bt(t)))return;let r;try{r=await Lm(t);let o=await Mm(t);if(o&&await Jl(o.helper.path,o),!o||o.pending||await Or(n)!==void 0)return;let a=await jn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Kt(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&$e.every(l=>ha(a.values[l],o.lastWritten[l]))))return;let i=await ba(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 OM(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?.()}},lv=async(e,t={})=>await cv(e,t)!==void 0,dv=async(e,t={})=>await cv(e,t)==="dynamic";var ka=(e=aB())=>e==="win32"?Dm:Vl,Wm="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",ed=async(e,t={})=>{let n=(t.profileRoot??uo)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Wm};if((t.appRunning??ka(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await uv.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 Ml(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 "+Wm}:{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??ek)();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=Ql(t.stagingRoot??sB(),`anyray-history-${process.pid}-${oB()}`);try{let s=await(t.runImporter??tk)({binary:o,exportPath:e,configDir:Ql(a,"config"),workDir:Ql(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. "+Wm};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 rk(r.dir,s.conversations),c=await ok({stagedProjectsDir:Ql(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 uv.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as St}from"node:fs";import{homedir as RB}from"node:os";import{join as en,sep as OB}from"node:path";import{isDeepStrictEqual as od}from"node:util";import{constants as iB}from"node:fs";import{promises as V}from"node:fs";import{dirname as va,isAbsolute as Hm,join as ae,relative as td,resolve as Qt,sep as li}from"node:path";import{randomUUID as ad}from"node:crypto";var vn=448,di=384,hv=448,cB=4,Gm=3e4,yv=5e3,lB=10*6e4,Um=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),ct=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ui=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),gv=(e,t)=>{let n=td(Qt(e),Qt(t));return n===""||!n.startsWith(`..${li}`)&&n!==".."&&!Hm(n)},ho=async e=>{try{let t=await V.readFile(e,"utf8"),n=JSON.parse(t);return ct(n)?{raw:t,value:n}:void 0}catch(t){return vt(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},vt=e=>e instanceof Error&&"code"in e,dB=e=>{try{return process.kill(e,0),!0}catch(t){return vt(t)&&t.code==="EPERM"}},wv=e=>e===0?"owner.json":`owner.${e}.json`,nd=async e=>{let t;try{t=await V.readdir(e)}catch{return}let r=t.map(d=>{if(d==="owner.json")return{name:d,generation:0};let u=/^owner\.(\d+)\.json$/.exec(d);if(!u)return;let f=Number(u[1]);return Number.isSafeInteger(f)&&f>0?{name:d,generation:f}:void 0}).filter(d=>!!d).sort((d,u)=>u.generation-d.generation)[0];if(!r)return;let o=ae(e,r.name),a,s,i;try{let d=JSON.parse(await V.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 V.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}},bv=e=>{if(e.pid===void 0||!dB(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Gm&&t-e.createdAtMs>lB},uB=async e=>{let t=`${e}.anyray-lock`;await V.mkdir(va(t),{recursive:!0,mode:vn});let n=ad(),r,o=!1;try{await V.mkdir(t,{mode:vn}),o=!0}catch(i){if(!vt(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await nd(t);if(d){if(!bv(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await V.stat(t).then(f=>Date.now()-f.mtimeMs).catch(()=>0)<=Gm)return}let l=ae(t,wv(c));try{await V.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
257
|
-
`,{flag:"wx",mode:di}),r=l}catch(d){if(vt(d)&&d.code==="EEXIST"){o=!1;continue}throw o&&await V.rm(t,{recursive:!0,force:!0}).catch(()=>{}),d}}if(!r)return;let a=r,s=setInterval(()=>{(async()=>{try{let i=JSON.parse(await V.readFile(a,"utf8"));if(!ct(i)||i.nonce!==n)return;let c=new Date;await V.utimes(a,c,c)}catch{}})()},yv);return s.unref(),async()=>{clearInterval(s);try{(await nd(t))?.nonce===n&&await V.rm(t,{recursive:!0,force:!0})}catch{}}},
|
|
258
|
-
`,{mode:di,flag:"wx"}),await V.rename(a,e)}catch(s){try{await V.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},sd=async(e,t)=>{for(let n=0;n<
|
|
259
|
-
`,{flag:"wx",mode:di}),o=u}catch(f){if(vt(f)&&f.code==="EEXIST"){n=!1;continue}n&&await V.rm(e,{recursive:!0,force:!0}).catch(()=>{});return}}if(!o)return;let a=o,s=setInterval(()=>{(async()=>{try{let l=JSON.parse(await V.readFile(a,"utf8"));if(!ct(l)||l.nonce!==r)return;let d=new Date;await V.utimes(a,d,d)}catch{}})()},yv);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await nd(e))?.nonce===r&&await V.rm(e,{recursive:!0,force:!0})}catch{}}}},Sv=async e=>{let t=await vv(e,!1);t&&await t.complete()},
|
|
260
|
-
`)}},jm=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),Pv=async e=>{let t=[];for(let n of PB)t.push({lane:n,sources:await LB(e,n)});return t},Dv=async(e={})=>{let t=(e.firstPartyRoot??(()=>zs()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([Pv(t),Vm(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=jm(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}},yo=async(e={})=>{let t=(e.home??RB)(),n=(e.firstPartyRoot??(()=>zs()))(),r=(e.thirdPartyRoot??(()=>uo()))();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??ka())())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([Pv(n),Vm(n)]),s;if(e.account){let m=e.account;for(let w of o)w.sources=w.sources.filter(y=>y.account.startsWith(m));let p=a.accounts.filter(w=>w.startsWith(m));if(o.every(w=>w.sources.length===0)&&p.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${m}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let h=jm(o);for(let w of p)h.add(w);if(h.size>1)return Ov(o,e.command??"anyray-connect desktop --migrate",`"${m}" matches ${h.size} accounts`,p);s=[...h]}else if(!e.allAccounts){let m=jm(o);for(let p of a.accounts)m.add(p);if(m.size>1)return Ov(o,e.command??"anyray-connect desktop --migrate",`the previous Claude Desktop profile holds local data for ${m.size} accounts`,a.accounts);s=[...m]}let i=e.command??"anyray-connect desktop --migrate",c=!await TB(r),l=await xv(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:m,sources:p}of o){if(p.length===0){d.push(Km(m));continue}let h=await NB(r,m);if("missing"in h){u.push({lane:m,reason:h.missing,waiting:p.reduce((w,y)=>w+y.ids.length,0)}),d.push(Km(m));continue}d.push(await BB(m,p,h.dir,t))}if(!(d.some(m=>m.migrated>0||m.alreadyPresent>0)||l.outcomes.some(m=>m.migrated>0||m.alreadyPresent>0||m.conflicts>0))&&(u.length>0||l.blocked.length>0)){let m=u[0];return m?{ok:!1,kind:m.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:m.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${m.lane} store`:`Claude Desktop has no ${m.lane} store in its third-party profile yet`,remedy:Zm(m.reason,m.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=>[Ne(e)],Lv=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 Nv="1.21459.0",VB=GB(UB),KB=async e=>{try{let{stdout:t}=await VB("/usr/bin/plutil",["-extract","CFBundleShortVersionString","raw","-o","-",e],{timeout:2e3,maxBuffer:4096});return String(t).trim()||void 0}catch{return}},jB=async e=>{try{return await HB(e)}catch{return}},$v="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",ZB=["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."],Sa=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(Mv??=Bv({}),Mv):Bv(e),Mv,Bv=async e=>{let t=(e.home??fi)(),n=["/Applications/Claude.app",Sn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??KB,o=e.readClaudeAppBundle??jB;for(let a of n){let s=await r(Sn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${$v}`}),c=Nl(s,Nv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${Nv} or newer.`);let l=await o(Sn(a,"Contents","Resources","app.asar"));return l?Ak.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. ${$v}`}},cd="anyray",Uv="--anyray-owner=claude-desktop-v1",ld=(e={})=>{let t=(e.platform??Tr)(),n=(e.home??fi)();return t==="darwin"?zt(e).appConfig:t==="win32"?Sn(process.env.APPDATA??Sn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):Sn(n,".config","Claude","claude_desktop_config.json")},qm=(e={})=>Sn((e.home??fi)(),"Library","Application Support","Claude","claude_desktop_config.json"),Hv=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,Uv]}},go=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Gv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},YB=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),JB=e=>{if(!go(e)||!Gv(e,["command","args"]))return!1;let t=Hv();return e.command===t.command&&YB(e.args,t.args)},XB=e=>go(e)&&Array.isArray(e.args)&&e.args.at(-1)===Uv,zB=e=>{if(!go(e)||!Gv(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||tt(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===sr&&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!tt(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},qB=e=>e===void 0?"absent":JB(e)?"exact":XB(e)||zB(e)?"stale-owned":"foreign",We=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},wo=async e=>{let t=await x(e),n;try{n=await B(e)}catch{throw new We(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!go(n.mcpServers))throw new We(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(go(n.mcpServers)?n.mcpServers:void 0)?.[cd];return{path:e,fileExisted:t,json:n,entry:o,ownership:qB(o)}},dd=e=>{if(e.ownership==="foreign")throw new We(`MCP name conflict in ${e.path}: mcpServers.${cd} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},Vv=(e,t)=>{let n={...e},r=go(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[cd]:r[cd]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Jm=async(e,t)=>{if(Ym(e.entry,t))return;let n=await wo(e.path);if(!Ym(n.entry,e.entry))throw new We(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Kn(e.path,Vv(n.json,t)),{reading:e,afterEntry:t}},Xm=async e=>{let t=await wo(e.reading.path);if(!Ym(t.entry,e.afterEntry))throw new We(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=Vv(t.json,e.reading.entry);await Kn(e.reading.path,n)},QB=async e=>{if(!oe())throw new We(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${De()} is temporary); no inference setting was changed.`);let t=await wo(ld(e));dd(t);let n=qm(e),r=(e.platform??Tr)()==="darwin"&&n!==t.path?await wo(n):void 0;return r&&dd(r),{active:t,...r?{legacy:r}:{}}},Fv=async e=>{let t=await wo(ld(e));dd(t);let n=qm(e),r=(e.platform??Tr)()==="darwin"&&n!==t.path?await wo(n):void 0;return r&&dd(r),{active:t,...r?{legacy:r}:{}}},eF=async e=>{let t=[];try{let n=await Jm(e.active,Hv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Jm(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Xm(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new We(`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 Xm(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new We(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},tF=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Jm(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Xm(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new We(`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)."]},nF={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},ud="claude-desktop",zm="migrate",Kv=new Set(["app-running","store-missing"]),rF={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},oF={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"}},aF="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",jv=e=>{let t=(e.platform??Tr)(),n=e.home??fi;return{home:n,appRunning:e.appRunning??ka(t),firstPartyRoot:()=>zs({home:n,runtimePlatform:t}),thirdPartyRoot:()=>uo({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},Zv=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=rF[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.`:"")},Yv=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=oF[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.`:"")},pi=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=jv(e),r=await(e.pendingDesktopMigrationCount??Dv)(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??yo)(n);if(a.ok){let c=Zv(a.lanes),l=Yv(a.portableAssets),d=a.ambiguousAssets??[],u=d.length>0?`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`:void 0,f=(a.blocked??[]).filter(g=>g.reason!=="ambiguous"),m=a.blockedAssets??[],p=a.retryableAssets??[];if(f.length===0&&m.length===0&&p.length===0)return[c,l,u].filter(g=>!!g);if(t.preservePendingOp)return[c,l,u].filter(g=>!!g);await xs(ud,zm);let h=f.reduce((g,b)=>g+b.waiting,0),w=[h>0?`${h} more session${h===1?"":"s"}`:"",m.length>0?`${m.length} extension ${m.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.`]:[],...p.length>0?[`Queued: ${p.length} portable configuration ${p.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...y]}if(!Kv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
|
|
261
|
-
${a.remedy}`];if(t.preservePendingOp)return[];await xs(ud,zm);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."]}},sF=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await yr(ud),[]}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."]}},iF=e=>Lv({id:ud,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??Tr)(),n=(e.home??fi)();return t==="darwin"?["/Applications/Claude.app",Sn(n,"Applications","Claude.app")]:t==="win32"?[Sn(process.env.LOCALAPPDATA??Sn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>te(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`."]}),cF=(e={})=>{let t=iF(e),n=()=>(e.platform??Tr)()==="darwin",r=()=>(e.platform??Tr)()==="win32",o=(s,i)=>n()?Rk(s,i,e):sv(s,s.clientKey??"",i,e),a=s=>n()?Ok(s,e):iv(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??ka((e.platform??Tr)()))(),quitTarget:nF,needsTarget:()=>!1,async complete(s){if(s!==zm)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??yo)(jv(e));if(i.ok){let c=Zv(i.lanes),l=Yv(i.portableAssets),d=i.ambiguousAssets??[];if(d.length>0)return{status:"manual",messages:[...c?[c]:[],...l?[l]:[],`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`]};let f=(i.blocked??[]).filter(h=>h.reason!=="ambiguous"),m=i.blockedAssets??[],p=i.retryableAssets??[];return f.length>0||m.length>0||p.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...f.length>0||m.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."]:[],...p.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 Kv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?_k(s,e):r()?dv(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=zt(e),m=await fo(f,e);if(m)return{status:"manual",manualAudience:"admin",messages:[Cm(m),...await pi(e,i)]}}if(r()){let f;try{f=await Or(e.runReg??Zn)}catch{return{status:"manual",manualAudience:"admin",messages:[aF,...await pi(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[Bm(f),...await pi(e,i)]}}if(r()&&te(s,"anthropic"))return{status:"manual",messages:["Claude Desktop subscription routing is not available on Windows: Connect could not verify a supported Claude subscription credential source, so inference was left unchanged instead of switching to API billing.","Use org/API mode for the Windows Gateway lane, or run subscription mode on a verified macOS build after signing in to Claude Code."]};if(n()){let f=await Sa(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await QB(e)}catch(f){let m=f instanceof We?f.changedFiles:[];return{status:"manual",...m.length>0?{changedFiles:m}:{},messages:[f instanceof We?f.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no inference setting was changed."]}}let l=await o(s,{dryRun:!0});if(l.status!=="configured")return l;if(i.dryRun){let f=c.legacy;return{...l,messages:[...l.messages,`Would register the ownership-marked Anyray retrieval MCP server in ${c.active.path}.`,...f&&f.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${f.path}.`]:[],...await pi(e,i)]}}let d;try{d=await eF(c)}catch(f){let m=f instanceof We?f.changedFiles:[];return{status:"manual",...m.length>0?{changedFiles:m}:{},messages:[f instanceof We?f.message:"Could not safely register Claude Desktop retrieval; the inference route was left unchanged."]}}let u;try{u=await o(s,{dryRun:!1})}catch{u={status:"manual",messages:["Claude Desktop inference setup failed before it returned a result."]}}if(u.status!=="configured")try{return await d.rollback(),{...u,changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])],messages:[...u.messages,"Restored the prior Claude Desktop MCP registration because inference setup did not complete. A config file that was absent before setup may remain as an inert object to avoid racing unrelated concurrent writes."]}}catch{return{status:"manual",changedFiles:[...u.changedFiles??[],...d.changedFiles],messages:[...u.messages,"Inference setup did not complete, and the prior MCP registration could not be fully restored. Re-run `anyray-connect desktop disconnect` to recover safely."]}}return{...u,messages:[...u.messages,"Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) with an ownership marker.",...await pi(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?ZB:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=ld(e),c=await sF(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 Fv(e)}catch(h){return l({status:"manual",messages:[h instanceof We?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 f=await a({dryRun:!1});if(f.status==="manual"){let h=r()?Bt(e):void 0;if(!(h!==void 0&&f.changedFiles?.includes(h)===!0&&!await x(h)))return l(f)}let m;try{m=await tF(await Fv(e))}catch(h){let w=h instanceof We?h.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...w])],messages:[...f.messages,h instanceof We?h.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await ie(i);let p=qm(e);return n()&&p!==i&&await ie(p),l({...f,messages:[...f.messages,...m.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...f.changedFiles??[],...m])]})},async mcpStatus(){if(!oe())return{registered:!1,command:null,reason:"ephemeral-runtime"};try{let s=await wo(ld(e));return s.ownership!=="exact"||!go(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 Sa(e)).supported?vm(s,e):!1:r()?lv(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await Sa(e)).supported)return["unknown"];let s=await Tk(e);return s?[s]:["unknown"]}if(r())return await x(Bt(e))?await Or(e.runReg??Zn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=zt(e);return!await x(s.journal)||await fo(s,e)?!1:(await Sa(e)).supported}return r()&&await x(Bt(e))?!await Or(e.runReg??Zn):!1}catch{return!1}}}},Jv=cF();import{homedir as $F}from"node:os";import{join as MF}from"node:path";import{rm as Ad}from"node:fs/promises";import{constants as Xv,accessSync as lF,statSync as dF}from"node:fs";import{platform as Qm}from"node:os";import{delimiter as uF,posix as pF,resolve as fF,win32 as mF}from"node:path";var hF="0.59.0",yF="1.1.4",Yn="Anyray \xB7 Claude",Jn="Anyray \xB7 Codex",pd="__anyray-acp-agent",zv=(e,t,n)=>{let{command:r,args:o}=an([pd,e,t,n]);return{command:r,args:o,env:{}}},fd=(e=Qm())=>e==="win32"?"npx.cmd":"npx",md=(e=process.env.PATH,t=Qm())=>{if(!e)return;let n=fd(t);for(let r of e.split(uF)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=fF(o,n);try{if(!dF(a).isFile())continue;return lF(a,t==="win32"?Xv.F_OK:Xv.X_OK),a}catch{}}},hd=(e,t=Qm())=>{let n=t==="win32"?mF:pF;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==fd(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},gF="https://chatgpt.com/backend-api/codex",wF="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",qv="ANYRAY_ACP_CODEX_AUTHORIZATION",Qv="ANYRAY_ACP_CODEX_CLIENT_KEY",eS="ANYRAY_ACP_CODEX_METADATA",tS=e=>me({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),bF=(e,t={})=>{let n=te(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":gF,"x-anyray-forward-headers":wF}:{},o=n?{...e.clientKey?{"x-anyray-api-key":Qv}:{}}:{Authorization:qv};return tS(e)&&(o["x-anyray-metadata"]=eS),{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}}}:{}}},AF=e=>{let t=te(e,"openai"),n=tS(e);return{...t?e.clientKey?{[Qv]:e.clientKey}:{}:{[qv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[eS]:n}:{}}},nS=(e,t=fd(),n={})=>({[Yn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${hF}`],env:sn(e).env},[Jn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${yF}`],env:{CODEX_CONFIG:JSON.stringify(bF(e,n)),...AF(e)}}}),mi=(e=fd(),t="jetbrains")=>({[Yn]:zv("claude",e,t),[Jn]:zv("codex",e,t)}),bo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yd=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as CF}from"node:zlib";import{open as kF,readFile as oh,readdir as bd}from"node:fs/promises";import{dirname as rS,join as he}from"node:path";import{homedir as iS,platform as ah}from"node:os";var gd="2025.3.2",Ea="253.30387.147",hi="com.intellij.ml.llm",eh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),vF=1e4,SF=256*1024*1024,EF=16*1024*1024,th=1024*1024,nh=22,IF=nh+65535,rh=Nl,xF=()=>{let e=iS(),t=he(e,".cache","JetBrains","RemoteDev");switch(ah()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:he(e,"Applications"),layout:"app-bundles"},{path:he(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:he(process.env.LOCALAPPDATA??he(e,"AppData","Local"),"Programs"),layout:"children"},{path:he(process.env.LOCALAPPDATA??he(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:he(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:he(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},RF=()=>ah()==="linux"?he(iS(),".local","share","JetBrains"):Ne("JetBrains"),OF=()=>ah()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),TF=async(e,t=vF)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await bd(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=he(r.path,i.name),l=r.layout==="app-bundles"?he(c,"Contents","Resources","product-info.json"):he(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=he(s,"product-info.json"),l=he(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 bd(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let f=he(s,u.name);(u.isDirectory()||u.isSymbolicLink())&&!["bin","jbr","lib","plugins","Contents"].includes(u.name)&&await a(f,i-1)}};await a(r.path,7)}return[...new Set(n)]},_F=e=>{let t=rS(e);return t.endsWith(`${he("Contents","Resources")}`)?rS(t):t},PF=async e=>{try{let t=JSON.parse(await oh(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!Js(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:_F(e)}}catch{return}},wd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},DF=async(e,t)=>{let n;try{n=await kF(e,"r");let{size:r}=await n.stat();if(r<nh||r>SF)return;let o=Math.min(r,IF),a=await wd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-nh;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>EF||c+i>r)return;let l=await wd(n,i,c);if(!l)return;let d=0;for(;d+46<=l.length;){if(l.readUInt32LE(d)!==33639248)return;let u=l.readUInt16LE(d+10),f=l.readUInt32LE(d+20),m=l.readUInt32LE(d+24),p=l.readUInt16LE(d+28),h=l.readUInt16LE(d+30),w=l.readUInt16LE(d+32),y=l.readUInt32LE(d+42),g=d+46+p+h+w;if(g>l.length)return;let b=l.subarray(d+46,d+46+p).toString("utf8");if(d=g,b!==t)continue;if(f===4294967295||m===4294967295||f>th||m>th)return;let k=await wd(n,30,y);if(!k||k.readUInt32LE(0)!==67324752)return;let C=k.readUInt16LE(26),S=k.readUInt16LE(28),E=await wd(n,f,y+30+C+S);return E?u===0?E.toString("utf8"):u===8?CF(E,{maxOutputLength:th}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},oS=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!Js(n)))return{id:t,version:n}},LF=async(e,t)=>{let n=he(e,"META-INF","plugin.xml");if(await x(n))try{let o=oS(await oh(n,"utf8"));return{present:o?.id===hi||t,descriptor:o?.id===hi?o:void 0}}catch{return{present:t}}let r=[];try{r=(await bd(he(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=>he(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await DF(o,"META-INF/plugin.xml"),s=a?oS(a):void 0;if(s?.id===hi)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},aS=async e=>{let t;try{t=await bd(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=eh.has(o.name.toLowerCase()),i=eh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=eh.has(o.name.toLowerCase());if(!a){let i=he(e,o.name,"META-INF","plugin.xml");if(!await x(i))continue}let s=await LF(he(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},NF=async e=>{try{return(await oh(he(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(hi)}catch{return!1}},sS=e=>e.reduce((t,n)=>t?(rh(n,t)??-1)>0?n:t:n,void 0),cS=async(e={})=>{let t=e.configRoot??Ne("JetBrains"),n=e.userPluginsRoot??RF(),r=await TF(e.productRoots?e.productRoots.map(p=>({path:p,layout:"recursive"})):xF(),e.scanBudget),o=(await Promise.all(r.map(p=>PF(p)))).filter(p=>p!==void 0),a=o.length>0||await x(t);if(e.wsl??OF())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(p=>(rh(p.version,gd)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let p of s){let h=he(t,p.dataDirectoryName);if(!await x(h)){d=!0;continue}let w=[he(h,"plugins"),he(n,p.dataDirectoryName),he(n,p.dataDirectoryName,"plugins")],y;for(let g of[...new Set(w)]){let b=await aS(g);if(b.present){y=b;break}}if(y??=await aS(he(p.root,"plugins")),y.present&&!y.descriptor){l=!0;continue}if(!(!y.descriptor||y.descriptor.id!==hi)){if(i.push(y.descriptor.version),await NF(h)){c=!0;continue}if(!((rh(y.descriptor.version,Ea)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${p.version}; AI Assistant ${y.descriptor.version}; ACP supported`,ideVersion:p.version,pluginVersion:y.descriptor.version}}}let u=sS(o.map(p=>p.version)),f=sS(i),m;return a?u?s.length===0?m=`JetBrains IDE ${u} is below the ACP minimum ${gd}; no ACP config was written.`:d?m=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${gd}+ once, enable AI Assistant ${Ea}+, then run Connect again. No ACP config was written.`:c?m=`JetBrains AI Assistant is disabled; enable version ${Ea}+ and run Connect again. No ACP config was written.`:f?m=`JetBrains AI Assistant ${f} is below the ACP minimum ${Ea}; no ACP config was written.`:l?m=`Could not verify the local JetBrains AI Assistant version; require ${Ea}+ before running Connect. No ACP config was written.`:m=`JetBrains AI Assistant ${Ea}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:m=`Could not prove JetBrains IDE ${gd}+ from local product-info.json; no ACP config was written.`:m="JetBrains IDE config or installation not found",{installed:a,capable:!1,detail:m,ideVersion:u,pluginVersion:f}};var BF=[Yn,Jn],sh=()=>MF($F(),".jetbrains","acp.json"),Ao=()=>`${sh()}.anyray-state`,FF=(e,t,n="npx")=>{let r=bo(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,mi(n,"jetbrains")),{...e,agent_servers:r}},WF=(e,t,n)=>{if(!bo(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=bo(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of BF)if(c in r){if(!yd(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}},UF=(e=cS)=>({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=sh(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=md();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await x(r),c;try{c=await B(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=mi(a,"jetbrains");return await nc({configPath:r,current:c,next:FF(c,t,a),journalPath:Ao(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,Ao()]}},async revert(t){let n=sh(),r=async()=>{if(!await x(n))return t.dryRun||(await ie(n),await Ad(Ao(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await B(n)}catch{return t.dryRun||(await ie(n),await Ad(Ao(),{force:!0}).catch(()=>{})),{status:"manual",messages:[`Could not parse ${n}; remove the two \u201CAnyray \xB7 \u2026\u201D agent entries manually.`]}}let a={},s=!1,i=!1;try{let u=await B(Ao());(u.version===1||u.version===2)&&bo(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await x(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await B(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await Ur(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 Ad(n,{force:!0}):await X(n,l.next,{backup:!1})),t.dryRun||(await ie(n),await Ad(Ao(),{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():tc(n,Ao(),r)}}),lS=UF();import{homedir as kd}from"node:os";import{join as vd}from"node:path";import{rm as ih}from"node:fs/promises";var ch="1.0.0",Sd=["anyray-claude-acp","anyray-codex-acp"],HF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],lh=()=>vd(kd(),".windsurf","acp","registry.json"),dh=()=>vd(kd(),".windsurf-next","acp","registry.json"),Ia=e=>`${e}.anyray-state`,dS=e=>({binary:Object.fromEntries(HF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),pS=(e="npx")=>{let t=mi(e,"windsurf");return[{id:Sd[0],name:Yn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:dS(t[Yn])},{id:Sd[1],name:Jn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:dS(t[Jn])}]},Cd=e=>!Array.isArray(e)||e.some(t=>!bo(t)||typeof t.id!="string")?null:e,GF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==ch||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:Cd(e.agents);if(!n)return null;let r=new Set(Sd);return{...e,version:typeof e.version=="string"?e.version:ch,agents:[...n.filter(o=>!r.has(o.id)),...pS(t)],extensions:e.extensions??[]}},VF=(e,t,n)=>{let r=Cd(e.agents);if(!r)return null;let o=Cd(t.agents)??[],a=new Map((Cd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!Sd.includes(u.id)){l.push(u);continue}if(!yd(u,a.get(u.id))){c.push(u.id),l.push(u);continue}let f=s.get(u.id);f&&l.push(f),i.push(u.id)}let d={...e,agents:l};return!Object.prototype.hasOwnProperty.call(t,"agents")&&l.length===0&&delete d.agents,!Object.prototype.hasOwnProperty.call(t,"version")&&d.version===ch&&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}},uS=async()=>{let e=[];return(await x(dh())||await x(vd(kd(),".windsurf-next")))&&e.push(dh()),(await x(lh())||await x(vd(kd(),".windsurf"))||await x(Ne("Devin"))||await x(Ne("Windsurf")))&&e.push(lh()),e},fS={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await uS();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await uS();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=md();if(!r)return{status:"manual",messages:["Devin ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP registry was written."]};let o=[],a=[];for(let s of n){let i;try{i=await B(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=GF(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=pS(r);await nc({configPath:s,current:i,next:c,journalPath:Ia(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,Ia(s))}}return o.push("Devin requires a one-time vendor UI enablement for local registry agents: Devin Settings \u2192 Agents \u2192 enable the two Anyray agents, then restart Devin Desktop."),o.push("Native Devin/Cascade subscription requests are not redirected. The official enterprise consumption connector imports content-free usage instead."),o.push("No proxy, certificate, DNS, DEVIN_API_URL, or private first-party endpoint was changed."),{status:"manual",messages:o,changedFiles:a.length?a:void 0}},async revert(e){let t=[lh(),dh()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await x(a)){e.dryRun||(await ie(a),await ih(Ia(a),{force:!0}).catch(()=>{}));return}let i;try{i=await B(a)}catch{n.push(`Could not parse ${a}; remove the anyray-* ACP agents manually.`),o=!0;return}let c=[],l=!1,d=!1;try{let m=await B(Ia(a));(m.version===1||m.version===2)&&Array.isArray(m.agents)&&(c=m.agents,l=m.version===2&&m.fileExisted===!1,d=m.version===2&&m.fileExisted===!0)}catch{}let u;if(d){let m=`${a}.anyray-bak`;if(!await x(m)){n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is missing. Restore it or remove the agents manually.`),o=!0;return}try{u=await B(m)}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 Ur(a);let f=VF(i,u,c);if(!f){n.push(`Unrecognized ACP registry shape in ${a}; left it unchanged.`),o=!0;return}f.removed.length&&(n.push(`Removed ${f.removed.join(", ")} from ${a}.`),e.dryRun||(l&&Object.keys(f.next).length===0?await ih(a,{force:!0}):await X(a,f.next,{backup:!1}),r.push(a))),f.conflicts.length?(n.push(`Preserved user-modified agents: ${f.conflicts.join(", ")}.`),o=!0):e.dryRun||(await ie(a),await ih(Ia(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await tc(a,Ia(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var fe=[lr,ab,Ps,iC,LC,jC,QC,lS,Jv,fS,fb],pt=e=>fe.find(t=>t.id===e);var Ue=async(e=P,t=wn)=>{let n=await e();if(!n.gateway||!n.clientKey)return;let r=await t().catch(()=>{});return{target:Re({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 uh=5e3,mS=3e4,KF=1440*60*1e3,jF=e=>new Promise(t=>setTimeout(t,e)),ZF=async(e=P,t=wn)=>(await Ue(e,t))?.target,YF=e=>pt(e)?.quitGated,hS=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??YF,o=t.readPending??Qc,a=t.clearPending??Xp,s=t.targetFromProfile??ZF,i=t.sleep??jF,c=t.now??Date.now,l=t.maxWaitMs??KF;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),f=c(),m=uh;for(;;){let p=await o(n);if(!p||c()-f>l)return 0;if(d.isRunning()){await i(m),m=Math.min(mS,m*2);continue}let h;if(d.needsTarget?.(p.op)&&(h=await s(),!h)){if(await a(n,p)!=="superseded")return 0;await i(m),m=uh;continue}if((await u(p.op,h,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(m),m=Math.min(mS,m*2);continue}if(await a(n,p)!=="superseded")return 0;await i(m),m=uh}}catch{return 0}};import{writeFileSync as $W}from"node:fs";import{chmod as vh,stat as MW}from"node:fs/promises";import{platform as jS}from"node:os";import{dirname as ZS,isAbsolute as BW}from"node:path";var JF="https://app.anyray.ai",XF=new Set(["localhost","::1","[::1]"]),zF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,qF=e=>XF.has(e)||zF.test(e),ph=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&qF(t.hostname)},QF=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Xn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!ph(e)?JF:QF(e)};import{createHash as pW,generateKeyPairSync as fW,randomBytes as hh}from"node:crypto";import{createPrivateKey as eW,sign as tW}from"node:crypto";var _r=async(e,t)=>{let n=eW(t);return tW(null,new TextEncoder().encode(e),n).toString("base64url")};var nW=["HTTPS_PROXY","https_proxy"],yS=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"]),gS=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),wS=new Set(["ENOTFOUND","EAI_AGAIN"]),bS=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),AS=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),rW=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 oW(e)},oW=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...yS,...gS,...wS,...bS,...AS])if(t.includes(n))return n}},aW=e=>e?.name==="AbortError"||e?.name==="TimeoutError",sW=e=>nW.filter(t=>(e[t]??"").trim()!==""),iW=(e,t=process.env)=>{let n=rW(e),r=sW(t);return{kind:n&&yS.has(n)?"tls-unknown-issuer":n&&gS.has(n)?"tls-invalid-cert":n&&wS.has(n)?"dns":aW(e)||n&&AS.has(n)?"timeout":n&&bS.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},cW=e=>{let t=e.proxyVars.length>0?` ${e.proxyVars.join(" and ")} ${e.proxyVars.length>1?"are":"is"} set \u2014 if that proxy is stale or unreachable, unset it and re-run.`:"";switch(e.kind){case"tls-unknown-issuer":return` (TLS certificate signed by an unknown authority: ${e.code}). Your network appears to inspect TLS traffic. curl trusts your system keychain and this binary does not, which is why the download worked and this step did not. Point NODE_EXTRA_CA_CERTS at your organization root certificate (PEM) and re-run.`+t;case"tls-invalid-cert":return` (TLS certificate rejected: ${e.code}). Check this machine's clock and date, and whether a proxy is rewriting HTTPS traffic, then re-run.`+t;case"dns":return` (DNS lookup failed: ${e.code}). Check your VPN or DNS, then re-run.`+t;case"refused":return` (connection failed: ${e.code}).`+(t||" Check your network or firewall, then re-run.");case"timeout":return" (timed out before the control plane answered)."+(t||" Check your connection and re-run.");default:return e.code?` (${e.code}).${t}`:t}},ft=(e,t=process.env)=>cW(iW(e,t));var lW="enl_",CS="enp_",kS=e=>e.startsWith(lW)||e.startsWith(CS),fh=e=>e.startsWith(CS),dW=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],mh=e=>dW.find(t=>e.startsWith(t.prefix)),vS=/^\/enroll\/([^/]+)\/?$/,SS=/^\/i\/([^/]+)\/?$/,ES=e=>{let t=e.match(vS);if(t)return mh(t[1])?void 0:t[1];let n=e.match(SS);return n&&kS(n[1])?n[1]:void 0},uW=1e4,Ed=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=ES(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!mh(t))return{cpOrigin:Xn(),token:t}},IS=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(vS)??o.pathname.match(SS);if(!a)return;n=a[1]}catch{}let r=mh(n);return r?{flag:r.flag,what:r.what}:void 0},gi=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:ES(n.pathname)!==void 0}catch{return kS(t)}},xa=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},yi=e=>typeof e=="string"&&e.trim()?e.trim():void 0,xS=async(e,t={})=>{let n=t.timeoutMs??uW,r=`${e.cpOrigin}/enroll-info/${e.token}`,o=new AbortController,a=setTimeout(()=>o.abort(),n),s;try{s=await fetch(r,{method:"GET",signal:o.signal})}catch(u){let f=u instanceof Error&&u.name==="AbortError"?` no response within ${n}ms.`:ft(u);throw new Error(`could not reach the enrollment page at ${e.cpOrigin}.${f}`)}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 xa(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"&&yi(u.url)!==void 0),d=yi(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:yi(l?.deploymentId),org:yi(i.org),email:yi(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 Ee="0.11.188";var yh=1e4,Co=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Co).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Co(e[n])}`).join(",")}}`,RS="stable-key-heartbeat-v1",OS="key-heartbeat",mW=["reapply_config","remint","revert"],gh=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var TS=e=>pW("sha256").update(e).digest("hex"),je=e=>typeof e=="string"&&e.trim()?e.trim():void 0,hW=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],_S={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"},yW=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${_S[e]}. Ask your IT admin.`,gW=e=>typeof e=="string"&&e in _S,wh=async e=>{try{let t=await e.json(),n=je(t?.message),r=je(t?.error),o=gW(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:yW(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},wW=async e=>(await wh(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}},PS=e=>e instanceof xa||e instanceof lt&&e.policyCode==="sso_required",Ra=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}},bh=async(e,t,n,r)=>{try{return await r(Co(e),t)}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},Id=()=>{let{publicKey:e,privateKey:t}=fW("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},tn=async(e,t,n,r={})=>{let o=r.timeoutMs??yh,a=`${e}/connect/verify`,s=je(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:hh(16).toString("hex"),...gh(t,r.machineUuid)},c=await bh(i,n,"verification",r.signer??_r),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":Ee},body:JSON.stringify({cert:t,challenge:i,sig:c,...r.health?{health:r.health}:{},...r.ack?{ack:r.ack}:{},...r.telemetryOnly?{telemetryOnly:!0}:{}}),signal:l.signal})}catch(g){let b=g instanceof Error&&g.name==="AbortError"?` no response within ${o}ms.`:ft(g);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:g})}finally{clearTimeout(d)}if(!u.ok)throw new lt(u.status,await wh(u));let f;try{f=await u.text()}catch{f=""}let m;try{m=JSON.parse(f)}catch{let g=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(g)||/^\s*<(?:!doctype|html)/i.test(f);throw new Error(b?`developer verification failed: ${a} returned an HTML page, not the gateway \u2014 /connect/* is being routed to the console/proxy. Ask your admin to route /connect/* to the gateway service (:8787), the same as /v1/*.`:"developer verification failed: the gateway returned a malformed response")}let p=je(m?.key);if(!p)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(p))throw new Error("developer verification failed: the gateway returned a malformed key");let h=je(m.user);if(!h)throw new Error("developer verification failed: the gateway response is missing the user");let w=bW(m.directive),y=hW(m.capabilities);return{key:p,user:h,team:je(m.team),expiresAt:je(m.expiresAt),...y.length>0?{capabilities:y}:{},...w?{directive:w}:{}}},DS=async(e,t,n,r,o={})=>{let a=o.timeoutMs??yh,s=`${e}/connect/key/heartbeat`,i=je(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:hh(16).toString("hex"),purpose:OS,...gh(n,o.machineUuid)},l=await bh(c,r,"heartbeat",o.signer??_r),d=new AbortController,u=setTimeout(()=>d.abort(),a),f;try{f=await fetch(s,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":Ee},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.`:ft(h);throw new Error(`could not reach the gateway at ${s}.${w}`,{cause:h})}finally{clearTimeout(u)}if(!f.ok)throw new Ra(f.status,await wh(f));let m;try{m=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let p=je(m.expiresAt);if(!p||!Number.isFinite(Date.parse(p))||m.credentialMode!==RS||m.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:p,credentialMode:RS}},LS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??yh,i=`${e.replace(/\/$/,"")}/connect/machine`,c=je(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:hh(16).toString("hex"),purpose:OS,...gh(n,o)},d=await bh(l,r,"heartbeat",a.signer??_r),u=new AbortController,f=setTimeout(()=>u.abort(),s);try{return(await fetch(i,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":Ee},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(m){return console.error("connect machine report skipped:",m instanceof Error?m.name:"error"),!1}finally{clearTimeout(f)}},bW=e=>{if(e===null||typeof e!="object")return null;let t=e,n=je(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!mW.includes(r)?null:{id:n,kind:r}},AW=1e4,CW=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!je(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!je(r.deploymentId)&&!!je(r.user)&&!!je(r.devPublicKey)&&!!je(r.issuedAt)&&!!je(r.expiresAt)},kW=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??AW,s=`${e}/v1/enroll`,i=new AbortController,c=setTimeout(()=>i.abort(),a),l;try{l=await fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:t,devPublicKey:n,...r.email?{email:r.email}:{},...r.team?{team:r.team}:{},...r.machineId?{machineId:r.machineId}:{},...r.deploymentId?{deploymentId:r.deploymentId}:{}}),signal:i.signal})}catch(u){let f=u instanceof Error&&u.name==="AbortError"?` no response within ${a}ms.`:ft(u);throw new Error(`could not reach the control plane at ${s}.${f}`)}finally{clearTimeout(c)}if(!l.ok){let u=`enrollment failed: ${await wW(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new xa(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(!CW(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},NS=(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())},$S=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=Id();return{cert:await kW(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),...s}})(),a=await tn(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 Ah=1e4,vW=900*1e3,BS="tnt_",SW=/^\/sso\/([^/]+)\/?$/,EW=/^\/i\/([^/]+)\/?$/,IW=e=>{let t=e.match(SW);if(t)return t[1];let n=e.match(EW);return n?.[1].startsWith(BS)?n[1]:void 0},Et=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=IW(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(BS))return{cpOrigin:Xn(),tenantId:t}},ko=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Ft=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},Ch=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)}},xW=e=>new Promise(t=>setTimeout(t,e)),xd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??Id)(),a;try{a=await Ch(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},Ah,n)}catch(p){throw new ko("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ft(p)}`)}if(a.status!==200){let p=a.status===404,h=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new ko(p?"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 ko("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??vW,l=typeof s.expires_in=="number"&&s.expires_in>0?s.expires_in*1e3:c,d=typeof s.verification_uri=="string"?s.verification_uri:void 0,u=e.gatewayUrl??(typeof s.gateway_url=="string"?s.gateway_url:void 0),f={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:s.device_code,userCode:s.user_code,verificationUri:d,verificationUriComplete:s.verification_uri_complete,intervalMs:Math.max(1,s.interval||5)*1e3,grantExpiresAt:i+Math.min(c,l),startedAt:i,privateKeyPem:o,publicKeyPem:r,gatewayUrl:u},m=e.log??(()=>{});return m("To finish, sign in with your organization at:"),m(` ${f.verificationUriComplete}`),m(`Confirm this code matches your browser: ${f.userCode}`),RW(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},RW=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Rd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??xW,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 Ch(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},Ah,o)}catch(c){throw new Ft("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ft(c)}`)}if(s.status===200&&s.json.cert)return{cert:s.json.cert,privateKeyPem:e.privateKeyPem,gatewayUrl:t.gatewayUrl??(typeof s.json.gatewayUrl=="string"?s.json.gatewayUrl:e.gatewayUrl),deploymentId:typeof s.json.deploymentId=="string"?s.json.deploymentId:""};let i=typeof s.json.error=="string"?s.json.error:"";if(i!=="authorization_pending"){if(i==="slow_down"){a+=5e3;continue}throw i==="expired_token"?new Ft("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Ft("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Ft("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var MS="sdc_",FS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(MS))return{cpOrigin:Xn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!ph(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(MS)))return{cpOrigin:n.origin,claim:r}},WS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??Id)(),o;try{o=await Ch(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},Ah,t)}catch(s){throw new Ft("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ft(s)}`)}if(o.status===200&&o.json.cert)return{cert:o.json.cert,privateKeyPem:r,gatewayUrl:e.gatewayUrl??(typeof o.json.gatewayUrl=="string"?o.json.gatewayUrl:void 0),deploymentId:typeof o.json.deploymentId=="string"?o.json.deploymentId:"",...typeof o.json.ssoLink=="string"&&o.json.ssoLink?{ssoLink:o.json.ssoLink}:{}};let a=typeof o.json.error=="string"?o.json.error:"";throw a==="expired_token"?new Ft("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Ft("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Ft("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 OW}from"node:fs/promises";import{isAbsolute as TW,posix as US,win32 as kh}from"node:path";var wi=(e=process.platform,t=process.env)=>e==="darwin"?US.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?kh.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):US.join("/etc","anyray","bootstrap.json"),_W=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),HS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(TW(e)||kh.isAbsolute(e))&&!/ark_[A-Za-z0-9_-]{20,}|-----BEGIN/.test(e),PW=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}},Pr=async(e=wi())=>{try{let t=await OW(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!_W(n)||n.v!==1||typeof n.sso!="string")return;let r=Et(n.sso);if(!r)return;let o=PW(n.gateway)?n.gateway:void 0,a=HS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},GS=(e,t,n)=>{let r=Et(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!HS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&kh.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)}
|
|
262
|
-
`};var Oa=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,Od=Oa(process.stdout,process.env),VS=Oa(process.stderr,process.env),Ta=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,K=e=>Ta("1",e,Od),v=e=>Ta("2",e,Od),
|
|
263
|
-
${K(e)}`),L=e=>console.log(v(e)),M=e=>console.log(`${
|
|
254
|
+
}`,Zn=async e=>new Promise((t,n)=>{let r=kM("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",LM],{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(xm(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(xm({signal:c??void 0})));return}t({code:i,stdout:o,missing:i===3})}}),r.stdin.on("error",()=>{}),r.stdin.end(JSON.stringify(e))}),Bt=(e={})=>Aa((e.home??_m)(),".anyray","claude-desktop-windows.json"),NM=e=>Aa((e.home??_m)(),".anyray","claude-desktop-windows.lock"),ga=class extends Error{},$M=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Lm=async e=>{let t=NM(e);await Sm(ci(t),{recursive:!0,mode:448});for(let n=0;n<2;n++){let r=Zk("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex"),o=Aa(t,"owner.json");try{await Sm(t,{mode:448}),await we(o,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
255
|
+
`)}catch(a){if(a.code!=="EEXIST")throw await qt(t,{recursive:!0,force:!0}).catch(()=>{}),a;let s=!1;try{let i=JSON.parse(await Em(o,"utf8"));s=typeof i.pid=="number"&&Number.isSafeInteger(i.pid)&&i.pid>0&&!$M(i.pid)}catch{try{s=Date.now()-(await qk(t)).mtimeMs>3e4}catch{s=!1}}if(!s||n>0)throw new ga;await qt(t,{recursive:!0,force:!0});continue}return async()=>{try{JSON.parse(await Em(o,"utf8")).nonce===r&&await qt(t,{recursive:!0,force:!0})}catch{}}}throw new ga},ov=()=>Object.fromEntries($e.map(e=>[e,{present:!1}])),mo=e=>Zk("sha256").update(e).digest("hex"),MM=(e,t)=>t.present?e===Ca?{present:!0,type:t.type,sha256:mo(t.value??"")}:{present:!0,type:t.type,value:t.value??""}:{present:!1},ha=(e,t)=>e.present!==t.present?!1:e.present?e.type!==t.type?!1:t.sha256!==void 0?mo(e.value??"")===t.sha256:e.value===t.value:!0,Mt=(e,t)=>Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),zl=(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===Ca?Mt(n,["present","type","sha256"])&&typeof n.sha256=="string"&&/^[a-f0-9]{64}$/.test(n.sha256)&&n.value===void 0:Mt(n,["present","type","value"])&&typeof n.value=="string"&&n.sha256===void 0:Object.keys(n).length===1},Mk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Mt(e,$e)&&$e.every(t=>zl(e[t],t)),Bk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Mt(e,Pk)&&Pk.every(t=>zl(e[t],t)),BM=e=>typeof e=="string"&&/^[a-f0-9]{64}$/.test(e),Nm=(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 Mt(n,r)&&n.path===Pm(t)&&(n.lastWritten===void 0||$k(n.lastWritten))&&(n.pending===void 0||$k(n.pending))&&(n.lastWritten!==void 0||n.pending!==void 0)},FM=(e,t)=>Mt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===Xl&&e.registryKey===Le&&typeof e.keyExisted=="boolean"&&Mk(e.lastWritten)&&(e.pending===void 0||Mk(e.pending))&&Nm(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),WM=e=>Mt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten"]:["version","registryKey","keyExisted","lastWritten","pending"])&&e.version===2&&e.registryKey===Le&&typeof e.keyExisted=="boolean"&&Bk(e.lastWritten)&&(e.pending===void 0||Bk(e.pending)),Fk=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Mt(e,Dk)&&Dk.every(t=>zl(e[t],t)),UM=(e,t)=>Mt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===3&&e.registryKey===Le&&typeof e.keyExisted=="boolean"&&Fk(e.lastWritten)&&(e.pending===void 0||Fk(e.pending))&&Nm(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)&&Mt(e,Lk)&&Lk.every(t=>zl(e[t],t)),HM=(e,t)=>Mt(e,e.pending===void 0?["version","registryKey","keyExisted","lastWritten","helper"]:["version","registryKey","keyExisted","lastWritten","pending","helper"])&&e.version===4&&e.registryKey===Le&&typeof e.keyExisted=="boolean"&&Wk(e.lastWritten)&&(e.pending===void 0||Wk(e.pending))&&Nm(e.helper,t)&&(e.pending===void 0&&e.helper.pending===void 0||e.pending!==void 0&&e.helper.pending!==void 0),Uk=e=>({...e,coworkEgressAllowedHosts:{present:!1}}),$m=e=>{let{pending:t,...n}=e;return{...n,version:Xl,lastWritten:Uk(e.lastWritten),...t?{pending:Uk(t)}:{}}},Hk=e=>({...e,chatTabEnabled:{present:!1}}),GM=e=>{let{pending:t,...n}=e;return $m({...n,version:4,lastWritten:Hk(e.lastWritten),...t?{pending:Hk(t)}:{}})},Gk=e=>({inferenceProvider:e.inferenceProvider,inferenceGatewayBaseUrl:e.inferenceGatewayBaseUrl,inferenceGatewayAuthScheme:e.inferenceGatewayAuthScheme,inferenceCredentialKind:{present:!1},inferenceCredentialHelper:{present:!1},chatTabEnabled:{present:!1},inferenceGatewayApiKey:e.inferenceGatewayApiKey}),VM=(e,t)=>$m({version:4,registryKey:Le,keyExisted:e.keyExisted,lastWritten:Gk(e.lastWritten),...e.pending?{pending:Gk(e.pending)}:{},helper:{path:Pm(t)}}),Mm=async(e,t=!0)=>{let n=Bt(e),r=ci(n),o=`${Qk(n)}.anyray-old-`,a=(await Xk(r).catch(()=>[])).filter(l=>l.startsWith(o)).map(l=>Aa(r,l)),s=n;if(!await x(n)){if(a.length===0)return;if(a.length!==1)throw new Error("ambiguous Windows ownership journal recovery files");t?await zk(a[0],n):s=a[0]}let i=await B(s),c=WM(i)?VM(i,e):UM(i,e)?GM(i):HM(i,e)?$m(i):FM(i,e)?i:void 0;if(!c)throw new Error("invalid Windows ownership journal");return t&&await Promise.all(a.map(l=>qt(l,{force:!0}))),c},Vk=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:Le,keyExisted:e.keyExisted,lastWritten:Vk(e.lastWritten),...e.pending?{pending:Vk(e.pending)}:{}}:e,Zl=async(e,t)=>{let n=Bt(t),r=`${JSON.stringify(KM(e),null,2)}
|
|
256
|
+
`;t.writeJournalFile?await t.writeJournalFile(n,r):await we(n,r)},jM=/^(\S+)\s+(REG_[A-Z_]+)(?:\s+(.*))?$/,ZM=new Set(["REG_SZ","REG_EXPAND_SZ","REG_DWORD"]),YM=new Set(["REG_QWORD","REG_MULTI_SZ","REG_BINARY","REG_NONE"]),JM=e=>e.replace(/^HKCU\\/i,"HKEY_CURRENT_USER\\").replace(/^HKLM\\/i,"HKEY_LOCAL_MACHINE\\"),XM=(e,t)=>e.toUpperCase()===t.toUpperCase()||e.toUpperCase()===JM(t).toUpperCase(),Kk=(e,t,n,r,o)=>{let a=$e.find(i=>i.toLowerCase()===t.toLowerCase());if(!a)return!1;let s=n==="String"?"REG_SZ":n==="ExpandString"?"REG_EXPAND_SZ":n;if(s!=="REG_SZ"&&s!=="REG_EXPAND_SZ"){if(o)throw new Error("an owned Claude policy value has an unsupported type");return!1}if(e[a].present)throw new Error("a Claude policy value was returned more than once");return e[a]={present:!0,type:s,value:r},!0},zM=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,qM=(e,t)=>{if(!Ul(e,!0))return!1;let n=zM(t);if(YM.has(n))return!1;if(ZM.has(n))return n==="REG_EXPAND_SZ"?!0:!ik(e,!0)},QM=(e,t)=>{let n=ov(),r=!1,o=!1,a=!1,s=t.toUpperCase()===ii.toUpperCase(),i=(l,d)=>{if(!s)return;let u=qM(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),Kk(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=jM.exec(d);if(!u){r=!0,a=!0;continue}u[1]==="(Default)"&&(u[3]??"")==="(value not set)"||(i(u[1],u[2]),Kk(n,u[1],u[2],u[3]??"",!s)||(r=!0))}return{keyPresent:!0,values:n,foreignState:r,machinePolicyActive:o,unparsed:a}},jn=async(e,t=Le)=>{let n=await e(["query",t]);if(n.code!==0){if(n.missing===!0)return{keyPresent:!1,values:ov(),foreignState:!1,machinePolicyActive:!1,unparsed:!1};throw new Error("registry query failed without proving the key is absent")}return QM(n.stdout,t)},Or=async e=>{let t=await jn(e,ii);return t.keyPresent?t.unparsed?{names:[],unparsed:!0}:t.machinePolicyActive?{names:[...$e.filter(r=>t.values[r].present)],unparsed:!1}:void 0:void 0},Bm=e=>e.unparsed?`This machine may have a Claude policy under ${ii} that could not be read; it would shadow HKCU, so local configuration was left unchanged.`:e.names.length>0?`A Claude policy under ${ii} sets ${e.names.join(", ")}; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`:`A Claude policy under ${ii} contains a recognized configuration value; Claude treats HKLM as the complete configuration and shadows HKCU, so local configuration was left unchanged.`;var ql=(e,t)=>Rr(po(e,t)),av=(e,t,n,r="REG_SZ")=>["add",e,"/v",t,"/t",r,"/d",n,"/f"],eB=(e,t)=>{let n=ql(e,t);return Object.fromEntries($e.map(r=>{let o=n[r];return[r,o===void 0?{present:!1}:{present:!0,type:"REG_SZ",value:o}]}))},tB=(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}}),nB=e=>e.helper.lastWritten===void 0&&e.helper.pending===void 0&&e.lastWritten.inferenceGatewayApiKey.present,Rm=e=>Object.fromEntries($e.map(t=>[t,MM(t,e[t])])),jk=(e,t,n,r)=>({version:Xl,registryKey:Le,keyExisted:e,lastWritten:Rm(t),helper:{path:n,lastWritten:Im(r)}}),rB=(e,t,n,r,o,a)=>({version:Xl,registryKey:Le,keyExisted:e,lastWritten:Rm(t),pending:Rm(n),helper:{path:r,...o?{lastWritten:Im(o)}:{},pending:Im(a)}}),Om=(e,t,n)=>ha(n,e.lastWritten[t])||e.pending!==void 0&&ha(n,e.pending[t]),wa=async e=>{try{let t=await Em(e,"utf8");return{content:t,sha256:mo(t)}}catch(t){if(t.code==="ENOENT")return;throw t}},ba=async e=>(await wa(e))?.sha256,ya=(e,t)=>t===e.helper.lastWritten?.sha256||t===e.helper.pending?.sha256,Jl=async(e,t)=>{let n=PM(e),r;try{r=await Xk(ci(e))}catch(c){if(c.code==="ENOENT")return;throw c}let o=r.filter(c=>c.startsWith(n)).map(c=>Aa(ci(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([wa(e),wa(a)]);if(!i)throw new Error("credential helper recovery file disappeared");if(!s){if(!t||!ya(t,i.sha256))throw new Error("credential helper recovery is not journal-owned");if(!await rv(e,a))throw new Error("credential helper changed during recovery");return}if(t&&ya(t,s.sha256)&&ya(t,i.sha256)){await qt(a,{force:!0});return}throw new Error("credential helper recovery conflicts with current file")},Fm=async(e,t,n)=>(n.present?await e(av(Le,t,n.value??"",n.type??"REG_SZ")):await e(["delete",Le,"/v",t,"/f"])).code===0,oB=async(e,t,n)=>{let r=!0,o=await jn(e);for(let a of $e)if(!ma(o.values[a],t[a])){if(!ma(o.values[a],n[a])){r=!1;continue}await Fm(e,a,t[a])||(r=!1),o=await jn(e)}return r&&$e.every(a=>ma(o.values[a],t[a]))},ze=(e,t=!1,n={})=>({status:"manual",messages:[e],...t&&{changedFiles:[Bt(n)]}}),sv=async(e,t,n,r={})=>{if(!Ae(t))return ze("A valid personal ark_ gateway key is required.",!1,r);let o=Pm(r),a;try{a=xM((r.credentialCommand??ym)())}catch{return ze("A durable local anyray-connect runtime is required for Claude Desktop's automatic credential helper.",!1,r)}let s=mo(a),i=r.runReg??Zn,c=Bt(r),l;if(!n.dryRun)try{l=await Lm(r)}catch(h){return ze(h instanceof ga?"Another Claude Desktop policy operation is already in progress; retry shortly.":"Could not acquire the owner-only Claude Desktop policy lock; the registry was left unchanged.",!1,r)}let d,u,f,m,p=!1;try{let h=await Or(i);if(h)return ze(Bm(h),!1,r);let g=await Mm(r,!n.dryRun);n.dryRun||await Jl(o,g);let y=await jn(i),w=eB(e,o),b=await wa(o),k=b?.sha256,C=!1;if(d=g,u=y,f=w,g){let I=$e.find(_=>!Om(g,_,y.values[_]));if(I)return ze(`Claude's ${I} policy changed after Connect configured it; the existing value was preserved. Revert or remove that value before reapplying.`,!1,r);if(k!==void 0&&!ya(g,k))return ze(`Claude's credential helper changed after Connect configured it; ${o} was preserved. Revert or remove it before reapplying.`,!1,r);C=nB(g)}else{if(k!==void 0&&k!==s)return ze(`Existing file ${o} is not the Anyray helper for this runtime. It was left unchanged.`,!1,r);let I=y.foreignState||$e.some(W=>y.values[W].present),_=$e.every(W=>ma(y.values[W],w[W])),T=$e.every(W=>ma(y.values[W],tB(e,t.trim())[W]));if(I&&!_&&!T)return ze(`Existing Claude third-party-inference policy values under ${Le} are not owned by Anyray. They were left unchanged to avoid copying or overwriting another provider credential.`,!1,r);if(C=T,_&&k===s)return n.dryRun?{status:"configured",messages:[`Would adopt the exact dynamic-helper values under ${Le} into an owner-only journal without rewriting them.`]}:(await Zl(jk(y.keyPresent,w,o,a),r),{status:"configured",changedFiles:[c],messages:[`Adopted the exact dynamic-helper values under ${Le} into the ownership journal.`]})}if(C){let I=!0;try{I=(r.appRunning??Dm)()}catch{}if(I)return ze("Claude Desktop is running. Fully quit it, then re-run Connect to migrate the legacy static credential safely.",!1,r)}let S=rB(g?.keyExisted??y.keyPresent,y.values,w,o,b?.content,a);if(m=S,n.dryRun)return{status:"configured",messages:[`Would atomically configure Claude Desktop through ${Le}, install a dynamic credential helper at ${o}, and create an owner-only rollback journal.`]};await Zl(S,r),p=!0;for(let I of $e){let _=await jn(i);if(!ha(_.values[I],S.lastWritten[I])&&!ha(_.values[I],S.pending[I]))throw new Error("registry value changed during apply");if(!ma(_.values[I],w[I])&&!await Fm(i,I,w[I]))throw new Error("registry write failed")}let E=await jn(i);if(!$e.every(I=>ha(E.values[I],S.pending[I])))throw new Error("registry verification failed");if(k!==s&&(k===void 0?await _M(o,a):await Yl(o,k,a,"apply",r)),await ba(o)!==s)throw new Error("credential helper verification failed");return await Zl(jk(S.keyExisted,w,o,a),r),{status:"configured",changedFiles:[c,o],messages:[`Configured Claude Desktop through ${Le}.`,`Installed or updated the dynamic credential helper at ${o}; no personal key is stored in policy or the ownership journal.`,"Fully quit and reopen Claude Desktop to load the policy.",...Bl(gt("migrate"))]}}catch{if(!p||!u||!f||!m)return ze("Could not safely inspect or begin Claude Desktop's HKCU policy transaction; the registry was left unchanged.",!1,r);try{await Jl(o,m);let h=!0,g=await wa(o),y=m.helper.pending;if(g?.sha256!==m.helper.lastWritten?.sha256&&(y!==void 0&&g?.sha256===y.sha256?m.helper.lastWritten?(await Yl(o,y.sha256,m.helper.lastWritten.content,"rollback",r),h=await ba(o)===m.helper.lastWritten.sha256):await Yl(o,y.sha256,void 0,"rollback",r):h=g===void 0&&m.helper.lastWritten===void 0),h&&await oB(i,u.values,f))return d?await Zl(d,r):await qt(c,{force:!0}),ze("Claude Desktop's HKCU policy update failed and was rolled back to its exact pre-apply state.",!1,r)}catch{}return ze("Could not complete or fully roll back Claude Desktop's HKCU policy transaction. The owner-only journal was preserved; run `anyray-connect desktop disconnect` to recover safely.",!0,r)}finally{await l?.()}},iv=async(e,t={})=>{let n=t.runReg??Zn,r=Bt(t),o;if(!e.dryRun)try{o=await Lm(t)}catch(a){return ze(a instanceof ga?"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 Mm(t,!e.dryRun);a&&!e.dryRun&&await Jl(a.helper.path,a);let s=await jn(n);if(!a)return $e.filter(p=>s.values[p].present).length>0?ze(`Claude policy values exist under ${Le}, but Anyray has no ownership journal. Remove them manually only if you know they came from an older Connect run.`,!1,t):{status:"not-found",messages:["No Windows Claude setup to revert."]};let i=$e.filter(m=>s.values[m].present&&!Om(a,m,s.values[m])),c=await ba(a.helper.path),l=c!==void 0&&!ya(a,c);if(e.dryRun)return{status:i.length||l?"manual":"reverted",messages:[`Would remove Anyray-owned values from ${Le}.`,`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 m of $e){let h=(await jn(n)).values[m];if(h.present){if(!Om(a,m,h)){u.add(m);continue}await Fm(n,m,{present:!1})||(d=!0)}}let f=await ba(a.helper.path);if(f!==void 0)if(ya(a,f))try{await Yl(a.helper.path,f,void 0,"revert",t)}catch{d=!0,u.add("credential helper")}else u.add("credential helper");return d?ze(`Could not remove every Anyray-owned Claude policy value or credential-helper file. The ownership journal remains at ${r}; re-run revert.`,!0,t):(await qt(r,{force:!0}),{status:u.size?"manual":"reverted",changedFiles:[r],messages:[`Removed Anyray-owned Claude Desktop values from ${Le}.`,"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?[]:Fl]})}catch{return ze(`Could not safely inspect or revert ${Le}; no unproven value was removed.`,!1,t)}finally{await o?.()}},cv=async(e,t={})=>{let n=t.runReg??Zn;if(!await x(Bt(t)))return;let r;try{r=await Lm(t);let o=await Mm(t);if(o&&await Jl(o.helper.path,o),!o||o.pending||await Or(n)!==void 0)return;let a=await jn(n);if(!(a.values.inferenceProvider.value==="gateway"&&a.values.inferenceGatewayBaseUrl.value===Kt(e)&&a.values.inferenceGatewayAuthScheme.value==="bearer"&&$e.every(l=>ha(a.values[l],o.lastWritten[l]))))return;let i=await ba(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 TM(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?.()}},lv=async(e,t={})=>await cv(e,t)!==void 0,dv=async(e,t={})=>await cv(e,t)==="dynamic";var ka=(e=sB())=>e==="win32"?Dm:Vl,Wm="You can still make this export searchable with `anyray-connect history import <conversations.json>`.",ed=async(e,t={})=>{let n=(t.profileRoot??uo)();if(!n)return{ok:!1,reason:"this platform has no Claude Desktop third-party profile",remedy:Wm};if((t.appRunning??ka(t.runtimePlatform))())return{ok:!1,reason:"Claude Desktop is running",remedy:"Fully quit Claude Desktop, then run this again."};try{await uv.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 Ml(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 "+Wm}:{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??ek)();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=Ql(t.stagingRoot??iB(),`anyray-history-${process.pid}-${aB()}`);try{let s=await(t.runImporter??tk)({binary:o,exportPath:e,configDir:Ql(a,"config"),workDir:Ql(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. "+Wm};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 rk(r.dir,s.conversations),c=await ok({stagedProjectsDir:Ql(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 uv.rm(a,{recursive:!0,force:!0}).catch(()=>{})}};import{promises as St}from"node:fs";import{homedir as OB}from"node:os";import{join as en,sep as TB}from"node:path";import{isDeepStrictEqual as od}from"node:util";import{constants as cB}from"node:fs";import{promises as V}from"node:fs";import{dirname as va,isAbsolute as Hm,join as ae,relative as td,resolve as Qt,sep as li}from"node:path";import{randomUUID as ad}from"node:crypto";var vn=448,di=384,hv=448,lB=4,Gm=3e4,yv=5e3,dB=10*6e4,Um=e=>({kind:e,migrated:0,alreadyPresent:0,conflicts:0,invalid:0,failed:0}),ct=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ui=e=>typeof e=="string"&&e.length>0&&e.length<=255&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),gv=(e,t)=>{let n=td(Qt(e),Qt(t));return n===""||!n.startsWith(`..${li}`)&&n!==".."&&!Hm(n)},ho=async e=>{try{let t=await V.readFile(e,"utf8"),n=JSON.parse(t);return ct(n)?{raw:t,value:n}:void 0}catch(t){return vt(t)&&t.code==="ENOENT"?{raw:void 0,value:{}}:void 0}},vt=e=>e instanceof Error&&"code"in e,uB=e=>{try{return process.kill(e,0),!0}catch(t){return vt(t)&&t.code==="EPERM"}},wv=e=>e===0?"owner.json":`owner.${e}.json`,nd=async e=>{let t;try{t=await V.readdir(e)}catch{return}let r=t.map(d=>{if(d==="owner.json")return{name:d,generation:0};let u=/^owner\.(\d+)\.json$/.exec(d);if(!u)return;let f=Number(u[1]);return Number.isSafeInteger(f)&&f>0?{name:d,generation:f}:void 0}).filter(d=>!!d).sort((d,u)=>u.generation-d.generation)[0];if(!r)return;let o=ae(e,r.name),a,s,i;try{let d=JSON.parse(await V.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 V.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}},bv=e=>{if(e.pid===void 0||!uB(e.pid))return!0;let t=Date.now();return t-e.mtimeMs>Gm&&t-e.createdAtMs>dB},pB=async e=>{let t=`${e}.anyray-lock`;await V.mkdir(va(t),{recursive:!0,mode:vn});let n=ad(),r,o=!1;try{await V.mkdir(t,{mode:vn}),o=!0}catch(i){if(!vt(i)||i.code!=="EEXIST")throw i}for(let i=0;i<3&&!r;i+=1){let c=0;if(!o){let d=await nd(t);if(d){if(!bv(d)||!Number.isSafeInteger(d.generation+1))return;c=d.generation+1}else if(await V.stat(t).then(f=>Date.now()-f.mtimeMs).catch(()=>0)<=Gm)return}let l=ae(t,wv(c));try{await V.writeFile(l,`${JSON.stringify({pid:process.pid,nonce:n,createdAt:Date.now()})}
|
|
257
|
+
`,{flag:"wx",mode:di}),r=l}catch(d){if(vt(d)&&d.code==="EEXIST"){o=!1;continue}throw o&&await V.rm(t,{recursive:!0,force:!0}).catch(()=>{}),d}}if(!r)return;let a=r,s=setInterval(()=>{(async()=>{try{let i=JSON.parse(await V.readFile(a,"utf8"));if(!ct(i)||i.nonce!==n)return;let c=new Date;await V.utimes(a,c,c)}catch{}})()},yv);return s.unref(),async()=>{clearInterval(s);try{(await nd(t))?.nonce===n&&await V.rm(t,{recursive:!0,force:!0})}catch{}}},fB=async(e,t,n)=>{await V.mkdir(va(e),{recursive:!0,mode:vn});let r=await pB(e);if(!r)return!1;try{let o;try{o=await V.readFile(e,"utf8")}catch(s){if(!vt(s)||s.code!=="ENOENT")throw s}if(o!==t)return!1;let a=`${e}.anyray-tmp-${process.pid}-${ad()}`;try{await V.writeFile(a,`${JSON.stringify(n,null,2)}
|
|
258
|
+
`,{mode:di,flag:"wx"}),await V.rename(a,e)}catch(s){try{await V.rm(a,{force:!0})}catch{}throw s}return!0}finally{await r()}},sd=async(e,t)=>{for(let n=0;n<lB;n+=1){let r=await ho(e);if(!r)return"failed";let o=t(r.value);if(!o||od(o,r.value))return"unchanged";try{if(await fB(e,r.raw,o))return"written"}catch{return"failed"}}return"failed"},pv=async e=>{try{return(await V.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},id=async e=>{let t=[];for(let n of await pv(e))for(let r of await pv(ae(e,n)))t.push(ae(e,n,r));return t},mB=e=>Array.isArray(e.skills)?e.skills.filter(t=>ct(t)&&ui(t.name)&&t.creatorType==="user"&&t.syncManaged===!1):[],hB=async e=>{let t=ae(e,"local-agent-mode-sessions","skills-plugin"),n=[];for(let r of await id(t)){let o=await ho(ae(r,"manifest.json"));if(!o)continue;let a=r.split(li).at(-1)??"";for(let s of mB(o.value))n.push({account:a,packageDir:r,entry:s})}return n},yB=async e=>{let t=await ho(ae(e,".claude-plugin","plugin.json"));return!!t&&ui(t.value.name)},gB=(e,t)=>{let n=Hm(t)?Qt(t):Qt(e,t);if(!gv(e,n)||n===Qt(e))return;let r=td(Qt(e),n);return r.length>0?{absolute:n,relative:r}:void 0},wB=async e=>{let t=await id(ae(e,"local-agent-mode-sessions")),n=[];for(let r of t){if(r.split(li).includes("skills-plugin"))continue;let o=ae(r,"cowork_plugins"),a=await ho(ae(o,"installed_plugins.json"));if(!a||!ct(a.value.plugins))continue;let s=r.split(li).at(-2)??"";for(let[i,c]of Object.entries(a.value.plugins))if(!(!ui(i)||!Array.isArray(c)))for(let l of c){if(!ct(l)||l.scope!=="user"||typeof l.installPath!="string")continue;let d=gB(o,l.installPath);!d||!await yB(d.absolute)||n.push({account:s,id:i,entry:l,packageDir:d.absolute,relativeInstallPath:d.relative,settingsFile:ae(r,"cowork_account_settings.json")})}}return n},bB=async e=>{let t=await ho(ae(e,"claude_desktop_config.json"));return!t||!ct(t.value.mcpServers)?{}:Object.fromEntries(Object.entries(t.value.mcpServers).filter(([n,r])=>ui(n)&&n.toLowerCase()!=="anyray"&&ct(r)))},Av=async e=>{let[t,n,r]=await Promise.all([hB(e),wB(e),bB(e)]);return{skills:t,plugins:n,localMcpServers:r}},Vm=async e=>{let t=await Av(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)}},fv=async e=>{try{let n=await V.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())return!1}catch{return!1}let t=async n=>{let r;try{r=await V.readdir(n,{withFileTypes:!0})}catch{return!1}for(let o of r){if(!ui(o.name))return!1;let a=ae(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)},AB=async e=>{let t=async n=>{let r=await V.readdir(n,{withFileTypes:!0});for(let o of r){let a=ae(n,o.name);if(o.isDirectory())await t(a),await V.chmod(a,vn);else if(o.isFile()){let s=await V.stat(a);await V.chmod(a,(s.mode&73)!==0?hv:di)}}};await t(e),await V.chmod(e,vn)},Cv=async(e,t)=>{try{let[n,r]=await Promise.all([V.readFile(e),V.readFile(t)]);return n.equals(r)}catch{return!1}},rd=async(e,t)=>{try{let[n,r]=await Promise.all([V.readdir(e,{withFileTypes:!0}),V.readdir(t,{withFileTypes:!0})]),o=n.map(s=>s.name).sort(),a=r.map(s=>s.name).sort();if(!od(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 rd(ae(e,s),ae(t,s)))return!1}else if(!i.isFile()||!await Cv(ae(e,s),ae(t,s)))return!1}return!0}catch{return!1}},kv=e=>`${e}.anyray-incomplete`,vv=async(e,t)=>{let n=!1;if(t){await V.mkdir(va(e),{recursive:!0,mode:vn});try{await V.mkdir(e,{mode:vn}),n=!0}catch(l){if(!vt(l)||l.code!=="EEXIST")return}}else try{let l=await V.lstat(e);if(!l.isDirectory()||l.isSymbolicLink())return}catch{return}let r=ad(),o;for(let l=0;l<3&&!o;l+=1){let d=0;if(!n){let f;try{f=await nd(e)}catch{return}if(f){if(!bv(f)||!Number.isSafeInteger(f.generation+1))return;d=f.generation+1}else if(await V.stat(e).then(p=>Date.now()-p.mtimeMs).catch(()=>0)<=Gm)return}let u=ae(e,wv(d));try{await V.writeFile(u,`${JSON.stringify({pid:process.pid,nonce:r,createdAt:Date.now()})}
|
|
259
|
+
`,{flag:"wx",mode:di}),o=u}catch(f){if(vt(f)&&f.code==="EEXIST"){n=!1;continue}n&&await V.rm(e,{recursive:!0,force:!0}).catch(()=>{});return}}if(!o)return;let a=o,s=setInterval(()=>{(async()=>{try{let l=JSON.parse(await V.readFile(a,"utf8"));if(!ct(l)||l.nonce!==r)return;let d=new Date;await V.utimes(a,d,d)}catch{}})()},yv);s.unref();let i=!1,c=()=>{i||(i=!0,clearInterval(s))};return{abandon:c,complete:async()=>{c();try{(await nd(e))?.nonce===r&&await V.rm(e,{recursive:!0,force:!0})}catch{}}}},Sv=async e=>{let t=await vv(e,!1);t&&await t.complete()},CB=async(e,t,n)=>{let r=kv(t),o=!1;try{let c=await V.lstat(t);if(!c.isDirectory()||c.isSymbolicLink())return"conflict";if(o=!0,await rd(e,t))return await Sv(r),"present"}catch(c){if(!vt(c)||c.code!=="ENOENT")return"failed"}if(o)try{let c=await V.lstat(r);if(!c.isDirectory()||c.isSymbolicLink())return"conflict"}catch{return"conflict"}let a=await vv(r,!o);if(!a)return"failed";try{await n?.(t)}catch{return a.abandon(),"failed"}if(!o)try{await V.mkdir(t,{mode:vn})}catch(c){if(!vt(c)||c.code!=="EEXIST")return a.abandon(),"failed";try{let l=await V.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 V.readdir(c,{withFileTypes:!0})}catch{return"failed"}for(let u of d){let f=ae(c,u.name),m=ae(l,u.name);try{if(u.isDirectory()){try{await V.mkdir(m,{mode:vn})}catch(h){if(!vt(h)||h.code!=="EEXIST")throw h;let g=await V.lstat(m);if(!g.isDirectory()||g.isSymbolicLink())return"conflict"}let p=await s(f,m);if(p!=="copied")return p}else if(u.isFile())try{await V.copyFile(f,m,cB.COPYFILE_EXCL);let p=await V.stat(f);await V.chmod(m,(p.mode&73)!==0?hv:di)}catch(p){if(!vt(p)||p.code!=="EEXIST")throw p;if(!await Cv(f,m))return"conflict"}else return"failed"}catch(p){return vt(p)&&p.code==="EEXIST"?"conflict":"failed"}}return"copied"},i=await s(e,t);return i==="failed"?(a.abandon(),"failed"):i==="conflict"?(await a.complete(),"conflict"):await rd(e,t)?(await a.complete(),"copied"):(await a.complete(),"conflict")},Ev=async(e,t,n,r)=>{if(!await fv(e))return"invalid";try{let a=await V.lstat(t);if(!a.isDirectory()||a.isSymbolicLink())return"conflict";if(await rd(e,t))return await Sv(kv(t)),"present"}catch(a){if(!vt(a)||a.code!=="ENOENT")return"failed"}await V.mkdir(va(t),{recursive:!0,mode:vn});let o=ae(va(t),`.anyray-stage-${ad()}`);try{return await V.cp(e,o,{recursive:!0,force:!1,errorOnExist:!0}),await fv(o)?(await AB(o),await n?.(t),await CB(o,t,r)):"invalid"}catch{return"failed"}finally{try{await V.rm(o,{recursive:!0,force:!0})}catch{}}},mv=(e,t,n)=>n||!t?e:e.filter(r=>r.account.startsWith(t)),kB=async e=>{let t=await id(ae(e,"local-agent-mode-sessions","skills-plugin")),n=[];for(let r of t)(await ho(ae(r,"manifest.json")))?.raw!==void 0&&n.push(r);return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},vB=async e=>{let t=await id(ae(e,"local-agent-mode-sessions")),n=[];for(let r of t)if(!r.split(li).includes("skills-plugin"))try{await V.access(ae(r,"cowork_account_settings.json")),n.push(r)}catch{}return n.length===1?{state:"found",path:n[0]}:{state:n.length===0?"missing":"ambiguous"}},SB=async(e,t,n,r,o)=>{let a=ae(t,"manifest.json");for(let s of e){let i=ae(s.packageDir,"skills",s.entry.name);try{await V.access(ae(i,"SKILL.md"))}catch{n.invalid+=1;continue}let c=ae(t,"skills",s.entry.name),l=await Ev(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 sd(a,f=>{let m=Array.isArray(f.skills)?f.skills:[];if(m.find(h=>ct(h)&&typeof h.name=="string"&&h.name.toLowerCase()===s.entry.name.toLowerCase())){d=!0;return}return{...f,skills:[...m,s.entry]}})==="failed"?n.failed+=1:d||l==="present"?n.alreadyPresent+=1:n.migrated+=1}},Iv=(e,t)=>({...e,installPath:t}),EB=(e,t,n,r,o)=>{if(typeof r.installPath!="string")return!1;let a=Hm(r.installPath)?Qt(r.installPath):Qt(o,r.installPath),s=Iv(e,td(Qt(t),Qt(n))),i={...r,installPath:td(Qt(o),a)};return od(s,i)},IB=async(e,t,n)=>{let r=await ho(e);if(!r||!ct(r.value.enabledPlugins))return"unchanged";let o=r.value.enabledPlugins[n];return typeof o!="boolean"?"unchanged":sd(t,a=>{let s=ct(a.enabledPlugins)?a.enabledPlugins:{};if(!(n in s))return{...a,enabledPlugins:{...s,[n]:o}}})},xB=async(e,t,n,r,o)=>{let a=ae(t,"cowork_plugins"),s=ae(a,"installed_plugins.json"),i=ae(t,"cowork_account_settings.json");for(let c of e){let l=ae(a,c.relativeInstallPath);if(!gv(a,l)){n.invalid+=1;continue}let d=await Ev(c.packageDir,l,r,o);if(d==="conflict"){n.conflicts+=1;continue}if(d==="invalid"){n.invalid+=1;continue}if(d==="failed"){n.failed+=1;continue}let u=!1,f=!1;await sd(s,p=>{let h=ct(p.plugins)?p.plugins:{},g=h[c.id],y=Array.isArray(g)?g:[],w=y.find(k=>ct(k)&&k.scope==="user");if(w){u=EB(c.entry,va(c.settingsFile),c.packageDir,w,t),f=!u;return}let b=Iv(c.entry,l);return{...p,version:typeof p.version=="number"?p.version:2,plugins:{...h,[c.id]:[...y,b]}}})==="failed"?n.failed+=1:f?n.conflicts+=1:await IB(c.settingsFile,i,c.id)==="failed"?n.failed+=1:u||d==="present"?n.alreadyPresent+=1:n.migrated+=1}},RB=async(e,t,n)=>{let r=ae(t,"claude_desktop_config.json");for(let[o,a]of Object.entries(e)){let s={value:"migrated"};await sd(r,c=>{let l=ct(c.mcpServers)?c.mcpServers:{};if(o in l){s.value=od(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}},xv=async(e,t,n={})=>{let r=await Av(e),o=Um("skill"),a=Um("plugin"),s=Um("local-mcp"),i=[],c=[],l=mv(r.skills,n.account,n.allAccounts),d=mv(r.plugins,n.account,n.allAccounts);if(n.allowedAccounts&&!n.allAccounts){let f=new Set(n.allowedAccounts);if([...new Set([...l.map(p=>p.account),...d.map(p=>p.account)])].some(p=>!f.has(p)))return{outcomes:[o,a,s],blocked:i,ambiguous:c,sourceChanged:!0,retryable:[]}}if(l.length>0){let f=await kB(t);f.state==="found"?await SB(l,f.path,o,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("skill"):(o.conflicts+=l.length,c.push("skill"))}if(d.length>0){let f=await vB(t);f.state==="found"?await xB(d,f.path,a,n.beforeDirectoryPublish,n.afterDirectoryClaim):f.state==="missing"?i.push("plugin"):(a.conflicts+=d.length,c.push("plugin"))}await RB(r.localMcpServers,t,s);let u=[o,a,s];return{outcomes:u,blocked:i,ambiguous:c,sourceChanged:!1,retryable:u.filter(f=>f.failed>0).map(f=>f.kind)}};var _B=async e=>{try{return await St.access(e),!0}catch{return!1}},Rv=448,PB=384,Tv={code:"claude-code-sessions",cowork:"local-agent-mode-sessions"},DB=["code","cowork"],Zm=(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.",Km=e=>({lane:e,migrated:0,alreadyPresent:0,skippedNoTranscript:0,failed:0}),_v=async e=>{let t;try{t=(await St.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()&&da(r.name)).map(r=>r.name)}catch{return[]}let n=[];for(let r of t)try{let o=(await St.readdir(en(e,r),{withFileTypes:!0})).filter(a=>a.isDirectory()&&da(a.name)).map(a=>a.name);for(let a of o)n.push(en(e,r,a))}catch{}return n},LB=async e=>{try{return(await St.readdir(e)).filter(t=>t.startsWith(Vn)&&t.endsWith(".json")).map(t=>t.slice(Vn.length,-5)).filter(da)}catch{return[]}},NB=async(e,t)=>{let n=await _v(en(e,Tv[t])),r=[];for(let o of n){let a=await LB(o);a.length>0&&r.push({dir:o,ids:a,account:o.split(TB).slice(-2)[0]})}return r},$B=async(e,t)=>{if(t==="cowork"){let r=await Ml(e);return r.ok?{dir:r.dir}:{missing:r.reason}}let n=await _v(en(e,Tv.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 St.copyFile(e,n),await St.chmod(n,PB),await St.rename(n,t)},BB=async(e,t)=>{try{let n=JSON.parse(await St.readFile(e,"utf8"));if(!n||typeof n!="object")return!1;let{cwd:r,cliSessionId:o}=n;return typeof r!="string"||typeof o!="string"||r.length===0||!da(o)?!1:(await St.access(en(t,".claude","projects",dm(r),`${o}.jsonl`)),!0)}catch{return!1}},FB=async(e,t,n,r)=>{let o=Km(e),a=await um(n);for(let s of t)await WB(e,s,n,r,a,o);return o},WB=async(e,t,n,r,o,a)=>{for(let s of t.ids){if(o.has(s)){a.alreadyPresent+=1;continue}let i=`${Vn}${s}.json`,c=en(t.dir,i);try{if(e==="code"){if(!await BB(c,r)){a.skippedNoTranscript+=1;continue}}else{let l=en(t.dir,`${Vn}${s}`),d=en(n,`${Vn}${s}`),u=await St.readdir(l);await St.mkdir(d,{mode:Rv});for(let f of u)await St.cp(en(l,f),en(d,f),{recursive:!0,force:!1,errorOnExist:!0});await St.chmod(d,Rv)}await MB(c,en(n,i)),o.add(s),a.migrated+=1}catch{a.failed+=1}}},Ov=(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(`
|
|
260
|
+
`)}},jm=e=>new Set(e.flatMap(t=>t.sources.map(n=>n.account))),Pv=async e=>{let t=[];for(let n of DB)t.push({lane:n,sources:await NB(e,n)});return t},Dv=async(e={})=>{let t=(e.firstPartyRoot??(()=>zs()))();if(!t)return{sessions:0,accounts:0,userSkills:0,userPlugins:0,localMcpServers:0};let[n,r]=await Promise.all([Pv(t),Vm(t)]),o=n.reduce((s,i)=>s+i.sources.reduce((c,l)=>c+l.ids.length,0),0),a=jm(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}},yo=async(e={})=>{let t=(e.home??OB)(),n=(e.firstPartyRoot??(()=>zs()))(),r=(e.thirdPartyRoot??(()=>uo()))();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??ka())())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([Pv(n),Vm(n)]),s;if(e.account){let m=e.account;for(let g of o)g.sources=g.sources.filter(y=>y.account.startsWith(m));let p=a.accounts.filter(g=>g.startsWith(m));if(o.every(g=>g.sources.length===0)&&p.length===0)return{ok:!1,kind:"account-unmatched",reason:`no account in the previous profile starts with "${m}"`,remedy:`Run \`${e.command??"anyray-connect desktop --migrate"}\` with no flags to list the accounts.`};let h=jm(o);for(let g of p)h.add(g);if(h.size>1)return Ov(o,e.command??"anyray-connect desktop --migrate",`"${m}" matches ${h.size} accounts`,p);s=[...h]}else if(!e.allAccounts){let m=jm(o);for(let p of a.accounts)m.add(p);if(m.size>1)return Ov(o,e.command??"anyray-connect desktop --migrate",`the previous Claude Desktop profile holds local data for ${m.size} accounts`,a.accounts);s=[...m]}let i=e.command??"anyray-connect desktop --migrate",c=!await _B(r),l=await xv(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:m,sources:p}of o){if(p.length===0){d.push(Km(m));continue}let h=await $B(r,m);if("missing"in h){u.push({lane:m,reason:h.missing,waiting:p.reduce((g,y)=>g+y.ids.length,0)}),d.push(Km(m));continue}d.push(await FB(m,p,h.dir,t))}if(!(d.some(m=>m.migrated>0||m.alreadyPresent>0)||l.outcomes.some(m=>m.migrated>0||m.alreadyPresent>0||m.conflicts>0))&&(u.length>0||l.blocked.length>0)){let m=u[0];return m?{ok:!1,kind:m.reason==="ambiguous"?"account-ambiguous":"store-missing",reason:m.reason==="ambiguous"?`Claude Desktop's third-party profile holds more than one ${m.lane} store`:`Claude Desktop has no ${m.lane} store in its third-party profile yet`,remedy:Zm(m.reason,m.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 UB=e=>[Ne(e)],Lv=e=>({id:e.id,title:e.title,automatic:!1,async detect(){let t=[...UB(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 Nv="1.21459.0",KB=VB(HB),jB=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}},ZB=async e=>{try{return await GB(e)}catch{return}},$v="No native config was written; use Developer \u2192 Configure Third-Party Inference \u2192 Apply locally.",YB=["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."],Sa=async(e={})=>!e.home&&!e.readClaudeAppVersion&&!e.readClaudeAppBundle?(Mv??=Bv({}),Mv):Bv(e),Mv,Bv=async e=>{let t=(e.home??fi)(),n=["/Applications/Claude.app",Sn(t,"Applications","Claude.app")],r=e.readClaudeAppVersion??jB,o=e.readClaudeAppBundle??ZB;for(let a of n){let s=await r(Sn(a,"Contents","Info.plist"));if(!s)continue;let i=d=>({supported:!1,detectedVersion:s,appPath:a,message:`Claude Desktop ${s} is installed, but ${d} ${$v}`}),c=Nl(s,Nv);if(c===void 0)return i("its version string could not be interpreted.");if(c<0)return i(`automatic local setup requires ${Nv} or newer.`);let l=await o(Sn(a,"Contents","Resources","app.asar"));return l?Ak.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. ${$v}`}},cd="anyray",Uv="--anyray-owner=claude-desktop-v1",ld=(e={})=>{let t=(e.platform??Tr)(),n=(e.home??fi)();return t==="darwin"?zt(e).appConfig:t==="win32"?Sn(process.env.APPDATA??Sn(n,"AppData","Roaming"),"Claude","claude_desktop_config.json"):Sn(n,".config","Claude","claude_desktop_config.json")},qm=(e={})=>Sn((e.home??fi)(),"Library","Application Support","Claude","claude_desktop_config.json"),Hv=()=>{let e=Ge("profile");return{command:e.command,args:[...e.args,Uv]}},go=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Gv=(e,t)=>{let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((o,a)=>o===r[a])},JB=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r]),XB=e=>{if(!go(e)||!Gv(e,["command","args"]))return!1;let t=Hv();return e.command===t.command&&JB(e.args,t.args)},zB=e=>go(e)&&Array.isArray(e.args)&&e.args.at(-1)===Uv,qB=e=>{if(!go(e)||!Gv(e,["command","args"])||typeof e.command!="string"||!Array.isArray(e.args)||!e.args.every(a=>typeof a=="string")||tt(e.command))return!1;let t=e.args;if(!(t.length>=2&&t.at(-2)===sr&&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!tt(t[0])&&(/(?:^|\/)anyray-connect(?:\/|$)/.test(o)||/(?:^|\/)\.anyray\/bin\/connect-runtime-[0-9A-Za-z][0-9A-Za-z.-]*\/dist\/index\.js$/.test(o))},QB=e=>e===void 0?"absent":XB(e)?"exact":zB(e)||qB(e)?"stale-owned":"foreign",We=class extends Error{changedFiles;constructor(t,n=[]){super(t),this.changedFiles=n}},wo=async e=>{let t=await x(e),n;try{n=await B(e)}catch{throw new We(`Could not parse ${e}; it was left unchanged.`)}if("mcpServers"in n&&!go(n.mcpServers))throw new We(`Could not update ${e} because mcpServers is not an object; it was left unchanged.`);let o=(go(n.mcpServers)?n.mcpServers:void 0)?.[cd];return{path:e,fileExisted:t,json:n,entry:o,ownership:QB(o)}},dd=e=>{if(e.ownership==="foreign")throw new We(`MCP name conflict in ${e.path}: mcpServers.${cd} is not owned by Anyray Connect, so it was left untouched. Rename that existing server, then re-run Connect.`)},Vv=(e,t)=>{let n={...e},r=go(e.mcpServers)?{...e.mcpServers}:{};return t===void 0?delete r[cd]:r[cd]=t,Object.keys(r).length===0?delete n.mcpServers:n.mcpServers=r,n},Jm=async(e,t)=>{if(Ym(e.entry,t))return;let n=await wo(e.path);if(!Ym(n.entry,e.entry))throw new We(`The MCP configuration in ${e.path} changed during setup; it was left untouched. Re-run Connect.`);return await Kn(e.path,Vv(n.json,t)),{reading:e,afterEntry:t}},Xm=async e=>{let t=await wo(e.reading.path);if(!Ym(t.entry,e.afterEntry))throw new We(`The MCP configuration in ${e.reading.path} changed before rollback; the newer value was preserved.`);let n=Vv(t.json,e.reading.entry);await Kn(e.reading.path,n)},eF=async e=>{if(!oe())throw new We(`A durable anyray-connect runtime is required for Claude Desktop retrieval (${De()} is temporary); no inference setting was changed.`);let t=await wo(ld(e));dd(t);let n=qm(e),r=(e.platform??Tr)()==="darwin"&&n!==t.path?await wo(n):void 0;return r&&dd(r),{active:t,...r?{legacy:r}:{}}},Fv=async e=>{let t=await wo(ld(e));dd(t);let n=qm(e),r=(e.platform??Tr)()==="darwin"&&n!==t.path?await wo(n):void 0;return r&&dd(r),{active:t,...r?{legacy:r}:{}}},tF=async e=>{let t=[];try{let n=await Jm(e.active,Hv());if(n&&t.push(n),e.legacy&&e.legacy.ownership!=="absent"){let r=await Jm(e.legacy,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Xm(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new We(`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 Xm(r).catch(()=>{n.push(r.reading.path)});if(n.length>0)throw new We(`Claude Desktop MCP rollback could not restore ${n.join(", ")}. Newer values were preserved; re-run revert after resolving the conflict.`,n)}}},nF=async e=>{let t=[];try{for(let n of[e.active,e.legacy].filter(r=>!!r)){if(n.ownership==="absent")continue;let r=await Jm(n,void 0);r&&t.push(r)}}catch(n){let r=[];for(let o of[...t].reverse())await Xm(o).catch(()=>{r.push(o.reading.path)});throw r.length>0?new We(`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)."]},rF={darwinAppName:"Claude",darwinBundleId:"com.anthropic.claudefordesktop",win32Image:"Claude.exe",win32Install:[{root:"localAppData",path:"Programs\\Claude\\Claude.exe"}]},ud="claude-desktop",zm="migrate",Kv=new Set(["app-running","store-missing"]),oF={code:{one:"Claude Code session",many:"Claude Code sessions"},cowork:{one:"Cowork task",many:"Cowork tasks"}},aF={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"}},sF="Claude Desktop machine policy could not be read; Connect left inference and retrieval configuration unchanged.",jv=e=>{let t=(e.platform??Tr)(),n=e.home??fi;return{home:n,appRunning:e.appRunning??ka(t),firstPartyRoot:()=>zs({home:n,runtimePlatform:t}),thirdPartyRoot:()=>uo({home:n,runtimePlatform:t}),command:"anyray-connect migrate"}},Zv=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=oF[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.`:"")},Yv=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=aF[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.`:"")},pi=async(e,t)=>{if(!t.reportsToUser)return[];try{let n=jv(e),r=await(e.pendingDesktopMigrationCount??Dv)(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??yo)(n);if(a.ok){let c=Zv(a.lanes),l=Yv(a.portableAssets),d=a.ambiguousAssets??[],u=d.length>0?`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`:void 0,f=(a.blocked??[]).filter(w=>w.reason!=="ambiguous"),m=a.blockedAssets??[],p=a.retryableAssets??[];if(f.length===0&&m.length===0&&p.length===0)return[c,l,u].filter(w=>!!w);if(t.preservePendingOp)return[c,l,u].filter(w=>!!w);await xs(ud,zm);let h=f.reduce((w,b)=>w+b.waiting,0),g=[h>0?`${h} more session${h===1?"":"s"}`:"",m.length>0?`${m.length} extension ${m.length===1?"store":"stores"}`:""].filter(Boolean),y=[...g.length>0?[`Queued: ${g.join(" and ")} move across once Claude Desktop creates the required third-party stores and the app is fully quit.`]:[],...p.length>0?[`Queued: ${p.length} portable configuration ${p.length===1?"type":"types"} will retry automatically after a recoverable local-copy interruption.`]:[]];return[...c?[c]:[],...l?[l]:[],...u?[u]:[],...y]}if(!Kv.has(a.kind))return[`Your existing Claude Desktop local data was left where it is: ${a.reason}.
|
|
261
|
+
${a.remedy}`];if(t.preservePendingOp)return[];await xs(ud,zm);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."]}},iF=async e=>{if(!e.fullRevert||e.dryRun)return[];try{return await yr(ud),[]}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."]}},cF=e=>Lv({id:ud,title:"Claude desktop",appDir:"Claude",detectPaths:()=>{let t=(e.platform??Tr)(),n=(e.home??fi)();return t==="darwin"?["/Applications/Claude.app",Sn(n,"Applications","Claude.app")]:t==="win32"?[Sn(process.env.LOCALAPPDATA??Sn(n,"AppData","Local"),"Programs","Claude","Claude.exe")]:[]},steps:t=>te(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`."]}),lF=(e={})=>{let t=cF(e),n=()=>(e.platform??Tr)()==="darwin",r=()=>(e.platform??Tr)()==="win32",o=(s,i)=>n()?Rk(s,i,e):sv(s,s.clientKey??"",i,e),a=s=>n()?Ok(s,e):iv(s,e);return{...t,automatic:!0,changesOrgManagement:!0,quitGated:{isRunning:()=>(e.appRunning??ka((e.platform??Tr)()))(),quitTarget:rF,needsTarget:()=>!1,async complete(s){if(s!==zm)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??yo)(jv(e));if(i.ok){let c=Zv(i.lanes),l=Yv(i.portableAssets),d=i.ambiguousAssets??[];if(d.length>0)return{status:"manual",messages:[...c?[c]:[],...l?[l]:[],`Claude Desktop has more than one target ${d.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run the migration again.`]};let f=(i.blocked??[]).filter(h=>h.reason!=="ambiguous"),m=i.blockedAssets??[],p=i.retryableAssets??[];return f.length>0||m.length>0||p.length>0?{status:"queued",messages:[...c?[c]:[],...l?[l]:[],...f.length>0||m.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."]:[],...p.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 Kv.has(i.kind)?{status:"queued",messages:[i.reason]}:{status:"manual",messages:[i.reason,i.remedy]}}},async usesDynamicCredential(s){return n()?_k(s,e):r()?dv(s,e):!1},async apply(s,i){if(!n()&&!r())return t.apply(s,i);if(n()){let f=zt(e),m=await fo(f,e);if(m)return{status:"manual",manualAudience:"admin",messages:[Cm(m),...await pi(e,i)]}}if(r()){let f;try{f=await Or(e.runReg??Zn)}catch{return{status:"manual",manualAudience:"admin",messages:[sF,...await pi(e,i)]}}if(f)return{status:"manual",manualAudience:"admin",messages:[Bm(f),...await pi(e,i)]}}if(r()&&te(s,"anthropic"))return{status:"manual",messages:["Claude Desktop subscription routing is not available on Windows: Connect could not verify a supported Claude subscription credential source, so inference was left unchanged instead of switching to API billing.","Use org/API mode for the Windows Gateway lane, or run subscription mode on a verified macOS build after signing in to Claude Code."]};if(n()){let f=await Sa(e);if(!f.supported)return{status:"manual",messages:[f.message??"Claude Desktop version is unsupported."]}}let c;try{c=await eF(e)}catch(f){let m=f instanceof We?f.changedFiles:[];return{status:"manual",...m.length>0?{changedFiles:m}:{},messages:[f instanceof We?f.message:"Could not safely inspect Claude Desktop's retrieval MCP configuration; no inference setting was changed."]}}let l=await o(s,{dryRun:!0});if(l.status!=="configured")return l;if(i.dryRun){let f=c.legacy;return{...l,messages:[...l.messages,`Would register the ownership-marked Anyray retrieval MCP server in ${c.active.path}.`,...f&&f.ownership!=="absent"?[`Would remove the legacy owned Anyray MCP registration from ${f.path}.`]:[],...await pi(e,i)]}}let d;try{d=await tF(c)}catch(f){let m=f instanceof We?f.changedFiles:[];return{status:"manual",...m.length>0?{changedFiles:m}:{},messages:[f instanceof We?f.message:"Could not safely register Claude Desktop retrieval; the inference route was left unchanged."]}}let u;try{u=await o(s,{dryRun:!1})}catch{u={status:"manual",messages:["Claude Desktop inference setup failed before it returned a result."]}}if(u.status!=="configured")try{return await d.rollback(),{...u,changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])],messages:[...u.messages,"Restored the prior Claude Desktop MCP registration because inference setup did not complete. A config file that was absent before setup may remain as an inert object to avoid racing unrelated concurrent writes."]}}catch{return{status:"manual",changedFiles:[...u.changedFiles??[],...d.changedFiles],messages:[...u.messages,"Inference setup did not complete, and the prior MCP registration could not be fully restored. Re-run `anyray-connect desktop disconnect` to recover safely."]}}return{...u,messages:[...u.messages,"Registered the Anyray retrieval MCP server (anyray_retrieve / anyray_recall) with an ownership marker.",...await pi(e,i),...!i.dryRun&&i.reportsToUser&&i.explicit&&n()?YB:[]],changedFiles:[...new Set([...u.changedFiles??[],...d.changedFiles])]}},async revert(s){let i=ld(e),c=await iF(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 Fv(e)}catch(h){return l({status:"manual",messages:[h instanceof We?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 f=await a({dryRun:!1});if(f.status==="manual"){let h=r()?Bt(e):void 0;if(!(h!==void 0&&f.changedFiles?.includes(h)===!0&&!await x(h)))return l(f)}let m;try{m=await nF(await Fv(e))}catch(h){let g=h instanceof We?h.changedFiles:[];return l({status:"manual",changedFiles:[...new Set([...f.changedFiles??[],...g])],messages:[...f.messages,h instanceof We?h.message:"Restored Claude Desktop inference, but could not safely remove its retrieval MCP registration. Re-run revert."]})}await ie(i);let p=qm(e);return n()&&p!==i&&await ie(p),l({...f,messages:[...f.messages,...m.length>0?["Removed the Anyray retrieval MCP server (anyray_retrieve / anyray_recall)."]:[]],changedFiles:[...new Set([...f.changedFiles??[],...m])]})},async mcpStatus(){if(!oe())return{registered:!1,command:null,reason:"ephemeral-runtime"};try{let s=await wo(ld(e));return s.ownership!=="exact"||!go(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 Sa(e)).supported?vm(s,e):!1:r()?lv(s,e):!1},async inferenceAuthLanes(){try{if(n()){if(!(await Sa(e)).supported)return["unknown"];let s=await Tk(e);return s?[s]:["unknown"]}if(r())return await x(Bt(e))?await Or(e.runReg??Zn)?["unknown"]:["api_key"]:["unknown"]}catch{}return["unknown"]},async automaticRepairAllowed(){try{if(n()){let s=zt(e);return!await x(s.journal)||await fo(s,e)?!1:(await Sa(e)).supported}return r()&&await x(Bt(e))?!await Or(e.runReg??Zn):!1}catch{return!1}}}},Jv=lF();import{homedir as MF}from"node:os";import{join as BF}from"node:path";import{rm as Ad}from"node:fs/promises";import{constants as Xv,accessSync as dF,statSync as uF}from"node:fs";import{platform as Qm}from"node:os";import{delimiter as pF,posix as fF,resolve as mF,win32 as hF}from"node:path";var yF="0.59.0",gF="1.1.4",Yn="Anyray \xB7 Claude",Jn="Anyray \xB7 Codex",pd="__anyray-acp-agent",zv=(e,t,n)=>{let{command:r,args:o}=an([pd,e,t,n]);return{command:r,args:o,env:{}}},fd=(e=Qm())=>e==="win32"?"npx.cmd":"npx",md=(e=process.env.PATH,t=Qm())=>{if(!e)return;let n=fd(t);for(let r of e.split(pF)){let o=r.trim().replace(/^"|"$/g,"");if(!o)continue;let a=mF(o,n);try{if(!uF(a).isFile())continue;return dF(a,t==="win32"?Xv.F_OK:Xv.X_OK),a}catch{}}},hd=(e,t=Qm())=>{let n=t==="win32"?hF:fF;return!n.isAbsolute(e)||n.basename(e).toLowerCase()!==fd(t)?!1:t!=="win32"||!/["&|<>^%!\r\n]/.test(e)},wF="https://chatgpt.com/backend-api/codex",bF="chatgpt-account-id,originator,session_id,user-agent,x-codex-turn-metadata,x-codex-window-id,x-client-request-id",qv="ANYRAY_ACP_CODEX_AUTHORIZATION",Qv="ANYRAY_ACP_CODEX_CLIENT_KEY",eS="ANYRAY_ACP_CODEX_METADATA",tS=e=>me({...e.metadata,tool:e.metadata.tool??"codex",intent:e.metadata.intent??"jetbrains-acp",intentLabel:e.metadata.intentLabel??"JetBrains / Devin via Codex ACP"}),AF=(e,t={})=>{let n=te(e,"openai"),r=n?{"x-anyray-auth-mode":"passthrough","x-anyray-custom-host":wF,"x-anyray-forward-headers":bF}:{},o=n?{...e.clientKey?{"x-anyray-api-key":Qv}:{}}:{Authorization:qv};return tS(e)&&(o["x-anyray-metadata"]=eS),{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}}}:{}}},CF=e=>{let t=te(e,"openai"),n=tS(e);return{...t?e.clientKey?{[Qv]:e.clientKey}:{}:{[qv]:`Bearer ${e.clientKey??e.placeholderKey}`},...n?{[eS]:n}:{}}},nS=(e,t=fd(),n={})=>({[Yn]:{command:t,args:["--yes",`@agentclientprotocol/claude-agent-acp@${yF}`],env:sn(e).env},[Jn]:{command:t,args:["--yes",`@agentclientprotocol/codex-acp@${gF}`],env:{CODEX_CONFIG:JSON.stringify(AF(e,n)),...CF(e)}}}),mi=(e=fd(),t="jetbrains")=>({[Yn]:zv("claude",e,t),[Jn]:zv("codex",e,t)}),bo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yd=(e,t)=>JSON.stringify(e)===JSON.stringify(t);import{inflateRawSync as kF}from"node:zlib";import{open as vF,readFile as oh,readdir as bd}from"node:fs/promises";import{dirname as rS,join as he}from"node:path";import{homedir as iS,platform as ah}from"node:os";var gd="2025.3.2",Ea="253.30387.147",hi="com.intellij.ml.llm",eh=new Set(["ml-llm","llm","aia","ai-assistant","jetbrains-ai-assistant"]),SF=1e4,EF=256*1024*1024,IF=16*1024*1024,th=1024*1024,nh=22,xF=nh+65535,rh=Nl,RF=()=>{let e=iS(),t=he(e,".cache","JetBrains","RemoteDev");switch(ah()){case"darwin":return[{path:"/Applications",layout:"app-bundles"},{path:he(e,"Applications"),layout:"app-bundles"},{path:he(e,"Library","Application Support","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}];case"win32":return[{path:he(process.env.LOCALAPPDATA??he(e,"AppData","Local"),"Programs"),layout:"children"},{path:he(process.env.LOCALAPPDATA??he(e,"AppData","Local"),"JetBrains","Toolbox"),layout:"recursive"},{path:he(process.env.ProgramFiles??"C:\\Program Files","JetBrains"),layout:"children"}];default:return[{path:"/opt",layout:"children"},{path:he(e,".local","share","JetBrains","Toolbox"),layout:"recursive"},{path:t,layout:"recursive"}]}},OF=()=>ah()==="linux"?he(iS(),".local","share","JetBrains"):Ne("JetBrains"),TF=()=>ah()==="linux"&&!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP),_F=async(e,t=SF)=>{let n=[];for(let r of e){if(r.layout!=="recursive"){let s;try{s=await bd(r.path,{withFileTypes:!0})}catch{continue}for(let i of s.slice(0,t)){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=he(r.path,i.name),l=r.layout==="app-bundles"?he(c,"Contents","Resources","product-info.json"):he(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=he(s,"product-info.json"),l=he(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 bd(s,{withFileTypes:!0})}catch{return}for(let u of d){if(o>=t)return;o+=1;let f=he(s,u.name);(u.isDirectory()||u.isSymbolicLink())&&!["bin","jbr","lib","plugins","Contents"].includes(u.name)&&await a(f,i-1)}};await a(r.path,7)}return[...new Set(n)]},PF=e=>{let t=rS(e);return t.endsWith(`${he("Contents","Resources")}`)?rS(t):t},DF=async e=>{try{let t=JSON.parse(await oh(e,"utf8"));if(!t||typeof t!="object"||typeof t.version!="string"||typeof t.dataDirectoryName!="string")return;let n=t;return!Js(n.version)||!/^[A-Za-z0-9._-]+$/.test(n.dataDirectoryName)?void 0:{version:n.version,dataDirectoryName:n.dataDirectoryName,root:PF(e)}}catch{return}},wd=async(e,t,n)=>{let r=Buffer.alloc(t),{bytesRead:o}=await e.read(r,0,t,n);return o===t?r:void 0},LF=async(e,t)=>{let n;try{n=await vF(e,"r");let{size:r}=await n.stat();if(r<nh||r>EF)return;let o=Math.min(r,xF),a=await wd(n,o,r-o);if(!a)return;let s=-1;for(let u=a.length-nh;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>IF||c+i>r)return;let l=await wd(n,i,c);if(!l)return;let d=0;for(;d+46<=l.length;){if(l.readUInt32LE(d)!==33639248)return;let u=l.readUInt16LE(d+10),f=l.readUInt32LE(d+20),m=l.readUInt32LE(d+24),p=l.readUInt16LE(d+28),h=l.readUInt16LE(d+30),g=l.readUInt16LE(d+32),y=l.readUInt32LE(d+42),w=d+46+p+h+g;if(w>l.length)return;let b=l.subarray(d+46,d+46+p).toString("utf8");if(d=w,b!==t)continue;if(f===4294967295||m===4294967295||f>th||m>th)return;let k=await wd(n,30,y);if(!k||k.readUInt32LE(0)!==67324752)return;let C=k.readUInt16LE(26),S=k.readUInt16LE(28),E=await wd(n,f,y+30+C+S);return E?u===0?E.toString("utf8"):u===8?kF(E,{maxOutputLength:th}).toString("utf8"):void 0:void 0}return}catch{return}finally{await n?.close().catch(()=>{})}},oS=e=>{let t=e.match(/<id>\s*([^<]+?)\s*<\/id>/)?.[1]?.trim(),n=e.match(/<version>\s*([^<]+?)\s*<\/version>/)?.[1]?.trim();if(!(!t||!n||!Js(n)))return{id:t,version:n}},NF=async(e,t)=>{let n=he(e,"META-INF","plugin.xml");if(await x(n))try{let o=oS(await oh(n,"utf8"));return{present:o?.id===hi||t,descriptor:o?.id===hi?o:void 0}}catch{return{present:t}}let r=[];try{r=(await bd(he(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=>he(e,"lib",o.name))}catch{return{present:!1}}for(let o of r){let a=await LF(o,"META-INF/plugin.xml"),s=a?oS(a):void 0;if(s?.id===hi)return{present:!0,descriptor:s}}return{present:t&&r.length>0}},aS=async e=>{let t;try{t=await bd(e,{withFileTypes:!0})}catch{return{present:!1}}let n=t.filter(o=>o.isDirectory()||o.isSymbolicLink()).sort((o,a)=>{let s=eh.has(o.name.toLowerCase()),i=eh.has(a.name.toLowerCase());return Number(i)-Number(s)}).slice(0,512),r=!1;for(let o of n){let a=eh.has(o.name.toLowerCase());if(!a){let i=he(e,o.name,"META-INF","plugin.xml");if(!await x(i))continue}let s=await NF(he(e,o.name),a);if(s.descriptor)return s;s.present&&(r=!0)}return{present:r}},$F=async e=>{try{return(await oh(he(e,"disabled_plugins.txt"),"utf8")).split(/\r?\n/).map(n=>n.trim()).includes(hi)}catch{return!1}},sS=e=>e.reduce((t,n)=>t?(rh(n,t)??-1)>0?n:t:n,void 0),cS=async(e={})=>{let t=e.configRoot??Ne("JetBrains"),n=e.userPluginsRoot??OF(),r=await _F(e.productRoots?e.productRoots.map(p=>({path:p,layout:"recursive"})):RF(),e.scanBudget),o=(await Promise.all(r.map(p=>DF(p)))).filter(p=>p!==void 0),a=o.length>0||await x(t);if(e.wsl??TF())return{installed:a,capable:!1,detail:"JetBrains AI Assistant does not support ACP in WSL; no ACP config was written."};let s=o.filter(p=>(rh(p.version,gd)??-1)>=0),i=[],c=!1,l=!1,d=!1;for(let p of s){let h=he(t,p.dataDirectoryName);if(!await x(h)){d=!0;continue}let g=[he(h,"plugins"),he(n,p.dataDirectoryName),he(n,p.dataDirectoryName,"plugins")],y;for(let w of[...new Set(g)]){let b=await aS(w);if(b.present){y=b;break}}if(y??=await aS(he(p.root,"plugins")),y.present&&!y.descriptor){l=!0;continue}if(!(!y.descriptor||y.descriptor.id!==hi)){if(i.push(y.descriptor.version),await $F(h)){c=!0;continue}if(!((rh(y.descriptor.version,Ea)??-1)<0))return{installed:!0,capable:!0,detail:`JetBrains IDE ${p.version}; AI Assistant ${y.descriptor.version}; ACP supported`,ideVersion:p.version,pluginVersion:y.descriptor.version}}}let u=sS(o.map(p=>p.version)),f=sS(i),m;return a?u?s.length===0?m=`JetBrains IDE ${u} is below the ACP minimum ${gd}; no ACP config was written.`:d?m=`Could not prove that JetBrains AI Assistant is enabled for this user; start IDE ${gd}+ once, enable AI Assistant ${Ea}+, then run Connect again. No ACP config was written.`:c?m=`JetBrains AI Assistant is disabled; enable version ${Ea}+ and run Connect again. No ACP config was written.`:f?m=`JetBrains AI Assistant ${f} is below the ACP minimum ${Ea}; no ACP config was written.`:l?m=`Could not verify the local JetBrains AI Assistant version; require ${Ea}+ before running Connect. No ACP config was written.`:m=`JetBrains AI Assistant ${Ea}+ was not found; install or enable it, then run Connect again. No ACP config was written.`:m=`Could not prove JetBrains IDE ${gd}+ from local product-info.json; no ACP config was written.`:m="JetBrains IDE config or installation not found",{installed:a,capable:!1,detail:m,ideVersion:u,pluginVersion:f}};var FF=[Yn,Jn],sh=()=>BF(MF(),".jetbrains","acp.json"),Ao=()=>`${sh()}.anyray-state`,WF=(e,t,n="npx")=>{let r=bo(e.agent_servers)?{...e.agent_servers}:{};return Object.assign(r,mi(n,"jetbrains")),{...e,agent_servers:r}},UF=(e,t,n)=>{if(!bo(e.agent_servers))return{next:e,removed:[],conflicts:[]};let r={...e.agent_servers},o=bo(t.agent_servers)?t.agent_servers:{},a=[],s=[];for(let c of FF)if(c in r){if(!yd(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}},HF=(e=cS)=>({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=sh(),o=await e();if(!o.capable)return{status:o.installed?"manual":"not-found",messages:[o.detail]};let a=md();if(!a)return{status:"manual",messages:["JetBrains ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP config was written."]};let s=[`${r} \u2190 documented JetBrains ACP custom-agent configuration`,`${o.detail}.`,"Registered Claude and Codex ACP agents with Anyray routing; no IDE proxy, certificate, DNS, or private Copilot endpoint is changed.","Claude keeps Anthropic subscription auth when selected; Codex keeps ChatGPT subscription auth when selected. Org/API mode uses the enrolled personal gateway key.","The agents appear in AI Chat after the IDE reloads. Their first launch may ask for the provider sign-in if that seat is not already authenticated.","JetBrains Copilot remains a separate closed client; its content-free usage is covered by the Copilot usage connector, not endpoint interception."];if(n.dryRun)return{status:"configured",messages:s};let i=await x(r),c;try{c=await B(r)}catch{return{status:"manual",messages:[`Refused to overwrite malformed ${r}; fix or replace the file, then run Connect again.`]}}let l=mi(a,"jetbrains");return await nc({configPath:r,current:c,next:WF(c,t,a),journalPath:Ao(),journal:{version:2,fileExisted:i,entries:l},fileExisted:i}),{status:"configured",messages:s,changedFiles:[r,Ao()]}},async revert(t){let n=sh(),r=async()=>{if(!await x(n))return t.dryRun||(await ie(n),await Ad(Ao(),{force:!0}).catch(()=>{})),{status:"reverted",messages:["No JetBrains ACP config to remove."]};let o;try{o=await B(n)}catch{return t.dryRun||(await ie(n),await Ad(Ao(),{force:!0}).catch(()=>{})),{status:"manual",messages:[`Could not parse ${n}; remove the two \u201CAnyray \xB7 \u2026\u201D agent entries manually.`]}}let a={},s=!1,i=!1;try{let u=await B(Ao());(u.version===1||u.version===2)&&bo(u.entries)&&(a=u.entries,s=u.version===2&&u.fileExisted===!1,i=u.version===2&&u.fileExisted===!0)}catch{}let c;if(i){let u=`${n}.anyray-bak`;if(!await x(u))return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is missing. Restore or remove the entries manually.`]};try{c=await B(u)}catch{return{status:"manual",messages:[`Refused to remove JetBrains ACP entries because the original backup for ${n} is malformed. Repair it or remove the entries manually.`]}}}else c=await Ur(n);let l=UF(o,c,a),d=[];return l.removed.length&&d.push(`Removed ${l.removed.join(", ")} from ${n}.`),l.conflicts.length&&d.push(`Preserved user-modified ACP entries: ${l.conflicts.join(", ")}.`),!t.dryRun&&l.removed.length&&(s&&Object.keys(l.next).length===0?await Ad(n,{force:!0}):await X(n,l.next,{backup:!1})),t.dryRun||(await ie(n),await Ad(Ao(),{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():tc(n,Ao(),r)}}),lS=HF();import{homedir as kd}from"node:os";import{join as vd}from"node:path";import{rm as ih}from"node:fs/promises";var ch="1.0.0",Sd=["anyray-claude-acp","anyray-codex-acp"],GF=["darwin-aarch64","darwin-x86_64","linux-aarch64","linux-x86_64","windows-aarch64","windows-x86_64"],lh=()=>vd(kd(),".windsurf","acp","registry.json"),dh=()=>vd(kd(),".windsurf-next","acp","registry.json"),Ia=e=>`${e}.anyray-state`,dS=e=>({binary:Object.fromEntries(GF.map(t=>[t,{archive:"",cmd:e.command,args:e.args}]))}),pS=(e="npx")=>{let t=mi(e,"windsurf");return[{id:Sd[0],name:Yn,version:"1.0.0",description:"Claude through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:dS(t[Yn])},{id:Sd[1],name:Jn,version:"1.0.0",description:"Codex through the Anyray gateway via ACP",authors:["Anyray","Agent Client Protocol"],license:"Apache-2.0",distribution:dS(t[Jn])}]},Cd=e=>!Array.isArray(e)||e.some(t=>!bo(t)||typeof t.id!="string")?null:e,VF=(e,t="npx")=>{if(e.version!==void 0&&e.version!==ch||e.extensions!==void 0&&!Array.isArray(e.extensions))return null;let n=e.agents===void 0?[]:Cd(e.agents);if(!n)return null;let r=new Set(Sd);return{...e,version:typeof e.version=="string"?e.version:ch,agents:[...n.filter(o=>!r.has(o.id)),...pS(t)],extensions:e.extensions??[]}},KF=(e,t,n)=>{let r=Cd(e.agents);if(!r)return null;let o=Cd(t.agents)??[],a=new Map((Cd(n)??[]).map(u=>[u.id,u])),s=new Map(o.map(u=>[u.id,u])),i=[],c=[],l=[];for(let u of r){if(!Sd.includes(u.id)){l.push(u);continue}if(!yd(u,a.get(u.id))){c.push(u.id),l.push(u);continue}let f=s.get(u.id);f&&l.push(f),i.push(u.id)}let d={...e,agents:l};return!Object.prototype.hasOwnProperty.call(t,"agents")&&l.length===0&&delete d.agents,!Object.prototype.hasOwnProperty.call(t,"version")&&d.version===ch&&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}},uS=async()=>{let e=[];return(await x(dh())||await x(vd(kd(),".windsurf-next")))&&e.push(dh()),(await x(lh())||await x(vd(kd(),".windsurf"))||await x(Ne("Devin"))||await x(Ne("Windsurf")))&&e.push(lh()),e},fS={id:"windsurf",title:"Devin Desktop",automatic:!0,async detect(){let e=await uS();return e.length?{installed:!0,detail:e.join(", ")}:{installed:!1,detail:"Devin Desktop not found"}},async apply(e,t){let n=await uS();if(!n.length)return{status:"not-found",messages:["Devin Desktop is not installed; no ACP registry was written."]};let r=md();if(!r)return{status:"manual",messages:["Devin ACP requires Node.js with npm/npx. Install that prerequisite, then run Connect again; no ACP registry was written."]};let o=[],a=[];for(let s of n){let i;try{i=await B(s)}catch{o.push(`Refused to overwrite malformed ${s}; fix or replace the file, then run Connect again.`);continue}let c=VF(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=pS(r);await nc({configPath:s,current:i,next:c,journalPath:Ia(s),journal:{version:2,fileExisted:l,agents:d},fileExisted:l}),a.push(s,Ia(s))}}return o.push("Devin requires a one-time vendor UI enablement for local registry agents: Devin Settings \u2192 Agents \u2192 enable the two Anyray agents, then restart Devin Desktop."),o.push("Native Devin/Cascade subscription requests are not redirected. The official enterprise consumption connector imports content-free usage instead."),o.push("No proxy, certificate, DNS, DEVIN_API_URL, or private first-party endpoint was changed."),{status:"manual",messages:o,changedFiles:a.length?a:void 0}},async revert(e){let t=[lh(),dh()],n=[],r=[],o=!1;for(let a of t){let s=async()=>{if(!await x(a)){e.dryRun||(await ie(a),await ih(Ia(a),{force:!0}).catch(()=>{}));return}let i;try{i=await B(a)}catch{n.push(`Could not parse ${a}; remove the anyray-* ACP agents manually.`),o=!0;return}let c=[],l=!1,d=!1;try{let m=await B(Ia(a));(m.version===1||m.version===2)&&Array.isArray(m.agents)&&(c=m.agents,l=m.version===2&&m.fileExisted===!1,d=m.version===2&&m.fileExisted===!0)}catch{}let u;if(d){let m=`${a}.anyray-bak`;if(!await x(m)){n.push(`Refused to remove Devin ACP agents because the original backup for ${a} is missing. Restore it or remove the agents manually.`),o=!0;return}try{u=await B(m)}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 Ur(a);let f=KF(i,u,c);if(!f){n.push(`Unrecognized ACP registry shape in ${a}; left it unchanged.`),o=!0;return}f.removed.length&&(n.push(`Removed ${f.removed.join(", ")} from ${a}.`),e.dryRun||(l&&Object.keys(f.next).length===0?await ih(a,{force:!0}):await X(a,f.next,{backup:!1}),r.push(a))),f.conflicts.length?(n.push(`Preserved user-modified agents: ${f.conflicts.join(", ")}.`),o=!0):e.dryRun||(await ie(a),await ih(Ia(a),{force:!0}).catch(()=>{}))};e.dryRun?await s():await tc(a,Ia(a),s)}return{status:o?"manual":"reverted",messages:n.length?n:["No Anyray Devin ACP agents found."],changedFiles:r.length?r:void 0}}};var fe=[lr,ab,Ps,iC,LC,jC,QC,lS,Jv,fS,fb],pt=e=>fe.find(t=>t.id===e);var Ue=async(e=P,t=wn)=>{let n=await e();if(!n.gateway||!n.clientKey)return;let r=await t().catch(()=>{});return{target:Re({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 uh=5e3,mS=3e4,jF=1440*60*1e3,ZF=e=>new Promise(t=>setTimeout(t,e)),YF=async(e=P,t=wn)=>(await Ue(e,t))?.target,JF=e=>pt(e)?.quitGated,hS=async(e,t={})=>{let n=e[0];if(!n)return 0;let r=t.resolveSeam??JF,o=t.readPending??Qc,a=t.clearPending??Xp,s=t.targetFromProfile??YF,i=t.sleep??ZF,c=t.now??Date.now,l=t.maxWaitMs??jF;try{let d=r(n);if(!d?.complete)return await a(n),0;let u=d.complete.bind(d),f=c(),m=uh;for(;;){let p=await o(n);if(!p||c()-f>l)return 0;if(d.isRunning()){await i(m),m=Math.min(mS,m*2);continue}let h;if(d.needsTarget?.(p.op)&&(h=await s(),!h)){if(await a(n,p)!=="superseded")return 0;await i(m),m=uh;continue}if((await u(p.op,h,{dryRun:!1,preservePendingOp:!0})).status==="queued"){await i(m),m=Math.min(mS,m*2);continue}if(await a(n,p)!=="superseded")return 0;await i(m),m=uh}}catch{return 0}};import{writeFileSync as MW}from"node:fs";import{chmod as vh,stat as BW}from"node:fs/promises";import{platform as jS}from"node:os";import{dirname as ZS,isAbsolute as FW}from"node:path";var XF="https://app.anyray.ai",zF=new Set(["localhost","::1","[::1]"]),qF=/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,QF=e=>zF.has(e)||qF.test(e),ph=e=>{let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"?!0:t.protocol==="http:"&&QF(t.hostname)},eW=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Xn=()=>{let e=process.env.ANYRAY_CP_ORIGIN?.trim();return!e||!ph(e)?XF:eW(e)};import{createHash as fW,generateKeyPairSync as mW,randomBytes as hh}from"node:crypto";import{createPrivateKey as tW,sign as nW}from"node:crypto";var _r=async(e,t)=>{let n=tW(t);return nW(null,new TextEncoder().encode(e),n).toString("base64url")};var rW=["HTTPS_PROXY","https_proxy"],yS=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"]),gS=new Set(["CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),wS=new Set(["ENOTFOUND","EAI_AGAIN"]),bS=new Set(["ECONNREFUSED","ECONNRESET","EPIPE","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EHOSTDOWN"]),AS=new Set(["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]),oW=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 aW(e)},aW=e=>{let t=e?.message;if(!(typeof t!="string"||!t)){for(let n of[...yS,...gS,...wS,...bS,...AS])if(t.includes(n))return n}},sW=e=>e?.name==="AbortError"||e?.name==="TimeoutError",iW=e=>rW.filter(t=>(e[t]??"").trim()!==""),cW=(e,t=process.env)=>{let n=oW(e),r=iW(t);return{kind:n&&yS.has(n)?"tls-unknown-issuer":n&&gS.has(n)?"tls-invalid-cert":n&&wS.has(n)?"dns":sW(e)||n&&AS.has(n)?"timeout":n&&bS.has(n)?"refused":"unknown",...n?{code:n}:{},proxyVars:r}},lW=e=>{let t=e.proxyVars.length>0?` ${e.proxyVars.join(" and ")} ${e.proxyVars.length>1?"are":"is"} set \u2014 if that proxy is stale or unreachable, unset it and re-run.`:"";switch(e.kind){case"tls-unknown-issuer":return` (TLS certificate signed by an unknown authority: ${e.code}). Your network appears to inspect TLS traffic. curl trusts your system keychain and this binary does not, which is why the download worked and this step did not. Point NODE_EXTRA_CA_CERTS at your organization root certificate (PEM) and re-run.`+t;case"tls-invalid-cert":return` (TLS certificate rejected: ${e.code}). Check this machine's clock and date, and whether a proxy is rewriting HTTPS traffic, then re-run.`+t;case"dns":return` (DNS lookup failed: ${e.code}). Check your VPN or DNS, then re-run.`+t;case"refused":return` (connection failed: ${e.code}).`+(t||" Check your network or firewall, then re-run.");case"timeout":return" (timed out before the control plane answered)."+(t||" Check your connection and re-run.");default:return e.code?` (${e.code}).${t}`:t}},ft=(e,t=process.env)=>lW(cW(e,t));var dW="enl_",CS="enp_",kS=e=>e.startsWith(dW)||e.startsWith(CS),fh=e=>e.startsWith(CS),uW=[{prefix:"tnt_",flag:"--sso",what:"an SSO link"},{prefix:"sdc_",flag:"--claim",what:"a one-time enrollment code"}],mh=e=>uW.find(t=>e.startsWith(t.prefix)),vS=/^\/enroll\/([^/]+)\/?$/,SS=/^\/i\/([^/]+)\/?$/,ES=e=>{let t=e.match(vS);if(t)return mh(t[1])?void 0:t[1];let n=e.match(SS);return n&&kS(n[1])?n[1]:void 0},pW=1e4,Ed=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=ES(n.pathname);return r?{cpOrigin:n.origin,token:r}:void 0}if(!mh(t))return{cpOrigin:Xn(),token:t}},IS=e=>{let t=e.trim();if(!t)return;let n=t;try{let o=new URL(t),a=o.pathname.match(vS)??o.pathname.match(SS);if(!a)return;n=a[1]}catch{}let r=mh(n);return r?{flag:r.flag,what:r.what}:void 0},gi=e=>{let t=e.trim();if(!t)return!1;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?!1:ES(n.pathname)!==void 0}catch{return kS(t)}},xa=class extends Error{constructor(t){super(t),this.name="EnrollmentPermanentError"}},yi=e=>typeof e=="string"&&e.trim()?e.trim():void 0,xS=async(e,t={})=>{let n=t.timeoutMs??pW,r=`${e.cpOrigin}/enroll-info/${e.token}`,o=new AbortController,a=setTimeout(()=>o.abort(),n),s;try{s=await fetch(r,{method:"GET",signal:o.signal})}catch(u){let f=u instanceof Error&&u.name==="AbortError"?` no response within ${n}ms.`:ft(u);throw new Error(`could not reach the enrollment page at ${e.cpOrigin}.${f}`)}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 xa(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"&&yi(u.url)!==void 0),d=yi(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:yi(l?.deploymentId),org:yi(i.org),email:yi(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 Ee="0.11.189";var yh=1e4,Co=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Co).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Co(e[n])}`).join(",")}}`,RS="stable-key-heartbeat-v1",OS="key-heartbeat",hW=["reapply_config","remint","revert"],gh=(e,t)=>t&&e.payload.source==="mdm"?{machineUuid:t}:{};var TS=e=>fW("sha256").update(e).digest("hex"),je=e=>typeof e=="string"&&e.trim()?e.trim():void 0,yW=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&/^[a-z0-9-]{1,64}$/.test(t)):[],_S={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"},gW=e=>`This organization requires a managed (MDM-enrolled) device for this enrollment: ${_S[e]}. Ask your IT admin.`,wW=e=>typeof e=="string"&&e in _S,wh=async e=>{try{let t=await e.json(),n=je(t?.message),r=je(t?.error),o=wW(t?.reason)?t.reason:void 0;if(r==="managed_device_required"&&o)return{message:gW(o),code:r,reason:o};if(n)return{message:n,...r?{code:r}:{}}}catch{}return{message:`gateway responded ${e.status}`}},bW=async e=>(await wh(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}},PS=e=>e instanceof xa||e instanceof lt&&e.policyCode==="sso_required",Ra=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}},bh=async(e,t,n,r)=>{try{return await r(Co(e),t)}catch{throw new Error(`developer ${n} failed: could not sign the challenge with the provided private key`)}},Id=()=>{let{publicKey:e,privateKey:t}=mW("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}},tn=async(e,t,n,r={})=>{let o=r.timeoutMs??yh,a=`${e}/connect/verify`,s=je(t?.payload?.deploymentId);if(!s)throw new Error("developer verification failed: the cert is missing payload.deploymentId");let i={deploymentId:s,issuedAt:new Date().toISOString(),nonce:hh(16).toString("hex"),...gh(t,r.machineUuid)},c=await bh(i,n,"verification",r.signer??_r),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":Ee},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(w){let b=w instanceof Error&&w.name==="AbortError"?` no response within ${o}ms.`:ft(w);throw new Error(`could not reach the gateway at ${a}.${b}`,{cause:w})}finally{clearTimeout(d)}if(!u.ok)throw new lt(u.status,await wh(u));let f;try{f=await u.text()}catch{f=""}let m;try{m=JSON.parse(f)}catch{let w=u.headers.get("content-type")??"",b=/\btext\/html\b/i.test(w)||/^\s*<(?:!doctype|html)/i.test(f);throw new Error(b?`developer verification failed: ${a} returned an HTML page, not the gateway \u2014 /connect/* is being routed to the console/proxy. Ask your admin to route /connect/* to the gateway service (:8787), the same as /v1/*.`:"developer verification failed: the gateway returned a malformed response")}let p=je(m?.key);if(!p)throw new Error("developer verification failed: the gateway response is missing the key");if(!/^[A-Za-z0-9._-]{1,256}$/.test(p))throw new Error("developer verification failed: the gateway returned a malformed key");let h=je(m.user);if(!h)throw new Error("developer verification failed: the gateway response is missing the user");let g=AW(m.directive),y=yW(m.capabilities);return{key:p,user:h,team:je(m.team),expiresAt:je(m.expiresAt),...y.length>0?{capabilities:y}:{},...g?{directive:g}:{}}},DS=async(e,t,n,r,o={})=>{let a=o.timeoutMs??yh,s=`${e}/connect/key/heartbeat`,i=je(n?.payload?.deploymentId);if(!i)throw new Error("developer heartbeat failed: the cert is missing payload.deploymentId");let c={deploymentId:i,issuedAt:new Date().toISOString(),nonce:hh(16).toString("hex"),purpose:OS,...gh(n,o.machineUuid)},l=await bh(c,r,"heartbeat",o.signer??_r),d=new AbortController,u=setTimeout(()=>d.abort(),a),f;try{f=await fetch(s,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":Ee},body:JSON.stringify({cert:n,challenge:c,sig:l}),signal:d.signal})}catch(h){let g=h instanceof Error&&h.name==="AbortError"?` no response within ${a}ms.`:ft(h);throw new Error(`could not reach the gateway at ${s}.${g}`,{cause:h})}finally{clearTimeout(u)}if(!f.ok)throw new Ra(f.status,await wh(f));let m;try{m=await f.json()}catch{throw new Error("developer heartbeat failed: the gateway returned a malformed response")}let p=je(m.expiresAt);if(!p||!Number.isFinite(Date.parse(p))||m.credentialMode!==RS||m.key!==void 0)throw new Error("developer heartbeat failed: the gateway returned an unexpected response");return{expiresAt:p,credentialMode:RS}},LS=async(e,t,n,r,o,a={})=>{let s=a.timeoutMs??yh,i=`${e.replace(/\/$/,"")}/connect/machine`,c=je(n?.payload?.deploymentId);if(!c||!o)return!1;let l={deploymentId:c,issuedAt:new Date().toISOString(),nonce:hh(16).toString("hex"),purpose:OS,...gh(n,o)},d=await bh(l,r,"heartbeat",a.signer??_r),u=new AbortController,f=setTimeout(()=>u.abort(),s);try{return(await fetch(i,{method:"POST",headers:{"content-type":"application/json","x-anyray-api-key":t,"x-anyray-connect-version":Ee},body:JSON.stringify({cert:n,challenge:l,sig:d,machineUuid:o}),signal:u.signal})).ok}catch(m){return console.error("connect machine report skipped:",m instanceof Error?m.name:"error"),!1}finally{clearTimeout(f)}},AW=e=>{if(e===null||typeof e!="object")return null;let t=e,n=je(t.id),r=t.kind;return!n||!/^[A-Za-z0-9_-]{1,128}$/.test(n)||typeof r!="string"||!hW.includes(r)?null:{id:n,kind:r}},CW=1e4,kW=e=>{if(e===null||typeof e!="object")return!1;let t=e;if(t.alg!=="Ed25519"||!je(t.sig))return!1;let n=t.payload;if(n===null||typeof n!="object")return!1;let r=n;return typeof r.v=="number"&&!!je(r.deploymentId)&&!!je(r.user)&&!!je(r.devPublicKey)&&!!je(r.issuedAt)&&!!je(r.expiresAt)},vW=async(e,t,n,r={},o={})=>{let a=o.timeoutMs??CW,s=`${e}/v1/enroll`,i=new AbortController,c=setTimeout(()=>i.abort(),a),l;try{l=await fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:t,devPublicKey:n,...r.email?{email:r.email}:{},...r.team?{team:r.team}:{},...r.machineId?{machineId:r.machineId}:{},...r.deploymentId?{deploymentId:r.deploymentId}:{}}),signal:i.signal})}catch(u){let f=u instanceof Error&&u.name==="AbortError"?` no response within ${a}ms.`:ft(u);throw new Error(`could not reach the control plane at ${s}.${f}`)}finally{clearTimeout(c)}if(!l.ok){let u=`enrollment failed: ${await bW(l)}`;throw l.status>=400&&l.status<500&&l.status!==429?new xa(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(!kW(d))throw new Error("enrollment failed: the control plane returned an unexpected cert shape");return d},NS=(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())},$S=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=Id();return{cert:await vW(e.cpOrigin,e.token,s.publicKeyPem,{email:e.email,team:e.team,machineId:e.machineId,deploymentId:e.deploymentId},t),...s}})(),a=await tn(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 Ah=1e4,SW=900*1e3,BS="tnt_",EW=/^\/sso\/([^/]+)\/?$/,IW=/^\/i\/([^/]+)\/?$/,xW=e=>{let t=e.match(EW);if(t)return t[1];let n=e.match(IW);return n?.[1].startsWith(BS)?n[1]:void 0},Et=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=xW(n.pathname);return r?{cpOrigin:n.origin,tenantId:r}:void 0}if(t.startsWith(BS))return{cpOrigin:Xn(),tenantId:t}},ko=class extends Error{kind;status;constructor(t,n,r){super(n),this.name="SsoStartError",this.kind=t,this.status=r}},Ft=class extends Error{kind;constructor(t,n){super(n),this.name="SsoPollError",this.kind=t}},Ch=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await r(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:o.signal}),i={};try{i=await s.json()}catch{}return{status:s.status,json:i}}finally{clearTimeout(a)}},RW=e=>new Promise(t=>setTimeout(t,e)),xd=async e=>{let t=e.now??Date.now,n=e.fetch??fetch,{publicKeyPem:r,privateKeyPem:o}=(e.generateKeypair??Id)(),a;try{a=await Ch(`${e.cpOrigin}/sso/device`,{tenantId:e.tenantId,devPublicKey:r},Ah,n)}catch(p){throw new ko("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ft(p)}`)}if(a.status!==200){let p=a.status===404,h=typeof a.json.error=="string"?a.json.error:`status ${a.status}`;throw new ko(p?"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 ko("cp-unreachable","SSO start failed: the control plane returned an incomplete response.");let i=t(),c=e.deadlineMs??SW,l=typeof s.expires_in=="number"&&s.expires_in>0?s.expires_in*1e3:c,d=typeof s.verification_uri=="string"?s.verification_uri:void 0,u=e.gatewayUrl??(typeof s.gateway_url=="string"?s.gateway_url:void 0),f={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:s.device_code,userCode:s.user_code,verificationUri:d,verificationUriComplete:s.verification_uri_complete,intervalMs:Math.max(1,s.interval||5)*1e3,grantExpiresAt:i+Math.min(c,l),startedAt:i,privateKeyPem:o,publicKeyPem:r,gatewayUrl:u},m=e.log??(()=>{});return m("To finish, sign in with your organization at:"),m(` ${f.verificationUriComplete}`),m(`Confirm this code matches your browser: ${f.userCode}`),OW(f.verificationUriComplete,e.cpOrigin)&&e.open?.(f.verificationUriComplete),f},OW=(e,t)=>{try{return new URL(e).origin===new URL(t).origin}catch{return!1}},Rd=async(e,t={})=>{let n=t.now??Date.now,r=t.sleep??RW,o=t.fetch??fetch,a=t.pollIntervalMs??e.intervalMs;for(;n()<e.grantExpiresAt&&(await r(Math.min(a,e.grantExpiresAt-n())),!(n()>=e.grantExpiresAt));){let s;try{s=await Ch(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.deviceCode,devPublicKey:e.publicKeyPem},Ah,o)}catch(c){throw new Ft("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ft(c)}`)}if(s.status===200&&s.json.cert)return{cert:s.json.cert,privateKeyPem:e.privateKeyPem,gatewayUrl:t.gatewayUrl??(typeof s.json.gatewayUrl=="string"?s.json.gatewayUrl:e.gatewayUrl),deploymentId:typeof s.json.deploymentId=="string"?s.json.deploymentId:""};let i=typeof s.json.error=="string"?s.json.error:"";if(i!=="authorization_pending"){if(i==="slow_down"){a+=5e3;continue}throw i==="expired_token"?new Ft("expired","SSO sign-in timed out before you finished. Re-run anyray-connect --sso to try again."):new Ft("denied","SSO sign-in was not completed. Re-run anyray-connect --sso to try again.")}}throw new Ft("expired","SSO sign-in timed out. Re-run anyray-connect --sso to try again.")};var MS="sdc_",FS=e=>{let t=e.trim();if(!t)return;if(t.startsWith(MS))return{cpOrigin:Xn(),claim:t};let n;try{n=new URL(t)}catch{return}if(!ph(n.origin))return;let r=n.searchParams.get("claim")?.trim();if(!(!r||!r.startsWith(MS)))return{cpOrigin:n.origin,claim:r}},WS=async e=>{let t=e.fetch??fetch,{publicKeyPem:n,privateKeyPem:r}=(e.generateKeypair??Id)(),o;try{o=await Ch(`${e.cpOrigin}/sso/device/token`,{deviceCode:e.claim,devPublicKey:n},Ah,t)}catch(s){throw new Ft("cp-unreachable",`could not reach the control plane at ${e.cpOrigin}${ft(s)}`)}if(o.status===200&&o.json.cert)return{cert:o.json.cert,privateKeyPem:r,gatewayUrl:e.gatewayUrl??(typeof o.json.gatewayUrl=="string"?o.json.gatewayUrl:void 0),deploymentId:typeof o.json.deploymentId=="string"?o.json.deploymentId:"",...typeof o.json.ssoLink=="string"&&o.json.ssoLink?{ssoLink:o.json.ssoLink}:{}};let a=typeof o.json.error=="string"?o.json.error:"";throw a==="expired_token"?new Ft("expired","This enrollment link has expired. Open your organization\u2019s Anyray link again to get a new one."):a==="authorization_pending"?new Ft("denied","This enrollment link is not ready yet. Finish signing in in your browser, then run the command it gives you."):new Ft("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 TW}from"node:fs/promises";import{isAbsolute as _W,posix as US,win32 as kh}from"node:path";var wi=(e=process.platform,t=process.env)=>e==="darwin"?US.join("/Library","Application Support","Anyray","bootstrap.json"):e==="win32"?kh.join(t.ProgramData??"C:\\ProgramData","Anyray","bootstrap.json"):US.join("/etc","anyray","bootstrap.json"),PW=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),HS=e=>typeof e=="string"&&e.length>0&&e.length<=512&&[...e].every(t=>{let n=t.charCodeAt(0);return n>=32&&n!==127})&&(_W(e)||kh.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}},Pr=async(e=wi())=>{try{let t=await TW(e,"utf-8");if(t.length>4096)return;let n=JSON.parse(t);if(!PW(n)||n.v!==1||typeof n.sso!="string")return;let r=Et(n.sso);if(!r)return;let o=DW(n.gateway)?n.gateway:void 0,a=HS(n.bin)?n.bin:void 0;return{sso:`${r.cpOrigin}/sso/${r.tenantId}`,gateway:o,bin:a}}catch{return}},GS=(e,t,n)=>{let r=Et(e);if(!r)throw new Error("invalid --sso link");if(n!==void 0&&!HS(n))throw new Error("--bin must be an absolute fleet-stable path");if(n!==void 0&&kh.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)}
|
|
262
|
+
`};var Oa=(e,t)=>t.NO_COLOR?!1:t.FORCE_COLOR&&t.FORCE_COLOR!=="0"?!0:!!e.isTTY,Od=Oa(process.stdout,process.env),VS=Oa(process.stderr,process.env),Ta=(e,t,n)=>n?`\x1B[${e}m${t}\x1B[0m`:t,K=e=>Ta("1",e,Od),v=e=>Ta("2",e,Od),LW=e=>Ta("32",e,Od),NW=e=>Ta("33",e,VS),$W=e=>Ta("31",e,VS),qe=e=>Ta("36",e,Od),A=e=>console.log(e),H=e=>console.log(`
|
|
263
|
+
${K(e)}`),L=e=>console.log(v(e)),M=e=>console.log(`${LW("\u2713")} ${e}`),O=e=>console.error(`${NW("!")} ${e}`),R=e=>console.error(`${$W("\u2717")} ${e}`);var Sh=`${K("anyray-connect managed")} \u2014 fleet-wide Claude Code routing via managed-settings.json
|
|
264
264
|
|
|
265
265
|
Emit or install the OS \`managed-settings.json\` that points a managed fleet's
|
|
266
266
|
Claude Code at the Anyray gateway. It reads at a HIGHER precedence than a user's
|
|
@@ -343,15 +343,15 @@ ${K("Examples")}
|
|
|
343
343
|
anyray-connect managed --print --tool jetbrains --bin /usr/local/bin/anyray-connect --npx /usr/local/bin/npx > acp.json
|
|
344
344
|
|
|
345
345
|
# Shell/SDK fleet snippet (base URLs only; keys stay per-user):
|
|
346
|
-
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,KS=["claude-code","jetbrains","shell","bootstrap"],
|
|
347
|
-
`)},_d=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}
|
|
348
|
-
`),
|
|
349
|
-
`),Ze(v("# acp.json for ~/.jetbrains/acp.json (per user).")),Ze(v(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ze(v("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ze(v("# An MDM file drop REPLACES the file \u2014 deploy at provision time, or merge agent_servers in your config tool if devs add their own agents.")),0},
|
|
350
|
-
`),Ze(v(`# managed-settings.json for ${Pt()}`)),n)Ze(v("# Deferred SSO: hooks only; no credential or managed env block.")),Ze(v(`# Push the binary to ${n.binaryPath} before this file.`)),Ze(v("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of QS(t))Ze(v(`# ${o}`));xh(t,Ze)}return 0},
|
|
346
|
+
anyray-connect managed --print --tool shell --gateway https://gw.acme.com > /tmp/anyray.sh # deploy to /etc/profile.d`,KS=["claude-code","jetbrains","shell","bootstrap"],WW=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(!KS.includes(a))throw new Error(`unknown --tool ${a} (expected ${KS.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&&!Et(t.sso))throw new Error("invalid --sso link (expected <origin>/sso/tnt_\u2026 or tnt_\u2026)");return t};function Td(e,t,n={}){if(!t&&e.authMode==="subscription")throw new Error("subscription managed settings require deferred SSO; a seat OAuth token does not replace the required personal gateway key");if(t){let o=["__anyray-sso-gate","--sso",t.sso,...t.gateway?["--gateway",t.gateway]:[],...t.team?["--team",t.team]:[]];return{hooks:{PostToolUse:[xn(us(t.binaryPath,[Ye]),{matcher:"*"})],UserPromptSubmit:[xn(us(t.binaryPath,o),{timeout:30}),xn(us(t.binaryPath,[or]))],SessionStart:[xn(us(t.binaryPath,[...o,"--session-start"]),{async:!0})]}}}let{env:r}=sn(e,{includeAuthToken:!1,includeClientKey:!1});return n.scrubDirectMode?{env:{...Object.fromEntries(Rn.map(o=>[o.name,""])),...r}}:{env:r}}var UW=(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 Vr)delete o[a];if(Object.keys(o).length?r.env=o:delete r.env,ip(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},HW=e=>{let t=e.env,n=ip(e);if(t){for(let r of Vr)r in t&&(delete t[r],n=!0);for(let{name:r}of Rn)t[r]===""&&(delete t[r],n=!0);Object.keys(t).length===0&&delete e.env}return n},YS=async e=>{let t=async n=>{try{return(await BW(n)).mode&511}catch{return}};return{mode:await t(e),dirExisted:await t(ZS(e))!==void 0}},JS=async(e,t)=>(t.dirExisted||await vh(ZS(e),493).catch(()=>{}),t.mode===void 0||t.mode&4?(await vh(e,420),{mode:420,keptRestricted:!1}):(await vh(e,t.mode),{mode:t.mode,keptRestricted:!0})),XS=(e,t)=>{t.keptRestricted&&(O(`${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.")))},zS=()=>process.getuid?.()===0,Ze=e=>{process.stderr.write(`${e}
|
|
347
|
+
`)},_d=(e,t)=>{if(e.out===void 0){process.stdout.write(t);return}MW(e.out,t,"utf8"),Ze(v(`# Wrote ${e.out}`))},Eh=e=>Re({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=>FW(e)||/^[A-Za-z]:[\\/]/.test(e),qS=e=>{if(!e.sso)return;let t=Et(e.sso);if(!t)throw new Error("invalid --sso link");let n=e.bin??De();if(!e.bin&&!oe())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}},QS=e=>[`Gateway: ${e.origin}`,"Fleet mode: api-key (routing + headers only \u2014 per-dev keys stay in user settings)",`Attribution: ${me(e.metadata)??"(none \u2014 pass --team)"}`],xh=(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{}},GW=(e,t)=>({agent_servers:{[Yn]:{command:e,args:[pd,"claude",t,"jetbrains"],env:{}},[Jn]:{command:e,args:[pd,"codex",t,"jetbrains"],env:{}}}}),VW=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=${Oe(e.openaiBaseUrl)}`,`export ANTHROPIC_BASE_URL=${Oe(e.anthropicBaseUrl)}`,""].join(`
|
|
348
|
+
`),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(!hd(e.npx))throw new Error("--npx must be an absolute path to an npx executable");return _d(e,`${JSON.stringify(GW(e.bin,e.npx),null,2)}
|
|
349
|
+
`),Ze(v("# acp.json for ~/.jetbrains/acp.json (per user).")),Ze(v(`# Push the binary to ${e.bin} (and npx to ${e.npx}) first.`)),Ze(v("# Credentialless: each user still enrolls once (--enroll / --sso) before first agent use.")),Ze(v("# An MDM file drop REPLACES the file \u2014 deploy at provision time, or merge agent_servers in your config tool if devs add their own agents.")),0},jW=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 _d(e,GS(e.sso,e.gateway,e.bin)),Ze(v(`# Fleet bootstrap for ${wi("linux")}`)),Ze(v(`# macOS: ${wi("darwin")}`)),Ze(v(`# Windows: ${wi("win32",{ProgramData:"C:\\ProgramData"})}`)),Ze(v("# Content-free (SSO link + gateway origin + optional binary path). World-readable is fine; deploy via MDM.")),0},ZW=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=Eh(e);return _d(e,VW(t)),Ze(v("# Shell fleet snippet for /etc/profile.d/anyray.sh (or an MDM shell include).")),xh(t,Ze),0},YW=e=>{let t=Eh(e),n=qS(e),r=n?Td(t,n):Td(t,void 0,{scrubDirectMode:e.scrubDirectMode});if(_d(e,`${JSON.stringify(r,null,2)}
|
|
350
|
+
`),Ze(v(`# managed-settings.json for ${Pt()}`)),n)Ze(v("# Deferred SSO: hooks only; no credential or managed env block.")),Ze(v(`# Push the binary to ${n.binaryPath} before this file.`)),Ze(v("# Configure SSO in the portal BEFORE pushing; sign-in happens in-tool on first prompt."));else{for(let o of QS(t))Ze(v(`# ${o}`));xh(t,Ze)}return 0},JW=async e=>{let t=jS();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(!zS())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=Eh(e),r=qS(e);r||xh(n,u=>O(u.replace(/^!\s*/,"")));let o=Pt(t),a=await B(o),s=r?Td(n,r):Td(n,void 0,{scrubDirectMode:e.scrubDirectMode}),i=e.scrubDirectMode?Rn.filter(({name:u})=>{let f=a.env?.[u];return typeof f=="string"&&f.trim()!==""}):[],c=UW(a,s),l=await YS(o);await X(o,c);let d=await JS(o,l);M(`Wrote ${o}`),XS(o,d);for(let{name:u,cloud:f}of i)O(`${u} was set in this file and is now pinned empty \u2014 Claude Code no longer talks to ${f} directly. The gateway serves it instead; re-add the key here to undo.`);if(r)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 QS(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=jS();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(!zS())return R("Refusing to edit the system managed-settings.json without root \u2014 re-run with `sudo`."),1;let t=Pt(e);if(!await x(t))return A(`Nothing to revert \u2014 ${t} does not exist.`),0;let n=await B(t);if(!HW(n))return A(`No Anyray-owned keys found in ${t} \u2014 left unchanged.`),0;let r=await YS(t);await X(t,n);let o=await JS(t,r);return M(`Removed Anyray-owned keys from ${t} (other keys left intact).`),XS(t,o),0},eE=async e=>{let t;try{t=WW(e)}catch(n){return R(n instanceof Error?n.message:"invalid managed arguments"),A(`
|
|
351
351
|
`+Sh),1}if(t.help||e.length===0&&!t.mode)return A(Sh),0;if(!t.mode)return R("Specify a mode: --print, --write, or --revert."),A(`
|
|
352
|
-
`+Sh),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"?
|
|
352
|
+
`+Sh),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"?jW(t):ZW(t):t.mode==="print"?YW(t):t.mode==="write"?await JW(t):await XW()}catch(n){return R(n instanceof Error?n.message:"managed settings failed"),1}};import{spawn as oH}from"node:child_process";import{homedir as aH}from"node:os";import{join as FE}from"node:path";import{readFile as sH,writeFile as WE,chmod as iH,stat as cH,unlink as OE}from"node:fs/promises";var zW=["hook_registration","mcp_registration","hook_binary","beacon_target"],vo=e=>e.status==="configured"||e.status==="queued",So=async(e,t=fe)=>{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},_a=async(e,t,n=fe)=>{let r=[];for(let o of await So(e,n))if(o.pointsAt)try{if(o.automaticRepairAllowed&&!await o.automaticRepairAllowed())continue;await o.pointsAt(t)||r.push(o)}catch{}return r},Rh=async(e,t=fe)=>{let n=[];for(let r of await So(e,t))if(r.integrationStatus)try{n.push({adapter:r,checks:await r.integrationStatus()})}catch{n.push({adapter:r,checks:Object.fromEntries(zW.map(o=>[o,"unreadable"]))})}return n},tE=e=>e.filter(t=>!t.integrationStatus),qW=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"||t==="EROFS"?"settings_not_writable":"apply_threw"},Wt=async(e,t)=>{let n=[];for(let r of e)try{let o=await r.apply(t,{dryRun:!1});n.push({id:r.id,title:r.title,status:o.status,...o.errorClass?{errorClass:o.errorClass}:{}})}catch(o){let a=qW(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 eU,writeFile as tU}from"node:fs/promises";import{join as rE}from"node:path";import{z as Te}from"zod";var Pa="required",QW=e=>e==="subscription"?"subscription":"placeholder",nE=(e,t)=>{let n=t.routingOrigin!=null&&t.routingOrigin!==e.gateway,r=!!t.team&&t.team!==e.team,o=t.lane?QW(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}:{}}},Pd=(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]??Pa,l=[],d=[];for(let u of r){if(o.includes(u))continue;let f=c(u);if(f!=="optional"){if(f!=="locked"){if(!i)continue;if(s.has(u)){f==="required"&&d.push(u);continue}}l.push(u)}}return{candidateIds:a,freshIds:l,tombstonedIds:d}};var nU=1e4,rU=1,oU=Te.string().min(1).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).refine(e=>e!=="."&&e!==".."),aU=Te.object({id:oU,name:Te.string().min(1),version:Te.string().min(1),body:Te.string()}),sU=Te.object({version:Te.literal(rU).optional(),skills:Te.array(aU),updatedAt:Te.string().min(1).optional(),routing:Te.object({origin:Te.string().min(1)}).optional(),team:Te.string().min(1).optional(),lane:Te.enum(["subscription","org"]).optional().catch(void 0),tools:Te.object({enabled:Te.array(Te.string().min(1)),tiers:Te.record(Te.string().min(1),Te.enum(["locked","required","recommended","optional"]).catch("optional")).optional()}).optional(),updates:Te.object({mode:Te.enum(["auto","directed","off"]).catch("directed")}).optional()}),Da=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="TeamPolicyFetchError"}},Oh=e=>e instanceof Da&&e.kind==="auth",iU=e=>/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)&&e!=="."&&e!=="..",Th=e=>e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",La=async(e,t,n={})=>{let r=n.timeoutMs??nU,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.`:ft(l);throw new Da("unavailable",`could not reach the gateway at ${o}.${d}`)}finally{clearTimeout(s)}if(!i.ok)throw new Da(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 Da("malformed","team policy fetch failed: the gateway returned a malformed response")}return sU.parse(c)},oE=/^[a-z0-9][a-z0-9-]{0,31}$/,aE=64,cU=e=>{let t=e.tools;if(!t)return;let n=t.enabled.filter(o=>oE.test(o)).slice(0,aE).sort(),r=Object.entries(t.tiers??{}).filter(([o])=>oE.test(o)).slice(0,aE).sort(([o],[a])=>o.localeCompare(a));return{enabled:n,...r.length>0?{tiers:Object.fromEntries(r)}:{}}},lU=e=>e.updates?{mode:e.updates.mode}:void 0,bi=(e,t)=>{let n=e.fleetToolPolicy;return n?.enabled.includes(t)?(n.tiers?.[t]??Pa)==="locked":!1},Na=async(e,t={})=>{let n=t.loadProfile??P,r=t.saveProfile??ce,o=t.targetFromProfile??Ue,a=t.adapters??fe,s=t.repairTools??Wt,i=t.recordManaged??er,c=await n(),l={...c},d=nE(c,{routingOrigin:e.routing?.origin?jt(e.routing.origin):void 0,team:e.team,lane:e.lane}),{routingUpdated:u,teamUpdated:f,laneUpdated:m}=d;(u||f||m)&&(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 p=Pd(l,{enabled:e.tools?.enabled,tiers:e.tools?.tiers},u||f||m),{candidateIds:h,freshIds:g}=p,y=0,w=0,b=0;if(h.length>0||g.length>0){let _=await o(async()=>l);if(_){let T;if(u||f||m){let G=new Set(h);T=[];for(let ne of a)if(G.has(ne.id))try{(await ne.detect()).installed&&T.push(ne)}catch{}}else T=await _a(h,_.target.origin,a);let W=new Set(g),Q=[];for(let G of a)if(W.has(G.id))try{(await G.detect()).installed&&Q.push(G)}catch{}if(y=T.length+Q.length,y>0){let G=await s([...T,...Q],_.target);w=G.filter(vo).length;let ne=G.filter(z=>W.has(z.id));if(b=ne.filter(vo).length,ne.length>0)try{await i(ne,!1)}catch{}}}}let k=cU(e),C=lU(e),S=await n(),E=JSON.stringify(k??null)!==JSON.stringify(S.fleetToolPolicy??null),I=JSON.stringify(C??null)!==JSON.stringify(S.fleetUpdatePolicy??null);if(E||I){let{fleetToolPolicy:_,fleetUpdatePolicy:T,...W}=S;await r({...W,...k?{fleetToolPolicy:k}:{},...C?{fleetUpdatePolicy:C}:{}})}return{routingUpdated:u,teamUpdated:f,laneUpdated:m,toolsRequested:y,toolsApplied:w,toolsEnrolled:b,toolsTombstoned:p.tombstonedIds,profileUpdated:u||f||m,updatesMode:C?.mode??"auto",updatesUpdated:I}},sE=async(e,t,n)=>{let r=[],o={},a=0,s=0;for(let i of e.skills){if(!iU(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=rE(d,i.id),f=rE(u,"SKILL.md");await eU(u,{recursive:!0}),await tU(f,dU(i.body),"utf-8"),l.push(f)}a+=1,r.push({id:i.id,name:i.name,version:i.version,written:!0,files:l})}return{results:r,changed:a,unchanged:s,versions:o,updatedAt:e.updatedAt}},dU=e=>e.endsWith(`
|
|
353
353
|
`)?e:`${e}
|
|
354
|
-
`;import{randomBytes as dU}from"node:crypto";var uU=1e4,pU="machine:",iE=e=>e.startsWith(pU),fU="cert-renew",mU=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)},cE=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Xn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:dU(16).toString("hex"),purpose:fU},c;try{c=await(n.signer??_r)(Co(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),uU),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 m=(await u.json().catch(()=>null))?.cert;return mU(m)?{ok:!0,cert:m}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var _h=async(e,t=e.origin,n=fe)=>{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=fe)=>(await _h(e,t,n)).complete;var hU=["claude","codex","cursor","opencode"],yU=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],gU=new Set(["missing_key","key_expired"]);var wU=600*1e3,bU=600*1e3,lE=1440*60*1e3,AU=1440*60*1e3,CU=10080*60*1e3,kU=3600*1e3,vU=720*60*1e3,SU=e=>Math.min(vU,kU*2**Math.max(0,e-1)),Ai=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$a=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,dE=e=>typeof e=="string"&&yU.includes(e),En=e=>{if(!Ai(e))return{};let t={};if($a(e.watchSince)&&(t.watchSince=e.watchSince),Ai(e.invoked)){let n={};for(let r of hU){let o=e.invoked[r];$a(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return Ai(e.authFailure)&&$a(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...dE(e.authFailure.code)?{code:e.authFailure.code}:{}}),Ai(e.repair)&&$a(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,...$a(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Dd=e=>{try{let n=JSON.parse(e);if(Ai(n)&&dE(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"},Dh=e=>e!==void 0&&gU.has(e),Lh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=wU},uE=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),Nh=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=bU},pE=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),fE=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,mE=(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},hE=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>lE||!Dh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<SU(r.failures??1))},Ld=e=>{let t=Object.values(e?.invoked??{}).filter($a);return t.length>0?Math.max(...t):null},$h=(e,t)=>{if(Ld(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=CU},yE=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=AU)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=lE)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var Mh="x-anyray-retrieve-probe",Nd=8e3,EU=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",gE=(e,t)=>{let n=Yt(e);return t?.probe&&(n[Mh]="1"),n},Ma=async(e,t,n)=>{if(!e)return{ok:!1,kind:"unconfigured",message:"Anyray gateway not configured (run `anyray-connect` to point your tools at it)."};let r=new AbortController,o=setTimeout(()=>r.abort(),Nd);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:gE(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=EU(i)&&i.code==="slice_unsupported";return{ok:!1,kind:a.status===401||a.status===403?"auth":c?"slice-unsupported":"unavailable",message:`Retrieval unavailable (gateway returned HTTP ${a.status}).`}}let s;try{s=await a.json()}catch{return{ok:!1,kind:"malformed",message:"Retrieval returned malformed JSON."}}return typeof s?.content!="string"?{ok:!1,kind:"malformed",message:"Retrieval returned no content."}:{ok:!0,content:s.content,...typeof s.totalLines=="number"&&{totalLines:s.totalLines},...typeof s.totalChars=="number"&&{totalChars:s.totalChars},...typeof s.partial=="boolean"&&{partial:s.partial},...typeof s.startLine=="number"&&{startLine:s.startLine},...typeof s.endLine=="number"&&{endLine:s.endLine},...typeof s.grepMatches=="number"&&{grepMatches:s.grepMatches},...typeof s.grepTruncated=="boolean"&&{grepTruncated:s.grepTruncated}}}catch(a){let s=a instanceof Error&&a.name==="AbortError";return{ok:!1,kind:s?"timeout":"network",message:s?"Retrieval timed out.":`Retrieval failed: ${a instanceof Error?a.message:String(a)}`}}finally{clearTimeout(o)}},$d=async(e,t,n,r)=>{if(!e)return{ok:!1,kind:"unconfigured",message:"Anyray gateway not configured (run `anyray-connect` to point your tools at it)."};let o=new AbortController,a=setTimeout(()=>o.abort(),Nd);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:gE(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 IU=5e3,xU=2048,RU=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}"`))},Ba=async(e={})=>{let t=e.readTarget??nt,n=e.fetch??fetch,r=e.timeoutMs??IU,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=Yt(o);i["content-type"]="application/json",i[Mh]="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,xU);if(!RU(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=Dd(u);return{verdict:"dark",reason:"key_rejected",status:c.status,...f?{code:f}:{}}}if(!c.ok)return{verdict:"indeterminate",reason:c.status>=500?"unreachable":"unsupported",status:c.status};let l;try{l=await c.json()}catch{return{verdict:"indeterminate",reason:"unsupported",status:c.status}}return typeof l=="object"&&l!==null&&l.handled===!0?{verdict:"live",reason:"ok",status:c.status}:{verdict:"indeterminate",reason:"gateway_mismatch",status:c.status}}catch{return{verdict:"indeterminate",reason:"unreachable"}}finally{clearTimeout(s)}},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 _U}from"node:crypto";import{execSync as Fh}from"node:child_process";import{hostname as OU}from"node:os";var TU=e=>{try{if(e==="darwin"){let t=Fh("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=Fh('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 Fh("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Md=(e={platform:process.platform,read:()=>TU(process.platform),hostname:OU})=>e.read().trim()||e.hostname().trim();var Ut=(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??(()=>Md());try{return r().trim().toLowerCase()}catch{return""}}return""};var PU=500,wE=2e3,DU=2e3,LU=250,bE=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),PU);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)}},NU=e=>{let t=e.headers?.get?.("retry-after");if(!t)return;let n=Number(t.trim());return Number.isFinite(n)&&n>=0?n*1e3:void 0},$U=e=>new Promise(t=>setTimeout(t,e)),MU=async(e,t,n=$U)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),wE),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=NU(i)??LU,s>DU))return!1}finally{clearTimeout(a)}await n(s)}},BU=async(e,t={})=>{try{let r=(await(t.loadProfile??P)()).enrolledCert,o=await(t.loadDevKey??Fe)(),a=r?.payload?.deploymentId;if(!r||!o||!a)return!1;let s={deploymentId:a,issuedAt:new Date().toISOString(),nonce:_U(16).toString("hex"),events:e},i;try{i=await(t.signer??_r)(Co(s),o)}catch{return!1}return await(t.post??MU)(`${t.origin??Xn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},FU=async(e,t,n={})=>{try{let o=(await(n.loadProfile??P)()).enrolledCert,a=await(n.loadDevKey??Fe)();if(!o||!a)return;await(n.verify??tn)(e,o,a,{timeoutMs:wE,machineUuid:(n.machineUuid??Ut)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},AE=async(e,t)=>{if(e.length!==0)try{let n=await nt(),r=n&&await bE(n.origin,Yt(n),e,t);if(n&&await FU(n.origin,e),r)return;await BU(e)}catch{}},Wh=async(e,t,n={readTarget:()=>nt("profile"),post:bE})=>{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 Io=["hook_registration","mcp_registration","hook_binary","beacon_target"];var kE=128,vE=300*1e3,WU=["repaired","repair_failed","flapping","pending"],UU=["settings_not_writable","mcp_unreadable","mcp_not_writable","mcp_foreign","mcp_not_persisted","apply_unconfirmed","apply_threw"],SE=["rebroke_same_day","repeat_days"],EE=new Set(fe.map(e=>e.id)),Eo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ki=(e,t)=>typeof e=="string"&&t.some(n=>n===e),IE=e=>ki(e,Io),Bd=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},Dr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,Ci=e=>{if(!(!Array.isArray(e)||!e.every(IE)))return zn(e)},HU=e=>{if(!Eo(e))return;let t=Ci(e.checks);if(!(!Dr(e.since)||!ki(e.reason,SE)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},GU=e=>{if(!Eo(e))return;let t={};Bd(e.day)&&(t.day=e.day),Dr(e.attempts)&&(t.attempts=e.attempts);let n=Ci(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=Ci(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=Ci(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=Ci(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Bd(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Dr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),Eo(e.lastRepaired)){let i={};for(let c of Io){let l=e.lastRepaired[c];Dr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=HU(e.flapping);return s&&(t.flapping=s),t},VU=e=>{if(!Eo(e)||!Bd(e.day)||!Dr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!EE.has(e.tool)||!IE(e.checkId)||!ki(e.status,WU)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!ki(e.errorClass,UU))return;t=e.errorClass}else if(e.status==="flapping"){if(!ki(e.errorClass,SE))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,...Dr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},CE=e=>{if(!Eo(e))return{};let t={};if(Eo(e.adapters)){let n={};for(let r of EE){let o=GU(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(VU).filter(n=>n!==void 0).slice(-kE)),Dr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),Eo(e.report)&&Bd(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Dr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},KU=e=>new Date(e).toISOString().slice(0,10),jU=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,zn=e=>[...new Set(e)],Fd=(e,t)=>{let n=e??{};if(n.day===t)return n;let r=n.day!==void 0&&n.dayHadNeed===!1;return{...n,day:t,attempts:0,attemptedChecks:[],confirmedChecks:[],brokenReportedChecks:[],dayHadNeed:!1,...r?{consecutiveRepairDays:0,lastConfirmedDay:void 0,flapping:void 0}:{}}},vi=(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(-kE),nextSequence:r}},ZU=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),YU=async e=>await Ue(async()=>e)??null,JU=async(e,t,n)=>{let r=new Map(e.map(({adapter:o,checks:a})=>[o.id,Object.values(a).some(s=>s==="missing")]));await n.claimState(o=>{let a={...o.adapters??{}};for(let{adapter:s}of e){let i=Fd(a[s.id],t);a[s.id]={...i,dayHadNeed:!!(i.dayHadNeed||r.get(s.id))}}return{next:{...o,adapters:a,events:(o.events??[]).filter(s=>s.day===t)},result:void 0}},void 0)},xE=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:jU(e.lastConfirmedDay,n)?(e.consecutiveRepairDays??0)+1:1,a=o>=3,s={...e.lastRepaired??{}};for(let c of t)s[c]=r;let i=e.flapping;return{adapter:{...e,confirmedChecks:zn([...e.confirmedChecks??[],...t]),brokenReportedChecks:(e.brokenReportedChecks??[]).filter(c=>!t.includes(c)),lastConfirmedDay:n,consecutiveRepairDays:o,lastRepaired:s,...a?{flapping:{since:i?.since??r,reason:"repeat_days",checks:zn([...i?.checks??[],...t])}}:{}},slowFlap:a}},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=Fd(d,n),f=u.awaiting??[],m=a.get(l);if(f.length===0||t.has(l)||!m){c[l]=u;continue}let p=f.filter(g=>m.checks[g]==="owned"),h=f.filter(g=>{let b=m.checks[g];return b==="missing"||b==="foreign"}),w=f.filter(g=>{let b=m.checks[g];return b===void 0||b==="unreadable"}),y=xE(u,p,n,r);c[l]={...y.adapter,awaiting:w.length>0?w:void 0},i=vi(i,n,[...p.map(g=>({tool:l,checkId:g,status:"repaired"})),...h.map(g=>({tool:l,checkId:g,status:"repair_failed",errorClass:"apply_unconfirmed"})),...y.slowFlap?p.map(g=>({tool:l,checkId:g,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},zU=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Fd(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],f=t.filter(y=>!d.includes(y)||u.includes(y)),m=f.filter(y=>u.includes(y)),p=l.attempts??0;if(p>=2||f.length===0&&!n){let y=m.filter(k=>!(l.brokenReportedChecks??[]).includes(k));if(y.length===0)return{result:void 0};let g=l.flapping;return c[e]={...l,brokenReportedChecks:zn([...l.brokenReportedChecks??[],...y]),flapping:{since:g?.since??a,reason:"rebroke_same_day",checks:zn([...g?.checks??[],...y])}},{next:vi({...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:p+1,attemptedChecks:zn([...d,...f]),confirmedChecks:u.filter(y=>!f.includes(y)),brokenReportedChecks:zn([...l.brokenReportedChecks??[],...m]),...m.length>0?{flapping:{since:h?.since??a,reason:"rebroke_same_day",checks:zn([...h?.checks??[],...m])}}:{}},{next:vi({...i,adapters:c},o,m.map(y=>({tool:e,checkId:y,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:m}}},void 0),qU=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Fd(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:zn([...l.awaiting??[],...t])},{next:vi({...i,adapters:c},o,t.map(p=>({tool:e,checkId:p,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(p=>r[p]==="owned"):[],u=n.status==="configured"&&r?t.filter(p=>{let h=r[p];return h==="missing"||h==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],f=xE(l,d,o,a);c[e]=f.adapter;let m=n.status==="failed"?n.errorClass??"apply_threw":n.errorClass??"apply_unconfirmed";return{next:vi({...i,adapters:c},o,[...d.map(p=>({tool:e,checkId:p,status:"repaired"})),...u.map(p=>({tool:e,checkId:p,status:"repair_failed",errorClass:m})),...f.slowFlap?d.map(p=>({tool:e,checkId:p,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},QU=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>=vE));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??Wh)(o.map(ZU),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)},eH=async(e,t,n,r,o,a)=>{let s=[],i=!1,c=new Set(n.map(u=>u.adapter));for(let{adapter:u,checks:f}of t){let m=r.adapters?.[u.id];for(let p of Io){let h=f[p];if(!h||h==="unreadable")continue;let w,y;m?.awaiting?.includes(p)&&c.has(u.id)?w="pending":h==="missing"&&m?.flapping?.checks.includes(p)?(w="flapping",y=m.flapping.reason):w=h==="owned"?"ok":h,w!=="ok"&&w!=="pending"&&(i=!0),s.push({tool:u.id,checkId:p,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&&Je(e)&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??Pn)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??gr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=yE(await a.readHookLane?.().catch(()=>({})),o);return d&&(d.status!=="repaired"&&(i=!0),s.push({tool:"connect",checkId:"hook_lane",status:d.status,...d.errorClass?{errorClass:d.errorClass}:{}})),s.push({tool:"connect",checkId:"selfcheck_report",status:i?"problems":"ok"}),s},tH=async(e,t,n,r,o,a,s)=>{if(!await s.claimState(u=>u.report?.day===r&&u.report.delivered?{result:!1}:u.report?.day===r&&u.report.attemptedAt!==void 0&&u.report.attemptedAt<=o&&o-u.report.attemptedAt<vE?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await eH(e,t,n,c,o,s);await(s.report??Wh)(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)},RE=async(e,t,n)=>{let r=n.now??Date.now,o=KU(r()),a=e.managedTools??[],s={...n,readState:async()=>CE(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(CE(l)),c)};try{let i=await(s.findIntegrations??Rh)(a);await JU(i,o,s);let c=await(s.listPending??hr)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await XU(i,l,o,r(),s);let d=await(s.resolveTarget??YU)(e),u=d?await(s.findDrifted??_a)(a,d.target.origin):[],f=new Set(u.map(y=>y.id)),m=new Map(i.map(y=>[y.adapter.id,y]));for(let y of u)m.has(y.id)||m.set(y.id,{adapter:y,checks:{}});let p=!1,h=(s.runtimeDurable??oe)();if(d)for(let{adapter:y,checks:g}of m.values()){let b=h?Io.filter(T=>g[T]==="missing"):[];if(b.length===0&&!f.has(y.id))continue;let k=g;if(y.integrationStatus)try{k=await y.integrationStatus()}catch{k=Object.fromEntries(Io.map(T=>[T,"unreadable"]))}let C=b.filter(T=>k[T]==="missing"),S=f.has(y.id);if(S&&y.pointsAt&&(S=!await y.pointsAt(d.target.origin).catch(()=>!0)),C.length===0&&!S)continue;let E=await zU(y.id,C,S,l.has(y.id),o,r(),s);if(!E)continue;let[I]=await(s.repair??Wt)([y],d.target);if(!I)continue;p=!0;let _;I.status==="configured"&&y.integrationStatus&&(_=await y.integrationStatus().catch(()=>{})),await qU(y.id,E.checks,I,_,o,r(),s)}await QU(o,r(),t,s),i=await(s.findIntegrations??Rh)(a);let w=await(s.listPending??hr)().catch(()=>[]);return await tH(e,i,w,o,r(),t,s),p}catch{return!1}};var cH=14,lH=.35,dH=900*1e3,TE=360*60*1e3,uH=.2,pH=1800*1e3,_E=3600*1e3,fH=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),mH=300*1e3,hH=30*1e3,yH=900*1e3,gH=(e=0)=>Math.min(yH,hH*2**Math.max(0,e)),PE=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}},DE=1440*60*1e3,wH=300*1e3,bH=.25,AH=.5,LE=3600*1e3,CH=720*60*60*1e3,kH=360*60*1e3,vH=1440*60*1e3,SH=()=>FE(oH(),".anyray"),Uh=()=>FE(SH(),"refresh-state.json"),Hh=e=>process.env?.[e],UE=()=>Hh("ANYRAY_REFRESH_DISABLE")==="true",Gh=()=>{let e=Hh("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:cH)*vH},Vh=e=>{let t=Gh(),n=e?ws(e):void 0;if(!n)return t;let r=Math.max(dH,Math.round(n*lH));return Math.min(t,r)},EH=e=>{let t=Hh("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(TE,Math.max(pH,Math.round(e*uH))):TE},It=async()=>{try{let e=await aH(Uh(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Ud=async e=>{try{let t=Uh(),n=`${t}.${process.pid}.tmp`;await WE(n,JSON.stringify(e),{mode:384}),await ye(n,t),await sH(t,384).catch(()=>{})}catch{}},IH=3e4,xH=()=>`${Uh()}.lock`,NE=async e=>{try{return await WE(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??Ud,s=xH(),i=!1;try{if(i=await NE(s),!i){if(await iH(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<IH)return t;await OE(s).catch(()=>{}),i=await NE(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await OE(s).catch(()=>{})}},Wd=async(e,t={})=>{await dt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Fa=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(()=>{})},xo=async(e={})=>{let t=e.now??Date.now;await dt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},RH=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(CH,Math.max(LE,Math.round(o*AH))):LE},HE=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,Kh=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??ce,a=n.loadProfile??P,s=n.loadDevKey??Fe,i=n.renew??cE,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(iE(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()>RH(e))return{outcome:"not-due",profile:e};if(!await dt(w=>r()-(w.lastCertRenewAt??0)<kH?{result:!1}:{next:{...w,lastCertRenewAt:r()},result:!0},!1,n).catch(()=>!1))return{outcome:"throttled",profile:e};let u=await i(c,t);if(!u.ok)return{outcome:u.refused?"refused":"failed",profile:e};let f=await a().catch(()=>e);if(!f.enrolledCert)return{outcome:"failed",profile:e};if(!await HE(f,c.sig,t,s))return{outcome:"superseded",profile:f};let m=u.cert.payload.expiresAt,p=Date.parse(m)-r(),h={...f,enrolledCert:u.cert,enrolledCertExpiry:m,...Number.isFinite(p)&&p>0?{enrolledCertLifetimeMs:p}:{}};return await o(h),{outcome:"renewed",profile:h}},$E=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*bH):DE,r=Math.min(DE,n);return Math.min(r,wH*2**Math.max(0,e-1))},OH=()=>{let{command:e,args:t}=dr(ar);return{exe:e,args:t}},Lr=async(e={})=>{if(UE())return;let t=e.now??Date.now,n=e.readState??It,r=e.writeState??Ud,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=OH();rH(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await dt(s=>t()-(s.lastSpawnAt??0)<EH(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},TH=Ph,_H=async(e,t=!1)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await Ue(async()=>e);if(!r)return!1;let o=await _a(n,r.target.origin),a=t?tE(o):o;return a.length===0?!1:(await Wt(a,r.target),!0)}catch{return!1}},PH=async(e,t,n,r,o)=>{try{let a=new Set(e.managedTools??[]),s=fe.filter(d=>a.has(d.id));if(s.length===0)return!1;let i=await r().catch(()=>{}),c=Re({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}},DH=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??It,a=t.writeState??Ud;return RE(e,Ee,{now:r,deadWatcherObserved:n,readHookLane:()=>Hd({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})})},Hd=async(e={})=>{let n=await(e.readState??It)().catch(()=>({}));return En(n.hookLane)},GE=async(e,t={})=>{try{let n=t.now??Date.now,r=await Hd(t);if(!Lh(r,e,n()))return;await dt(o=>{let a=En(o.hookLane);return Lh(a,e,n())?{next:{...o,hookLane:uE(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},VE=async(e,t={})=>{try{let n=t.now??Date.now,r=await Hd(t);if(!Nh(r,n()))return;await dt(o=>{let a=En(o.hookLane);return Nh(a,n())?{next:{...o,hookLane:pE(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},LH=async(e={})=>{try{let t=e.now??Date.now;if((await Hd(e)).watchSince!==void 0)return;await dt(n=>{let r=En(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:fE(r,t())},result:void 0}},void 0,e)}catch{}},ME=async(e,t={})=>{try{let n=t.now??Date.now;await dt(r=>{let o=En(r.hookLane),a=mE(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},KE=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??cw)())return await r()?"stamped":"skipped";let o=await(e.load??P)(),s=await(e.findTools??So)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await Ue(async()=>o);return!i||!await r()?"skipped":(await(e.repair??Wt)(s,i.target),"repathed")}catch{return"skipped"}},jE=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??P)(),i=await(e.findTools??So)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await Ue(async()=>a);return!c||!await o()?"skipped":(await(e.repair??Wt)(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"}},NH=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await La(e.gateway,e.clientKey),n=await Na(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},BE=async(e,t,n)=>{let o=await(t.reconcilePolicy??NH)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>_H(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},Ht=async(e={})=>{if(UE())return"disabled";let t=e.now??Date.now,n=e.loadProfile??P,r=e.saveProfile??ce,o=e.loadDevKey??Fe,a=e.readState??It,s=e.writeState??Ud,i=e.remint??tn,c=e.heartbeat??DS,l=e.detectSeat??wn,d=e.rewriteTools??TH,u=e.rewriteHookLaneTools??_h,f=e.probeHookLane??Ba,m=e.classifyBeacon??bc,p=e.force===!0,h=!1,w=!1,y=!1,g=!1;e.hookLaneRepair===!0&&(p=!0,g=!0);let b=async C=>{if(!g){C==="repaired"&&await ME("none",{now:t,readState:a,writeState:s});return}let S=C;if(C==="repaired"){let E=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));S=E.verdict==="live"?"repaired":E.verdict==="dark"?"repair_failed":"unverified"}await ME(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??(E=>DH(E,{now:t,readState:a,writeState:s},y)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await hr().then(U=>U.some(Y=>!gr(Y.watcherPid))).catch(()=>!1),await LH({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??xb)();let C=await n();if(h=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let S=C.gateway,E=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(E)||E<=t())return"cert-expired";let I=await o();if(!I)return"not-enrolled";let _=(e.resolveMachineUuid??Ut)()||void 0,T=await Kh(C,I,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=T.profile;let W=T.outcome==="renewed",Q=C.enrolledCert;if(!Q)return"not-enrolled";let G=Date.parse(C.clientKeyExpiresAt??""),ne=Number.isFinite(G)?G-t():0,z=await a(),Z=!C.clientKey||ne<=Vh(C);if(!p&&hE(En(z.hookLane),t())&&await m().catch(()=>"unreadable")!=="foreign"&&(p=!0,g=!0),C.clientKey&&(p||Z)){let U=await dt(Y=>{let re=t()-(Y.lastAttemptAt??0);return re<_E?{result:"throttled"}:Y.failureCount&&re<$E(Y.failureCount,Y.keyTtlMs)?{result:"backoff"}:{next:{...Y,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(U!=="ok")return U;try{let Y=await c(S,C.clientKey,Q,I,{machineUuid:_}),re=await n().catch(()=>C);return re.clientKey!==C.clientKey||re.enrolledCert?.sig!==Q.sig?"failed":(await r({...re,clientKeyExpiresAt:Y.expiresAt}),await Wd(({lastError:Qe,...Ie})=>({...Ie,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:ws(C)??Ie.keyTtlMs}),{now:t,readState:a,writeState:s}),g?await b(await PH(C,S,C.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Y){let re=PE(Y);return await Wd(Qe=>({...Qe,lastAttemptAt:t(),failureCount:(Qe.failureCount??0)+1,lastError:{name:Y instanceof Error?Y.name:"Error",...re!==void 0?{code:re}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),Y instanceof Ra&&Y.policyCode==="managed_device_required"&&console.error(Y.message),Y instanceof Ra?Y.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!p&&C.clientKey&&!Z){let U=await BE(C,e,n),Y=await k();return U||Y?"repaired":W?"cert-renewed":"not-due"}let le=await dt(U=>{let Y=t()-(U.lastAttemptAt??0);if(p)return Y<gH(U.failureCount)?{result:"throttled"}:{next:{...U,lastAttemptAt:t()},result:"ok"};let re=U.lastError?.code!==void 0&&fH.has(U.lastError.code)?mH:_E;return Y<re?{result:"throttled"}:U.failureCount&&Y<$E(U.failureCount,U.keyTtlMs)?{result:"backoff"}:{next:{...U,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(le!=="ok")return le;try{let U=await i(S,Q,I,{machineUuid:_}),Y=await l().catch(()=>{}),re=Re({origin:S,clientKey:U.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Y,user:C.name,team:C.team});if(await d(re,re.origin)===!1)throw new Error("one or more configured tools rejected the refreshed key");let Ie=await n().catch(()=>C),ke=null;Ie.enrolledCert&&await HE(Ie,Q.sig,I,o)&&(ke={...Ie,clientKey:U.key,clientKeyExpiresAt:U.expiresAt??Ie.clientKeyExpiresAt},await r(ke));let Rt=U.expiresAt?Date.parse(U.expiresAt):NaN,D=ws(C)??(Number.isFinite(Rt)&&Rt-t()>0?Rt-t():void 0);return await Wd(({lastError:N,...j})=>({...j,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:D??j.keyTtlMs}),{now:t,readState:a,writeState:s}),ke&&await BE(ke,e,n),await b(ke?"repaired":"repair_failed"),await k(),"refreshed"}catch(U){let Y=PE(U);return await Wd(re=>({...re,lastAttemptAt:t(),failureCount:(re.failureCount??0)+1,lastError:{name:U instanceof Error?U.name:"Error",...Y!==void 0?{code:Y}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),U instanceof lt&&U.policyCode==="managed_device_required"&&console.error(U.message),U instanceof lt?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await k()}catch{}}};var $H=`anyray-connect print-key [--json | --passthrough-headers]
|
|
354
|
+
`;import{randomBytes as uU}from"node:crypto";var pU=1e4,fU="machine:",iE=e=>e.startsWith(fU),mU="cert-renew",hU=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)},cE=async(e,t,n={})=>{let r=n.fetchImpl??fetch,o=n.now??Date.now,a=n.origin??Xn();try{let s=e?.payload?.deploymentId;if(!s)return{ok:!1,refused:!1};let i={deploymentId:s,issuedAt:new Date(o()).toISOString(),nonce:uU(16).toString("hex"),purpose:mU},c;try{c=await(n.signer??_r)(Co(i),t)}catch{return{ok:!1,refused:!1}}let l=new AbortController,d=setTimeout(()=>l.abort(),pU),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 m=(await u.json().catch(()=>null))?.cert;return hU(m)?{ok:!0,cert:m}:{ok:!1,refused:!1}}catch{return{ok:!1,refused:!1}}};var _h=async(e,t=e.origin,n=fe)=>{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=fe)=>(await _h(e,t,n)).complete;var yU=["claude","codex","cursor","opencode"],gU=["missing_key","key_invalid","key_unknown","key_expired","key_revoked","user_deactivated"],wU=new Set(["missing_key","key_expired"]);var bU=600*1e3,AU=600*1e3,lE=1440*60*1e3,CU=1440*60*1e3,kU=10080*60*1e3,vU=3600*1e3,SU=720*60*1e3,EU=e=>Math.min(SU,vU*2**Math.max(0,e-1)),Ai=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$a=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,dE=e=>typeof e=="string"&&gU.includes(e),En=e=>{if(!Ai(e))return{};let t={};if($a(e.watchSince)&&(t.watchSince=e.watchSince),Ai(e.invoked)){let n={};for(let r of yU){let o=e.invoked[r];$a(o)&&(n[r]=o)}Object.keys(n).length>0&&(t.invoked=n)}return Ai(e.authFailure)&&$a(e.authFailure.at)&&typeof e.authFailure.status=="number"&&Number.isSafeInteger(e.authFailure.status)&&(t.authFailure={at:e.authFailure.at,status:e.authFailure.status,...dE(e.authFailure.code)?{code:e.authFailure.code}:{}}),Ai(e.repair)&&$a(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,...$a(e.repair.failures)&&e.repair.failures>0?{failures:e.repair.failures}:{}}),t},Dd=e=>{try{let n=JSON.parse(e);if(Ai(n)&&dE(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"},Dh=e=>e!==void 0&&wU.has(e),Lh=(e,t,n)=>{let r=e.invoked?.[t];return r===void 0?!0:r>n||n-r>=bU},uE=(e,t,n)=>({...e,watchSince:e.watchSince??n,invoked:{...e.invoked??{},[t]:n}}),Nh=(e,t)=>{let n=e.authFailure?.at;return n===void 0?!0:n>t||t-n>=AU},pE=(e,t)=>({...e,watchSince:e.watchSince??t.at,authFailure:t}),fE=(e,t)=>e.watchSince===void 0?{...e,watchSince:t}:e,mE=(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},hE=(e,t)=>{let n=e?.authFailure;if(!n||n.at>t||t-n.at>lE||!Dh(n.code))return!1;let r=e?.repair;return!(r&&r.outcome!=="repaired"&&r.at<=t&&t-r.at<EU(r.failures??1))},Ld=e=>{let t=Object.values(e?.invoked??{}).filter($a);return t.length>0?Math.max(...t):null},$h=(e,t)=>{if(Ld(e)!==null)return!1;let n=e?.watchSince;return n===void 0||n>t?!1:t-n>=kU},yE=(e,t)=>{let n=e?.repair;if(n&&n.outcome!=="unverified"&&n.at<=t&&t-n.at<=CU)return{status:n.outcome,...e?.authFailure?.code?{errorClass:e.authFailure.code}:{}};let r=e?.authFailure;if(r&&r.at<=t&&t-r.at<=lE)return{status:"key_rejected",...r.code?{errorClass:r.code}:{}}};var Mh="x-anyray-retrieve-probe",Nd=8e3,IU=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",gE=(e,t)=>{let n=Yt(e);return t?.probe&&(n[Mh]="1"),n},Ma=async(e,t,n)=>{if(!e)return{ok:!1,kind:"unconfigured",message:"Anyray gateway not configured (run `anyray-connect` to point your tools at it)."};let r=new AbortController,o=setTimeout(()=>r.abort(),Nd);try{let a=await fetch(`${e.origin}/connect/retrieve`,{method:"POST",headers:gE(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=IU(i)&&i.code==="slice_unsupported";return{ok:!1,kind:a.status===401||a.status===403?"auth":c?"slice-unsupported":"unavailable",message:`Retrieval unavailable (gateway returned HTTP ${a.status}).`}}let s;try{s=await a.json()}catch{return{ok:!1,kind:"malformed",message:"Retrieval returned malformed JSON."}}return typeof s?.content!="string"?{ok:!1,kind:"malformed",message:"Retrieval returned no content."}:{ok:!0,content:s.content,...typeof s.totalLines=="number"&&{totalLines:s.totalLines},...typeof s.totalChars=="number"&&{totalChars:s.totalChars},...typeof s.partial=="boolean"&&{partial:s.partial},...typeof s.startLine=="number"&&{startLine:s.startLine},...typeof s.endLine=="number"&&{endLine:s.endLine},...typeof s.grepMatches=="number"&&{grepMatches:s.grepMatches},...typeof s.grepTruncated=="boolean"&&{grepTruncated:s.grepTruncated}}}catch(a){let s=a instanceof Error&&a.name==="AbortError";return{ok:!1,kind:s?"timeout":"network",message:s?"Retrieval timed out.":`Retrieval failed: ${a instanceof Error?a.message:String(a)}`}}finally{clearTimeout(o)}},$d=async(e,t,n,r)=>{if(!e)return{ok:!1,kind:"unconfigured",message:"Anyray gateway not configured (run `anyray-connect` to point your tools at it)."};let o=new AbortController,a=setTimeout(()=>o.abort(),Nd);try{let s=await fetch(`${e.origin}/connect/recall`,{method:"POST",headers:gE(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 xU=5e3,RU=2048,OU=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}"`))},Ba=async(e={})=>{let t=e.readTarget??nt,n=e.fetch??fetch,r=e.timeoutMs??xU,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=Yt(o);i["content-type"]="application/json",i[Mh]="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,RU);if(!OU(u))return{verdict:"indeterminate",reason:"unsupported",status:c.status};let f=Dd(u);return{verdict:"dark",reason:"key_rejected",status:c.status,...f?{code:f}:{}}}if(!c.ok)return{verdict:"indeterminate",reason:c.status>=500?"unreachable":"unsupported",status:c.status};let l;try{l=await c.json()}catch{return{verdict:"indeterminate",reason:"unsupported",status:c.status}}return typeof l=="object"&&l!==null&&l.handled===!0?{verdict:"live",reason:"ok",status:c.status}:{verdict:"indeterminate",reason:"gateway_mismatch",status:c.status}}catch{return{verdict:"indeterminate",reason:"unreachable"}}finally{clearTimeout(s)}},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 PU}from"node:crypto";import{execSync as Fh}from"node:child_process";import{hostname as TU}from"node:os";var _U=e=>{try{if(e==="darwin"){let t=Fh("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(t)?.[1]??""}if(e==="win32"){let t=Fh('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 Fh("cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null",{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return""}},Md=(e={platform:process.platform,read:()=>_U(process.platform),hostname:TU})=>e.read().trim()||e.hostname().trim();var Ut=(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??(()=>Md());try{return r().trim().toLowerCase()}catch{return""}}return""};var DU=500,wE=2e3,LU=2e3,NU=250,bE=async(e,t,n,r)=>{let o=new AbortController,a=setTimeout(()=>o.abort(),DU);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)}},$U=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},MU=e=>new Promise(t=>setTimeout(t,e)),BU=async(e,t,n=MU)=>{for(let r=0;;r++){let o=new AbortController,a=setTimeout(()=>o.abort(),wE),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=$U(i)??NU,s>LU))return!1}finally{clearTimeout(a)}await n(s)}},FU=async(e,t={})=>{try{let r=(await(t.loadProfile??P)()).enrolledCert,o=await(t.loadDevKey??Fe)(),a=r?.payload?.deploymentId;if(!r||!o||!a)return!1;let s={deploymentId:a,issuedAt:new Date().toISOString(),nonce:PU(16).toString("hex"),events:e},i;try{i=await(t.signer??_r)(Co(s),o)}catch{return!1}return await(t.post??BU)(`${t.origin??Xn()}/v1/connect-events`,JSON.stringify({cert:r,challenge:s,sig:i}))}catch{return!1}},WU=async(e,t,n={})=>{try{let o=(await(n.loadProfile??P)()).enrolledCert,a=await(n.loadDevKey??Fe)();if(!o||!a)return;await(n.verify??tn)(e,o,a,{timeoutMs:wE,machineUuid:(n.machineUuid??Ut)()||void 0,health:{events:t},telemetryOnly:!0})}catch{}},AE=async(e,t)=>{if(e.length!==0)try{let n=await nt(),r=n&&await bE(n.origin,Yt(n),e,t);if(n&&await WU(n.origin,e),r)return;await FU(e)}catch{}},Wh=async(e,t,n={readTarget:()=>nt("profile"),post:bE})=>{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 Io=["hook_registration","mcp_registration","hook_binary","beacon_target"];var kE=128,vE=300*1e3,UU=["repaired","repair_failed","flapping","pending"],HU=["settings_not_writable","mcp_unreadable","mcp_not_writable","mcp_foreign","mcp_not_persisted","apply_unconfirmed","apply_threw"],SE=["rebroke_same_day","repeat_days"],EE=new Set(fe.map(e=>e.id)),Eo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ki=(e,t)=>typeof e=="string"&&t.some(n=>n===e),IE=e=>ki(e,Io),Bd=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},Dr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,Ci=e=>{if(!(!Array.isArray(e)||!e.every(IE)))return zn(e)},GU=e=>{if(!Eo(e))return;let t=Ci(e.checks);if(!(!Dr(e.since)||!ki(e.reason,SE)||!t?.length))return{since:e.since,reason:e.reason,checks:t}},VU=e=>{if(!Eo(e))return;let t={};Bd(e.day)&&(t.day=e.day),Dr(e.attempts)&&(t.attempts=e.attempts);let n=Ci(e.attemptedChecks);n&&(t.attemptedChecks=n);let r=Ci(e.confirmedChecks);r&&(t.confirmedChecks=r);let o=Ci(e.brokenReportedChecks);o&&(t.brokenReportedChecks=o);let a=Ci(e.awaiting);if(a&&(t.awaiting=a),typeof e.dayHadNeed=="boolean"&&(t.dayHadNeed=e.dayHadNeed),Bd(e.lastConfirmedDay)&&(t.lastConfirmedDay=e.lastConfirmedDay),Dr(e.consecutiveRepairDays)&&(t.consecutiveRepairDays=e.consecutiveRepairDays),Eo(e.lastRepaired)){let i={};for(let c of Io){let l=e.lastRepaired[c];Dr(l)&&(i[c]=l)}Object.keys(i).length>0&&(t.lastRepaired=i)}let s=GU(e.flapping);return s&&(t.flapping=s),t},KU=e=>{if(!Eo(e)||!Bd(e.day)||!Dr(e.sequence)||e.sequence===0||typeof e.tool!="string"||!EE.has(e.tool)||!IE(e.checkId)||!ki(e.status,UU)||typeof e.delivered!="boolean")return;let t;if(e.status==="repair_failed"){if(!ki(e.errorClass,HU))return;t=e.errorClass}else if(e.status==="flapping"){if(!ki(e.errorClass,SE))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,...Dr(e.attemptedAt)?{attemptedAt:e.attemptedAt}:{}}},CE=e=>{if(!Eo(e))return{};let t={};if(Eo(e.adapters)){let n={};for(let r of EE){let o=VU(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(KU).filter(n=>n!==void 0).slice(-kE)),Dr(e.nextSequence)&&e.nextSequence>0&&(t.nextSequence=e.nextSequence),Eo(e.report)&&Bd(e.report.day)&&typeof e.report.delivered=="boolean"&&(t.report={day:e.report.day,delivered:e.report.delivered,...Dr(e.report.attemptedAt)?{attemptedAt:e.report.attemptedAt}:{}}),t},jU=e=>new Date(e).toISOString().slice(0,10),ZU=(e,t)=>e!==void 0&&Date.parse(`${t}T00:00:00.000Z`)-Date.parse(`${e}T00:00:00.000Z`)===1440*60*1e3,zn=e=>[...new Set(e)],Fd=(e,t)=>{let n=e??{};if(n.day===t)return n;let r=n.day!==void 0&&n.dayHadNeed===!1;return{...n,day:t,attempts:0,attemptedChecks:[],confirmedChecks:[],brokenReportedChecks:[],dayHadNeed:!1,...r?{consecutiveRepairDays:0,lastConfirmedDay:void 0,flapping:void 0}:{}}},vi=(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(-kE),nextSequence:r}},YU=e=>({tool:e.tool,checkId:e.checkId,status:e.status,...e.errorClass?{errorClass:e.errorClass}:{}}),JU=async e=>await Ue(async()=>e)??null,XU=async(e,t,n)=>{let r=new Map(e.map(({adapter:o,checks:a})=>[o.id,Object.values(a).some(s=>s==="missing")]));await n.claimState(o=>{let a={...o.adapters??{}};for(let{adapter:s}of e){let i=Fd(a[s.id],t);a[s.id]={...i,dayHadNeed:!!(i.dayHadNeed||r.get(s.id))}}return{next:{...o,adapters:a,events:(o.events??[]).filter(s=>s.day===t)},result:void 0}},void 0)},xE=(e,t,n,r)=>{if(t.length===0)return{adapter:e,slowFlap:!1};let o=e.lastConfirmedDay===n?e.consecutiveRepairDays??1:ZU(e.lastConfirmedDay,n)?(e.consecutiveRepairDays??0)+1:1,a=o>=3,s={...e.lastRepaired??{}};for(let c of t)s[c]=r;let i=e.flapping;return{adapter:{...e,confirmedChecks:zn([...e.confirmedChecks??[],...t]),brokenReportedChecks:(e.brokenReportedChecks??[]).filter(c=>!t.includes(c)),lastConfirmedDay:n,consecutiveRepairDays:o,lastRepaired:s,...a?{flapping:{since:i?.since??r,reason:"repeat_days",checks:zn([...i?.checks??[],...t])}}:{}},slowFlap:a}},zU=async(e,t,n,r,o)=>{let a=new Map(e.map(s=>[s.adapter.id,s]));await o.claimState(s=>{let i=s,c={...s.adapters??{}};for(let[l,d]of Object.entries(c)){let u=Fd(d,n),f=u.awaiting??[],m=a.get(l);if(f.length===0||t.has(l)||!m){c[l]=u;continue}let p=f.filter(w=>m.checks[w]==="owned"),h=f.filter(w=>{let b=m.checks[w];return b==="missing"||b==="foreign"}),g=f.filter(w=>{let b=m.checks[w];return b===void 0||b==="unreadable"}),y=xE(u,p,n,r);c[l]={...y.adapter,awaiting:g.length>0?g:void 0},i=vi(i,n,[...p.map(w=>({tool:l,checkId:w,status:"repaired"})),...h.map(w=>({tool:l,checkId:w,status:"repair_failed",errorClass:"apply_unconfirmed"})),...y.slowFlap?p.map(w=>({tool:l,checkId:w,status:"flapping",errorClass:"repeat_days"})):[]])}return{next:{...i,adapters:c},result:void 0}},void 0)},qU=async(e,t,n,r,o,a,s)=>s.claimState(i=>{let c={...i.adapters??{}},l=Fd(c[e],o);if(r&&(l.awaiting?.length??0)>0)return{result:void 0};let d=l.attemptedChecks??[],u=l.confirmedChecks??[],f=t.filter(y=>!d.includes(y)||u.includes(y)),m=f.filter(y=>u.includes(y)),p=l.attempts??0;if(p>=2||f.length===0&&!n){let y=m.filter(k=>!(l.brokenReportedChecks??[]).includes(k));if(y.length===0)return{result:void 0};let w=l.flapping;return c[e]={...l,brokenReportedChecks:zn([...l.brokenReportedChecks??[],...y]),flapping:{since:w?.since??a,reason:"rebroke_same_day",checks:zn([...w?.checks??[],...y])}},{next:vi({...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:p+1,attemptedChecks:zn([...d,...f]),confirmedChecks:u.filter(y=>!f.includes(y)),brokenReportedChecks:zn([...l.brokenReportedChecks??[],...m]),...m.length>0?{flapping:{since:h?.since??a,reason:"rebroke_same_day",checks:zn([...h?.checks??[],...m])}}:{}},{next:vi({...i,adapters:c},o,m.map(y=>({tool:e,checkId:y,status:"flapping",errorClass:"rebroke_same_day"}))),result:{checks:f,fastFlaps:m}}},void 0),QU=async(e,t,n,r,o,a,s)=>{await s.claimState(i=>{let c={...i.adapters??{}},l=Fd(c[e],o);if(n.status==="queued")return c[e]={...l,awaiting:zn([...l.awaiting??[],...t])},{next:vi({...i,adapters:c},o,t.map(p=>({tool:e,checkId:p,status:"pending"}))),result:void 0};let d=n.status==="configured"&&r?t.filter(p=>r[p]==="owned"):[],u=n.status==="configured"&&r?t.filter(p=>{let h=r[p];return h==="missing"||h==="foreign"}):n.status==="failed"||n.status!=="configured"?t:[],f=xE(l,d,o,a);c[e]=f.adapter;let m=n.status==="failed"?n.errorClass??"apply_threw":n.errorClass??"apply_unconfirmed";return{next:vi({...i,adapters:c},o,[...d.map(p=>({tool:e,checkId:p,status:"repaired"})),...u.map(p=>({tool:e,checkId:p,status:"repair_failed",errorClass:m})),...f.slowFlap?d.map(p=>({tool:e,checkId:p,status:"flapping",errorClass:"repeat_days"})):[]]),result:void 0}},void 0)},eH=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>=vE));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??Wh)(o.map(YU),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)},tH=async(e,t,n,r,o,a)=>{let s=[],i=!1,c=new Set(n.map(u=>u.adapter));for(let{adapter:u,checks:f}of t){let m=r.adapters?.[u.id];for(let p of Io){let h=f[p];if(!h||h==="unreadable")continue;let g,y;m?.awaiting?.includes(p)&&c.has(u.id)?g="pending":h==="missing"&&m?.flapping?.checks.includes(p)?(g="flapping",y=m.flapping.reason):g=h==="owned"?"ok":h,g!=="ok"&&g!=="pending"&&(i=!0),s.push({tool:u.id,checkId:p,status:g,...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&&Je(e)&&e.persistenceOwner!=="tray"&&!await(a.schedulerInstalled??Pn)()&&(i=!0,s.push({tool:"connect",checkId:"refresh_scheduler",status:"missing",errorClass:"refresh_scheduler_missing"})),(a.deadWatcherObserved||n.some(u=>!(a.pidAlive??gr)(u.watcherPid)))&&(i=!0,s.push({tool:"connect",checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}));let d=yE(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},nH=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<vE?{result:!1}:{next:{...u,report:{day:r,delivered:!1,attemptedAt:o}},result:!0},!1))return;let c=await s.readState().catch(()=>({})),l=await tH(e,t,n,c,o,s);await(s.report??Wh)(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)},RE=async(e,t,n)=>{let r=n.now??Date.now,o=jU(r()),a=e.managedTools??[],s={...n,readState:async()=>CE(await n.readState()),claimState:async(i,c)=>n.claimState(l=>i(CE(l)),c)};try{let i=await(s.findIntegrations??Rh)(a);await XU(i,o,s);let c=await(s.listPending??hr)().catch(()=>[]),l=new Set(c.map(y=>y.adapter));await zU(i,l,o,r(),s);let d=await(s.resolveTarget??JU)(e),u=d?await(s.findDrifted??_a)(a,d.target.origin):[],f=new Set(u.map(y=>y.id)),m=new Map(i.map(y=>[y.adapter.id,y]));for(let y of u)m.has(y.id)||m.set(y.id,{adapter:y,checks:{}});let p=!1,h=(s.runtimeDurable??oe)();if(d)for(let{adapter:y,checks:w}of m.values()){let b=h?Io.filter(T=>w[T]==="missing"):[];if(b.length===0&&!f.has(y.id))continue;let k=w;if(y.integrationStatus)try{k=await y.integrationStatus()}catch{k=Object.fromEntries(Io.map(T=>[T,"unreadable"]))}let C=b.filter(T=>k[T]==="missing"),S=f.has(y.id);if(S&&y.pointsAt&&(S=!await y.pointsAt(d.target.origin).catch(()=>!0)),C.length===0&&!S)continue;let E=await qU(y.id,C,S,l.has(y.id),o,r(),s);if(!E)continue;let[I]=await(s.repair??Wt)([y],d.target);if(!I)continue;p=!0;let _;I.status==="configured"&&y.integrationStatus&&(_=await y.integrationStatus().catch(()=>{})),await QU(y.id,E.checks,I,_,o,r(),s)}await eH(o,r(),t,s),i=await(s.findIntegrations??Rh)(a);let g=await(s.listPending??hr)().catch(()=>[]);return await nH(e,i,g,o,r(),t,s),p}catch{return!1}};var lH=14,dH=.35,uH=900*1e3,TE=360*60*1e3,pH=.2,fH=1800*1e3,_E=3600*1e3,mH=new Set(["ENOTFOUND","EAI_AGAIN","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETDOWN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),hH=300*1e3,yH=30*1e3,gH=900*1e3,wH=(e=0)=>Math.min(gH,yH*2**Math.max(0,e)),PE=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}},DE=1440*60*1e3,bH=300*1e3,AH=.25,CH=.5,LE=3600*1e3,kH=720*60*60*1e3,vH=360*60*1e3,SH=1440*60*1e3,EH=()=>FE(aH(),".anyray"),Uh=()=>FE(EH(),"refresh-state.json"),Hh=e=>process.env?.[e],UE=()=>Hh("ANYRAY_REFRESH_DISABLE")==="true",Gh=()=>{let e=Hh("ANYRAY_REFRESH_WINDOW_DAYS"),t=e?Number.parseInt(e,10):NaN;return(Number.isFinite(t)&&t>0?t:lH)*SH},Vh=e=>{let t=Gh(),n=e?ws(e):void 0;if(!n)return t;let r=Math.max(uH,Math.round(n*dH));return Math.min(t,r)},IH=e=>{let t=Hh("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(TE,Math.max(fH,Math.round(e*pH))):TE},It=async()=>{try{let e=await sH(Uh(),"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Ud=async e=>{try{let t=Uh(),n=`${t}.${process.pid}.tmp`;await WE(n,JSON.stringify(e),{mode:384}),await ye(n,t),await iH(t,384).catch(()=>{})}catch{}},xH=3e4,RH=()=>`${Uh()}.lock`,NE=async e=>{try{return await WE(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??Ud,s=RH(),i=!1;try{if(i=await NE(s),!i){if(await cH(s).then(l=>r()-l.mtimeMs).catch(()=>1/0)<xH)return t;await OE(s).catch(()=>{}),i=await NE(s).catch(()=>!1)}}catch{}try{let c=await o(),{next:l,result:d}=e(c);return l&&await a(l),d}finally{i&&await OE(s).catch(()=>{})}},Wd=async(e,t={})=>{await dt(n=>({next:e(n),result:void 0}),void 0,t).catch(()=>{})},Fa=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(()=>{})},xo=async(e={})=>{let t=e.now??Date.now;await dt(n=>({next:{...n,lastAttemptAt:t()},result:void 0}),void 0,e).catch(()=>{})},OH=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(kH,Math.max(LE,Math.round(o*CH))):LE},HE=async(e,t,n,r)=>e.enrolledCert?.sig!==t?!1:await r().catch(()=>{})===n,Kh=async(e,t,n={})=>{let r=n.now??Date.now,o=n.saveProfile??ce,a=n.loadProfile??P,s=n.loadDevKey??Fe,i=n.renew??cE,c=e.enrolledCert;if(!c)return{outcome:"not-due",profile:e};if(iE(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()>OH(e))return{outcome:"not-due",profile:e};if(!await dt(g=>r()-(g.lastCertRenewAt??0)<vH?{result:!1}:{next:{...g,lastCertRenewAt:r()},result:!0},!1,n).catch(()=>!1))return{outcome:"throttled",profile:e};let u=await i(c,t);if(!u.ok)return{outcome:u.refused?"refused":"failed",profile:e};let f=await a().catch(()=>e);if(!f.enrolledCert)return{outcome:"failed",profile:e};if(!await HE(f,c.sig,t,s))return{outcome:"superseded",profile:f};let m=u.cert.payload.expiresAt,p=Date.parse(m)-r(),h={...f,enrolledCert:u.cert,enrolledCertExpiry:m,...Number.isFinite(p)&&p>0?{enrolledCertLifetimeMs:p}:{}};return await o(h),{outcome:"renewed",profile:h}},$E=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)&&t>0?Math.round(t*AH):DE,r=Math.min(DE,n);return Math.min(r,bH*2**Math.max(0,e-1))},TH=()=>{let{command:e,args:t}=dr(ar);return{exe:e,args:t}},Lr=async(e={})=>{if(UE())return;let t=e.now??Date.now,n=e.readState??It,r=e.writeState??Ud,o=e.spawnRefresh??(()=>{let{exe:a,args:s}=TH();oH(a,s,{detached:!0,stdio:"ignore"}).unref()});try{if(!await dt(s=>t()-(s.lastSpawnAt??0)<IH(s.keyTtlMs)?{result:!1}:{next:{...s,lastSpawnAt:t()},result:!0},!1,{now:t,readState:n,writeState:r}))return;o()}catch{}},_H=Ph,PH=async(e,t=!1)=>{try{let n=e.managedTools??[];if(n.length===0)return!1;let r=await Ue(async()=>e);if(!r)return!1;let o=await _a(n,r.target.origin),a=t?tE(o):o;return a.length===0?!1:(await Wt(a,r.target),!0)}catch{return!1}},DH=async(e,t,n,r,o)=>{try{let a=new Set(e.managedTools??[]),s=fe.filter(d=>a.has(d.id));if(s.length===0)return!1;let i=await r().catch(()=>{}),c=Re({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}},LH=async(e,t,n)=>{let r=t.now??Date.now,o=t.readState??It,a=t.writeState??Ud;return RE(e,Ee,{now:r,deadWatcherObserved:n,readHookLane:()=>Hd({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})})},Hd=async(e={})=>{let n=await(e.readState??It)().catch(()=>({}));return En(n.hookLane)},GE=async(e,t={})=>{try{let n=t.now??Date.now,r=await Hd(t);if(!Lh(r,e,n()))return;await dt(o=>{let a=En(o.hookLane);return Lh(a,e,n())?{next:{...o,hookLane:uE(a,e,n())},result:void 0}:{result:void 0}},void 0,t)}catch{}},VE=async(e,t={})=>{try{let n=t.now??Date.now,r=await Hd(t);if(!Nh(r,n()))return;await dt(o=>{let a=En(o.hookLane);return Nh(a,n())?{next:{...o,hookLane:pE(a,e)},result:void 0}:{result:void 0}},void 0,t)}catch{}},NH=async(e={})=>{try{let t=e.now??Date.now;if((await Hd(e)).watchSince!==void 0)return;await dt(n=>{let r=En(n.hookLane);return r.watchSince!==void 0?{result:void 0}:{next:{...n,hookLane:fE(r,t())},result:void 0}},void 0,e)}catch{}},ME=async(e,t={})=>{try{let n=t.now??Date.now;await dt(r=>{let o=En(r.hookLane),a=mE(o,n(),e);return JSON.stringify(a)===JSON.stringify(o)?{result:void 0}:{next:{...r,hookLane:a},result:void 0}},void 0,t)}catch{}},KE=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??cw)())return await r()?"stamped":"skipped";let o=await(e.load??P)(),s=await(e.findTools??So)(o.managedTools??[]);if(s.length===0)return await r()?"stamped":"skipped";let i=await Ue(async()=>o);return!i||!await r()?"skipped":(await(e.repair??Wt)(s,i.target),"repathed")}catch{return"skipped"}},jE=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??P)(),i=await(e.findTools??So)(a.managedTools??[]);if(i.length===0)return await o()?"stamped":"skipped";let c=await Ue(async()=>a);return!c||!await o()?"skipped":(await(e.repair??Wt)(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"}},$H=async e=>{if(!e.gateway||!e.clientKey)return!1;try{let t=await La(e.gateway,e.clientKey),n=await Na(t);return n.profileUpdated||n.toolsApplied>0}catch{return!1}},BE=async(e,t,n)=>{let o=await(t.reconcilePolicy??$H)(e).catch(()=>!1),a=o?await n().catch(()=>e):e,i=await(t.repairDrift??(c=>PH(c,t.runAmbientSelfcheck===!0)))(a).catch(()=>!1);return o||i},Ht=async(e={})=>{if(UE())return"disabled";let t=e.now??Date.now,n=e.loadProfile??P,r=e.saveProfile??ce,o=e.loadDevKey??Fe,a=e.readState??It,s=e.writeState??Ud,i=e.remint??tn,c=e.heartbeat??DS,l=e.detectSeat??wn,d=e.rewriteTools??_H,u=e.rewriteHookLaneTools??_h,f=e.probeHookLane??Ba,m=e.classifyBeacon??bc,p=e.force===!0,h=!1,g=!1,y=!1,w=!1;e.hookLaneRepair===!0&&(p=!0,w=!0);let b=async C=>{if(!w){C==="repaired"&&await ME("none",{now:t,readState:a,writeState:s});return}let S=C;if(C==="repaired"){let E=await f().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));S=E.verdict==="live"?"repaired":E.verdict==="dark"?"repair_failed":"unverified"}await ME(S,{now:t,readState:a,writeState:s})},k=async()=>{if(!e.runAmbientSelfcheck||g||!h)return!1;g=!0;let C;try{C=await n()}catch{return!1}return(e.ambientSelfcheck??(E=>LH(E,{now:t,readState:a,writeState:s},y)))(C).catch(()=>!1)};try{e.runAmbientSelfcheck&&(y=await hr().then(U=>U.some(Y=>!gr(Y.watcherPid))).catch(()=>!1),await NH({now:t,readState:a,writeState:s})),await(e.revivePendingWatchers??xb)();let C=await n();if(h=!0,!C.gateway||!C.enrolledCert)return"not-enrolled";let S=C.gateway,E=C.enrolledCertExpiry?Date.parse(C.enrolledCertExpiry):Date.parse(C.enrolledCert.payload.expiresAt);if(!Number.isFinite(E)||E<=t())return"cert-expired";let I=await o();if(!I)return"not-enrolled";let _=(e.resolveMachineUuid??Ut)()||void 0,T=await Kh(C,I,{now:t,loadProfile:n,saveProfile:r,loadDevKey:o,readState:a,writeState:s,...e.renewCert?{renew:e.renewCert}:{}});C=T.profile;let W=T.outcome==="renewed",Q=C.enrolledCert;if(!Q)return"not-enrolled";let G=Date.parse(C.clientKeyExpiresAt??""),ne=Number.isFinite(G)?G-t():0,z=await a(),Z=!C.clientKey||ne<=Vh(C);if(!p&&hE(En(z.hookLane),t())&&await m().catch(()=>"unreadable")!=="foreign"&&(p=!0,w=!0),C.clientKey&&(p||Z)){let U=await dt(Y=>{let re=t()-(Y.lastAttemptAt??0);return re<_E?{result:"throttled"}:Y.failureCount&&re<$E(Y.failureCount,Y.keyTtlMs)?{result:"backoff"}:{next:{...Y,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(U!=="ok")return U;try{let Y=await c(S,C.clientKey,Q,I,{machineUuid:_}),re=await n().catch(()=>C);return re.clientKey!==C.clientKey||re.enrolledCert?.sig!==Q.sig?"failed":(await r({...re,clientKeyExpiresAt:Y.expiresAt}),await Wd(({lastError:Qe,...Ie})=>({...Ie,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:ws(C)??Ie.keyTtlMs}),{now:t,readState:a,writeState:s}),w?await b(await DH(C,S,C.clientKey,l,u)?"repaired":"repair_failed"):await b("repaired"),"heartbeat-refreshed")}catch(Y){let re=PE(Y);return await Wd(Qe=>({...Qe,lastAttemptAt:t(),failureCount:(Qe.failureCount??0)+1,lastError:{name:Y instanceof Error?Y.name:"Error",...re!==void 0?{code:re}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),Y instanceof Ra&&Y.policyCode==="managed_device_required"&&console.error(Y.message),Y instanceof Ra?Y.status===404?"gateway-incompatible":"cert-rejected":"failed"}}if(!p&&C.clientKey&&!Z){let U=await BE(C,e,n),Y=await k();return U||Y?"repaired":W?"cert-renewed":"not-due"}let le=await dt(U=>{let Y=t()-(U.lastAttemptAt??0);if(p)return Y<wH(U.failureCount)?{result:"throttled"}:{next:{...U,lastAttemptAt:t()},result:"ok"};let re=U.lastError?.code!==void 0&&mH.has(U.lastError.code)?hH:_E;return Y<re?{result:"throttled"}:U.failureCount&&Y<$E(U.failureCount,U.keyTtlMs)?{result:"backoff"}:{next:{...U,lastAttemptAt:t()},result:"ok"}},"throttled",{now:t,readState:a,writeState:s});if(le!=="ok")return le;try{let U=await i(S,Q,I,{machineUuid:_}),Y=await l().catch(()=>{}),re=Re({origin:S,clientKey:U.key,subscription:C.authMode==="subscription",placeholder:C.authMode==="placeholder",byoUpstream:C.byoUpstream,seat:Y,user:C.name,team:C.team});if(await d(re,re.origin)===!1)throw new Error("one or more configured tools rejected the refreshed key");let Ie=await n().catch(()=>C),ke=null;Ie.enrolledCert&&await HE(Ie,Q.sig,I,o)&&(ke={...Ie,clientKey:U.key,clientKeyExpiresAt:U.expiresAt??Ie.clientKeyExpiresAt},await r(ke));let Rt=U.expiresAt?Date.parse(U.expiresAt):NaN,D=ws(C)??(Number.isFinite(Rt)&&Rt-t()>0?Rt-t():void 0);return await Wd(({lastError:N,...j})=>({...j,lastAttemptAt:t(),lastSuccessAt:t(),failureCount:0,keyTtlMs:D??j.keyTtlMs}),{now:t,readState:a,writeState:s}),ke&&await BE(ke,e,n),await b(ke?"repaired":"repair_failed"),await k(),"refreshed"}catch(U){let Y=PE(U);return await Wd(re=>({...re,lastAttemptAt:t(),failureCount:(re.failureCount??0)+1,lastError:{name:U instanceof Error?U.name:"Error",...Y!==void 0?{code:Y}:{}}}),{now:t,readState:a,writeState:s}),await b("repair_failed"),U instanceof lt&&U.policyCode==="managed_device_required"&&console.error(U.message),U instanceof lt?"cert-rejected":"failed"}}catch{return"failed"}finally{try{await k()}catch{}}};var MH=`anyray-connect print-key [--json | --passthrough-headers]
|
|
355
355
|
|
|
356
356
|
Print the current short-lived Anyray client key for a consuming app.
|
|
357
357
|
|
|
@@ -363,8 +363,8 @@ Options:
|
|
|
363
363
|
"x-anyray-provider":"anthropic","x-anyray-metadata":"..."}).
|
|
364
364
|
Carries the client key, never the seat OAuth token.
|
|
365
365
|
--help Show this help.
|
|
366
|
-
`,
|
|
367
|
-
`);let s=o.passthroughHeaders?
|
|
366
|
+
`,BH=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}},FH=(e,t)=>{let n=Date.parse(e.clientKeyExpiresAt??"");return Number.isFinite(n)?n-t()<=Vh(e):!0},ZE=e=>{if(!e.gateway)throw new Error("Not enrolled or configured. Run `anyray-connect` before `anyray-connect print-key`.")},YE=(e,t)=>{if(!Ae(e.clientKey))return!1;if(!e.clientKeyExpiresAt)return!0;let n=Date.parse(e.clientKeyExpiresAt);return Number.isFinite(n)&&n>t()},jh=e=>`npx anyray-connect@latest --sso ${e.ssoLink??"<link>"}`,WH=(e,t)=>{switch(e){case"cert-expired":return t.ssoLink?`Your SSO reconnect credential expired. Reconnect with \`${jh(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 \`${jh(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 \`${jh(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""}},Si=async(e={})=>{let t=e.loadProfile??P,n=e.refreshIfDue??Ht,r=e.now??Date.now,o=await t();if(ZE(o),!o.enrolledCert){if(!YE(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||FH(o,r)){let i=WH(await n(),o);if(i){if(!YE(o,r))throw new Error(i);a=`${i} Using the stored key (valid until ${o.clientKeyExpiresAt}).`}}let s=await t();if(ZE(s),!Ae(s.clientKey))throw new Error("No Anyray client key is stored for this enrollment.");return{profile:s,token:s.clientKey,warning:a}},JE=e=>me({user:e.name,team:e.team}),Gd=({profile:e,token:t})=>{let n={},r=JE(e);return r&&(n["x-anyray-metadata"]=r),JSON.stringify({token:t,headers:n})},Zh=({profile:e,token:t})=>{let n={"x-anyray-api-key":t,"x-anyray-auth-mode":"passthrough","x-anyray-provider":"anthropic"},r=JE(e);return r&&(n["x-anyray-metadata"]=r),n},UH=e=>JSON.stringify(Zh(e)),XE=async(e=process.argv.slice(2),t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=BH(e);if(o.help)return n.write(MH),0;let a=await Si(t);a.warning&&r.write(`${a.warning}
|
|
367
|
+
`);let s=o.passthroughHeaders?UH(a):o.json?Gd(a):a.token;return n.write(`${s}
|
|
368
368
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
369
369
|
`),1}};var zE=`anyray-connect models [<model-id>] [--json]
|
|
370
370
|
|
|
@@ -378,8 +378,8 @@ Options:
|
|
|
378
378
|
--json Emit {"origin","current","models":[{"id","wire",...caps}]} instead
|
|
379
379
|
of the table (listing only).
|
|
380
380
|
--help Show this help.
|
|
381
|
-
`,
|
|
382
|
-
`),0;A(K(`Copilot models your seat serves (via ${o.origin})`));for(let p of l){let h=p.id===m?"*":" ",
|
|
381
|
+
`,HH=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},GH=e=>{let t=fe.find(n=>n.id===io);if(!t)throw new Error("copilot-cli adapter missing from REGISTRY");return t.apply(e,{dryRun:!1,explicit:!0})},VH=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${Vs(t)}/${Bn(n)==="responses"?"responses":"chat/completions"}`,qE=async(e=[],t={})=>{let n=HH(e);if(n.help)return process.stdout.write(zE),0;if(n.error)return R(n.error),process.stdout.write(zE),1;let r=await(t.loadTarget??Ue)();if(!r)return R("Not enrolled \u2014 run `anyray-connect` first."),1;let{target:o}=r,a=await(t.discoverSeatToken??vl)({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??aa)(s,{},i,{laneOrigin:o.origin.replace(/\/+$/,""),...o.clientKey?{clientKey:o.clientKey}:{}}),l=Mf(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 m=process.env.COPILOT_MODEL?.trim();if(n.json)return process.stdout.write(`${JSON.stringify({origin:o.origin,current:m??null,models:l.map(p=>({id:p.id,wire:Bn(p.id),...p.maxPromptTokens?{maxPromptTokens:p.maxPromptTokens}:{},...p.maxOutputTokens?{maxOutputTokens:p.maxOutputTokens}:{}}))})}
|
|
382
|
+
`),0;A(K(`Copilot models your seat serves (via ${o.origin})`));for(let p of l){let h=p.id===m?"*":" ",g=VH(p);A(` ${h} ${p.id.padEnd(24)}${g?v(g):""}`)}return L("Switch the startup model: `anyray-connect models <id>` (per launch: `copilot --model <id>`)."),L("The CLI's own /models cannot list models on a custom provider \u2014 this list is the picker."),0}let d=l.find(m=>m.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??kl)(KH(o,i,d.id),{...$f(),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"?O("Could not verify the model over the lane (offline?) \u2014 applying anyway."):M(`'${d.id}' answers on your lane.`);let f=process.env.ANYRAY_COPILOT_MODEL;process.env.ANYRAY_COPILOT_MODEL=d.id;try{let m=await(t.applyCopilotCli??GH)(o);if(m.status!=="configured"){for(let p of m.messages)A(p);return R("Apply did not complete \u2014 see above."),1}}finally{f===void 0?delete process.env.ANYRAY_COPILOT_MODEL:process.env.ANYRAY_COPILOT_MODEL=f}return M(`Copilot CLI startup model \u2192 ${d.id}`),L("Open a fresh terminal (or re-source your profile), then run `copilot`."),0};var jH=`anyray-connect copilot-login
|
|
383
383
|
|
|
384
384
|
Sign Anyray in to GitHub Copilot (device flow) so the Copilot CLI seat lane
|
|
385
385
|
can run your plan's current models. Opens no browser for you: it prints a
|
|
@@ -387,23 +387,23 @@ code to type at github.com/login/device.
|
|
|
387
387
|
|
|
388
388
|
Options:
|
|
389
389
|
--help Show this help.
|
|
390
|
-
`,QE=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(
|
|
391
|
-
`,{mode:384}),await
|
|
390
|
+
`,QE=async(e=[],t={})=>{if(e.includes("--help")||e.includes("-h"))return process.stdout.write(jH),0;A(K("Anyray connect \u2014 Copilot sign-in"));let n=await(t.start??dC)();if(!n)return R("Could not reach GitHub to start the sign-in. Check connectivity and retry."),1;A(` 1. Open ${qe(n.verificationUri)}`),A(` 2. Enter the code: ${K(n.userCode)}`),L(" Waiting for you to finish in the browser\u2026");let r=await(t.poll??uC)(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??pC)(r.token,o);M(`Signed in. Stored owner-only at ${a}`);let s=await(t.probeAccess??Of)(r.token);if(s.verdict==="no-copilot")return R("That GitHub account holds no Copilot seat."),1;let i=await(t.loadTarget??Ue)(),c=i?{laneOrigin:i.target.origin.replace(/\/+$/,""),...i.target.clientKey?{clientKey:i.target.clientKey}:{}}:void 0,l=await(t.fetchCatalog??aa)(r.token,{},s.capiSegment,c);return l.length===0?O("Signed in, but no model list came back \u2014 that is usually this machine or its network, not the sign-in. Continue with `anyray-connect --tools copilot-cli`; it verifies the model with a live check of its own."):M(`${l.length} models available (e.g. ${l[0].id}).`),L("Now run: anyray-connect --tools copilot-cli"),0};import{randomBytes as ZH}from"node:crypto";import{chmod as YH,readFile as JH,rm as tI,writeFile as XH}from"node:fs/promises";import{join as zH}from"node:path";var qH=/^[A-Za-z0-9_-]{43}$/,eI=3900,QH=1e4,Yh=()=>zH(ee(),"device-token.json"),eG=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.v===1&&typeof t.token=="string"&&qH.test(t.token)&&typeof t.expiresAt=="number"&&Number.isFinite(t.expiresAt)},nI=async()=>{try{let e=JSON.parse(await JH(Yh(),"utf-8"));return eG(e)?e:null}catch{return null}},tG=0,nG=async e=>{await et();let t=Yh(),n=`${t}.${process.pid}.${tG++}.tmp`;try{await XH(n,`${JSON.stringify(e)}
|
|
391
|
+
`,{mode:384}),await YH(n,384),await ye(n,t)}catch(r){throw await tI(n,{force:!0}).catch(()=>{}),r}},Vd=async()=>{await tI(Yh(),{force:!0}).catch(()=>{})},rG=()=>ZH(32).toString("base64url"),oG=e=>e instanceof Error?e.name:"UnknownError",rI=async(e={})=>{let t=e.now??Date.now,n=e.fetchFn??fetch;try{let r=await(e.loadProfile??P)(),o=r.gateway?.replace(/\/+$/,""),a=r.clientKey;if(!o||!a)return!1;let s=rG(),i=new AbortController,c=setTimeout(()=>i.abort(),QH),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:eI}),signal:i.signal})}finally{clearTimeout(c)}return l.ok?(await nG({v:1,token:s,expiresAt:t()+eI*1e3}),!0):(l.status!==503&&console.error(`anyray device-token registration: HTTP ${l.status}`),!1)}catch(r){return console.error(`anyray device-token registration: ${oG(r)}`),!1}};var oI=async(e={})=>{let t=e.stdout??process.stdout,n=e.stderr??process.stderr,r=e.now??Date.now,o;try{o=await(e.loadProfile??P)()}catch{o={}}let a=o.gateway?.replace(/\/+$/,"");if(!a||!o.clientKey)return n.write("Not enrolled on this machine \u2014 run `npx anyray-connect` first.\n"),1;let s=e.readState??nI,i=await s();return(!i||i.expiresAt<=r())&&(await(e.rotateToken??rI)(),i=await s()),!i||i.expiresAt<=r()?(n.write(`Could not register a device token \u2014 retry after checking gateway connectivity.
|
|
392
392
|
`),1):(t.write(`${a}/device?dt=${i.token}
|
|
393
|
-
`),0)};import{join as uI,dirname as
|
|
393
|
+
`),0)};import{join as uI,dirname as hG}from"node:path";import{mkdir as yG,readFile as ny,rm as pI,writeFile as fI}from"node:fs/promises";import{fstatSync as cG,openSync as lG,statSync as dG}from"node:fs";import{createInterface as uG}from"node:readline/promises";import{ReadStream as pG}from"node:tty";import{execFileSync as aI}from"node:child_process";import aG from"node:os";var Jh=e=>{try{return aI("git",["config","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},sG=e=>{try{return aI("git",["config","--global","--get",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},iG=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"]),Xh=e=>{let t=e.trim().toLowerCase();return t?t.includes("@")?!1:iG.has(t):!0},Kd=()=>{try{return aG.userInfo().username||void 0}catch{return}},sI=()=>Jh("user.name")??Jh("user.email")??Kd()??"unknown",iI=e=>{let t=e.gitConfig??e.globalGitConfig;return{local:e.gitConfig??(t||Jh),global:e.globalGitConfig??(t||sG)}},Ro=e=>{try{return e()?.trim()||void 0}catch{return}},zh=(e={})=>{let t=iI(e),n=Ro(e.osUsername??Kd),r=Ro(()=>t.global("user.email"))??Ro(()=>t.local("user.email"));return r||(Ro(()=>t.global("user.name"))??Ro(()=>t.local("user.name"))??n??"unknown")},cI=(e={})=>{let t=zh(e);if(Xh(t))return{identity:t,distinct:!1,reason:"machine_default"};let n=iI(e);return!!(Ro(()=>n.global("user.email"))??Ro(()=>n.local("user.email")))?{identity:t,distinct:!0}:{identity:t,distinct:!1,reason:"no_git_email"}};var ht=()=>!!process.stdin.isTTY,fG=()=>{try{let e=cG(0);return e.isCharacterDevice()&&e.rdev===dG("/dev/tty").rdev}catch{return!1}},qh=()=>{if(fG()){for(let[e,t]of[[1,process.stdout],[2,process.stderr]])if(t.isTTY)try{let n=new pG(lG(`/dev/fd/${e}`,"r"));return{stream:n,close:()=>n.destroy()}}catch{}}return{stream:process.stdin,close:()=>{}}},mt=class extends Error{constructor(){super("prompt cancelled"),this.name="PromptCancelledError"}},lI=async(e,t)=>{let n=t.input??qh(),r=t.output??process.stdout,o=uG({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 mt))}),o.question(e).then(d=>l(()=>a(d)),d=>l(()=>s(c?d:new mt)))})}finally{o.close(),n.close()}},Oo=async(e,t={})=>{let n=(await lI(`${e} ${v("[y/N]")} `,t)).trim();return/^y(es)?$/i.test(n)},Wa=async(e,t,n={})=>{let r=t?` ${v(`[${t}]`)}`:"";return(await lI(`${e}${r}: `,n)).trim()||t},Qh=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return L(`Your name: ${t} ${v("(cached \u2014 pass --user to change)")}`),t;let r=sI();return n||!ht()?(L(`Your name: ${r} ${v("(auto-detected \u2014 pass --user to change)")}`),r):Wa("? Your name",r)},ey=async(e,t,n)=>{if(e!==void 0)return e.trim()||void 0;if(t)return L(`Team: ${t} ${v("(cached \u2014 pass --team to change)")}`),t;if(!(n||!ht()))return Wa("? Team (optional)")},Nr=(e,t)=>{let n=!e&&!process.env.ANYRAY_GATEWAY_URL?t.gateway:void 0;return jt(e??n)},dI=(e,t)=>process.env.ANYRAY_CLIENT_KEY?.trim()||e?.trim()||t,Ua="claude-desktop",jd=async(e={})=>{let t=(e.platform??(()=>process.platform))(),n=r=>({authoritative:!1,reason:r});try{if(t==="win32"){try{if(await Or(e.runReg??Zn))return n("managed-policy")}catch{return n("policy-unreadable")}let s=Bt({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=zt(r);return await fo(o,r)?n("managed-policy"):(await Sa({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")}},Zd=e=>e.id!==Ua||!e.installed?null:e.pointedAt===!0?"routed":e.pointedAt!==!1?null:e.introspectable?e.mcpRegistered?"not-routed":null:"unverifiable",mG={"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"},Yd=(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=mG[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 ty=["claude-code","codex"],gG="anyray-connect print-key",ry=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wG=e=>({origin:e,anthropicBaseUrl:e,openaiBaseUrl:`${e}/v1`,placeholderKey:rs,authMode:"placeholder",metadata:{}}),oy=e=>uI(e,".claude","settings.json"),bG=async(e,t,n)=>{let r=oy(e),o=await B(r),{env:a}=sn(t,{includeAuthToken:!1,includeClientKey:!1}),s=ry(o.env)?{...o.env}:{};Object.assign(s,a),o.env=s;let i=[];return typeof o.apiKeyHelper=="string"&&!Kr(o)?i.push(`Kept the existing apiKeyHelper in ${r} \u2014 make sure it prints an Anyray client key, or remove it and re-run.`):o.apiKeyHelper=gG,n||await X(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]}},mI=async(e=process.cwd())=>{let t=[],n=oy(e);try{if(await x(n)){let o=await B(n),a=ry(o.env)?o.env:{};(Vr.some(s=>s in a)||Kr(o))&&t.push(n)}}catch{}let r=ay(e);try{if(await x(r)){let o=await ny(r,"utf-8");Lp(o)&&t.push(r)}}catch{}return t},AG=async(e,t)=>{let n=oy(e);if(!await x(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await B(n),o=!1;if(ry(r.env)){let s={...r.env};for(let i of Vr)i in s&&(delete s[i],o=!0);Object.keys(s).length===0?delete r.env:r.env=s}if(Kr(r)&&(delete r.apiKeyHelper,o=!0),!o)return{messages:[`No Anyray keys in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=Object.keys(r).length===0;return t||(a?await pI(n,{force:!0}):await X(n,r,{backup:!1})),{messages:[`${t?"Would remove":"Removed"} the Anyray routing from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},ay=e=>uI(e,".codex","config.toml"),CG=async(e,t,n)=>{let r=ay(e),o=await ny(r,"utf-8").catch(()=>""),a=Bc(o,Cs(t,{auth:"command",authCommand:"anyray-connect",authArgs:["print-key"],ignoreEnv:!0}),["model_provider"]);return n||(await yG(hG(r),{recursive:!0}),await fI(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]}},kG=async(e,t)=>{let n=ay(e);if(!await x(n))return{messages:[`No ${n} \u2014 nothing to remove.`],changedFiles:[]};let r=await ny(n,"utf-8"),o=Fc(r);if(o===null)return{messages:[`No Anyray block in ${n} \u2014 nothing to remove.`],changedFiles:[]};let a=!o.trim();return t||(a?await pI(n,{force:!0}):await fI(n,o)),{messages:[`${t?"Would remove":"Removed"} the Anyray block from ${n}${a?" (file was only ours \u2014 deleted)":""}.`],changedFiles:t?[]:[n]}},hI=async e=>{let t=process.cwd(),n=e.tools&&e.tools.length>0?e.tools:[...ty],r=n.filter(s=>!ty.includes(s));if(r.length>0)return R(`--project supports ${ty.join(", ")} \u2014 not: ${r.join(", ")}. Other tools keep per-machine state (run anyray-connect without --project there).`),1;let o;if(!e.revert){let s=await P(),i=e.gateway??s.gateway;if(!i)return 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=wG(Kt(i))}if(A(K(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||(O(`
|
|
394
394
|
A committed project config routes these tools through the org API lane on EVERY machine that opens this repo \u2014 subscription seats included.`),L(" 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(!ht())return R(`
|
|
395
395
|
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 Oo(`
|
|
396
396
|
${s} ${n.length} tool(s)?`))return L("Aborted. Nothing changed."),0}e.dryRun&&L(`
|
|
397
|
-
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
|
|
397
|
+
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 bG(t,o,e.dryRun):await CG(t,o,e.dryRun):s==="claude-code"?await AG(t,e.dryRun):await kG(t,e.dryRun);for(let c of i.messages)A(` ${c}`);a.push(...i.changedFiles)}if(a.length>0)if(H("Next"),e.revert)M(" Project config removed. Commit the change to propagate it.");else{M(" Commit these files to route every checkout of this repo:");for(let s of a)A(` ${s}`);A(v(" On each machine: install anyray-connect (PATH) and enroll once \u2014 `anyray-connect --sso <link> --yes`."))}return 0};import{execFile as vG}from"node:child_process";var SG="/usr/bin/security",EG=["find-generic-password","-s","Claude Code-credentials","-w"],IG=1e4,xG=64*1024,RG=/^sk-ant-oat[0-9A-Za-z._-]{16,8192}$/,sy="Anyray: could not resolve the Claude subscription credential. Sign in with Claude Code and try again.",OG=(e,t,n)=>new Promise((r,o)=>{vG(e,t,n,(a,s)=>{if(a){o(new Error("keychain credential unavailable"));return}r({stdout:s})})}),yI=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),TG=e=>{let t=JSON.parse(e);if(!yI(t)||!yI(t.claudeAiOauth))throw new Error("unexpected keychain credential shape");let n=t.claudeAiOauth.accessToken;if(typeof n!="string"||!RG.test(n))throw new Error("unexpected keychain access token");return n},_G=async(e,t)=>{let n=Zh(e),r=await(t.execSecurity??OG)(SG,[...EG],{encoding:"utf8",timeout:IG,maxBuffer:xG,shell:!1});return JSON.stringify({token:TG(r.stdout),headers:n})},gI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${sy}
|
|
398
398
|
`),1;let o;try{o=await Si(t)}catch(i){let c=i instanceof Error&&i.message?i.message:sy;return r.write(`${c}
|
|
399
|
-
`),1}let a=o.profile.authMode??"auto",s;if(a==="placeholder")s=Gd(o);else try{s=await
|
|
399
|
+
`),1}let a=o.profile.authMode??"auto",s;if(a==="placeholder")s=Gd(o);else try{s=await _G(o,t)}catch{if(a==="subscription")return r.write(`${sy}
|
|
400
400
|
`),1;s=Gd(o)}return o.warning&&r.write(`${o.warning}
|
|
401
401
|
`),n.write(`${s}
|
|
402
402
|
`),0};var wI="Anyray: could not resolve the Anyray client key for the Claude Desktop bootstrap fetch. Run `anyray-connect` and try again.",bI=async(e=[],t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;if(e.length>0)return r.write(`${wI}
|
|
403
403
|
`),1;try{let o=await Si(t);return o.warning&&r.write(`${o.warning}
|
|
404
404
|
`),n.write(`${JSON.stringify({Authorization:`Bearer ${o.token}`})}
|
|
405
405
|
`),0}catch{return r.write(`${wI}
|
|
406
|
-
`),1}};import{mkdir as
|
|
406
|
+
`),1}};import{mkdir as n1,writeFile as r1}from"node:fs/promises";import{dirname as o1}from"node:path";import{Buffer as a1}from"node:buffer";import{constants as AI}from"node:fs";import{access as PG,chmod as DG,lstat as LG,mkdir as NG,open as $G,readFile as MG,realpath as BG,rm as FG,stat as kI,writeFile as WG}from"node:fs/promises";import{randomUUID as UG}from"node:crypto";import{platform as cy}from"node:os";import{dirname as HG,join as GG,posix as VG,win32 as vI}from"node:path";var xi="/usr/local/bin/anyray-credential-helper",Ri="C:\\Program Files\\Anyray\\anyray-credential-helper.cmd",Jd="/usr/local/bin/anyray-bootstrap-headers-helper",Xd="C:\\Program Files\\Anyray\\anyray-bootstrap-headers-helper.cmd",Ii="Managed by anyray-connect desktop helper; do not edit.",KG=`anyray-connect desktop helper <--write|--print> --bin <absolute> [options]
|
|
407
407
|
|
|
408
408
|
Create the helpers required by Claude Desktop and Codex fleet artifacts: the
|
|
409
409
|
credential helper (inferenceCredentialHelper, also used by Codex) and the
|
|
@@ -445,15 +445,15 @@ Examples:
|
|
|
445
445
|
anyray-connect desktop helper --print --wrapper bootstrap-headers \\
|
|
446
446
|
--platform posix --bin /usr/local/bin/anyray-connect \\
|
|
447
447
|
> anyray-bootstrap-headers-helper
|
|
448
|
-
`,iy=(e=cy())=>e==="win32"?"windows":"posix",SI=e=>e==="windows"?Ri:xi,EI=e=>e==="windows"?Xd:Jd,CI=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},
|
|
448
|
+
`,iy=(e=cy())=>e==="win32"?"windows":"posix",SI=e=>e==="windows"?Ri:xi,EI=e=>e==="windows"?Xd:Jd,CI=(e,t)=>{if(e.mode)throw new Error("pick exactly one helper mode: --write or --print");e.mode=t},jG=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":CI(t,"write");break;case"--print":CI(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},ZG=e=>/[\0\r\n]/.test(e),YG=e=>/^[A-Za-z]:[\\/]/.test(e)&&vI.isAbsolute(e),Oi=(e,t)=>!ZG(e)&&(t==="windows"?YG(e):VG.isAbsolute(e)),Ei=e=>e.replace(/\\/g,"/").toLowerCase(),zd=(e,t)=>{if(!Oi(e,t))return!1;let n=Ei(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)))},Ti=(e,t)=>t==="windows"?vI.normalize(e):e,ly=e=>`'${e.replace(/'/g,`'"'"'`)}'`,II=(e,t)=>{if(!zd(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Ti(t,e);if(e==="windows")return["@echo off",`REM ${Ii}`,'if "%~1"=="" goto json','if not "%~2"=="" exit /b 64','if "%~1"=="--token" goto token',"exit /b 64",":json",`"${n}" ${xr}`,"exit /b %ERRORLEVEL%",":token",`"${n}" print-key`,"exit /b %ERRORLEVEL%",""].join(`\r
|
|
449
449
|
`);let r=ly(n);return["#!/bin/sh",`# ${Ii}`,'if [ "$#" -eq 0 ]; then',` exec ${r} ${xr}`,"fi",'if [ "$#" -eq 1 ] && [ "$1" = "--token" ]; then',` exec ${r} print-key`,"fi","exit 64",""].join(`
|
|
450
450
|
`)},xI=(e,t)=>{if(!zd(t,e))throw new Error("--bin must be an absolute, fleet-stable anyray-connect executable outside npm/npx and temporary paths");let n=Ti(t,e);return e==="windows"?["@echo off",`REM ${Ii}`,'if not "%~1"=="" exit /b 64',`"${n}" ${Qs}`,"exit /b %ERRORLEVEL%",""].join(`\r
|
|
451
451
|
`):["#!/bin/sh",`# ${Ii}`,'if [ "$#" -eq 0 ]; then',` exec ${ly(n)} ${Qs}`,"fi","exit 64",""].join(`
|
|
452
|
-
`)},qd=(e,t)=>{if(!Oi(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=Ti(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"]}},RI=async e=>{try{return await
|
|
453
|
-
`),0}if(s!==iy(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await
|
|
452
|
+
`)},qd=(e,t)=>{if(!Oi(t,e))throw new Error(`--helper-path must be an absolute ${e} path`);let n=Ti(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"]}},RI=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}`)}},JG=async(e,t)=>{try{let n=await BG(e),r=t==="windows"?n.replace(/^\\\\\?\\/,""):n;if(!zd(r,t))throw new Error;if(!(await kI(n)).isFile())throw new Error;await PG(n,t==="posix"?AI.X_OK:AI.F_OK)}catch{throw new Error("--bin must resolve to an accessible, regular"+(t==="posix"?", executable":"")+" fleet-stable file")}},OI=e=>e.slice(0,300).includes(Ii),TI=async(e,t,n)=>{let r=await RI(e);if(r!==void 0&&r!==t&&!OI(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 kI(e)).mode&511)===493)return"unchanged"}catch{}}let o=HG(e);try{await NG(o,{recursive:!0,mode:493})}catch{throw new Error(`could not create helper directory ${o}`)}let a=GG(o,`.anyray-helper.${process.pid}.${UG()}.tmp`),s=!1;try{await WG(a,t,{encoding:"utf8",mode:n==="posix"?493:420,flag:"wx"}),n==="posix"&&await DG(a,493);let i=await $G(a,"r");try{await Qn(i)}finally{await i.close()}await ye(a,e),s=!0}catch{throw new Error(`could not install helper at ${e}`)}finally{s||await FG(a,{force:!0}).catch(()=>{})}return r===void 0?"installed":"updated"},XG=(e,t,n)=>{let r=n==="windows"?`"${Ti(t,n)}" `:` exec ${ly(t)} `;return e.split(/\r?\n/).some(o=>o.startsWith(r)&&o.length>r.length)},Qd=async(e,t={})=>{let n=iy((t.platform??cy)());if(!zd(e,n))return;let r=[{path:t.helperPath??SI(n),content:II(n,e)},{path:t.bootstrapHeadersHelperPath??EI(n),content:xI(n,e)}];for(let o of r)try{if((await LG(o.path).catch(()=>{}))?.isSymbolicLink())continue;let a=await RI(o.path);if(a===void 0||a===o.content||!OI(a)||!XG(a,e,n))continue;await TI(o.path,o.content,n)}catch{}},_I=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=jG(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??cy)(),s=o.targetPlatform??iy(a),i=o.binaryPath,c=(d,u,f)=>{let m=Ti(u??f,s);if(!Oi(m,s))throw new Error(`${d} must be an absolute ${s} path`);if(s==="windows"&&qd("windows",m),Ei(m)===Ei(i))throw new Error(`${d} must differ from --bin (the helper cannot invoke itself)`);return m},l=[{kind:"credential",label:"credential helper",path:c("--path",o.helperPath,SI(s)),content:II(s,i)},{kind:"bootstrap-headers",label:"bootstrap-headers helper",path:c("--bootstrap-headers-path",o.bootstrapHeadersHelperPath,EI(s)),content:xI(s,i)}];if(Ei(l[0].path)===Ei(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(f=>f.kind===d);return n.write(u.content),r.write(`Deploy this wrapper at ${u.path} after deploying the binary at ${i}.
|
|
453
|
+
`),0}if(s!==iy(a))throw new Error(`--write cannot install a ${s} helper on this ${a} host; use --print for cross-platform packaging`);await JG(i,s);for(let d of l){let u=await TI(d.path,d.content,s),f=d.label[0].toUpperCase()+d.label.slice(1);r.write(u==="unchanged"?`${f} already current at ${d.path}.
|
|
454
454
|
`:`${u==="installed"?"Installed":"Updated"} ${d.label} at ${d.path}.
|
|
455
455
|
`)}return 0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
456
|
-
`),1}};var
|
|
456
|
+
`),1}};var zG=new Set(["clientId","issuer","authorizationUrl","tokenUrl","scopes","redirectPort","additionalRedirectReferrerHosts"]),qG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,QG=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.")},e1=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),eu=(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!==""||QG(n.hostname))throw new Error(`${t} must be a non-loopback HTTPS URL without credentials or a fragment.`);return n.toString()},Ha=(e,t,n)=>{if(!(e===void 0&&!n)){if(typeof e!="string"||e.trim()==="")throw new Error(`--bootstrap-oidc ${t} must be a non-empty string.`);return e.trim()}},PI=e=>{if(!e1(e))throw new Error("--bootstrap-oidc must be a JSON object.");let t=Object.keys(e).filter(l=>!zG.has(l));if(t.length>0)throw new Error(`--bootstrap-oidc contains unsupported fields: ${t.join(", ")}.`);let n=Ha(e.clientId,"clientId",!0),r=Ha(e.scopes,"scopes",!0),o=Ha(e.issuer,"issuer",!1),a=Ha(e.authorizationUrl,"authorizationUrl",!1),s=Ha(e.tokenUrl,"tokenUrl",!1),i=Ha(e.additionalRedirectReferrerHosts,"additionalRedirectReferrerHosts",!1);if(!o&&!(a&&s))throw new Error("--bootstrap-oidc requires issuer, or both authorizationUrl and tokenUrl.");let c=e.redirectPort;if(c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<1||c>65535))throw new Error("--bootstrap-oidc redirectPort must be an integer from 1 to 65535.");return{clientId:n,scopes:r,...o?{issuer:eu(o,"bootstrap OIDC issuer")}:{},...a?{authorizationUrl:eu(a,"bootstrap OIDC authorizationUrl")}:{},...s?{tokenUrl:eu(s,"bootstrap OIDC tokenUrl")}:{},...c===void 0?{}:{redirectPort:c},...i?{additionalRedirectReferrerHosts:i}:{}}},DI=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error("--bootstrap-oidc must be valid JSON.")}return PI(t)},dy=e=>e==="windows"?Xd:Jd,t1=(e,t)=>{let n=new URL(e);return n.searchParams.set("os",t),n.toString()},tu=(e,t)=>{let n=t1(eu(e.url,"--bootstrap-url"),t),r=e.oidc?PI(e.oidc):void 0,o;if(e.deploymentOrganizationUuid!==void 0&&(o=e.deploymentOrganizationUuid.trim(),!qG.test(o)))throw new Error("--deployment-organization-uuid must be a UUID without braces.");return{bootstrapEnabled:!0,bootstrapUrl:n,bootstrapHeadersHelper:dy(t),...r?{bootstrapOidc:r}:{},...o?{deploymentOrganizationUuid:o}:{}}},LI=(e,t)=>Rr(tu(e,t));var s1=`anyray-connect desktop [disconnect] [options]
|
|
457
457
|
|
|
458
458
|
The minimum Claude Desktop workflow:
|
|
459
459
|
anyray-connect desktop Connect this machine
|
|
@@ -498,8 +498,8 @@ Options:
|
|
|
498
498
|
|
|
499
499
|
Older flag-based Claude artifacts and Codex fleet output remain accepted for
|
|
500
500
|
compatibility, but are not part of the recommended Claude Desktop workflow.
|
|
501
|
-
`,
|
|
502
|
-
<string>${qn(t)}</string>`,py=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>
|
|
501
|
+
`,i1=e=>e==="macos"?"--mobileconfig":e==="windows"?"--reg":"--json",c1=e=>e.map(t=>t==="--oidc"?"--bootstrap-oidc":t==="--organization"?"--deployment-organization-uuid":t),l1=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[i1(n),...a?[a]:[],t==="bootstrap"?"--bootstrap-url":"--helper-path",r,...c1(o)]},d1=new Set(["--help","-h","--migrate","--account","--all-accounts","--mobileconfig","--reg","--json","--helper-path","--bootstrap-url","--bootstrap-oidc","--deployment-organization-uuid","--tools"]),uy=e=>{let t=e[0]==="claude"?e.slice(1):[...e],n=t[0];if(!(n!==void 0&&!n.startsWith("-")&&n!=="disconnect"||t.some(r=>d1.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"]},qn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),NI=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),u1=(e,t)=>` <key>${qn(e)}</key>
|
|
502
|
+
<string>${qn(t)}</string>`,py=(e,t,n,r,o,a)=>{let s=Object.entries(a).map(([i,c])=>u1(i,c)).join(`
|
|
503
503
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
504
504
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
505
505
|
<plist version="1.0">
|
|
@@ -532,21 +532,21 @@ ${s}
|
|
|
532
532
|
<string>${qn(n)}</string>
|
|
533
533
|
</dict>
|
|
534
534
|
</plist>
|
|
535
|
-
`},_i={disableDeploymentModeChooser:!0},MI=(e,t)=>py("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",Rr({...po(e,t),..._i})),
|
|
536
|
-
`,
|
|
535
|
+
`},_i={disableDeploymentModeChooser:!0},MI=(e,t)=>py("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.gateway","Anyray Claude Desktop Gateway","5C26E2C1-B0D9-4C0E-9E26-7A7C9408B410","1E7C6758-6415-49E7-A368-D5FD4E7AE389",Rr({...po(e,t),..._i})),p1=(e,t)=>`${JSON.stringify({...po(e,t),..._i},null,2)}
|
|
536
|
+
`,f1=e=>py("com.anthropic.claudefordesktop","ai.anyray.claude-desktop.bootstrap","Anyray Claude Desktop Bootstrap","47D58D65-92C5-4E5C-B5F8-B6D25CC64383","890F9670-57D5-487D-88E8-D3321E73F564",Rr({...tu(e,"macos"),..._i})),m1=e=>`${JSON.stringify({...tu(e,"linux"),..._i},null,2)}
|
|
537
537
|
`,BI=e=>["Windows Registry Editor Version 5.00","","[HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Claude]",...Object.entries({...e,...Rr(_i)}).map(([n,r])=>`"${NI(n)}"="${NI(r)}"`),""].join(`
|
|
538
|
-
`),FI=(e,t)=>{let n=ql(e,t);return BI(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},
|
|
538
|
+
`),FI=(e,t)=>{let n=ql(e,t);return BI(Object.fromEntries(Object.entries(n).filter(r=>r[1]!==void 0)))},h1=e=>BI(LI(e,"windows")),WI=(e,t,n)=>{if(t==="darwin"){let r=xi;return{path:`${n}/claude-desktop-anyray.mobileconfig`,content:MI(e,r),helperPath:r}}if(t==="win32"){let r=Ri;return{path:`${n}\\claude-desktop-anyray.reg`,content:FI(e,r),helperPath:r}}},UI=(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."],y1=(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=qd(n,t),o={auth:"command",authCommand:r.command,authArgs:r.args,ignoreEnv:!0};return`${Cs(e,o).join(`
|
|
539
539
|
`)}
|
|
540
|
-
`},
|
|
540
|
+
`},g1=e=>py("com.openai.codex","ai.anyray.codex.gateway","Anyray Codex Gateway","F99FB627-DF28-4C90-A253-00B0B62F6B1A","817E3D74-0362-4A27-A7D6-4A74EB316527",{config_toml_base64:a1.from(e,"utf-8").toString("base64")}),w1=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},b1=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=jt(e.gateway);return{origin:t,anthropicBaseUrl:t,openaiBaseUrl:`${t}/v1`,placeholderKey:rs,authMode:"placeholder",metadata:{team:e.team?.trim()||void 0,intent:e.intent?.trim()||void 0,intentLabel:e.intentLabel?.trim()||void 0}}},$I=async(e,t,n)=>{if(!t){(n.stdout??process.stdout).write(e);return}let r=n.mkdir??n1,o=n.writeFile??r1;await r(o1(t),{recursive:!0}),await o(t,e)},A1=(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:
|
|
541
541
|
`),o.write(r==="windows"?` anyray-connect desktop helper --write --platform windows --bin "C:\\Program Files\\Anyray\\anyray-connect.exe" --path "${n}"
|
|
542
542
|
`:` sudo anyray-connect desktop helper --write --platform posix --bin /usr/local/bin/anyray-connect --path '${n.replace(/'/g,`'"'"'`)}'
|
|
543
543
|
`),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.
|
|
544
544
|
`):t==="json"&&o.write(`Deploy this file to /etc/claude-desktop/managed-settings.json.
|
|
545
|
-
`)},
|
|
545
|
+
`)},C1=(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.
|
|
546
546
|
`),t.write(`The bootstrap fetch is authenticated by the bootstrap-headers helper at ${dy(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).
|
|
547
547
|
`),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.
|
|
548
548
|
`),t.write(`Each bootstrap response replaces the allowed managed configuration; omitted keys are unset.
|
|
549
|
-
`)},
|
|
549
|
+
`)},k1=async(e,t)=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr,o=await(t.migrateProfile??yo)({account:e.account,allAccounts:e.allAccounts});if(!o.ok)return r.write(`Cannot migrate: ${o.reason}.
|
|
550
550
|
${o.remedy}
|
|
551
551
|
`),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("; ")})`:"")+`
|
|
552
552
|
`)}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)`:"")+`
|
|
@@ -557,10 +557,10 @@ Reopen Claude Desktop \u2014 migrated ${c} available in the Anyray profile.
|
|
|
557
557
|
Your previous profile is untouched, so \`desktop disconnect\` still works.
|
|
558
558
|
`)}else n.write(`
|
|
559
559
|
Nothing new to migrate \u2014 no local sessions or portable local data needed copying.
|
|
560
|
-
`);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},HI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=
|
|
561
|
-
`),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 ${xi} on macOS/Linux or ${Ri} 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(!Oi(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"&&qd("windows",i);let l=
|
|
560
|
+
`);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},HI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=l1(e);if(o[0]==="helper")return _I(o.slice(1),t);let a=w1(o);if(a.help)return n.write(s1),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 k1(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:DI(a.bootstrapOidc)},...a.deploymentOrganizationUuid===void 0?{}:{deploymentOrganizationUuid:a.deploymentOrganizationUuid}},f=a.artifact==="reg"?h1(u):a.artifact==="json"?m1(u):f1(u);return await $I(f,a.path,t),C1(a.artifact==="reg"?"windows":a.artifact==="json"?"linux":"macos",r),a.path&&n.write(`Wrote ${a.path}
|
|
561
|
+
`),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 ${xi} on macOS/Linux or ${Ri} 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(!Oi(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"&&qd("windows",i);let l=b1(a),d;if(a.target==="claude")d=a.artifact==="reg"?FI(l,i):a.artifact==="json"?p1(l,i):MI(l,i);else{let u=y1(l,i);d=a.artifact==="mobileconfig"?g1(u):u}return await $I(d,a.path,t),A1(a.target,a.artifact,i,c,r),a.path&&n.write(`Wrote ${a.path}
|
|
562
562
|
`),0}catch(o){let a=o instanceof Error?o.message:String(o);return r.write(`${a}
|
|
563
|
-
`),1}};var
|
|
563
|
+
`),1}};var v1=`anyray-connect retrieve <handle> [--source auto|claude|profile]
|
|
564
564
|
|
|
565
565
|
Print the original content Anyray externalized behind a "\xB7 retrieve ctx_\u2026"
|
|
566
566
|
marker. The content is written to stdout byte-for-byte (no trailing newline
|
|
@@ -570,7 +570,7 @@ Options:
|
|
|
570
570
|
--source <s> Which client config resolves the gateway: auto (default),
|
|
571
571
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
572
572
|
--help Show this help.
|
|
573
|
-
`,
|
|
573
|
+
`,S1=`anyray-connect recall <query> [--k N] [--source auto|claude|profile]
|
|
574
574
|
|
|
575
575
|
Semantic search over your externalized tool outputs. Prints one match per line
|
|
576
576
|
to stdout as: handle<TAB>score<TAB>preview. Fetch a full original with
|
|
@@ -581,36 +581,36 @@ Options:
|
|
|
581
581
|
--source <s> Which client config resolves the gateway: auto (default),
|
|
582
582
|
claude (~/.claude/settings.json), or profile (~/.anyray).
|
|
583
583
|
--help Show this help.
|
|
584
|
-
`,GI=(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},
|
|
584
|
+
`,GI=(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},E1=e=>e.replace(/[\t\r\n]+/g," ").trim(),VI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=GI(e,!1);if(o.help)return n.write(v1),0;let a=o.positional?.trim();if(!a)return r.write(`A handle is required: anyray-connect retrieve ctx_\u2026 (see --help)
|
|
585
585
|
`),1;let s=await(t.readTarget??nt)(o.source),i=await(t.retrieve??Ma)(s,a,{probe:!0});return i.ok?(n.write(i.content),0):(r.write(`${i.message}
|
|
586
586
|
`),1)}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
587
|
-
`),1}},KI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=GI(e,!0);if(o.help)return n.write(
|
|
587
|
+
`),1}},KI=async(e,t={})=>{let n=t.stdout??process.stdout,r=t.stderr??process.stderr;try{let o=GI(e,!0);if(o.help)return n.write(S1),0;let a=o.positional?.trim();if(!a)return r.write(`A query is required: anyray-connect recall "what to find" (see --help)
|
|
588
588
|
`),1;let s=await(t.readTarget??nt)(o.source),i=await(t.recall??$d)(s,a,o.k,{probe:!0});if(!i.ok)return r.write(`${i.message}
|
|
589
589
|
`),1;if(i.matches.length===0)return r.write(`No matching externalized outputs found.
|
|
590
|
-
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${
|
|
590
|
+
`),1;for(let c of i.matches){let l=Number.isFinite(c.score)?c.score.toFixed(3):"?";n.write(`${c.handle} ${l} ${E1(c.preview)}
|
|
591
591
|
`)}return r.write(`Fetch a full original: anyray-connect retrieve <handle>
|
|
592
592
|
`),0}catch(o){return r.write(`${o instanceof Error?o.message:String(o)}
|
|
593
|
-
`),1}};import{promises as
|
|
593
|
+
`),1}};import{promises as z1}from"node:fs";var In=e=>typeof e=="string"?e:"",I1=e=>{let t=In(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=In(o.text).trim();a&&r.push(a)}return r.join(`
|
|
594
594
|
|
|
595
|
-
`).trim()},
|
|
595
|
+
`).trim()},x1=e=>{let t=In(e.sender).trim().toLowerCase();return t==="human"||t==="user"?"user":"assistant"},R1=e=>{if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,o=I1(r);if(!o)continue;let a=In(r.created_at).trim();t.push({role:x1(r),text:o,...a?{createdAt:a}:{}})}return t},nu=e=>{let t;try{t=JSON.parse(e)}catch{return{ok:!1,conversations:[],skipped:0,message:"the file is not valid JSON"}}let n=Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.conversations)?t.conversations:null;if(!n)return{ok:!1,conversations:[],skipped:0,message:"expected a list of conversations \u2014 is this the conversations.json from a Claude data export?"};let r=[],o=0;for(let a of n){if(!a||typeof a!="object"){o+=1;continue}let s=a,i=R1(s.chat_messages??s.messages);if(i.length===0){o+=1;continue}let c=(In(s.uuid)||In(s.id)).trim(),l=(In(s.name)||In(s.title)).trim()||"Untitled conversation",d=In(s.created_at).trim(),u=In(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 Li}from"node:fs";import{homedir as qI}from"node:os";import{join as ou}from"node:path";import{promises as jI}from"node:fs";import fy from"node:path";var O1=4e4,T1=16*1024*1024,Pi=(e,t)=>({ok:!1,content:"",path:e,lines:0,truncated:!1,message:t}),Di=async(e,t={})=>{let n=(e??"").trim();if(!n)return Pi("","path is required");let r=t.cwd??process.cwd(),o=fy.resolve(r,n),a=fy.relative(r,o);if(a.startsWith("..")||fy.isAbsolute(a))return Pi(n,"path is outside the workspace");let s=t.maxBytes??O1,i;try{let g=await jI.stat(o);if(!g.isFile())return Pi(n,"not a regular file");let y=t.maxFileBytes??T1;if(g.size>y)return Pi(n,`file too large to read (${g.size} bytes; limit ${y})`);i=await jI.readFile(o,"utf8")}catch(g){return Pi(n,g instanceof Error?g.message:"read failed")}let c=i.split(`
|
|
596
596
|
`),l=Math.max(1,t.startLine??1),d=Math.min(c.length,t.endLine??c.length),u=l<=d?c.slice(l-1,d):[],f=u.join(`
|
|
597
|
-
`),m=l<=d?d:l,p=!1,h=!1;if(Buffer.byteLength(f,"utf8")>s){let
|
|
597
|
+
`),m=l<=d?d:l,p=!1,h=!1;if(Buffer.byteLength(f,"utf8")>s){let g=0,y=0;for(let w of u){let b=Buffer.byteLength(w,"utf8")+(y===0?0:1);if(g+b>s)break;g+=b,y+=1}y===0?(f=Buffer.from(u[0]??"","utf8").subarray(0,s).toString("utf8").replace(/\uFFFD$/,""),m=l,p=!0):(f=u.slice(0,y).join(`
|
|
598
598
|
`),m=l+y-1),h=!0}return{ok:!0,content:f,path:n,lines:c.length,truncated:h,span:{startLine:l,endLine:m,...p?{partialLine:!0}:{}}}},my=e=>{if(!e.ok)return`Read failed: ${e.message??"unknown error"}`;if(!e.truncated)return`${e.path}:
|
|
599
599
|
${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}
|
|
600
|
-
${e.content}`};import{spawn as
|
|
601
|
-
`)){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:YI(l,t)})}return r},
|
|
602
|
-
`);for(let C=0;C<k.length;C+=1){let S=c(k[C]);if(l.some(E=>S.includes(E))&&(u.push({file:yy.relative(t,
|
|
600
|
+
${e.content}`};import{spawn as _1}from"node:child_process";import{promises as hy}from"node:fs";import yy from"node:path";var gy=400,P1=240,D1=4e3,L1=4e3,N1=512*1024,$1=new Set([".git","node_modules","dist","build","out",".next","coverage",".turbo","vendor","__pycache__",".venv",".cache",".idea",".gradle",".pytest_cache",".mypy_cache"]),YI=(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"]),B1=8,F1=2e3,W1=["!.env*","!*.pem","!*.key","!*.p12","!*.pfx","!id_rsa*","!id_ed25519*","!*secret*","!*credential*","!**/.ssh/**","!**/.aws/**","!**/.gnupg/**"],U1=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")},JI=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>=B1))break}return n},XI=e=>{let t=Array.isArray(e)?e.join(" "):e;return new RegExp("\\p{Lu}","u").test(t)},H1=(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)},ZI=(e,t,n)=>{let r=[];for(let o of e.split(`
|
|
601
|
+
`)){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:YI(l,t)})}return r},G1=(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 p of n)c.push("-g",p);for(let p of W1)c.push("-g",p);if(s?.length){for(let p of s)c.push("-e",p);c.push("--",".")}else c.push("--",e,".");let l;try{l=_1("rg",c,{cwd:t})}catch{i({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let d="",u=!1,f=p=>{u||(u=!0,clearTimeout(m),i(p))},m=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}let p=ZI(d,o,r);f({ok:!0,matches:p,truncated:!0,engine:"ripgrep"})},a);l.stdout?.setEncoding("utf8"),l.stdout?.on("data",p=>{if(d+=p,d.length>r*(o+64))try{l.kill("SIGKILL")}catch{}}),l.on("error",()=>{f({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"})}),l.on("close",p=>{if(typeof p=="number"&&p>=2){f({ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:"ripgrep unavailable"});return}let h=ZI(d,o,r+1),g=h.length>r;f({ok:!0,matches:g?h.slice(0,r):h,truncated:g,engine:"ripgrep"})})}),V1=async(e,t,n,r,o,a,s)=>{let i=XI(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=[],f=0,m=!1,p=async h=>{if(u.length>=r||Date.now()>a){m=!0;return}let g;try{g=await hy.readdir(h,{withFileTypes:!0})}catch{return}for(let y of g){if(u.length>=r||Date.now()>a){m=!0;return}let w=yy.join(h,y.name);if(y.isDirectory()){if($1.has(y.name))continue;await p(w)}else if(y.isFile()){if(f>=L1){m=!0;return}if(d.length&&!d.some(C=>y.name.endsWith(C))||U1(yy.relative(t,w)))continue;f+=1;let b;try{if((await hy.stat(w)).size>N1)continue;b=await hy.readFile(w,"utf8")}catch{continue}if(b.indexOf("\0")>=0)continue;let k=b.split(`
|
|
602
|
+
`);for(let C=0;C<k.length;C+=1){let S=c(k[C]);if(l.some(E=>S.includes(E))&&(u.push({file:yy.relative(t,w),line:C+1,text:YI(k[C],o)}),u.length>=r)){m=!0;return}}}}};return await p(t),{ok:!0,matches:u,truncated:m,engine:"walk"}},ru=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??gy,s=t.maxColumns??P1,i=t.timeoutMs??D1,c=Date.now()+i,l=JI(n),d=l.length>1,u=Math.min(a*4,F1),f=(y,w)=>V1(n,r,o,y,s,c,w),m=async y=>{let w=await y(u,l);if(!w.ok)return w;let b=H1(w.matches,l,XI(l)),k=b.length>a;return{...w,matches:k?b.slice(0,a):b,truncated:w.truncated||k,matched:"tokens",tokens:l}};if(t.engine==="walk"){let y=await f(a);return y.matches.length>0||!d?y:m((w,b)=>f(w,b))}let p=(y,w)=>G1(n,r,o,y,s,Math.max(0,c-Date.now()),w),h=await p(a);if(h.ok){if(h.matches.length>0||!d)return h;let y=await m((w,b)=>p(w,b));return y.ok?y:m((w,b)=>f(w,b))}let g=await f(a);return g.matches.length>0||!d?g:m((y,w)=>f(y,w))},zI=(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=JI(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.
|
|
603
603
|
`:"";if(n==="paths"){let d=new Map;for(let f of t.matches)d.set(f.file,(d.get(f.file)??0)+1);let u=[...d].map(([f,m])=>`${f} (${m} match${m===1?"":"es"})`);return[`${r}${d.size}${t.truncated?"+":""} file${d.size===1?"":"s"} match "${e}":`,...u].join(`
|
|
604
604
|
`)}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(`
|
|
605
605
|
`):[o,...a.slice(0,Math.max(1,l)),s(a.length-Math.max(1,l))].join(`
|
|
606
|
-
`)};var QI=448,
|
|
606
|
+
`)};var QI=448,j1=384,Z1=4e4,Mr=async()=>{let e=process.env.ANYRAY_HISTORY_DIR;if(e)return e;let t=ou(qI(),".anyray");try{if((await Li.stat(t)).isDirectory())return ou(t,"history")}catch{}return ou(qI(),".anyray-history")},Y1=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:J1(e);return`${[n,t||"untitled",o].filter(Boolean).join("_")}.md`},J1=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}
|
|
607
607
|
|
|
608
608
|
${r.text}
|
|
609
609
|
`});return[...t,...n].join(`
|
|
610
610
|
`).replace(/\n{3,}/g,`
|
|
611
611
|
|
|
612
612
|
`)+`
|
|
613
|
-
`},au=async e=>{let t=await Mr();await Li.mkdir(t,{recursive:!0,mode:QI});try{await Li.chmod(t,QI)}catch{}let n=0,r=0;for(let o of e)try{await Li.writeFile(ou(t,
|
|
613
|
+
`},au=async e=>{let t=await Mr();await Li.mkdir(t,{recursive:!0,mode:QI});try{await Li.chmod(t,QI)}catch{}let n=0,r=0;for(let o of e)try{await Li.writeFile(ou(t,Y1(o)),X1(o),{mode:j1}),n+=1}catch{r+=1}return{dir:t,written:n,failed:r}},Ga=async()=>{try{let e=await Mr();return(await Li.readdir(e)).filter(n=>n.endsWith(".md")).length}catch{return 0}},ex=async e=>{let t=await Mr();return ru(e,{cwd:t,globs:["*.md"]})},tx=async e=>{let t=await Mr();return Di(e,{cwd:t,maxBytes:Z1})};var nx=`anyray-connect history <command>
|
|
614
614
|
|
|
615
615
|
Make past Claude conversations searchable from any Anyray-connected client.
|
|
616
616
|
|
|
@@ -631,7 +631,7 @@ Which one you want:
|
|
|
631
631
|
conversation into the chat when you ask for it. Recall, not a list.
|
|
632
632
|
|
|
633
633
|
Running both is fine, and gets you both.
|
|
634
|
-
`,
|
|
634
|
+
`,q1=async e=>{try{return{raw:await z1.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"})`}}},Q1=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 q1(t);if("error"in n)return R(n.error),1;let r=nu(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 au(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 M(`Imported ${o.written} conversation${o.written===1?"":"s"} into ${o.dir}`),r.skipped>0&&A(v(` ${r.skipped} entr${r.skipped===1?"y":"ies"} skipped (no readable messages).`)),o.failed>0&&O(`${o.failed} conversation${o.failed===1?"":"s"} could not be written.`),A(""),A(K("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},eV=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 ed(t);return n.ok?(M(`Restored ${n.registered} conversation${n.registered===1?"":"s"} into Claude Desktop`),n.skipped>0&&A(v(` ${n.skipped} already present, left untouched.`)),n.failed>0&&O(`${n.failed} conversation${n.failed===1?"":"s"} could not be written.`),A(""),A(K("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)},tV=async()=>{let e=await Mr(),t=await Ga();return t===0?(A(`No conversations imported yet. Archive would live at ${e}`),A(v(" Import one with: anyray-connect history import <conversations.json>")),0):(M(`${t} conversation${t===1?"":"s"} in ${e}`),0)},rx=async e=>{let t=e[0];return!t||t==="--help"||t==="-h"||t==="help"?(console.log(nx),0):t==="import"?Q1(e.slice(1)):t==="restore"?eV(e.slice(1)):t==="status"?tV():(R(`Unknown history command: ${t}`),console.log(nx),1)};import{promises as nV}from"node:fs";var rV=`anyray-connect migrate [options]
|
|
635
635
|
|
|
636
636
|
Bring what Claude Desktop was showing you onto Anyray. Quit Claude Desktop first.
|
|
637
637
|
|
|
@@ -660,57 +660,57 @@ Getting the export (you do this, not Anyray \u2014 it needs your Claude login):
|
|
|
660
660
|
Open claude.ai -> Settings -> Privacy -> Export data. Anthropic emails a link.
|
|
661
661
|
Pass the .zip to --export, and the conversations.json inside it to
|
|
662
662
|
--conversations. Both are safe to re-run; they skip what is already there.
|
|
663
|
-
`,
|
|
664
|
-
`).filter(Boolean))A(` ${s}`);return!1}for(let s of n.lanes)A(` ${
|
|
663
|
+
`,oV=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},ox={code:"Claude Code sessions",cowork:"Cowork tasks"},aV=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`${ox[e.lane]}: ${e.migrated} migrated`+(t.length>0?` (${t.join("; ")})`:"")},sV=async(e,t)=>{A(K("1. Local Claude Desktop data on this machine"));let n=await(t.migrateProfile??yo)({account:e.account,allAccounts:e.allAccounts,command:gt("migrate")});if(!n.ok){R(` ${n.reason}`);for(let s of n.remedy.split(`
|
|
664
|
+
`).filter(Boolean))A(` ${s}`);return!1}for(let s of n.lanes)A(` ${aV(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&&O(` ${c} preserved or skipped because the target wins or no single target store could be selected.`)}let r=n.ambiguousAssets??[];r.length>0&&O(` Claude Desktop has more than one target ${r.join(" and ")} store. No store was chosen and every target was preserved. Leave only the intended third-party account/workspace active, then run this again.`);let o=n.retryableAssets??[];o.length>0&&O(` ${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??[])O(` ${ox[s.lane]}: ${s.waiting} still waiting \u2014 no ${s.lane} store in the new profile yet.`),A(` ${Zm(s.reason,s.lane,gt("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},iV=async(e,t)=>{if(A(""),A(K("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(` ${gt("migrate --export ~/Downloads/claude-export.zip")}`));return}let n=await ed(e.exportZip);if(!n.ok){R(` ${n.reason}`),A(` ${n.remedy}`);return}M(` Restored ${n.registered} conversation${n.registered===1?"":"s"}`+(n.skipped>0?` (${n.skipped} already there)`:"")+(n.failed>0?`, ${n.failed} failed`:"")),A(v(" They are listed under Cowork \u2014 the Chat tab has no local store."));let r=n.projects;if(r.imported+r.alreadyPresent+r.skippedCollision+r.failed>0){let a=[r.alreadyPresent>0?`${r.alreadyPresent} already there`:"",r.skippedCollision>0?`${r.skippedCollision} skipped, a folder of that name already exists`:"",r.failed>0?`${r.failed} failed`:""].filter(Boolean);M(` Restored ${r.imported} project${r.imported===1?"":"s"}`+(a.length>0?` (${a.join("; ")})`:"")),r.imported>0&&A(v(` Instructions and docs are in ${r.root}, listed under Projects.`))}},cV=async e=>{if(A(""),A(K("3. Searchable from every Anyray client")),!e.conversations){let o=await Ga();o>0?A(` Archive already holds ${o} conversation${o===1?"":"s"}.`):(A(v(" Optional. Pass the conversations.json inside the export:")),A(v(` ${gt("migrate --conversations <path>/conversations.json")}`)));return}let t;try{t=await nV.readFile(e.conversations,"utf8")}catch{R(` could not read ${e.conversations}`);return}let n=nu(t);if(!n.ok){R(` ${n.message??"that file is not a Claude conversations export"}`);return}let r=await au(n.conversations);M(` Archived ${r.written} conversation${r.written===1?"":"s"}`+(n.skipped>0?` (${n.skipped} unreadable, skipped)`:"")+(r.failed>0?`, ${r.failed} failed to write`:"")),A(v(` Ask any Anyray-connected client about a past chat. ${await Mr()}`))},lV=e=>{A(""),A(K("Next")),A(" Reopen Claude Desktop. Chat, Cowork and Code should all be there."),e.exportZip||O(" 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 \`${gt("desktop")}\`.`))},ax=async(e,t={})=>{let n;try{n=oV(e)}catch(o){return R(o instanceof Error?o.message:"could not read the arguments"),1}if(n.help)return process.stdout.write(rV),0;A(K("Migrating Claude Desktop onto Anyray")),A(v("Claude Desktop must be fully quit.")),A("");let r=await sV(n,t);return await iV(n,!r),await cV(n),r?(lV(n),0):(A(""),O("Fix the item above and re-run to finish the migration."),1)};var dV=3e3,su=async(e,t={})=>{let n=t.timeoutMs??dV,r=`${e}/`,o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await fetch(r,{method:"GET",signal:o.signal});return s.ok?{reachable:!0,detail:`responded ${s.status}`}:{reachable:!1,detail:`responded ${s.status} at ${r} \u2014 a healthy gateway answers 200 there`}}catch(s){return{reachable:!1,detail:s instanceof Error&&s.name==="AbortError"?`no response within ${n}ms`:ft(s).trim()||"connection failed"}}finally{clearTimeout(a)}};import{execFileSync as cx}from"node:child_process";import{lstatSync as uV,readFileSync as pV}from"node:fs";import fV from"node:os";var lx="ai.anyray.connect",Ay="EnrollmentEmail",Cy="EnrollmentUrl",mV="HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Anyray\\Connect",sx="/etc/anyray/anyray-enroll.json",hV=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,yV=254,gV=2048,wV=64*1024,bV=e=>e.isFile()&&e.uid===0&&(e.mode&63)===0&&e.size<=wV,AV=()=>`/Library/Managed Preferences/${lx}.plist`,CV=e=>`/Library/Managed Preferences/${e}/${lx}.plist`;var wy=e=>{try{let t=JSON.parse(e);return{...typeof t[Ay]=="string"?{email:t[Ay]}:{},...typeof t[Cy]=="string"?{enrollmentUrl:t[Cy]}:{}}}catch{return{}}},ix=(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}},dx=e=>{if(!e)return;let t=e.trim().toLowerCase();if(!(!t||t.length>yV))return hV.test(t)?t:void 0},kV=e=>{if(!e)return;let t=e.trim();if(!(!t||t.length>gV))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}},vV=e=>{try{return cx("plutil",["-convert","json","-o","-",e],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},SV=()=>{try{return fV.userInfo().username||void 0}catch{return}},EV=()=>{try{return cx("reg",["query",mV],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return}},IV=()=>{try{let e=uV(sx);return bV(e)?pV(sx,"utf8"):void 0}catch{return}},ux={platform:process.platform,readMacPlistJson:vV,username:SV,readWindowsRegQuery:EV,readLinuxJson:IV},by=(e,t)=>{let n=e.map(dx).find(o=>o!==void 0),r=kV(t);return{...n?{email:n}:{},...r?{enrollmentUrl:r}:{}}},To=(e=ux)=>{try{if(e.platform==="darwin"){let t=e.username(),n=t?wy(e.readMacPlistJson(CV(t))??""):{},r=wy(e.readMacPlistJson(AV())??"");return by([n.email,r.email],r.enrollmentUrl)}if(e.platform==="win32"){let t=e.readWindowsRegQuery();return t?by([ix(t,Ay)],ix(t,Cy)):{}}if(e.platform==="linux"){let t=wy(e.readLinuxJson?.()??"");return by([t.email],t.enrollmentUrl)}return{}}catch{return{}}},px=(e,t)=>{if(!e?.length)return;let n=t?.trim().split(/[\\/]/).at(-1)?.toLowerCase();if(n)return dx(`${n}@${e[0]}`)},fx=(e=ux)=>To(e).email;import{spawn as xV}from"node:child_process";import{platform as RV}from"node:os";var Va=e=>{try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=RV(),r=n==="darwin"?"open":n==="win32"?"cmd":"xdg-open",o=n==="win32"?["/c","start",'""',`"${t.href}"`]:[t.href],a=xV(r,o,{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:n==="win32"});a.on("error",()=>{}),a.unref()}catch{}};var mx=()=>qh(),hx=(e={})=>{if(!(e.output??process.stderr).isTTY)return!1;let t=(e.openInput??mx)();try{return typeof t.stream.setRawMode=="function"}finally{t.close()}},OV=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},yx=async(e,t={})=>{let n=(t.openInput??mx)(),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(p=>p.selected===!0&&p.requiresExplicitChoice!==!0),s=0,i=0,c=Oa(o,t.env??process.env),l=(p,h)=>c?`\x1B[${p}m${h}\x1B[0m`:h,d=()=>{let p=[l("1",e.title)];for(let h=0;h<e.items.length;h++){let g=e.items[h],y=h===s?l("36","\u276F"):" ",w=e.single?a[h]?"(\u25CF)":"(\u25CB)":a[h]?"[x]":"[ ]",b=g.hint?` ${l("2",g.hint)}`:"";p.push(`${y} ${w} ${g.label}${b}`)}p.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(p.map(h=>`\r\x1B[2K${h}`).join(`
|
|
665
665
|
`)),o.write(`
|
|
666
666
|
`),i=p.length},u=()=>{i!==0&&(o.write(`\x1B[${i}A`),o.write(Array.from({length:i},()=>`\r\x1B[2K
|
|
667
|
-
`).join("")),o.write(`\x1B[${i}A`))},f=!!r.isRaw,m=!1;try{return m=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((p,h)=>{let
|
|
667
|
+
`).join("")),o.write(`\x1B[${i}A`))},f=!!r.isRaw,m=!1;try{return m=!0,r.setRawMode(!0),r.setEncoding?.("utf8"),r.resume?.(),o.write("\x1B[?25l"),d(),await new Promise((p,h)=>{let g=()=>{r.off("data",C),r.off("end",b),r.off("close",b),r.off("error",k)},y=S=>{g(),p(S)},w=S=>{g(),h(S)},b=()=>y({kind:"cancelled"}),k=S=>w(S),C=S=>{try{for(let E of OV(S)){if(E===""||E==="\x1B"||E==="q"){y({kind:"cancelled"});return}if(e.items.length===0){(E==="\r"||E===`
|
|
668
668
|
`)&&y({kind:"ok",values:[]});continue}if(E==="\x1B[A"||E==="k")s=(s-1+e.items.length)%e.items.length,d();else if(E==="\x1B[B"||E==="j")s=(s+1)%e.items.length,d();else if(E===" "){if(e.single){let I=!a[s];a.fill(!1),a[s]=I}else a[s]=!a[s];d()}else if(E==="a"&&!e.single){let I=e.items.map((T,W)=>({item:T,index:W})).filter(({item:T})=>T.requiresExplicitChoice!==!0),_=!I.every(({index:T})=>a[T]);for(let{index:T}of I)a[T]=_;d()}else if(E==="\r"||E===`
|
|
669
|
-
`){y({kind:"ok",values:e.items.filter((I,_)=>a[_]).map(I=>I.value)});return}}}catch(E){
|
|
670
|
-
`),t();let a=0,s=()=>{r.write(`\r${gx[a++%gx.length]} ${e}`)};s();let i=setInterval(s,
|
|
671
|
-
`)){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()}},HV=e=>e.mode==="off"?{allow:!1,outcome:"fleet-off"}:e.mode==="directed"&&e.initiator==="tick"?{allow:!1,outcome:"fleet-directed"}:{allow:!0},GV=e=>e==="auto",Cx=e=>{if(e.latest===e.current)return{apply:!1,mandatory:!1};if(e.autoUpdate||e.forced)return{apply:!0,mandatory:!1};let t=!!e.minVersion&&ja(e.current,e.minVersion)<0&&ja(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},VV=e=>ja(e.latest,e.current)<0?{apply:!1,mandatory:!1,downgradeBlocked:!0}:e.latest===e.current?{apply:e.autoUpdate||e.forced===!0,mandatory:!1,downgradeBlocked:!1}:{...Cx(e),downgradeBlocked:!1},KV=(e=process.execPath)=>{let t=rp(e);return t?nn(t):nn(nn(e))},jV=async(e=ut())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=Dn(KV(e.execPath)).launcher;try{if(await du(t)!==await du(e.execPath))return}catch{return}return t},xy=async(e=ut(),t=ee())=>{let n=await jV(e);if(n)return{kind:"managed",root:nn(nn(n)),link:n,entryPath:tr(e)};let r=tr(e);return ap(r,t)?{kind:"durable",root:t,entryPath:r}:tp(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},pu=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),t);try{return await fetch(e,{...n,signal:r.signal})}finally{clearTimeout(o)}},Ry=async(e=Bi)=>{let t=await pu(`${pr}/latest`,e,{redirect:"manual"});return UV(t.headers.get("location"))},ZV=async e=>{try{let t=await pu(`${e}/connect-update.json`,Bi);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}},Mi=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},Oy=async(e,t,n)=>{let r=await pu(e,BV);if(!r.ok||!r.body)throw new Mi(r.status);let o=DV("sha256"),a=0;if(await NV(LV.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>MV)throw new Error("asset exceeds size cap");o.update(c),yield c}},TV(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},YV=e=>cu(e)===fr()?cu(nn(e)):cu(e),JV=async e=>{let t=await uu(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await xt(Ka(e,n),{force:!0}).catch(()=>{})},kx=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await xt(r,{force:!0}).catch(()=>{});let o=!1;try{await iu(e,r),o=!0}catch{}try{await vy(t,e),await PV(ls(e),YV(t))}catch(a){throw o&&await iu(r,e).catch(()=>{}),a}await xt(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await xt(n,{force:!0}),await _V(t,n),await iu(n,e)},Ty=(e,t)=>e===t||cu(e)===Rp?448:493,$i=async(e,t)=>{let n=(await Ax(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await bx(e,n&4095|t).catch(()=>{})},lu=async(e,t)=>{await Ey(e,{recursive:!0,mode:t}),await $i(e,t)},XV=async(e,t,n)=>{let r=Ty(e,ee());if(r!==448){let o=Dn(e),a=o.versionsDir;await $i(e,r),await $i(nn(o.launcher),r),await $i(a,r);for(let s of await uu(a).catch(()=>[]))await $i(Ka(a,s),r)}await(n.refreshDesktopHelpers??Qd)(t)},zV=async(e,t={})=>{let n=Dn(e.root),r=nn(n.launcher),{versionsDir:o,launcher:a}=n,s=Ty(e.root,(t.privateRoot??ee)());await lu(r,s),await lu(o,s);let i=Ka(o,e.version),l=(await Sy(i).catch(()=>{}))?.isFile()?i:Ka(i,fr());if(!(await Sy(l).catch(()=>{}))?.isFile()){let u=await(t.fetchResponse??pu)(`${e.tagUrl}/SHA256SUMS`,Bi),f=u.ok?Iy(await u.text(),e.asset):void 0;if(!f)throw new Error("no published checksum");await lu(nn(l),s),await JV(nn(l));let m=`${l}.part-${process.pid}`;try{await(t.download??Oy)(`${e.tagUrl}/${e.asset}`,m,f),await bx(m,493),await iu(m,l)}catch(p){throw await xt(m,{force:!0}).catch(()=>{}),p}}return await(t.activate??kx)(a,l),{link:a,target:l,versionsDir:o}},qV=async e=>{wx(e.target,[zr,e.link],{stdio:"ignore",timeout:Bi})},QV=async e=>{if(process.platform==="darwin"){let t=wx("/usr/bin/codesign",["--verify","--strict",e],{stdio:"ignore",timeout:Bi});return!t.error&&t.status===0}return!0},eK=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??So)(n);if(r.length>0){let o=await(t.resolveTarget??Ue)(async()=>e);if(!o||!(await(t.repair??Wt)(r,o.target)).every(vo))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&Je(e)&&!(await(t.installScheduler??ur)()).ok)},tK=async e=>{let t=await e.install();if(!await(e.smoke??QV)(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},nK=async(e,t)=>{let n=await uu(e).catch(()=>[]);for(let r of n)t.includes(r)||await xt(Ka(e,r),{force:!0,recursive:!0}).catch(()=>{})},rK=async e=>{let t=await uu(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await xt(Ka(e,n),{force:!0}).catch(()=>{})},oK=async(e,t)=>{let n=async()=>{await xt(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await Ey(e,{recursive:!1}),n}catch{}let r=await Ax(e).catch(()=>{});if(!(!r||t-r.mtimeMs<WV)){await n();try{return await Ey(e,{recursive:!1}),n}catch{return}}},ky=e=>Dn(e).state,aK=async e=>{let t=await B(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},Za=async(e={})=>{let t=e.now??Date.now,n=Ee;if(Tn(cn(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??ut(),o=e.root??ee(),a;try{let s=await xy(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??P)().catch(()=>({})),d=l.autoUpdate!==!1,u=l.fleetUpdatePolicy?.mode??"auto",f=HV({mode:u,initiator:e.initiator??"tick"});if(!f.allow)return{outcome:f.outcome,current:n};!i&&s.link&&!e.checkOnly&&(d||c)&&await XV(o,s.link,e).catch(()=>{});let m=bs(e.platform??process.platform,e.arch??process.arch);if(!m)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??Ry)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let p=a;if(!i&&p===n)return{outcome:"current",current:n,latest:p};if(i&&ja(p,n)<0)return{outcome:"migration-deferred",current:n,latest:p};let h=await aK(ky(o));if((e.respectFailureBackoff===!0||!c)&&h.failedVersion===p&&h.failedAt!==void 0&&t()-h.failedAt<FV)return{outcome:"failed",current:n,latest:p};let w=`${pr}/download/${Xr}${p}`,y=d||c||!GV(u)?void 0:await(e.minimumVersion??ZV)(w),g={current:n,latest:p,autoUpdate:d,forced:c,minVersion:y},b=i?VV(g):{...Cx(g),downgradeBlocked:!1};if(b.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:p};if(!b.apply)return{outcome:"disabled",current:n,latest:p};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:p,mandatory:b.mandatory};o===ee()?await et():await lu(o,Ty(o,ee()));let k=Dn(o),C=await oK(k.lock,t());if(!C)return{outcome:i?"migration-available":"available",current:n,latest:p};let S,E;try{await rK(nn(k.launcher));let I=await du(k.versionsDir).catch(()=>{}),_=await du(k.launcher).catch(()=>{}),T=_&&lc(_,I)?_:void 0,W=k.launcher;i&&process.platform==="win32"&&(await Sy(W).catch(()=>{}))?.isFile()&&(E=`${W}.rollback-${process.pid}`,await vy(W,E));let Q=()=>(e.installBinary??zV)({root:o,version:p,asset:m,tagUrl:w});i?S=await tK({install:Q,smoke:e.smoke,rollback:async({link:G,target:ne})=>{E?(await vy(E,G),await xt(ls(G),{force:!0}).catch(()=>{})):T&&T!==ne?await kx(G,T):(await xt(G,{force:!0}),await xt(ls(G),{force:!0}).catch(()=>{}))},repoint:async G=>e.repoint?e.repoint(l,G):eK(l),prune:async()=>{await(e.pruneDurable??(G=>uc(G)))(r)}}):S=await Q(),await nK(S.versionsDir,[p,n]),await(e.refreshHelpersFromInstalled??qV)(S).catch(()=>{}),await xt(ky(o),{force:!0}).catch(()=>{})}finally{E&&await xt(E,{force:!0}).catch(()=>{}),await C()}return{outcome:i?"migrated":"updated",current:n,latest:p,managedPath:S.link,mandatory:b.mandatory}}catch{return a&&await X(ky(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},vx=async(e={})=>{let t=e.context??ut(),n=await xy(t,e.root??ee()),r=Go(e.root??ee());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:Ee,managedPath:n.link??r}:Za({initiator:"human",...e,context:t,allowNpmMigration:!0})},_o=async(e={})=>{let t=e.context??ut(),n=e.root??ee(),r=await xy(t,n),o=r.kind==="npm"||r.kind==="durable"?Go(n):void 0,a=await(e.load??P)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!bs(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=Tn(cn(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:Ee,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l,fleetMode:a.fleetUpdatePolicy?.mode??"auto"}};import{z as Sx}from"zod";var sK=5e3,iK=Sx.object({lane:Sx.enum(["subscription","org"]).optional().catch(void 0)}),Ex=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??sK);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=iK.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},Ix=(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 cK=12e3,lK="anyray-wiring-probe-not-a-real-token",dK={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"}]},Po=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},Rx=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},Dy=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},xx=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."],uK=e=>e.includes("no provider key configured for"),Ly=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},Ny=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>"]}),Fi=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."]}),pK=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:uK(t)?{kind:"provider-rejected",providerKeyAbsent:!0,detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${Po(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")?xx([" \u2022 add a provider key in the console \u2192 Providers (fixes it for everyone), or"]):["If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]]}:e===401||e===403?Ly(t)?Ny(e):Dy(t)?Fi(e):Rx(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${Po(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}): ${Po(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).",...xx([" \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}: ${Po(t)}`,remedy:[]},fK=(e,t)=>{if(Dy(t))return Fi(e);if(Ly(t))return Ny(e);if(Rx(t))return{kind:"routed-elsewhere",detail:"gateway sent the request to the org provider, not your subscription.",remedy:["Pass-through isn\u2019t being honored for this gateway \u2014 your seat token would","not be used. Check the gateway is current (subscription pass-through support)."]};let n=t.toLowerCase();return e===401||n.includes("authentication_error")||n.includes("invalid bearer")||n.includes('"provider":"anthropic"')?{kind:"ok",detail:"gateway passes your sign-in through to Anthropic \u2014 your Claude seat will be used.",remedy:[]}:e>=200&&e<300?{kind:"ok",detail:"gateway pass-through reached the provider \u2014 your seat will be used.",remedy:[]}:{kind:"unknown",detail:`seat-wiring probe got HTTP ${e}: ${Po(t)}`,remedy:[]}},mK=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),hK=(e,t)=>{if(Dy(t))return Fi(e);if(Ly(t))return Ny(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:","set it as the gateway upstream (console \u2192 Routing), or for a","caller-supplied host add it to ANYRAY_CUSTOM_HOST_ALLOWLIST."]};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")||mK(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}: ${Po(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."]}},_y=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)}},yK=async(e,t)=>{if(!e.clientKey)return Fi(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?Fi(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${Po(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},gK=(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."]}},wK=e=>e.providerKeyAbsent===!0?!1:e.kind==="ok"?!0:null,Ox=async(e,t={})=>{try{return wK(await Ya(e,t))}catch{return null}},Ya=async(e,t={})=>{let n=t.timeoutMs??cK,r=me(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await yK(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 _y(`${e.anthropicBaseUrl}/v1/messages`,l,Py,n);return hK(d,u)}if(te(e,"anthropic")){let l={Authorization:`Bearer ${lK}`,"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 _y(`${e.anthropicBaseUrl}/v1/messages`,l,Py,n);return fK(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await _y(`${e.openaiBaseUrl}/chat/completions`,s,dK,n);return pK(i,c,t.tools??[])}catch(o){return gK(n,o)}};var Tx=async(e,t={})=>{let n=await P(),r=!n.enrolledCert&&n.managedEnrollmentDisabled!==!0&&!!(t.managedEnrollment??To)().enrollmentUrl,o;try{o=Nr(e.gateway,n)}catch(s){return A(K("Anyray connect \u2014 status")),L(`Gateway: ${s.message}`),0}A(K("Anyray connect \u2014 status")),H("Gateway"),A(` Origin: ${qe(o)}`),n.gateway?L(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?L(" (from $ANYRAY_GATEWAY_URL)"):r?L(" (default \u2014 enrollment is managed by your organization and re-enrolls on the next refresh)"):e.gateway||L(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),H("Identity"),A(` Name: ${n.name??v("(not set)")}`),A(` Team: ${n.team??v("(not set)")}`);let a=cn();a&&(H("Environment"),A(` Remote dev context: ${Ko(a)}`),Tn(a)&&L(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),L(" VS Code tools configure the remote server variant backing this window.")),n.enrolledCert&&n.clientKey&&(H("Credential renewal"),M(" Direct gateway routing with a proof-backed key heartbeat."),L(" Renewal extends the same key; tool configuration is not rewritten.")),H("Tools");for(let s of fe){if(!(await s.detect()).installed){L(` ${s.title}: not installed`);continue}if(!s.pointsAt){L(` ${s.title}: installed ${v("(status not introspectable)")}`);continue}let c=await s.pointsAt(o);if(c){if(s.id==="cursor"&&(n.authMode==="auto"||n.authMode==="subscription")){M(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}M(` ${s.title}: pointed at Anyray`)}else{let l=null,d=null;if(s.id===Ua&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,f=await jd();l=Zd({id:s.id,installed:!0,pointedAt:c,mcpRegistered:u,introspectable:f.authoritative}),d={...f.authoritative?{}:{reason:f.reason},mcpRegistered:u}}catch{l=null,d=null}if((l==="not-routed"||l==="unverifiable")&&d){let u=Yd(l,d);O(` ${s.title}: ${u.headline}`);for(let f of u.detail)A(v(` ${f}`))}else L(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as UK}from"node:fs";import{isAbsolute as HK}from"node:path";import{homedir as GK}from"node:os";import{readFile as bK,stat as AK}from"node:fs/promises";import{homedir as CK,platform as kK}from"node:os";var vK=e=>e.replace(/\\(\d{3})/g,(t,n)=>String.fromCharCode(parseInt(n,8))),SK=e=>e.split(`
|
|
672
|
-
`).map(t=>t.split(" ")[4]).filter(t=>!!t).map(
|
|
673
|
-
`)){let o=new RegExp(`${MK}=(\\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"},WK=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",mu=(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 ${hn} and ${yn}; 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."}},Px=async(e={})=>{let{installedVariant:t=ta,receiptMode:n=ml,awaitingReload:r=fl,readSettings:o=BK,probeBridge:a=FK,home:s=DK()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:mu("not-applicable","unknown")};let c=await n(i,s);if(c!=="copilot-seat"){let f=c===void 0&&await r(i,s);return{state:f?"unknown":"not-applicable",bridge:"unknown",detail:f?"Agents window: VS Code has an Anyray configuration staged but not applied yet, so its state is unknown. Restart VS Code to finish.":mu("not-applicable","unknown")}}let l=await o($s(i)),d=await a(),u=WK({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:mu(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:mu("not-applicable","unknown")}}};var rn="connect",hu=e=>e.replace(/-/g,"_"),Dx=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:rn,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:rn,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:rn,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:rn,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.removed&&e.serviceRemoval.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.identity.sharedIdentityRisk&&t.push({tool:rn,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:rn,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=hu(e.retrieval.kind);t.push({tool:rn,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":hu(e.verify.kind);t.push({tool:rn,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:rn,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:hu(e.hookLane.reason)}:{}})}t.push({tool:rn,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:hu(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:rn,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};var VK=e=>{let t=GK();return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e};function Lx(){return Ee}var KK="ctx_doctor-probe-synthetic",jK=(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: ${By(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 ZK(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 By(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 Nx=e=>Zd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),$y=e=>e.pointedAt===!1&&e.tombstoned!==!0&&Nx(e)!=="unverifiable",$x=e=>e.registered&&e.command&&HK(e.command)?UK(e.command):null,JK=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."}},My=e=>($y(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),XK=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,zK=async(e,t)=>{if(e.length===0)return!1;for(let n of e){let r=t.find(a=>a.id===n);if(!r?.inferenceAuthLanes)return!1;let o=await r.inferenceAuthLanes().catch(()=>["unknown"]);if(o.length===0||o.some(a=>a!=="subscription"&&a!=="native"))return!1}return!0},Mx=async e=>{for(let t of e)if(t.integrationStatus)try{if(!(await t.detect()).installed)continue;if((await t.integrationStatus()).hook_registration==="owned")return!0}catch{}return!1},qK=(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(Io),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})),f=n(l.flapping)?l.flapping:void 0,m=Array.isArray(f?.checks)?f.checks.filter(w=>typeof w=="string"&&a.has(w)):[],p=f?.reason==="rebroke_same_day"||f?.reason==="repeat_days"?f.reason:void 0,h=f&&r(f.since)&&p&&m.length>0?{since:f.since,reason:p,checks:m}:void 0;(u.length>0||h)&&s.push({tool:c,repaired:u,...h?{flapping:h}:{}})}return s},QK=async(e,t,n,r,o,a,s,i=n,c=Ya,l=!0,d=jo,u=_o,f=It,m=Ba)=>{let p=l?await su(e):null,h=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,w=J=>J&&Xh(J)?"machine_default":null,y=t.enrolledCert?.payload,g=y?.expiresAt??t.enrolledCertExpiry??null,k=(await a())?.sso??null,C=YK({ssoLink:k,enrolledViaToken:!!t.enrolledTokenHash}),S=!y&&t.managedEnrollmentDisabled!==!0&&!!s().enrollmentUrl,E=wt(),I=await cb(E),_=I?[]:jc(Re({origin:e})),T=[];for(let J of r){let pe=await J.detect(),Be=null;if(pe.installed&&J.mcpStatus)try{let Nu=await J.mcpStatus();Be={...Nu,commandOk:$x(Nu)}}catch{}let yt=pe.installed&&J.id===Ua?await o():void 0,No=pe.installed&&J.pointsAt?await J.pointsAt(e):null,$o=await XK(No,J,t.managedTools??[]),zi=No===!1&&$o===null,qi=$o===!1&&J.routingPendingReload?await J.routingPendingReload().catch(()=>!1):!1,Qi=pe.installed?J.runtimeDiagnostics?await J.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:J.routingOverrides?await J.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Mo,claudeCodeHookPolicy:ns}=Qi,xe=t.fleetToolPolicy,be=xe?.enabled.includes(J.id)?xe.tiers?.[J.id]??Pa:void 0;T.push({id:J.id,title:J.title,installed:pe.installed,...pe.detail?{detail:pe.detail}:{},pointedAt:$o,...zi?{routingHeld:!0}:{},...qi?{routingPendingReload:!0}:{},...Mo.length?{routingOverrides:Mo}:{},...ns===void 0?{}:{claudeCodeHookPolicy:ns},mcp:Be,...be?{policyTier:be}:{},...t.revertedTools?.includes(J.id)?{tombstoned:!0}:{},...J.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...yt===void 0?{}:{inferenceIntrospectable:yt.authoritative,...yt.authoritative?{}:{inferenceUnverifiableReason:yt.reason}}})}let W=i?await(async()=>{let{kind:J,detail:pe,remedy:Be}=await c(Re({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:pe,remedy:Be}})():null,Q=W?.kind==="provider-rejected"&&await zK(t.managedTools??[],r),G=W?{...W,...Q?{notApplicableSubscription:!0}:{}}:null,ne=n?jK(await Ma({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:me({user:t.name,team:t.team})},KK,{probe:!0}),{mode:C,ssoLink:k}):null,z=await f().catch(()=>({})),Z=En(z.hookLane),le=i?await Mx(r):!1,U=le?await(async()=>{let J=await m().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...Bh(J,{hookRegistered:le,neverInvoked:$h(Z,Date.now())}),lastInvokedAt:Ld(Z)}})():null,Y=(await hr()).map(J=>({adapter:J.adapter,op:J.op,requestedAt:J.requestedAt,watcherAlive:gr(J.watcherPid)})),re=Y.find(J=>J.adapter==="cursor"),Qe=re?{op:re.op,requestedAt:re.requestedAt,watcherAlive:re.watcherAlive}:null,Ie=!!t.refreshSchedulerEnabled,ke=await Pn(),Rt=Ie&&!ke&&!Je(t),D=await u(),N=t.persistenceOwner==="tray",j=N?await d(t)==="healthy":null,on=await Yw({schedulerEnabled:Ie&&!N&&!Rt,schedulerInstalled:ke,binaryDurable:!tt(jr()),schedulerInstalledOnce:t.refreshSchedulerInstalledOnce===!0,trayManaged:N}),ve=0;p&&!p.reachable&&(ve+=1),N?Ie&&!j&&(ve+=1):Ie&&!ke&&!Rt&&(ve+=1);for(let J of T)ve+=My(J);G&&G.kind!=="ok"&&!G.notApplicableSubscription&&(ve+=1),ne&&ne.kind!=="ok"&&(ve+=1),U?.verdict==="dark"&&(ve+=1),_.length>0&&(ve+=1),ve+=Y.filter(J=>!J.watcherAlive).length;let Vt=await Px();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:Lx(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:cn(),fileBindMounts:await fu(),selfUpdate:{managed:D.managed,available:D.available,autoUpdate:D.autoUpdate,state:D.state,fleetMode:D.fleetMode}},gateway:{origin:e,reachable:p?p.reachable:null,detail:p?p.detail:"not probed (--quick)"},refreshScheduler:{enabled:Ie,installed:ke,owner:N?"tray":"os",...N?{trayHealthy:!!j}:{},...Rt?{retired:!0}:{}},serviceRemoval:on,fleetdPresent:await Do(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:h,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:w(t.name)},enrollment:{enrolled:!!y,deploymentId:y?.deploymentId??null,issuedAt:y?.issuedAt??null,expiresAt:g,expired:g?Date.parse(g)<Date.now():null,orgMode:C,ssoLink:k,managedPending:S},shell:{profilePath:E,blockPresent:I,staleExports:_},tools:T,...t.fleetToolPolicy?{fleetPlan:Pd(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Qe,pendingOps:Y,ambientRepairs:qK(z,r),verify:G,retrieval:ne,hookLane:U,agentsWindow:Vt,problems:ve}},e2=e=>{if(e.serviceRemoval.suspected){if(!e.serviceRemoval.removed){H("Automatic key refresh"),O(" This seat expects the key-refresh schedule, but no unit is installed and"),O(" Anyray has no record of ever installing one here. Re-run `anyray-connect`"),O(" to install it.");for(let t of e.serviceRemoval.missingPaths)A(v(` expected: ${t}`));return}H("Endpoint security"),O(" Anyray installed these background services, but their files are gone from disk \u2014"),O(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),O(" 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."))}},t2=e=>{if(A(K("Anyray connect \u2014 doctor")),e.connect.remoteContext||e.connect.fileBindMounts.length>0){H("Environment"),e.connect.remoteContext&&(A(` Remote dev context: ${Ko(e.connect.remoteContext)}`),Tn(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.")));for(let c of e.connect.fileBindMounts)A(` Bind-mounted config file: ${VK(c)}`),A(v(" A file mounted into this container cannot be replaced atomically; connect writes it in place (verified). Mount the parent directory instead to restore atomic writes."))}switch(H("CLI updates"),e.connect.selfUpdate.state){case"managed":M(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.fleetMode==="off"?A(v(" Your organization manages Connect updates; this machine downloads nothing.")):e.connect.selfUpdate.fleetMode==="directed"?A(v(" Your organization applies Connect updates centrally; an administrator pushes new versions.")):e.connect.selfUpdate.autoUpdate||O(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":O(" 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":O(" 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?M(` 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?M(" 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?M(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):e.refreshScheduler.retired?M(" Retired \u2014 this key does not expire between sessions, and your tools already trigger renewal. No background schedule is needed."):(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.")))),e2(e),H("Personal key"),ZK(e)){case"env":M(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":M(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":O(" 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:if(e.enrollment.managedPending){O(" Enrollment is managed by your organization, but this machine holds no local enrollment state."),A(v(" Fix: none needed \u2014 it re-enrolls unattended on the next refresh; run `anyray-connect refresh` to do it now."));break}O(" Enrollment required \u2014 no personal gateway key is available."),A(v(` Fix: ${By(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?O(` Enrollment cert expired ${v(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):M(` Enrollment cert valid until ${e.enrollment.expiresAt} ${v(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(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(` ${gc(c)}.`),A(v(` ${wc(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."))):M(` ${c.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(O(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),A(v(` Fix: ${JK(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){M(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}M(` ${c.title}: pointed at ${e.gateway.origin}`),o(c),c.id==="claude-code"&&A(v(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===Ua&&A(v(` ${ak(gt("migrate"),gt("desktop"))}`)),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=Nx(c);if(l==="not-routed"||l==="unverifiable"){let d=Yd(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});O(` ${c.title}: ${d.headline}`);for(let u of d.detail)A(v(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(O(` ${c.title}: reverted locally against admin policy (out of compliance)`),A(v(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?O(` ${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&&(O(" 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=pt(c.adapter)?.title??c.adapter;c.watcherAlive?O(` ${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=pt(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:m,at:p})=>`${c(m)} ${new Date(p).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let f=` ${d}: ${u.join("; ")}`;l.flapping?O(f):A(f)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){H("Fleet policy");let c=l=>l.map(d=>pt(d)?.title??d).join(", ");i.freshIds.length>0&&A(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&O(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(H("Auth probe"),e.verify.notApplicableSubscription)M(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")M(` ${e.verify.detail}`);else{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")M(` ${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")M(` ${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{O(` ${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"),O(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(H("VS Code Agents window"),M(` ${e.agentsWindow.detail}`)),H("Summary"),e.problems===0?(e.verify?M(" No problems found."):M(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),A(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):R(` ${e.problems} problem(s) found \u2014 see fixes above.`)},n2=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}),r2=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!Dh(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??Ba,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??Ht)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=En((await(t.readRefreshState??It)().catch(()=>({}))).hookLane),l=Bh(i,{hookRegistered:await Mx(t.adapters??fe).catch(()=>!1),neverInvoked:$h(c,Date.now())}),d=s==="disabled"?"Hook lane: key refresh is disabled here (ANYRAY_REFRESH_DISABLE), so no key was minted and the finding stands.":l.verdict==="live"?"Hook lane: re-minted the personal key and rewrote the configured tools \u2014 the lane answers again.":l.verdict==="indeterminate"?`Hook lane: re-mint reported '${s}', but the confirming probe could not establish the lane's state \u2014 nothing is proven fixed and the finding stands.`:`Hook lane: re-mint reported '${s}' and the lane is still not live \u2014 re-enroll (see the Hook lane fixes above).`;return{hookLane:{...l,lastInvokedAt:Ld(c)},note:d}},o2=async(e,t,n={})=>{let r=n.adapters??fe,o=n.resolveTarget??Ue,a=n.applyTools??Wt,s=await r2(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&&($y(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 ${By(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),f=[],m=[...c.notes],p=[];for(let g of l){let b=r.find(k=>k.id===g.id);if(!u.has(g.id)||!b){f.push({id:g.id,title:g.title,status:"skipped-unmanaged"});continue}p.push(b)}f.length>0&&m.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(p,d.target),w=new Map,y=0;for(let g of h){if(f.push(g),!vo(g))continue;let b=e.tools.find(T=>T.id===g.id);if(!b)continue;let k=r.find(T=>T.id===g.id),C=b.mcp;if(k?.mcpStatus)try{let T=await k.mcpStatus();C={...T,commandOk:$x(T)}}catch{}let S=$y(b)?!0:b.pointedAt;if(k?.pointsAt&&b.pointedAt!==null)try{S=await k.pointsAt(e.gateway.origin)}catch{}let E=b.routingOverrides,I=b.claudeCodeHookPolicy;if(k?.runtimeDiagnostics)try{let T=await k.runtimeDiagnostics();E=T.routingOverrides.length?T.routingOverrides:void 0,I=T.claudeCodeHookPolicy}catch{}else if(k?.routingOverrides)try{let T=await k.routingOverrides();E=T.length?T:void 0}catch{}let _={...b,pointedAt:S,mcp:C,...E?{routingOverrides:E}:{},...I===void 0?{}:{claudeCodeHookPolicy:I}};E||delete _.routingOverrides,I===void 0&&delete _.claudeCodeHookPolicy,w.set(g.id,_),y+=My(b)-My(_)}return{entries:f,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:w,...s?{hookLane:s.hookLane}:{},notes:m}},a2=e=>{H("Repair"),e.entries.length===0&&M(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?M(` ${t.title}: re-applied`):t.status==="queued"?M(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?A(v(` ${t.title}: ${t.status}`)):R(` ${t.title}: ${t.status}`);for(let t of e.notes)A(v(` ${t}`))},yu=async(e,t={})=>{let n=await P();if(e.securityReview){if(e.json){let c;try{c=n.gateway?new URL(n.gateway).hostname:void 0}catch{}return console.log(JSON.stringify(Jw({connectVersion:Lx(),...c?{gatewayHost:c}:{}}),null,2)),0}if(!e.silent){A(K("Anyray connect \u2014 security review"));for(let c of Xw())A(c?` ${c}`:"")}return 0}let r;try{r=Nr(e.gateway,n)}catch(c){return e.silent?1:e.json?(console.log(JSON.stringify({error:c.message})),1):(A(K("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(K("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 QK(r,n,!!e.verify&&!e.quick,t.adapters??fe,t.inferenceIntrospection??jd,t.fleetBootstrap??Pr,t.managedEnrollment??To,o,t.verifyAuth??Ya,!e.quick,t.checkTray??jo,t.updateStatus??_o,t.readRefreshState??It,t.probeHookLane??Ba),s=e.repair?await o2(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(n2(i),null,2)):(t2(i),s&&a2(s)));try{e.quick||await(t.reportHealth??AE)(Dx(i),i.connect.version)}catch{}return i.problems===0?0:1};var s2=()=>{let e=[];for(let t of fe){let n=t.skillsDir?.();n&&e.push(n)}return e},Bx=async e=>{let t=await P();A(K("Anyray connect \u2014 sync"));let n;try{n=Nr(e.gateway,t)}catch(s){return R(s.message),1}L(`Gateway: ${n}`);let r=dI(t.clientKey,"anyray-placeholder"),o;try{o=await La(n,r)}catch(s){return R(`Team policy sync failed: ${Th(s)}`),1}let a=s2();if(a.length===0)i2();else if(o.skills.length===0)L("No team skills published yet \u2014 nothing to sync.");else{let s=await sE(o,a,t.syncedSkills??{});H("Skills");for(let i of s.results)i.written?M(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):L(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await ce({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){L(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}H("Summary"),A(` ${qe(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Na(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&&L(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){L(`Fleet policy reconcile skipped: ${Th(s)}`)}return 0},i2=()=>{L("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as uj}from"node:zlib";import{promisify as pj}from"node:util";var Br={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},Fy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),Fx=e=>`
|
|
669
|
+
`){y({kind:"ok",values:e.items.filter((I,_)=>a[_]).map(I=>I.value)});return}}}catch(E){w(E)}};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?.(),m&&r.setRawMode(f)}catch{}n.close()}};var gx=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],TV=80,Ni=async(e,t,n={})=>{let r=n.output??process.stderr;if(!(!!r.isTTY&&Oa(r,n.env??process.env)))return r.write(`${e}
|
|
670
|
+
`),t();let a=0,s=()=>{r.write(`\r${gx[a++%gx.length]} ${e}`)};s();let i=setInterval(s,TV);i.unref();try{return await t()}finally{try{clearInterval(i),r.write("\r\x1B[2K")}catch{}}};import{createWriteStream as _V}from"node:fs";import{spawnSync as wx}from"node:child_process";import{chmod as bx,copyFile as vy,lstat as Sy,mkdir as Ey,readdir as uu,realpath as du,rename as iu,rm as xt,stat as Ax,symlink as PV,writeFile as DV}from"node:fs/promises";import{createHash as LV}from"node:crypto";import{basename as cu,dirname as nn,join as Ka}from"node:path";import{Readable as NV}from"node:stream";import{pipeline as $V}from"node:stream/promises";var MV=new RegExp(`/releases/tag/${Xr}([0-9][0-9A-Za-z.-]*)$`),BV=300*1024*1024,Bi=1e4,FV=5*6e4,WV=360*6e4,UV=30*6e4,ja=(e,t)=>{let n=s=>s.split("-")[0].split(".").map(i=>Number.parseInt(i,10)||0),r=n(e),o=n(t);for(let s=0;s<Math.max(r.length,o.length);s++){let i=(r[s]??0)-(o[s]??0);if(i!==0)return i<0?-1:1}let a=s=>s.includes("-")?0:1;return a(e)-a(t)};var HV=e=>{if(e)return MV.exec(e.trim())?.[1]},Iy=(e,t)=>{for(let n of e.split(`
|
|
671
|
+
`)){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()}},GV=e=>e.mode==="off"?{allow:!1,outcome:"fleet-off"}:e.mode==="directed"&&e.initiator==="tick"?{allow:!1,outcome:"fleet-directed"}:{allow:!0},VV=e=>e==="auto",Cx=e=>{if(e.latest===e.current)return{apply:!1,mandatory:!1};if(e.autoUpdate||e.forced)return{apply:!0,mandatory:!1};let t=!!e.minVersion&&ja(e.current,e.minVersion)<0&&ja(e.latest,e.minVersion)>=0;return{apply:t,mandatory:t}},KV=e=>ja(e.latest,e.current)<0?{apply:!1,mandatory:!1,downgradeBlocked:!0}:e.latest===e.current?{apply:e.autoUpdate||e.forced===!0,mandatory:!1,downgradeBlocked:!1}:{...Cx(e),downgradeBlocked:!1},jV=(e=process.execPath)=>{let t=rp(e);return t?nn(t):nn(nn(e))},ZV=async(e=ut())=>{if(/[\\/]node(\.exe)?$/i.test(e.execPath))return;let t=Dn(jV(e.execPath)).launcher;try{if(await du(t)!==await du(e.execPath))return}catch{return}return t},xy=async(e=ut(),t=ee())=>{let n=await ZV(e);if(n)return{kind:"managed",root:nn(nn(n)),link:n,entryPath:tr(e)};let r=tr(e);return ap(r,t)?{kind:"durable",root:t,entryPath:r}:tp(r)?{kind:"npm",root:t,entryPath:r}:{kind:"unmanaged",root:t,entryPath:r}},pu=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),t);try{return await fetch(e,{...n,signal:r.signal})}finally{clearTimeout(o)}},Ry=async(e=Bi)=>{let t=await pu(`${pr}/latest`,e,{redirect:"manual"});return HV(t.headers.get("location"))},YV=async e=>{try{let t=await pu(`${e}/connect-update.json`,Bi);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}},Mi=class extends Error{status;constructor(t){super(`download failed (${t})`),this.status=t,this.name="DownloadHttpError"}},Oy=async(e,t,n)=>{let r=await pu(e,FV);if(!r.ok||!r.body)throw new Mi(r.status);let o=LV("sha256"),a=0;if(await $V(NV.fromWeb(r.body),async function*(s){for await(let i of s){let c=i;if(a+=c.length,a>BV)throw new Error("asset exceeds size cap");o.update(c),yield c}},_V(t,{mode:493})),o.digest("hex")!==n)throw new Error("checksum mismatch")},JV=e=>cu(e)===fr()?cu(nn(e)):cu(e),XV=async e=>{let t=await uu(e).catch(()=>[]);for(let n of t)/\.part-\d+$/.test(n)&&await xt(Ka(e,n),{force:!0}).catch(()=>{})},kx=async(e,t)=>{if(process.platform==="win32"){let r=`${e}.old-${process.pid}`;await xt(r,{force:!0}).catch(()=>{});let o=!1;try{await iu(e,r),o=!0}catch{}try{await vy(t,e),await DV(ls(e),JV(t))}catch(a){throw o&&await iu(r,e).catch(()=>{}),a}await xt(r,{force:!0}).catch(()=>{});return}let n=`${e}.new-${process.pid}`;await xt(n,{force:!0}),await PV(t,n),await iu(n,e)},Ty=(e,t)=>e===t||cu(e)===Rp?448:493,$i=async(e,t)=>{let n=(await Ax(e).catch(()=>{}))?.mode;n===void 0||(n&t)===t||await bx(e,n&4095|t).catch(()=>{})},lu=async(e,t)=>{await Ey(e,{recursive:!0,mode:t}),await $i(e,t)},zV=async(e,t,n)=>{let r=Ty(e,ee());if(r!==448){let o=Dn(e),a=o.versionsDir;await $i(e,r),await $i(nn(o.launcher),r),await $i(a,r);for(let s of await uu(a).catch(()=>[]))await $i(Ka(a,s),r)}await(n.refreshDesktopHelpers??Qd)(t)},qV=async(e,t={})=>{let n=Dn(e.root),r=nn(n.launcher),{versionsDir:o,launcher:a}=n,s=Ty(e.root,(t.privateRoot??ee)());await lu(r,s),await lu(o,s);let i=Ka(o,e.version),l=(await Sy(i).catch(()=>{}))?.isFile()?i:Ka(i,fr());if(!(await Sy(l).catch(()=>{}))?.isFile()){let u=await(t.fetchResponse??pu)(`${e.tagUrl}/SHA256SUMS`,Bi),f=u.ok?Iy(await u.text(),e.asset):void 0;if(!f)throw new Error("no published checksum");await lu(nn(l),s),await XV(nn(l));let m=`${l}.part-${process.pid}`;try{await(t.download??Oy)(`${e.tagUrl}/${e.asset}`,m,f),await bx(m,493),await iu(m,l)}catch(p){throw await xt(m,{force:!0}).catch(()=>{}),p}}return await(t.activate??kx)(a,l),{link:a,target:l,versionsDir:o}},QV=async e=>{wx(e.target,[zr,e.link],{stdio:"ignore",timeout:Bi})},eK=async e=>{if(process.platform==="darwin"){let t=wx("/usr/bin/codesign",["--verify","--strict",e],{stdio:"ignore",timeout:Bi});return!t.error&&t.status===0}return!0},tK=async(e,t={})=>{let n=e.managedTools??[];if(n.length>0){let r=await(t.findTools??So)(n);if(r.length>0){let o=await(t.resolveTarget??Ue)(async()=>e);if(!o||!(await(t.repair??Wt)(r,o.target)).every(vo))return!1}}return e.persistenceOwner==="tray"?!0:!(e.refreshSchedulerEnabled&&Je(e)&&!(await(t.installScheduler??ur)()).ok)},nK=async e=>{let t=await e.install();if(!await(e.smoke??eK)(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},rK=async(e,t)=>{let n=await uu(e).catch(()=>[]);for(let r of n)t.includes(r)||await xt(Ka(e,r),{force:!0,recursive:!0}).catch(()=>{})},oK=async e=>{let t=await uu(e).catch(()=>[]);for(let n of t)/\.(new|old|rollback)-\d+$/.test(n)&&await xt(Ka(e,n),{force:!0}).catch(()=>{})},aK=async(e,t)=>{let n=async()=>{await xt(e,{recursive:!0,force:!0}).catch(()=>{})};try{return await Ey(e,{recursive:!1}),n}catch{}let r=await Ax(e).catch(()=>{});if(!(!r||t-r.mtimeMs<UV)){await n();try{return await Ey(e,{recursive:!1}),n}catch{return}}},ky=e=>Dn(e).state,sK=async e=>{let t=await B(e).catch(()=>({})),n=t.failedVersion,r=t.failedAt;return{failedVersion:typeof n=="string"?n:void 0,failedAt:typeof r=="number"?r:void 0}},Za=async(e={})=>{let t=e.now??Date.now,n=Ee;if(Tn(cn(e.env??process.env)))return{outcome:"container",current:n};let r=e.context??ut(),o=e.root??ee(),a;try{let s=await xy(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??P)().catch(()=>({})),d=l.autoUpdate!==!1,u=l.fleetUpdatePolicy?.mode??"auto",f=GV({mode:u,initiator:e.initiator??"tick"});if(!f.allow)return{outcome:f.outcome,current:n};!i&&s.link&&!e.checkOnly&&(d||c)&&await zV(o,s.link,e).catch(()=>{});let m=bs(e.platform??process.platform,e.arch??process.arch);if(!m)return{outcome:"platform-unsupported",current:n};if(a=await(e.latestVersion??Ry)().catch(()=>{}),!a)return{outcome:"unavailable",current:n};let p=a;if(!i&&p===n)return{outcome:"current",current:n,latest:p};if(i&&ja(p,n)<0)return{outcome:"migration-deferred",current:n,latest:p};let h=await sK(ky(o));if((e.respectFailureBackoff===!0||!c)&&h.failedVersion===p&&h.failedAt!==void 0&&t()-h.failedAt<WV)return{outcome:"failed",current:n,latest:p};let g=`${pr}/download/${Xr}${p}`,y=d||c||!VV(u)?void 0:await(e.minimumVersion??YV)(g),w={current:n,latest:p,autoUpdate:d,forced:c,minVersion:y},b=i?KV(w):{...Cx(w),downgradeBlocked:!1};if(b.downgradeBlocked)return{outcome:"migration-deferred",current:n,latest:p};if(!b.apply)return{outcome:"disabled",current:n,latest:p};if(e.checkOnly)return{outcome:i?"migration-available":"available",current:n,latest:p,mandatory:b.mandatory};o===ee()?await et():await lu(o,Ty(o,ee()));let k=Dn(o),C=await aK(k.lock,t());if(!C)return{outcome:i?"migration-available":"available",current:n,latest:p};let S,E;try{await oK(nn(k.launcher));let I=await du(k.versionsDir).catch(()=>{}),_=await du(k.launcher).catch(()=>{}),T=_&&lc(_,I)?_:void 0,W=k.launcher;i&&process.platform==="win32"&&(await Sy(W).catch(()=>{}))?.isFile()&&(E=`${W}.rollback-${process.pid}`,await vy(W,E));let Q=()=>(e.installBinary??qV)({root:o,version:p,asset:m,tagUrl:g});i?S=await nK({install:Q,smoke:e.smoke,rollback:async({link:G,target:ne})=>{E?(await vy(E,G),await xt(ls(G),{force:!0}).catch(()=>{})):T&&T!==ne?await kx(G,T):(await xt(G,{force:!0}),await xt(ls(G),{force:!0}).catch(()=>{}))},repoint:async G=>e.repoint?e.repoint(l,G):tK(l),prune:async()=>{await(e.pruneDurable??(G=>uc(G)))(r)}}):S=await Q(),await rK(S.versionsDir,[p,n]),await(e.refreshHelpersFromInstalled??QV)(S).catch(()=>{}),await xt(ky(o),{force:!0}).catch(()=>{})}finally{E&&await xt(E,{force:!0}).catch(()=>{}),await C()}return{outcome:i?"migrated":"updated",current:n,latest:p,managedPath:S.link,mandatory:b.mandatory}}catch{return a&&await X(ky(o),{failedVersion:a,failedAt:t()},{backup:!1}).catch(()=>{}),{outcome:"failed",current:n,latest:a}}},vx=async(e={})=>{let t=e.context??ut(),n=await xy(t,e.root??ee()),r=Go(e.root??ee());return n.kind==="managed"||(n.kind==="npm"||n.kind==="durable")&&r?{outcome:"current",current:Ee,managedPath:n.link??r}:Za({initiator:"human",...e,context:t,allowNpmMigration:!0})},_o=async(e={})=>{let t=e.context??ut(),n=e.root??ee(),r=await xy(t,n),o=r.kind==="npm"||r.kind==="durable"?Go(n):void 0,a=await(e.load??P)().catch(()=>({})),s=r.kind==="managed"||r.kind==="durable"||r.kind==="npm"||!!o,i=s&&!!bs(e.platform??process.platform,e.arch??process.arch),c=r.link??o,l=Tn(cn(e.env??process.env))?"container":s?i?c?"managed":"will-migrate":"platform-unsupported":"unmanaged";return{version:Ee,managed:!!c,available:i,autoUpdate:a.autoUpdate!==!1,path:c??r.entryPath,state:l,fleetMode:a.fleetUpdatePolicy?.mode??"auto"}};import{z as Sx}from"zod";var iK=5e3,cK=Sx.object({lane:Sx.enum(["subscription","org"]).optional().catch(void 0)}),Ex=async(e,t,n={})=>{if(!t?.trim())return;let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??iK);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=cK.safeParse(await a.json());return s.success?s.data.lane:void 0}catch{return}finally{clearTimeout(o)}},Ix=(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 lK=12e3,dK="anyray-wiring-probe-not-a-real-token",uK={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"}]},Po=e=>{let t=e.replace(/\s+/g," ").trim();return t.length>160?`${t.slice(0,157)}\u2026`:t},Rx=e=>{let t=e.toLowerCase();return t.includes("bedrock")||t.includes("unsupported model")},Dy=e=>{let t=e.toLowerCase();return t.includes("client key required")||["missing_key","key_unknown","key_expired","key_revoked"].some(n=>t.includes(`"${n}"`))},xx=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."],pK=e=>e.includes("no provider key configured for"),Ly=e=>{let t=e.toLowerCase();return t.includes("verified_dev_required")||t.includes("verified developers")},Ny=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>"]}),Fi=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."]}),fK=(e,t,n=[])=>e>=200&&e<300?{kind:"ok",detail:"gateway served a completion with the org key \u2014 traffic flows.",remedy:[]}:pK(t)?{kind:"provider-rejected",providerKeyAbsent:!0,detail:`gateway has no server-side provider key for this lane (HTTP ${e}): ${Po(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")?xx([" \u2022 add a provider key in the console \u2192 Providers (fixes it for everyone), or"]):["If you ONLY use a subscription tool (e.g. Copilot), this org-key check","does not apply \u2014 you can ignore it."]]}:e===401||e===403?Ly(t)?Ny(e):Dy(t)?Fi(e):Rx(t)?{kind:"routed-elsewhere",detail:`gateway routed to the org provider and it rejected the request: ${Po(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}): ${Po(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).",...xx([" \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}: ${Po(t)}`,remedy:[]},mK=(e,t)=>{if(Dy(t))return Fi(e);if(Ly(t))return Ny(e);if(Rx(t))return{kind:"routed-elsewhere",detail:"gateway sent the request to the org provider, not your subscription.",remedy:["Pass-through isn\u2019t being honored for this gateway \u2014 your seat token would","not be used. Check the gateway is current (subscription pass-through support)."]};let n=t.toLowerCase();return e===401||n.includes("authentication_error")||n.includes("invalid bearer")||n.includes('"provider":"anthropic"')?{kind:"ok",detail:"gateway passes your sign-in through to Anthropic \u2014 your Claude seat will be used.",remedy:[]}:e>=200&&e<300?{kind:"ok",detail:"gateway pass-through reached the provider \u2014 your seat will be used.",remedy:[]}:{kind:"unknown",detail:`seat-wiring probe got HTTP ${e}: ${Po(t)}`,remedy:[]}},hK=e=>e.includes("anthropic_messages:")||e.includes("invalid model name passed in model=")||e.includes("to view available models"),yK=(e,t)=>{if(Dy(t))return Fi(e);if(Ly(t))return Ny(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:","set it as the gateway upstream (console \u2192 Routing), or for a","caller-supplied host add it to ANYRAY_CUSTOM_HOST_ALLOWLIST."]};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")||hK(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}: ${Po(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."]}},_y=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)}},gK=async(e,t)=>{if(!e.clientKey)return Fi(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?Fi(o.status):{kind:"unknown",detail:`Cursor hook-auth probe got HTTP ${o.status}: ${Po(a)}`,remedy:o.status===404?["Update the gateway image \u2014 this one predates the content-free /connect/savings key check."]:[]}}finally{clearTimeout(r)}},wK=(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."]}},bK=e=>e.providerKeyAbsent===!0?!1:e.kind==="ok"?!0:null,Ox=async(e,t={})=>{try{return bK(await Ya(e,t))}catch{return null}},Ya=async(e,t={})=>{let n=t.timeoutMs??lK,r=me(e.metadata);try{if(e.authMode!=="placeholder"&&t.tools?.length===1&&t.tools[0]==="cursor")return await gK(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 _y(`${e.anthropicBaseUrl}/v1/messages`,l,Py,n);return yK(d,u)}if(te(e,"anthropic")){let l={Authorization:`Bearer ${dK}`,"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 _y(`${e.anthropicBaseUrl}/v1/messages`,l,Py,n);return mK(d,u)}let s={Authorization:`Bearer ${e.clientKey??e.placeholderKey}`};r&&(s["x-anyray-metadata"]=r);let{status:i,bodyText:c}=await _y(`${e.openaiBaseUrl}/chat/completions`,s,uK,n);return fK(i,c,t.tools??[])}catch(o){return wK(n,o)}};var Tx=async(e,t={})=>{let n=await P(),r=!n.enrolledCert&&n.managedEnrollmentDisabled!==!0&&!!(t.managedEnrollment??To)().enrollmentUrl,o;try{o=Nr(e.gateway,n)}catch(s){return A(K("Anyray connect \u2014 status")),L(`Gateway: ${s.message}`),0}A(K("Anyray connect \u2014 status")),H("Gateway"),A(` Origin: ${qe(o)}`),n.gateway?L(" (cached in ~/.anyray)"):process.env.ANYRAY_GATEWAY_URL?L(" (from $ANYRAY_GATEWAY_URL)"):r?L(" (default \u2014 enrollment is managed by your organization and re-enrolls on the next refresh)"):e.gateway||L(" (default \u2014 not yet connected; run `anyray-connect` to set up)"),H("Identity"),A(` Name: ${n.name??v("(not set)")}`),A(` Team: ${n.team??v("(not set)")}`);let a=cn();a&&(H("Environment"),A(` Remote dev context: ${Ko(a)}`),Tn(a)&&L(" No per-user service manager here \u2014 key refresh rides the Claude Code helper and `anyray-connect` runs, not an OS schedule."),L(" VS Code tools configure the remote server variant backing this window.")),n.enrolledCert&&n.clientKey&&(H("Credential renewal"),M(" Direct gateway routing with a proof-backed key heartbeat."),L(" Renewal extends the same key; tool configuration is not rewritten.")),H("Tools");for(let s of fe){if(!(await s.detect()).installed){L(` ${s.title}: not installed`);continue}if(!s.pointsAt){L(` ${s.title}: installed ${v("(status not introspectable)")}`);continue}let c=await s.pointsAt(o);if(c){if(s.id==="cursor"&&(n.authMode==="auto"||n.authMode==="subscription")){M(` ${s.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Claude/Opus model requests remain Cursor-hosted; only supported local Shell/MCP context is optimized by Anyray."));continue}M(` ${s.title}: pointed at Anyray`)}else{let l=null,d=null;if(s.id===Ua&&s.mcpStatus)try{let u=(await s.mcpStatus()).registered,f=await jd();l=Zd({id:s.id,installed:!0,pointedAt:c,mcpRegistered:u,introspectable:f.authoritative}),d={...f.authoritative?{}:{reason:f.reason},mcpRegistered:u}}catch{l=null,d=null}if((l==="not-routed"||l==="unverifiable")&&d){let u=Yd(l,d);O(` ${s.title}: ${u.headline}`);for(let f of u.detail)A(v(` ${f}`))}else L(` ${s.title}: installed, not pointed at this gateway`)}}return 0};import{existsSync as HK}from"node:fs";import{isAbsolute as GK}from"node:path";import{homedir as VK}from"node:os";import{readFile as AK,stat as CK}from"node:fs/promises";import{homedir as kK,platform as vK}from"node:os";var SK=e=>e.replace(/\\(\d{3})/g,(t,n)=>String.fromCharCode(parseInt(n,8))),EK=e=>e.split(`
|
|
672
|
+
`).map(t=>t.split(" ")[4]).filter(t=>!!t).map(SK),IK=async(e,t,n=async r=>(await CK(r)).isFile())=>{let r=t.endsWith("/")?t:`${t}/`,o=[];for(let a of e)a.startsWith(r)&&await n(a).catch(()=>!1)&&o.push(a);return o},fu=async()=>{if(vK()!=="linux")return[];try{let e=await AK("/proc/self/mountinfo","utf-8");return await IK(EK(e),kK())}catch{return[]}};import{access as xK}from"node:fs/promises";import{constants as RK}from"node:fs";import{platform as OK}from"node:os";var TK=async e=>{try{return await xK(e,RK.F_OK),!0}catch{return!1}},_K=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"]:[],Do=async(e={})=>{let t=e.os??OK(),n=e.exists??TK;for(let r of _K(t))if(await n(r))return!0;return!1};import{execFile as PK}from"node:child_process";import{readFile as DK}from"node:fs/promises";import{homedir as LK,platform as NK}from"node:os";import{promisify as $K}from"node:util";var MK=$K(PK),BK="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",_x=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),FK=async e=>{let t;try{t=await DK(e,"utf-8")}catch(n){return n?.code==="ENOENT"?{readable:!0}:{readable:!1}}try{if(t.trim()==="")return{readable:!0};let n=bt(t);if(!_x(n))return{readable:!1};let r=n[hn],o=n[yn];return{readable:!0,supportsAnyray:_x(r)?r[q]===!0:void 0,bridgeEnabled:typeof o=="boolean"?o:void 0}}catch{return{readable:!1}}},WK=async(e=async()=>(await MK("ps",["ewwx"],{maxBuffer:64*1024*1024})).stdout)=>{if(NK()==="win32")return"unknown";let t;try{t=await e()}catch{return"unknown"}let n=!1;for(let r of t.split(`
|
|
673
|
+
`)){let o=new RegExp(`${BK}=(\\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"},UK=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",mu=(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 ${hn} and ${yn}; 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."}},Px=async(e={})=>{let{installedVariant:t=ta,receiptMode:n=ml,awaitingReload:r=fl,readSettings:o=FK,probeBridge:a=WK,home:s=LK()}=e;try{let i=await t();if(!i)return{state:"not-applicable",bridge:"unknown",detail:mu("not-applicable","unknown")};let c=await n(i,s);if(c!=="copilot-seat"){let f=c===void 0&&await r(i,s);return{state:f?"unknown":"not-applicable",bridge:"unknown",detail:f?"Agents window: VS Code has an Anyray configuration staged but not applied yet, so its state is unknown. Restart VS Code to finish.":mu("not-applicable","unknown")}}let l=await o($s(i)),d=await a(),u=UK({mode:c,settings:l,bridge:d});return{state:u,bridge:d,detail:mu(u,d)}}catch{return{state:"not-applicable",bridge:"unknown",detail:mu("not-applicable","unknown")}}};var rn="connect",hu=e=>e.replace(/-/g,"_"),Dx=e=>{let t=[];e.gateway.reachable!==null&&t.push({tool:rn,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:rn,checkId:"enrollment_cert",status:e.enrollment.expired?"expired":o?"problems":e.enrollment.enrolled?"ok":"unenrolled",...o?{errorClass:"cert_expiring"}:{}}),t.push({tool:rn,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:rn,checkId:"refresh_scheduler",status:i?"ok":"missing",...i?{}:{errorClass:e.serviceRemoval?.removed&&e.serviceRemoval.kinds.includes("scheduler")?"unit_deleted":"refresh_scheduler_missing"}})}if(e.identity.sharedIdentityRisk&&t.push({tool:rn,checkId:"identity_distinct",status:"problems",errorClass:e.identity.sharedIdentityRisk}),e.pendingOps.some(i=>!i.watcherAlive)&&t.push({tool:rn,checkId:"pending_op",status:"problems",errorClass:"watcher_dead"}),e.retrieval){let i=hu(e.retrieval.kind);t.push({tool:rn,checkId:"retrieval_loop",status:i,...i==="ok"?{}:{errorClass:`retrieval_${i}`}})}if(e.verify){let i=e.verify.notApplicableSubscription===!0,c=i?"ok":hu(e.verify.kind);t.push({tool:rn,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:rn,checkId:"hook_lane",status:i?"dark":"ok",...i?{errorClass:hu(e.hookLane.reason)}:{}})}t.push({tool:rn,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:hu(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:rn,checkId:"doctor_report",status:e.problems===0?"ok":"problems"}),t};var KK=e=>{let t=VK();return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e};function Lx(){return Ee}var jK="ctx_doctor-probe-synthetic",ZK=(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: ${By(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 YK(e){return e.identity.personalKeySource==="env"?"env":e.identity.personalKeySource==="profile"?"profile":e.enrollment.enrolled?"enrolled-no-key":"none"}function JK(e){return e.ssoLink?"sso":e.enrolledViaToken?"passwordless":"unknown"}function By(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 Nx=e=>Zd({id:e.id,installed:e.installed,pointedAt:e.pointedAt,mcpRegistered:e.mcp?.registered===!0,introspectable:e.inferenceIntrospectable===!0}),$y=e=>e.pointedAt===!1&&e.tombstoned!==!0&&Nx(e)!=="unverifiable",$x=e=>e.registered&&e.command&&GK(e.command)?HK(e.command):null,XK=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."}},My=e=>($y(e)?1:0)+(e.mcp?.commandOk===!1?1:0)+(e.routingOverrides?.length?1:0)+(e.claudeCodeHookPolicy&&e.claudeCodeHookPolicy!=="fine"?1:0),zK=async(e,t,n)=>e===!1&&t.routingExpected&&!await t.routingExpected(n)?null:e,qK=async(e,t)=>{if(e.length===0)return!1;for(let n of e){let r=t.find(a=>a.id===n);if(!r?.inferenceAuthLanes)return!1;let o=await r.inferenceAuthLanes().catch(()=>["unknown"]);if(o.length===0||o.some(a=>a!=="subscription"&&a!=="native"))return!1}return!0},Mx=async e=>{for(let t of e)if(t.integrationStatus)try{if(!(await t.detect()).installed)continue;if((await t.integrationStatus()).hook_registration==="owned")return!0}catch{}return!1},QK=(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(Io),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(g=>a.has(g[0])&&r(g[1])).map(([g,y])=>({checkId:g,at:y})),f=n(l.flapping)?l.flapping:void 0,m=Array.isArray(f?.checks)?f.checks.filter(g=>typeof g=="string"&&a.has(g)):[],p=f?.reason==="rebroke_same_day"||f?.reason==="repeat_days"?f.reason:void 0,h=f&&r(f.since)&&p&&m.length>0?{since:f.since,reason:p,checks:m}:void 0;(u.length>0||h)&&s.push({tool:c,repaired:u,...h?{flapping:h}:{}})}return s},e2=async(e,t,n,r,o,a,s,i=n,c=Ya,l=!0,d=jo,u=_o,f=It,m=Ba)=>{let p=l?await su(e):null,h=process.env.ANYRAY_CLIENT_KEY?.trim()?"env":t.clientKey?"profile":null,g=J=>J&&Xh(J)?"machine_default":null,y=t.enrolledCert?.payload,w=y?.expiresAt??t.enrolledCertExpiry??null,k=(await a())?.sso??null,C=JK({ssoLink:k,enrolledViaToken:!!t.enrolledTokenHash}),S=!y&&t.managedEnrollmentDisabled!==!0&&!!s().enrollmentUrl,E=wt(),I=await cb(E),_=I?[]:jc(Re({origin:e})),T=[];for(let J of r){let pe=await J.detect(),Be=null;if(pe.installed&&J.mcpStatus)try{let Nu=await J.mcpStatus();Be={...Nu,commandOk:$x(Nu)}}catch{}let yt=pe.installed&&J.id===Ua?await o():void 0,No=pe.installed&&J.pointsAt?await J.pointsAt(e):null,$o=await zK(No,J,t.managedTools??[]),zi=No===!1&&$o===null,qi=$o===!1&&J.routingPendingReload?await J.routingPendingReload().catch(()=>!1):!1,Qi=pe.installed?J.runtimeDiagnostics?await J.runtimeDiagnostics().catch(()=>({routingOverrides:[]})):{routingOverrides:J.routingOverrides?await J.routingOverrides().catch(()=>[]):[]}:{routingOverrides:[]},{routingOverrides:Mo,claudeCodeHookPolicy:ns}=Qi,xe=t.fleetToolPolicy,be=xe?.enabled.includes(J.id)?xe.tiers?.[J.id]??Pa:void 0;T.push({id:J.id,title:J.title,installed:pe.installed,...pe.detail?{detail:pe.detail}:{},pointedAt:$o,...zi?{routingHeld:!0}:{},...qi?{routingPendingReload:!0}:{},...Mo.length?{routingOverrides:Mo}:{},...ns===void 0?{}:{claudeCodeHookPolicy:ns},mcp:Be,...be?{policyTier:be}:{},...t.revertedTools?.includes(J.id)?{tombstoned:!0}:{},...J.id==="cursor"&&(t.authMode==="auto"||t.authMode==="subscription")?{nativeSubscription:!0}:{},...yt===void 0?{}:{inferenceIntrospectable:yt.authoritative,...yt.authoritative?{}:{inferenceUnverifiableReason:yt.reason}}})}let W=i?await(async()=>{let{kind:J,detail:pe,remedy:Be}=await c(Re({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:pe,remedy:Be}})():null,Q=W?.kind==="provider-rejected"&&await qK(t.managedTools??[],r),G=W?{...W,...Q?{notApplicableSubscription:!0}:{}}:null,ne=n?ZK(await Ma({origin:e,apiKey:process.env.ANYRAY_CLIENT_KEY?.trim()||t.clientKey||void 0,metadata:me({user:t.name,team:t.team})},jK,{probe:!0}),{mode:C,ssoLink:k}):null,z=await f().catch(()=>({})),Z=En(z.hookLane),le=i?await Mx(r):!1,U=le?await(async()=>{let J=await m().catch(()=>({verdict:"indeterminate",reason:"unreachable"}));return{...Bh(J,{hookRegistered:le,neverInvoked:$h(Z,Date.now())}),lastInvokedAt:Ld(Z)}})():null,Y=(await hr()).map(J=>({adapter:J.adapter,op:J.op,requestedAt:J.requestedAt,watcherAlive:gr(J.watcherPid)})),re=Y.find(J=>J.adapter==="cursor"),Qe=re?{op:re.op,requestedAt:re.requestedAt,watcherAlive:re.watcherAlive}:null,Ie=!!t.refreshSchedulerEnabled,ke=await Pn(),Rt=Ie&&!ke&&!Je(t),D=await u(),N=t.persistenceOwner==="tray",j=N?await d(t)==="healthy":null,on=await Yw({schedulerEnabled:Ie&&!N&&!Rt,schedulerInstalled:ke,binaryDurable:!tt(jr()),schedulerInstalledOnce:t.refreshSchedulerInstalledOnce===!0,trayManaged:N}),ve=0;p&&!p.reachable&&(ve+=1),N?Ie&&!j&&(ve+=1):Ie&&!ke&&!Rt&&(ve+=1);for(let J of T)ve+=My(J);G&&G.kind!=="ok"&&!G.notApplicableSubscription&&(ve+=1),ne&&ne.kind!=="ok"&&(ve+=1),U?.verdict==="dark"&&(ve+=1),_.length>0&&(ve+=1),ve+=Y.filter(J=>!J.watcherAlive).length;let Vt=await Px();return{report:{format:1,generatedAt:new Date().toISOString()},connect:{version:Lx(),node:process.versions.node,platform:`${process.platform}/${process.arch}`,remoteContext:cn(),fileBindMounts:await fu(),selfUpdate:{managed:D.managed,available:D.available,autoUpdate:D.autoUpdate,state:D.state,fleetMode:D.fleetMode}},gateway:{origin:e,reachable:p?p.reachable:null,detail:p?p.detail:"not probed (--quick)"},refreshScheduler:{enabled:Ie,installed:ke,owner:N?"tray":"os",...N?{trayHealthy:!!j}:{},...Rt?{retired:!0}:{}},serviceRemoval:on,fleetdPresent:await Do(),identity:{user:t.name??null,team:t.team??null,authMode:t.authMode??null,personalKeySource:h,clientKeyExpiresAt:t.clientKeyExpiresAt??null,sharedIdentityRisk:g(t.name)},enrollment:{enrolled:!!y,deploymentId:y?.deploymentId??null,issuedAt:y?.issuedAt??null,expiresAt:w,expired:w?Date.parse(w)<Date.now():null,orgMode:C,ssoLink:k,managedPending:S},shell:{profilePath:E,blockPresent:I,staleExports:_},tools:T,...t.fleetToolPolicy?{fleetPlan:Pd(t,t.fleetToolPolicy,!1)}:{},cursorQueue:Qe,pendingOps:Y,ambientRepairs:QK(z,r),verify:G,retrieval:ne,hookLane:U,agentsWindow:Vt,problems:ve}},t2=e=>{if(e.serviceRemoval.suspected){if(!e.serviceRemoval.removed){H("Automatic key refresh"),O(" This seat expects the key-refresh schedule, but no unit is installed and"),O(" Anyray has no record of ever installing one here. Re-run `anyray-connect`"),O(" to install it.");for(let t of e.serviceRemoval.missingPaths)A(v(` expected: ${t}`));return}H("Endpoint security"),O(" Anyray installed these background services, but their files are gone from disk \u2014"),O(" endpoint-security software (SentinelOne, CrowdStrike, Defender \u2026) quarantines them"),O(" 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."))}},n2=e=>{if(A(K("Anyray connect \u2014 doctor")),e.connect.remoteContext||e.connect.fileBindMounts.length>0){H("Environment"),e.connect.remoteContext&&(A(` Remote dev context: ${Ko(e.connect.remoteContext)}`),Tn(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.")));for(let c of e.connect.fileBindMounts)A(` Bind-mounted config file: ${KK(c)}`),A(v(" A file mounted into this container cannot be replaced atomically; connect writes it in place (verified). Mount the parent directory instead to restore atomic writes."))}switch(H("CLI updates"),e.connect.selfUpdate.state){case"managed":M(" Managed standalone binary installed; one updater owns this seat."),e.connect.selfUpdate.fleetMode==="off"?A(v(" Your organization manages Connect updates; this machine downloads nothing.")):e.connect.selfUpdate.fleetMode==="directed"?A(v(" Your organization applies Connect updates centrally; an administrator pushes new versions.")):e.connect.selfUpdate.autoUpdate||O(" Automatic CLI updates are off (`anyray-connect update --auto on`).");break;case"will-migrate":O(" 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":O(" 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?M(` 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?M(" 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?M(" Scheduled \u2014 your gateway key re-mints every ~30 min, so no tool 401s on a stale key mid-session."):e.refreshScheduler.retired?M(" Retired \u2014 this key does not expire between sessions, and your tools already trigger renewal. No background schedule is needed."):(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.")))),t2(e),H("Personal key"),YK(e)){case"env":M(" Personal gateway key present ($ANYRAY_CLIENT_KEY).");break;case"profile":M(" Personal gateway key present (enrolled via connect).");break;case"enrolled-no-key":O(" 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:if(e.enrollment.managedPending){O(" Enrollment is managed by your organization, but this machine holds no local enrollment state."),A(v(" Fix: none needed \u2014 it re-enrolls unattended on the next refresh; run `anyray-connect refresh` to do it now."));break}O(" Enrollment required \u2014 no personal gateway key is available."),A(v(` Fix: ${By(e.enrollment.orgMode,e.enrollment.ssoLink)}, or set $ANYRAY_CLIENT_KEY to a minted ark_ key.`))}e.enrollment.enrolled&&(e.enrollment.expired?O(` Enrollment cert expired ${v(`(${e.enrollment.expiresAt})`)} \u2014 the next run re-enrolls.`):M(` Enrollment cert valid until ${e.enrollment.expiresAt} ${v(`(deployment ${e.enrollment.deploymentId})`)}`)),e.shell.staleExports.length>0&&(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(` ${gc(c)}.`),A(v(` ${wc(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."))):M(` ${c.title}: retrieval MCP server registered ${v("(anyray_retrieve / anyray_recall)")}`):(O(` ${c.title}: retrieval MCP server not registered \u2014 externalized output can't be pulled back.`),A(v(` Fix: ${XK(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){M(` ${c.title}: native Cursor subscription; Anyray hooks/MCP active`),A(v(" Note: Claude/Opus model requests remain Cursor-hosted. Anyray can optimize and measure only the supported local Shell/MCP context seams.")),a(c);continue}M(` ${c.title}: pointed at ${e.gateway.origin}`),o(c),c.id==="claude-code"&&A(v(" Note: settings.json routing covers the Claude Code CLI and VS Code extension. For Claude Desktop, use the supported third-party Gateway setup; verified macOS builds can use the Claude Code subscription helper, while Windows remains API-billed.")),c.id===Ua&&A(v(` ${ak(gt("migrate"),gt("desktop"))}`)),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=Nx(c);if(l==="not-routed"||l==="unverifiable"){let d=Yd(l,{...c.inferenceUnverifiableReason?{reason:c.inferenceUnverifiableReason}:{},mcpRegistered:c.mcp?.registered===!0});O(` ${c.title}: ${d.headline}`);for(let u of d.detail)A(v(` ${u}`));l==="unverifiable"&&(r=!0)}else c.tombstoned?c.policyTier==="required"?(O(` ${c.title}: reverted locally against admin policy (out of compliance)`),A(v(` Re-enroll with \`anyray-connect --tools ${c.id}\`.`))):c.policyTier==="locked"?O(` ${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&&(O(" 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=pt(c.adapter)?.title??c.adapter;c.watcherAlive?O(` ${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=pt(l.tool)?.title??l.tool,u=l.repaired.map(({checkId:m,at:p})=>`${c(m)} ${new Date(p).toISOString().slice(0,10)}`);l.flapping&&u.push(`flapping since ${new Date(l.flapping.since).toISOString().slice(0,10)} (${l.flapping.reason})`);let f=` ${d}: ${u.join("; ")}`;l.flapping?O(f):A(f)}}let i=e.fleetPlan;if(i&&(i.freshIds.length>0||i.tombstonedIds.length>0)){H("Fleet policy");let c=l=>l.map(d=>pt(d)?.title??d).join(", ");i.freshIds.length>0&&A(` Pending enrollment (the next policy sync applies): ${c(i.freshIds)}`),i.tombstonedIds.length>0&&O(` Out of compliance (reverted against required policy): ${c(i.tombstonedIds)}`)}if(e.verify)if(H("Auth probe"),e.verify.notApplicableSubscription)M(" Provider-key verification is not applicable to subscription/native inference lanes.");else if(e.verify.kind==="ok")M(` ${e.verify.detail}`);else{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")M(` ${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")M(` ${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{O(` ${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"),O(` ${e.agentsWindow.detail}`)):e.agentsWindow?.state==="ready"&&(H("VS Code Agents window"),M(` ${e.agentsWindow.detail}`)),H("Summary"),e.problems===0?(e.verify?M(" No problems found."):M(" No configuration problems found (no request was sent \u2014 drop `--no-verify` to test one)."),A(v(" Sharing with support? `anyray-connect doctor --json` prints this as a content-free report."))):R(` ${e.problems} problem(s) found \u2014 see fixes above.`)},r2=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}),o2=async(e,t)=>{let n=e.hookLane;if(!n||n.verdict!=="dark"||n.reason!=="key_rejected")return null;if(!Dh(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??Ba,o,a=async()=>(o??=await r().catch(()=>({verdict:"indeterminate",reason:"unreachable"})),o),s=await(t.refreshKey??Ht)({force:!0,hookLaneRepair:!0,probeHookLane:a}).catch(()=>"failed"),i=await a(),c=En((await(t.readRefreshState??It)().catch(()=>({}))).hookLane),l=Bh(i,{hookRegistered:await Mx(t.adapters??fe).catch(()=>!1),neverInvoked:$h(c,Date.now())}),d=s==="disabled"?"Hook lane: key refresh is disabled here (ANYRAY_REFRESH_DISABLE), so no key was minted and the finding stands.":l.verdict==="live"?"Hook lane: re-minted the personal key and rewrote the configured tools \u2014 the lane answers again.":l.verdict==="indeterminate"?`Hook lane: re-mint reported '${s}', but the confirming probe could not establish the lane's state \u2014 nothing is proven fixed and the finding stands.`:`Hook lane: re-mint reported '${s}' and the lane is still not live \u2014 re-enroll (see the Hook lane fixes above).`;return{hookLane:{...l,lastInvokedAt:Ld(c)},note:d}},a2=async(e,t,n={})=>{let r=n.adapters??fe,o=n.resolveTarget??Ue,a=n.applyTools??Wt,s=await o2(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(w=>w.installed&&($y(w)||w.mcp?.commandOk===!1||w.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(w=>({id:w.id,title:w.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 ${By(e.enrollment?.orgMode??"unknown",e.enrollment?.ssoLink??null)}, then re-run.`]};let u=new Set(t.managedTools??[]),f=[],m=[...c.notes],p=[];for(let w of l){let b=r.find(k=>k.id===w.id);if(!u.has(w.id)||!b){f.push({id:w.id,title:w.title,status:"skipped-unmanaged"});continue}p.push(b)}f.length>0&&m.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(p,d.target),g=new Map,y=0;for(let w of h){if(f.push(w),!vo(w))continue;let b=e.tools.find(T=>T.id===w.id);if(!b)continue;let k=r.find(T=>T.id===w.id),C=b.mcp;if(k?.mcpStatus)try{let T=await k.mcpStatus();C={...T,commandOk:$x(T)}}catch{}let S=$y(b)?!0:b.pointedAt;if(k?.pointsAt&&b.pointedAt!==null)try{S=await k.pointsAt(e.gateway.origin)}catch{}let E=b.routingOverrides,I=b.claudeCodeHookPolicy;if(k?.runtimeDiagnostics)try{let T=await k.runtimeDiagnostics();E=T.routingOverrides.length?T.routingOverrides:void 0,I=T.claudeCodeHookPolicy}catch{}else if(k?.routingOverrides)try{let T=await k.routingOverrides();E=T.length?T:void 0}catch{}let _={...b,pointedAt:S,mcp:C,...E?{routingOverrides:E}:{},...I===void 0?{}:{claudeCodeHookPolicy:I}};E||delete _.routingOverrides,I===void 0&&delete _.claudeCodeHookPolicy,g.set(w.id,_),y+=My(b)-My(_)}return{entries:f,remainingProblems:Math.max(0,e.problems-y-i),refreshedTools:g,...s?{hookLane:s.hookLane}:{},notes:m}},s2=e=>{H("Repair"),e.entries.length===0&&M(" Nothing to repair.");for(let t of e.entries)t.status==="configured"||t.status==="reverted"?M(` ${t.title}: re-applied`):t.status==="queued"?M(` ${t.title}: re-apply queued (completes when the app quits)`):t.status.startsWith("skipped-")?A(v(` ${t.title}: ${t.status}`)):R(` ${t.title}: ${t.status}`);for(let t of e.notes)A(v(` ${t}`))},yu=async(e,t={})=>{let n=await P();if(e.securityReview){if(e.json){let c;try{c=n.gateway?new URL(n.gateway).hostname:void 0}catch{}return console.log(JSON.stringify(Jw({connectVersion:Lx(),...c?{gatewayHost:c}:{}}),null,2)),0}if(!e.silent){A(K("Anyray connect \u2014 security review"));for(let c of Xw())A(c?` ${c}`:"")}return 0}let r;try{r=Nr(e.gateway,n)}catch(c){return e.silent?1:e.json?(console.log(JSON.stringify({error:c.message})),1):(A(K("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(K("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 e2(r,n,!!e.verify&&!e.quick,t.adapters??fe,t.inferenceIntrospection??jd,t.fleetBootstrap??Pr,t.managedEnrollment??To,o,t.verifyAuth??Ya,!e.quick,t.checkTray??jo,t.updateStatus??_o,t.readRefreshState??It,t.probeHookLane??Ba),s=e.repair?await a2(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(r2(i),null,2)):(n2(i),s&&s2(s)));try{e.quick||await(t.reportHealth??AE)(Dx(i),i.connect.version)}catch{}return i.problems===0?0:1};var i2=()=>{let e=[];for(let t of fe){let n=t.skillsDir?.();n&&e.push(n)}return e},Bx=async e=>{let t=await P();A(K("Anyray connect \u2014 sync"));let n;try{n=Nr(e.gateway,t)}catch(s){return R(s.message),1}L(`Gateway: ${n}`);let r=dI(t.clientKey,"anyray-placeholder"),o;try{o=await La(n,r)}catch(s){return R(`Team policy sync failed: ${Th(s)}`),1}let a=i2();if(a.length===0)c2();else if(o.skills.length===0)L("No team skills published yet \u2014 nothing to sync.");else{let s=await sE(o,a,t.syncedSkills??{});H("Skills");for(let i of s.results)i.written?M(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2192 ${i.files.length} file(s)`):L(` ${i.name} ${v(`(${i.id}@${i.version})`)} \u2014 up to date`);try{await ce({...t,syncedSkills:s.versions,syncedAt:s.updatedAt??new Date().toISOString()})}catch(i){L(`Could not record sync state: ${i instanceof Error?i.message:String(i)}`)}H("Summary"),A(` ${qe(String(s.changed))} updated, ${s.unchanged} unchanged, across ${a.length} tool dir(s).`)}try{let s=await Na(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&&L(` Locally reverted against admin policy (out of compliance): ${s.toolsTombstoned.join(", ")}. Re-run \`anyray-connect --tools <id>\` to re-enroll.`))}catch(s){L(`Fleet policy reconcile skipped: ${Th(s)}`)}return 0},c2=()=>{L("No installed tool exposes a skills directory \u2014 nothing to sync.")};import{gzip as pj}from"node:zlib";import{promisify as fj}from"node:util";var Br={maxChars:12e3,headChars:6e3,tailChars:4e3,middleWindows:3},Fy=e=>({text:e,trimmed:!1,originalChars:e.length,trimmedChars:e.length,charsRemoved:0,estTokensSaved:0}),Fx=e=>`
|
|
674
674
|
|
|
675
675
|
\u2026[anyray-hook trimmed ${e} chars (~${Math.round(e/3.3)} tokens) \u2014 elided locally, cache-safe]\u2026
|
|
676
676
|
|
|
677
|
-
`,gu=(e,t={})=>{if(typeof e!="string")return Fy(String(e??""));let n=Math.max(1,t.maxChars??Br.maxChars);if(e.length<=n)return Fy(e);let r=e.length,o=Math.max(0,t.headChars??Br.headChars),a=Math.max(0,t.tailChars??Br.tailChars),s=Math.max(0,t.middleWindows??Br.middleWindows),i=100*(s+2),c=Math.max(1,n-1-i);o+a>c&&(a=Math.min(a,c),o=Math.max(0,c-a));let l=o,d=r-a,u=[];o>0&&u.push([0,o]);let f=c-o-a;if(s>0&&f>0&&d>l){let y=d-l,
|
|
677
|
+
`,gu=(e,t={})=>{if(typeof e!="string")return Fy(String(e??""));let n=Math.max(1,t.maxChars??Br.maxChars);if(e.length<=n)return Fy(e);let r=e.length,o=Math.max(0,t.headChars??Br.headChars),a=Math.max(0,t.tailChars??Br.tailChars),s=Math.max(0,t.middleWindows??Br.middleWindows),i=100*(s+2),c=Math.max(1,n-1-i);o+a>c&&(a=Math.min(a,c),o=Math.max(0,c-a));let l=o,d=r-a,u=[];o>0&&u.push([0,o]);let f=c-o-a;if(s>0&&f>0&&d>l){let y=d-l,w=Math.max(1,Math.floor(f/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(w/2)),S=Math.max(l,C-w),E=e.lastIndexOf(`
|
|
678
678
|
`,S);E>=l&&(S=E+1);let I=e.indexOf(`
|
|
679
|
-
`,C);I!==-1&&I<d&&(C=I),C>S&&u.push([S,C])}}a>0&&u.push([d,r]),u.sort((y,
|
|
679
|
+
`,C);I!==-1&&I<d&&(C=I),C>S&&u.push([S,C])}}a>0&&u.push([d,r]),u.sort((y,w)=>y[0]-w[0]);let m=[];for(let[y,w]of u){let b=m[m.length-1];b&&y<=b[1]?b[1]=Math.max(b[1],w):m.push([y,w])}let p="",h=0;for(let[y,w]of m)y>h&&(p+=Fx(y-h)),p+=e.slice(y,w),h=w;if(r>h&&(p+=Fx(r-h)),p.length>=r)return Fy(e);let g=r-p.length;return{text:p,trimmed:!0,originalChars:r,trimmedChars:p.length,charsRemoved:g,estTokensSaved:Math.round(g/3.3)}},l2=["stdout","content","output","text","result"],Wx=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} ---
|
|
680
680
|
${d}`);s&&i.push(`--- MCP structuredContent ---
|
|
681
681
|
${JSON.stringify(t.structuredContent)}`);let c=a[0],l=new Set(a.map(({index:d})=>d));return{body:i.join(`
|
|
682
682
|
|
|
683
|
-
`),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((f,m)=>l.has(m)?m!==c?.index?[]:[{...c.part,text:d}]:[f]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n=
|
|
684
|
-
`),s=0,i=0;for(let c of a)c.trim()&&(s++,
|
|
685
|
-
${e.slice(-Wy)}`:e;return
|
|
686
|
-
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},
|
|
687
|
-
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},
|
|
688
|
-
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},jx=(e,t)=>{if(typeof t!="string"||t.length===0||
|
|
689
|
-
`).filter(s=>s.trim()!==""),r=Uy(e),o=
|
|
683
|
+
`),rebuild:d=>{let u={...t};return delete u.structuredContent,u.content=o.flatMap((f,m)=>l.has(m)?m!==c?.index?[]:[{...c.part,text:d}]:[f]),c||(u.content=[{type:"text",text:d},...u.content]),u}}}}let n=l2.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 d2=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},Wi={minChars:8e3,minDataLineRatio:.6,minDataLines:20},wu=(e,t={})=>{if(typeof e!="string")return!1;let n=t.minChars??Wi.minChars;if(e.length<n)return!1;let r=t.minDataLineRatio??Wi.minDataLineRatio,o=t.minDataLines??Wi.minDataLines,a=e.split(`
|
|
684
|
+
`),s=0,i=0;for(let c of a)c.trim()&&(s++,d2(c)&&i++);return s===0||i<o?!1:i/s>=r};var Ui=(e,t=200)=>e.length>t?`${e.slice(0,t)}\u2026`:e,bu={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"},Gx=new Set(["npm","pnpm","yarn","bun"]),Au=e=>{let t=e.lastIndexOf("/");return t===-1?e:e.slice(t+1)},u2=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=Au(r[0]);if(o in bu)return bu[o];if((o==="npx"||o==="bunx")&&r[1]){let a=Au(r[1]);if(a in bu)return bu[a]}return o==="git"&&r[1]==="grep"?"grep":o==="node"&&r.includes("--test")||Gx.has(o)&&(r[1]==="test"||r[1]==="t"||r[1]==="run"&&r[2]&&/test/i.test(r[2]))?"test-run":null},Uy=e=>{if(typeof e!="string"||!e.trim())return null;for(let t of e.split(/\|\||&&|;|\||\n/)){let n=u2(t);if(n)return n}return null},p2={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},f2=/^(build|lint|typecheck|type-check|check|compile|tsc)/i,m2=(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},Vx=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=Au(r[0]);if(Gx.has(o)){let i=r[1]==="run"?r[2]:r[1];return i!=null&&f2.test(i)}let a=r[1]?Au(r[1]):void 0;if(m2(o,a,r))return!1;let s=p2[o];return s===void 0?!1:s===null||a!=null&&s.has(a)},h2=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==="]"},y2=e=>{for(let t=1;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==='"')return t}return-1},g2=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=y2(t);return r>0&&t[r+1]===":"},w2=80,b2=e=>{if(e.length===0)return!1;let t=Math.ceil(e.length/w2),n=0,r=0;for(let o=0;o<e.length;o+=t)n++,g2(e[o])&&r++;return n>0&&r/n>.3},A2=/^(import |export |from |const |let |var |function |class |def |async |await |#include |@charset |\/\/ |\/\* |\* )/,C2=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();(A2.test(o)||/[{};]$/.test(o))&&n++}return n/t.length>.3},k2=[/\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],Wy=8192,v2=e=>{let t=e.length>2*Wy?`${e.slice(0,Wy)}
|
|
685
|
+
${e.slice(-Wy)}`:e;return k2.some(n=>n.test(t))},S2=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),E2=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),I2=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},x2=e=>/^(PASS|ok)\b/.test(e)||/^--- PASS: /.test(e)||/^\s*(✓|✔)/.test(e)||/\[\s*\d+%\]$/.test(e),Ux=e=>{let t=[],n=0,r=0,o=0;for(let s of e){let i=s.trim();if(!i)continue;if(E2(i)){t.push(Ui(i));continue}let c=I2(i);if(c){if(n>=10){r++,o=0;continue}n++,t.push(Ui(c)),o=12;continue}S2(i)||x2(i)||o>0&&(t.push(Ui(s)),o--)}if(t.length===0)return null;let a=r>0?` (+${r} more)`:"";return{text:t.join(`
|
|
686
|
+
`),router:"test-run",stat:`test run: kept ${n} failure block(s)${a}`,kept:n,total:n+r}},R2=/^([^\s:]+):(\d+):(?:\d+:)?(.*)$/,Kx=e=>{let t=R2.exec(e);return t&&/[/.]/.test(t[1])?t:null},O2=/^([^\s:]+)-(\d+)-/,T2=e=>{if(e==="--")return!0;let t=O2.exec(e);return t!=null&&/[/.]/.test(t[1])},_2=e=>{let t=e.slice(0,50);if(t.length<3)return!1;let n=t.filter(r=>Kx(r)!=null).length;return n>=3&&n/t.length>=.7},Hx=(e,t)=>{let n=new Map,r=0,o=0;for(let c of e){let l=Kx(c);if(!l){if(T2(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(Ui(` ${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(`
|
|
687
|
+
`),router:"grep",stat:`grep: ${o} hits in ${n.size} files, kept ${s}`,kept:s,total:o}},P2=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(),D2=e=>{if(e.length<12)return null;let t=new Map,n=[];for(let o of e){let a=P2(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=Ui(a.trim());return s>1?`[\xD7${s}] ${i}`:i}).join(`
|
|
688
|
+
`),router:"log-dedup",stat:`log: ${e.length} lines \u2192 ${n.length} unique`,kept:n.length,total:e.length}},jx=(e,t)=>{if(typeof t!="string"||t.length===0||h2(t))return null;let n=t.split(`
|
|
689
|
+
`).filter(s=>s.trim()!==""),r=Uy(e),o=v2(t),a=null;return r==="test-run"&&o?a=Ux(n):r==="grep"&&(a=Hx(n,.5)),a||(o?a=Ux(n):_2(n)?a=Hx(n,.7):!C2(n)&&!b2(n)&&(a=D2(n))),!a||a.text.length>=t.length?null:a},Zx=e=>`full output: Read ${e}`,Hy=(e,t)=>t?`
|
|
690
690
|
|
|
691
691
|
\u2026[anyray-hook digest \u2014 ${e}; ${Zx(t)}]\u2026`:`
|
|
692
692
|
|
|
693
693
|
\u2026[anyray-hook digest \u2014 ${e}]\u2026`,Yx=e=>`
|
|
694
694
|
|
|
695
|
-
\u2026[anyray-hook \u2014 ${Zx(e)}]\u2026`;import{createHash as
|
|
696
|
-
`):"",
|
|
697
|
-
`).slice(0,p0)};var
|
|
698
|
-
`);i=l>=0?i.slice(l+1):""}let c=
|
|
699
|
-
`));return
|
|
700
|
-
`:"",zy=e=>Math.round(Math.max(0,e)/4),m0=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",
|
|
701
|
-
${m0(r.tool_input)}`:m0(r.tool_input),y=c0(o,
|
|
702
|
-
`,{mode:384}),await
|
|
695
|
+
\u2026[anyray-hook \u2014 ${Zx(e)}]\u2026`;import{createHash as L2}from"node:crypto";import{homedir as N2}from"node:os";import{join as Fr}from"node:path";import{chmod as $2,mkdir as M2,readdir as qx,stat as Gi,unlink as Hi,utimes as B2,writeFile as Vy}from"node:fs/promises";var Cu={ttlMs:720*60*60*1e3,maxAgeMs:2160*60*60*1e3,maxTotalBytes:128*1024*1024,maxFiles:2e4,sweepIntervalMs:3600*1e3,writeGraceMs:30*1e3},Qx=".swept",F2=".sweeping",Jx=64,Xx=448,Ky=384,jy=()=>(process.env.ANYRAY_HOOK_TEE??"").trim().toLowerCase()==="off",e0=e=>Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0?e.birthtimeMs:e.mtimeMs,Zy=async()=>{let e=process.env.ANYRAY_HOOK_TEE_DIR;if(e)return e;let t=ee();try{if((await Gi(t)).isDirectory())return Fr(t,"hook-tee")}catch{}return Fr(N2(),".anyray-hook-tee")},W2=/^(?:ctx_)?([0-9a-f]{16})$/,Yy=e=>e.trim().match(W2)?.[1]??null,Jy=async e=>{let t=Yy(e);return t?Fr(await Zy(),`${t}.txt`):null},U2=async(e,t={})=>{let n=t.limits??Cu;try{let r=Date.now(),o=(await qx(e)).filter(c=>c.endsWith(".txt")),a=[];for(let c=0;c<o.length;c+=Jx)await Promise.all(o.slice(c,c+Jx).map(async l=>{let d=Fr(e,l);try{let u=await Gi(d);if(!u.isFile())return;let f=r-u.mtimeMs>n.ttlMs||r-e0(u)>n.maxAgeMs;if(d!==t.protect&&f){await Hi(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 Hi(c.path).catch(()=>{})}}catch{}},t0=async e=>{try{return Date.now()-(await Gi(e)).mtimeMs}catch{return Number.POSITIVE_INFINITY}},zx=async e=>{try{return await Vy(e,"",{mode:Ky,flag:"wx"}),!0}catch{return!1}},H2=async(e,t)=>{let n=Cu,r=Fr(e,F2),o=Fr(e,Qx);if(!await zx(r)){let a=0;try{a=Date.now()-(await Gi(r)).mtimeMs}catch{return!1}if(a<=n.sweepIntervalMs||(await Hi(r).catch(()=>{}),!await zx(r)))return!1}try{return await t0(o)<n.sweepIntervalMs?!1:(await Vy(o,"",{mode:Ky}).catch(()=>{}),await U2(e,{protect:t}),!0)}finally{await Hi(r).catch(()=>{})}},Gy=async(e,t)=>await t0(Fr(e,Qx))<Cu.sweepIntervalMs?!1:H2(e,t),G2=async()=>{try{let e=await Zy();if(!(await qx(e)).some(t=>t.endsWith(".txt")))return;await Gy(e)}catch{}},n0=async e=>{if(jy())return await G2(),null;try{let t=await Zy();await M2(t,{recursive:!0,mode:Xx}),await $2(t,Xx).catch(()=>{});let n=`${L2("sha256").update(e).digest("hex").slice(0,16)}.txt`,r=Fr(t,n),o=Date.now();try{let a=await Gi(r);if(a.isFile()){if(o-e0(a)<=Cu.maxAgeMs){let s=new Date(o);return await B2(r,s,s).catch(()=>{}),await Gy(t,r),r}await Hi(r).catch(()=>{})}}catch{}return await Vy(r,e,{mode:Ky}),await Gy(t,r),r}catch{return null}};import{createHash as V2}from"node:crypto";import{homedir as r0}from"node:os";import{join as Xy}from"node:path";import{readFile as K2,writeFile as j2,chmod as Z2,stat as Y2,unlink as J2}from"node:fs/promises";var X2=200,z2=1440*60*1e3,q2=4e6,o0=()=>(process.env.ANYRAY_HOOK_CACHE??"").trim().toLowerCase()==="off",a0=(e,t)=>{let n=process.env[e];if(!n)return t;let r=Number(n);return Number.isFinite(r)&&r>0?r:t},Q2=()=>a0("ANYRAY_HOOK_CACHE_MAX_ENTRIES",X2),s0=()=>a0("ANYRAY_HOOK_CACHE_TTL_MS",z2),i0=async()=>{let e=process.env.ANYRAY_HOOK_CACHE_FILE?.trim();if(e)return e;let t=Xy(r0(),".anyray");try{if((await Y2(t)).isDirectory())return Xy(t,"hook-cache.json")}catch{}return Xy(r0(),".anyray-hook-cache.json")},c0=(e,t,n)=>V2("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex"),l0=async e=>{try{let t=JSON.parse(await K2(e,"utf-8"));if(t?.v===1&&t.entries&&typeof t.entries=="object")return t}catch{}return{v:1,entries:{}}},d0=async e=>{if(o0())return null;try{let n=(await l0(await i0())).entries[e];return!n||Date.now()-n.at>s0()?null:typeof n.o=="string"?{optimized:!0,output:n.o,tokensSaved:Number.isFinite(n.t)?n.t:0}:{optimized:!1}}catch{return null}},ej=e=>{let t=Date.now(),n=s0(),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=Q2();for(let i of r){if(o.length>=s||(a+=i[1].o?.length??0,a>q2&&o.length>0))break;o.push(i)}return Object.fromEntries(o)},u0=async(e,t)=>{if(o0())return;let n;try{let r=await i0(),o=await l0(r);o.entries[e]=t.optimized?{o:t.output,t:t.tokensSaved,at:Date.now()}:{at:Date.now()},o.entries=ej(o.entries),n=`${r}.${process.pid}.tmp`,await j2(n,JSON.stringify(o),{mode:384}),await Z2(n,384),await ye(n,r)}catch{if(n)try{await J2(n)}catch{}}};import{open as tj,stat as nj}from"node:fs/promises";var p0=600,rj=3,oj=256e3,aj=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(`
|
|
696
|
+
`):"",sj=e=>e.startsWith("<command-name>")||e.startsWith("<command-message>")||e.startsWith("<local-command-"),ij=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},cj=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=aj(o.message?.content).trim();if(!(!a||sj(a))&&(t.unshift(a),n+=a.length,t.length>=rj||n>=p0))break}return t.join(`
|
|
697
|
+
`).slice(0,p0)};var lj=e=>/(^|[\\/])subagents[\\/]/i.test(e),dj=e=>/\.jsonl$/i.test(e),uj=e=>e.some(t=>(t.type==="user"||t.type==="assistant")&&t.message!==null&&typeof t.message=="object"),f0=async e=>{let t={intent:"",kind:"unknown"};if(!e||!dj(e))return t;let n;try{let{size:r}=await nj(e),o=Math.max(0,r-oj),a=r-o;if(a<=0)return t;n=await tj(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(`
|
|
698
|
+
`);i=l>=0?i.slice(l+1):""}let c=ij(i.split(`
|
|
699
|
+
`));return uj(c)?{intent:cj(c),kind:lj(e)?"subagent":"main"}:t}catch{return t}finally{try{await n?.close()}catch{}}};var mj=3e3,hj=1500,yj=()=>{let e=Number(process.env.ANYRAY_HOOK_OPTIMIZE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:mj},gj={claude:"claude-code",codex:"codex",cursor:"cursor",opencode:"opencode"},wj=new Set(["claude","opencode"]),bj=(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:gj[t]})},Aj={cacheGet:async()=>null,cachePut:async()=>{}},Cj=(e,t={cacheGet:d0,cachePut:u0,tee:n0})=>e==="claude"?t:Aj,kj=1e3,vj=e=>JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:e}}),ku=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Sj=e=>{try{let t=JSON.parse(e);if(!ku(t)||typeof t.tool_name!="string"||!t.tool_name.startsWith("MCP:")||typeof t.tool_output!="string")return;let n=JSON.parse(t.tool_output);return ku(n)?JSON.stringify({...t,tool_output:n}):void 0}catch{return}},Ej=e=>{try{let t=JSON.parse(e);return ku(t)&&typeof t.tool_name=="string"&&t.tool_name.startsWith("MCP:")}catch{return!1}},Ij=e=>ku(e)?`${JSON.stringify({updated_mcp_tool_output:e})}
|
|
700
|
+
`:"",zy=e=>Math.round(Math.max(0,e)/4),m0=e=>typeof e=="string"?e:e!=null?JSON.stringify(e):"",xj=new Set(["Edit","MultiEdit","Write","NotebookEdit","ExitPlanMode","TodoWrite"]),Rj=e=>/(^|[^a-z0-9])anyray_(retrieve|recall)$/i.test(e.trim()),Oj=["tool_output","tool_response","tool_result"],Tj=e=>{for(let t of Oj)if(t in e)return e[t]},_j=(e,t)=>{if(e!=="Bash"||t==null||typeof t!="object")return"";let n=t.command;return typeof n=="string"?n:""},Pj=120,Dj=async(e,t,n)=>{if(!e.digestCommand||!t||n.length<(e.digestGate??kj))return null;let r=null;try{r=e.digestCommand(t,n)}catch{return null}if(!r)return null;let o=Hy(r.stat,null).length+Pj;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=Hy(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}}},Lj=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(xj.has(o)||Rj(o))return n;let a=Wx(Tj(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(h0(o)&&l.retrievalContext!=="available")return n;let d=await Dj(t,_j(o,r.tool_input),i),u=d?.body??i,f=d?.marker??"";if(!d&&i.length<=t.sizeGate&&(!t.mediumBand||!wu(i,{minChars:hj})))return n;let m=i.length-u.length-f.length,p=async(S,E,I=S.length+f.length)=>{let _=d?.teePath??null;if(!_&&t.tee)try{_=await t.tee(i)}catch{_=null}let T=_?S.replaceAll("; not retrievable in this context]","]"):S,W=_&&!f?Yx(_):"",Q=T+f+W,G=W.length,ne=Q;if(t.finalizeOutput)try{let U=t.finalizeOutput(Q);U.length<=Q.length&&(ne=U)}catch{ne=Q}let z=Q.length-ne.length,Z=zy(Math.max(0,m-G))+E+zy(z);Z>0&&await s({originalChars:i.length,trimmedChars:Math.max(0,I+G-z),estTokensSaved:Z,...d&&{digest:d.decision}});let le=a.rebuild(ne);return{stdout:vj(le),replacement:le}},h=async()=>d?p(u,0):n;if(d&&u.length<=t.sizeGate)return p(u,0);let g=l.intent?`${l.intent}
|
|
701
|
+
${m0(r.tool_input)}`:m0(r.tool_input),y=c0(o,g,u),w=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?p(b.output,b.tokensSaved):h();let k=null;try{k=Wj(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 w({optimized:!0,output:k.output,tokensSaved:zy(u.length-k.output.length)}),p(k.output,0,u.length+f.length)):(await w({optimized:!1}),h());let C;try{C=t.localTrim(u)}catch{return h()}return C.trimmed?p(C.text,C.estTokensSaved):h()},Vi=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")}},$j=fj(pj),Mj=async e=>{try{let t=await $j(e);return{body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),encoding:"gzip"}}catch{return{body:e}}},h0=e=>/(^|[^a-z0-9])anyray_read$/i.test(e.trim()),Bj=e=>{let t=e.trim();return/anyray_/i.test(t)?!1:/(^|[^a-z0-9])(read|read_file|readfile)$/i.test(t)},Fj=e=>/(^|[^a-z0-9])anyray_(search|read)$/i.test(e.trim()),Wj=e=>/(^|[^a-z0-9])anyray_history$/i.test(e.trim()),Uj=2048,Hj=async e=>{try{let t=(await e.text().catch(()=>"")).slice(0,Uj),n=Dd(t);if(!n)return;await VE({at:Date.now(),status:e.status,code:n})}catch{}},Gj=async(e,t,n,r,o,a)=>{if(!e)return null;let s=new AbortController,i=setTimeout(()=>s.abort(),yj());try{let c=await Mj(JSON.stringify({tool:t,toolInput:n,...o?{intent:o}:{},retrievalContext:a,...h0(t)||Bj(t)&&a==="available"?{reversible:!0}:{},...Fj(t)?{semanticRerank:!0}:{},output:r})),l=Yt(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 Hj(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)}},y0=async(e="claude")=>{let t=await Vi();if(e!=="cursor"&&Ej(t))return 0;let n=e==="cursor"?Sj(t):t;if(n===void 0)return 0;let{stdout:r,replacement:o}=await qy(n,e);if(e==="cursor"){let a=Ij(o);return a&&process.stdout.write(a),0}return r&&process.stdout.write(r),0},qy=async(e,t="claude",n)=>{await Lr(),await GE(t);let r=Nj(),o=await nt(),a=o&&{...o,metadata:bj(o.metadata,t)},s=Cj(t);return Lj(e,{optimize:(i,c,l,d,u)=>Gj(a,i,c,l,d,u),...t==="claude"?{readContext:async i=>{let c=await f0(i);return{intent:c.intent,retrievalContext:c.kind==="main"?"available":c.kind==="subagent"?"unavailable":"unknown"}},defaultRetrievalContext:"unknown"}:{defaultRetrievalContext:"available"},localTrim:i=>gu(i,r),beacon:(i,c)=>Ac(a,"hook",c,i),cacheGet:s.cacheGet,cachePut:s.cachePut,sizeGate:r.maxChars??Br.maxChars,digestCommand:jx,tee:s.tee,mediumBand:wj.has(t),finalizeOutput:n})};var g0=async()=>0;import{spawn as Xj}from"node:child_process";import{homedir as zj}from"node:os";import{join as qj}from"node:path";import{chmod as Vj,readFile as Kj,rm as w0,writeFile as jj}from"node:fs/promises";import{join as Zj}from"node:path";var Qy=()=>Zj(ee(),"sso-gate.json"),Yj=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))},Ja=async()=>{try{let e=JSON.parse(await Kj(Qy(),"utf-8"));return Yj(e)?e:null}catch{return null}},Jj=0,vu=async e=>{await et();let t=Qy(),n=`${t}.${process.pid}.${Jj++}.tmp`;try{await jj(n,`${JSON.stringify(e)}
|
|
702
|
+
`,{mode:384}),await Vj(n,384),await ye(n,t)}catch(r){throw await w0(n,{force:!0}).catch(()=>{}),r}},b0=async()=>{await w0(Qy(),{force:!0}).catch(()=>{})},A0=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 Qj=3e4,eZ=5*6e4,tZ=30*6e4,nZ=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},rZ=()=>qj(zj(),".claude","settings.json"),oZ=async e=>{try{let n=(await B(rZ())).env;if(!n)return!1;let r=sn(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}},aZ=async e=>{await lr.apply(e,{dryRun:!1})},sZ=()=>{let{command:e,args:t}=dr("__anyray-sso-poll");return{exe:e,args:t}},iZ=()=>{let{exe:e,args:t}=sZ(),n=Xj(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))}}},cZ=e=>{let t=Date.parse(e.enrolledCert?.payload.expiresAt??""),n=Date.parse(e.enrolledCertExpiry??"");return Number.isFinite(n)?Math.min(t,n):t},C0=(e,t,n,r)=>Re({origin:e,clientKey:r,subscription:!0,user:t.name??t.enrolledCert?.payload.user,team:n??t.team??t.enrolledCert?.payload.team}),Xa=(e,t)=>e.sessionStart?{exitCode:0}:{exitCode:2,stderr:t},k0=e=>`Anyray: one-time sign-in required to use AI tools on this device.
|
|
703
703
|
1. Open ${e.verificationUriComplete}
|
|
704
704
|
2. Confirm code ${e.userCode}
|
|
705
705
|
Your prompt was not sent \u2014 complete sign-in, then resubmit it.
|
|
706
706
|
`,eg=(e,t)=>e==="sso-unavailable"?`Anyray: SSO isn't configured \u2014 ask your Anyray admin.
|
|
707
707
|
`:e==="gateway-unreachable"?`Anyray: can't reach the gateway \u2014 check your network/VPN, then resubmit your prompt.
|
|
708
708
|
`:`Anyray: can't reach ${t} \u2014 check your network/VPN, then resubmit your prompt.
|
|
709
|
-
`,
|
|
710
|
-
`))}let z;await h();let Z=(t.resolveMachineUuid??Ut)()||void 0;try{z=await d(I,b.enrolledCert,C,{timeoutMs:1e4,machineUuid:Z})}catch(le){if(!(le instanceof lt))return Xa(e,eg("gateway-unreachable",
|
|
711
|
-
`}catch{return}},
|
|
709
|
+
`,lZ=e=>Math.min(eZ,Qj*2**Math.max(0,e-1)),dZ=(e,t)=>{if(e.lastFailure!=="cp-unreachable"&&e.lastFailure!=="sso-unavailable")return;let n=e.lastFailure==="sso-unavailable"?tZ:lZ(e.failureCount??1);return t-(e.lastAttemptAt??0)<n?e.lastFailure:void 0},Lo=async(e,t={})=>{let n=t.now??Date.now,r=t.loadProfile??P,o=t.saveProfile??ce,a=t.loadDevKey??Fe,s=t.readGateState??Ja,i=t.writeGateState??vu,c=t.isProcessAlive??A0,l=t.startGrant??xd,d=t.verify??tn,u=t.routingIntact??oZ,f=t.applyClaudeCode??aZ,m=t.maybeSpawnRefresh??Lr,p=t.recordMint??Fa,h=t.reserveMint??xo,g=t.spawnPoller??iZ,y=t.openBrowser??Va;try{let w=Et(e.sso);if(!w)return{exitCode:0};let b=await r(),k=await s(),C=b.enrolledCert?await a():void 0,S=cZ(b),E=!!(b.enrolledCert&&C)&&Number.isFinite(S)&&S>n(),I=e.gateway??b.gateway;if(E&&b.enrolledCert&&C&&I){let G=Date.parse(b.clientKeyExpiresAt??"");if(!!b.clientKey?.startsWith("ark_")&&Number.isFinite(G)&&G>n()&&b.clientKey){let le=C0(I,b,e.team,b.clientKey);return await u(le)?(G-n()<=Gh()&&await m(),{exitCode:0}):(await f(le),Xa(e,`Anyray: routing restored \u2014 restart this Claude Code session, then resubmit your prompt.
|
|
710
|
+
`))}let z;await h();let Z=(t.resolveMachineUuid??Ut)()||void 0;try{z=await d(I,b.enrolledCert,C,{timeoutMs:1e4,machineUuid:Z})}catch(le){if(!(le instanceof lt))return Xa(e,eg("gateway-unreachable",w.cpOrigin));await o({...b,enrolledCert:void 0,enrolledCertExpiry:void 0,clientKey:void 0,clientKeyExpiresAt:void 0})}if(z){let le={...b,gateway:I,name:z.user,team:e.team??z.team??b.team,clientKey:z.key,clientKeyExpiresAt:z.expiresAt,authMode:"subscription"};return await o(le),await p({expiresAt:z.expiresAt}),await f(C0(I,le,e.team,z.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 Xa(e,k0(k))}if(k){let G=dZ(k,n());if(G)return Xa(e,eg(G,w.cpOrigin))}let _;try{_=await l({cpOrigin:w.cpOrigin,tenantId:w.tenantId,gatewayUrl:e.gateway,now:n})}catch(G){let ne=G instanceof ko?G.kind:"cp-unreachable";return await i({v:1,lastAttemptAt:n(),failureCount:k?.lastFailure===ne?(k.failureCount??0)+1:1,lastFailure:ne}),Xa(e,eg(ne,w.cpOrigin))}let T={v:1,status:"pending",userCode:_.userCode,verificationUriComplete:_.verificationUriComplete,grantExpiresAt:_.grantExpiresAt,startedAt:_.startedAt,lastAttemptAt:n(),failureCount:0};await i(T);let W=g(),Q={...T,pollerPid:W.pid};if(await i(Q),W.handoff({deviceCode:_.deviceCode,privateKeyPem:_.privateKeyPem,publicKeyPem:_.publicKeyPem,cpOrigin:_.cpOrigin,tenantId:_.tenantId,intervalMs:_.intervalMs,grantExpiresAt:_.grantExpiresAt,startedAt:_.startedAt,gatewayUrl:_.gatewayUrl,gatewayOverride:e.gateway,team:e.team}),e.sessionStart)try{y(_.verificationUriComplete)}catch{}return Xa(e,k0(Q))}catch{return{exitCode:0}}},uZ=async()=>{try{for await(let e of process.stdin);}catch{}},v0=async e=>{await uZ();try{let t=await Lo(nZ(e));return t.stderr&&process.stderr.write(t.stderr),t.exitCode}catch{return 0}};var pZ=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},fZ=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??Pr)();if(!r)return;let o=await(t.ssoGate??Lo)({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})}
|
|
711
|
+
`}catch{return}},mZ=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t)}catch{return""}return Buffer.concat(e).toString("utf-8")},hZ=()=>{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")}},yZ=(e,t)=>{let n=t.minChars??Wi.minChars,r={maxChars:Math.min(Br.maxChars,n)},o=gu(e,r);return!o.trimmed||o.estTokensSaved<=0?null:{originalChars:o.originalChars,trimmedChars:o.trimmedChars,estTokensSaved:o.estTokensSaved}},S0=async()=>{let e=await mZ(),t=await fZ(e);t&&process.stdout.write(t);let n=hZ(),r=await nt();return await pZ(e,{isPaste:o=>wu(o,n),measure:o=>yZ(o,n),beacon:o=>Ac(r,"prompt",o)}),0};import{spawn as gZ}from"node:child_process";var E0=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),wZ=/[|&;<>`$()\n]/,I0=e=>{if(wZ.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},bZ=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!E0(n)||n.tool_name!=="Shell")return"";let r=n.tool_input;if(!E0(r)||typeof r.command!="string")return"";let o=r.command;return!o||o.includes(cp)||!t.isRecognized(o)||I0(o)===null?"":JSON.stringify({updated_input:{...r,command:t.wrap(o)}})},AZ=async(e,t)=>{let n="";try{n=Buffer.from(String(e??""),"base64").toString("utf8")}catch{n=""}let r=n?I0(n):null;if(!n||!r)return t.writeErr(`anyray: could not run wrapped command
|
|
712
712
|
`),1;let o;try{o=await t.exec(r)}catch{return t.writeErr(`anyray: failed to run wrapped command
|
|
713
|
-
`),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},
|
|
713
|
+
`),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},CZ=16*1024*1024,kZ=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=gZ(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>CZ){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)}}),vZ=async(e,t)=>{let n=JSON.stringify({tool_name:"Bash",tool_input:{command:e},tool_response:t}),{replacement:r}=await qy(n,"cursor");return typeof r=="string"?r:t},x0=e=>{let t=e[0]==="--b64"?e[1]:void 0;return AZ(t,{exec:kZ,trim:vZ,write:n=>process.stdout.write(n),writeErr:n=>process.stderr.write(n)})},R0=async()=>{let e=await Vi();if(process.platform==="win32")return 0;let t=bZ(e,{isRecognized:n=>Uy(n)!==null||Vx(n),wrap:n=>Tt(cp,["--b64",Buffer.from(n,"utf8").toString("base64")])});return t&&process.stdout.write(t),0};import{createHash as SZ}from"node:crypto";import{homedir as O0}from"node:os";import{extname as EZ,isAbsolute as IZ,join as tg,resolve as Ki,sep as T0}from"node:path";import{chmod as xZ,readFile as RZ,stat as N0,unlink as OZ,writeFile as TZ}from"node:fs/promises";var rg=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),_Z=16*1024,_0=["path","file_path","target_file","targetFile","relative_workspace_path","relativeWorkspacePath","filePath"],PZ=["pattern","query","regex","search"],DZ=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"]),LZ=720*60*1e3,NZ=512,ng=(e,t)=>{for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}return null},$Z=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],P0=(e,t)=>t.some(n=>e===n||e.startsWith(n.endsWith(T0)?n:n+T0)),MZ=(e,t,n)=>IZ(e)?[Ki(e)]:[...new Set([Ki(t,e),...n.map(r=>Ki(r,e))])],D0=(e,t,n)=>SZ("sha256").update(`${e.length}:${e}`).update(`${t.length}:${t}`).update(n).digest("hex").slice(0,32),L0=e=>JSON.stringify({permission:"deny",agent_message:e,user_message:"Anyray routed this through its context tools to keep the request small."}),BZ=async(e,t)=>{let n;try{n=JSON.parse(e)}catch{return""}if(!rg(n))return"";let r=n.tool_name;if(r!=="Read"&&r!=="Grep")return"";let o=n.tool_input;if(!rg(o))return"";let a=$Z(n.workspace_roots).map(d=>Ki(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=ng(o,PZ);if(!d)return"";let u=ng(o,_0);return u&&!P0(Ki(s,u),a)||!await t.remember(D0(i,"Grep",d))?"":L0(`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=ng(o,_0);if(!c||DZ.has(EZ(c).toLowerCase()))return"";let l=await t.resolveFile(MZ(c,s,a));return!l||l.bytes<_Z||!P0(l.path,a)||!await t.remember(D0(i,"Read",l.path))?"":L0(`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.`)},FZ=async e=>{for(let t of e)try{let n=await N0(t);if(n.isFile())return{path:t,bytes:n.size}}catch{}return null},WZ=async()=>{let e=tg(O0(),".anyray");try{if((await N0(e)).isDirectory())return tg(e,"cursor-redirects.json")}catch{}return tg(O0(),".anyray-cursor-redirects.json")},UZ=async e=>{let t;try{let n=await WZ(),r=Date.now(),o={};try{let s=JSON.parse(await RZ(n,"utf-8"));if(s?.v===1&&rg(s.seen))for(let[i,c]of Object.entries(s.seen))typeof c=="number"&&r-c<=LZ&&(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 TZ(t,JSON.stringify({v:1,seen:Object.fromEntries(a)}),{mode:384}),await xZ(t,384),await ye(t,n),!0}catch{if(t)try{await OZ(t)}catch{}return!1}},$0=async()=>{let e=await Vi(),t="";try{t=await BZ(e,{resolveFile:FZ,remember:UZ})}catch{t=""}return t&&process.stdout.write(t),0};import{execFileSync as JY}from"node:child_process";import{createReadStream as HZ}from"node:fs";import{spawnSync as Y0}from"node:child_process";import{createHash as GZ}from"node:crypto";import{access as J0,chmod as sg,copyFile as VZ,lstat as KZ,mkdir as jZ,mkdtemp as X0,readFile as Ru,rename as ZZ,rm as Wr,stat as YZ,writeFile as JZ}from"node:fs/promises";import{constants as z0}from"node:fs";import{platform as Qa,tmpdir as XZ}from"node:os";import{dirname as zZ,isAbsolute as qZ,join as Eu}from"node:path";import{z as Me}from"zod";var QZ="fleetd-installer-v4.89.2",M0=`https://github.com/anyrayHQ/install/releases/download/${QZ}`,eY=1e4,tY=1e4,B0=31,nY=1500,q0=20*1024,og=20,rY="0.25",oY="/var/tmp",qa="/Library/LaunchDaemons/com.fleetdm.orbit.plist",Iu="/etc/default/orbit",Zi="/opt/orbit/anyray-enroll-secret.txt",Q0="/opt/orbit/secret-orbit-node-key.txt",aY="/opt/orbit/bin/orbit/orbit",Yi="C:\\Program Files\\Orbit",sY=`${Yi}\\bin\\orbit`,eR=`${Yi}\\secret-orbit-node-key.txt`,ji=`${Yi}\\secret.txt`,iY=`${Yi}\\fleet_url.txt`,tR=`${Yi}\\anyray-managed.txt`,xu="Fleet osquery",ig="C:\\Windows\\System32\\sc.exe",ug="C:\\Windows\\System32\\whoami.exe",Su="C:\\Windows\\System32\\icacls.exe",cY="C:\\Windows\\System32\\msiexec.exe",cg="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",F0=["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 250"],lY=e=>["-NoProfile","-NonInteractive","-Command",`$s = Get-Service -Name '${e}' -ErrorAction SilentlyContinue; if ($s) { $s.Status.ToString() } else { 'absent' }`],dY=`anyray-connect endpoint install
|
|
714
714
|
|
|
715
715
|
Install Fleet's signed endpoint agent and enroll this machine in Anyray.
|
|
716
716
|
|
|
@@ -718,11 +718,11 @@ Supported on macOS, Linux and Windows.
|
|
|
718
718
|
|
|
719
719
|
The command uses the current seat's stored gateway key. Administrator access is
|
|
720
720
|
required: on macOS and Linux Connect asks through sudo once when /dev/tty is
|
|
721
|
-
available; on Windows, run it from a shell started as Administrator.`,pg=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),nR=(e,t=Qa())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),rR=(e,t=Qa(),n=!1)=>(pg(e)||n)&&t!=="win32",de=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},
|
|
722
|
-
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",Zi)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},lg=(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()},oR=e=>{let t=e(ig,["qc",xu,"8192"]);return t.status===0?t.stdout:""},dg=e=>{let t=e(cg,
|
|
723
|
-
`&&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},
|
|
721
|
+
available; on Windows, run it from a shell started as Administrator.`,pg=e=>!!(e.endpoint&&!e.noEndpoint&&(e.sso||e.enroll||e.claim)&&!e.revert&&!e.dryRun),nR=(e,t=Qa())=>t!=="win32"&&(e==="installed"||e==="already-enrolled"),rR=(e,t=Qa(),n=!1)=>(pg(e)||n)&&t!=="win32",de=class extends Error{publicMessage;constructor(t){super(t),this.publicMessage=t,this.name="EndpointInstallError"}},uY=Me.object({kind:Me.enum(["pkg","deb","rpm","msi"]),path:Me.string().min(1).refine(qZ),sha256:Me.string().regex(/^[0-9a-f]{64}$/)}).strict(),pY=Me.object({action:Me.literal("restart"),os:Me.enum(["darwin","linux","win32"])}).strict(),fY=Me.object({action:Me.literal("configure"),os:Me.enum(["darwin","linux","win32"]),fleetUrl:Me.string().min(1).max(2048),enrollSecret:Me.string().min(1).max(4096),package:uY.optional()}).strict(),mY=Me.discriminatedUnion("action",[pY,fY]),Ji=(e,t)=>{let n=Y0(e,t,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:6e5,maxBuffer:1048576});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:""}},fg=async e=>{try{return await J0(e,z0.F_OK),!0}catch{return!1}},hY=async e=>{try{let t=await YZ(e);return t.isFile()&&t.size>0}catch{return!1}},mg=(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}},ag=(e,t)=>mg(e,t)!==null,W0=e=>e==="win32"?ji:Zi,yY=e=>e==="win32"?eR:Q0,gY=e=>ag(e,"ORBIT_FLEET_URL")&&ag(e,"ORBIT_ENROLL_SECRET_PATH")&&e.includes(`<string>${Zi}</string>`)&&!ag(e,"ORBIT_USE_SYSTEM_CONFIGURATION"),wY=e=>{let t=(n,r)=>e.split(`
|
|
722
|
+
`).some(o=>r===void 0?o.startsWith(`${n}=`):o.trim()===`${n}=${r}`);return t("ORBIT_FLEET_URL")&&t("ORBIT_ENROLL_SECRET_PATH",Zi)&&!t("ORBIT_ENROLL_SECRET")&&!t("ORBIT_USE_SYSTEM_CONFIGURATION")},lg=(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()},oR=e=>{let t=e(ig,["qc",xu,"8192"]);return t.status===0?t.stdout:""},dg=e=>{let t=e(cg,lY(xu)),n=t.status===0?t.stdout.trim():"";return n.length>0?n:"absent"},bY=async e=>{try{return e==="win32"?lg(e,oR(Ji)):lg(e,await Ru(e==="darwin"?qa:Iu,"utf8"))}catch{return}},AY=async e=>{try{if(e==="win32")return await fg(tR)&&lg(e,oR(Ji))!==void 0;let n=await Ru(e==="darwin"?qa:Iu,"utf8");return e==="darwin"?gY(n):wY(n)}catch{return!1}},aR=async(e,t={})=>{let n=t.exists??fg,r=t.command??Ji,o,a="absent";if(e==="win32")a=dg(r),o=await n(sY)&&a!=="absent";else{let l=e==="darwin"?await n(qa):await n("/etc/systemd/system/orbit.service")||await n("/usr/lib/systemd/system/orbit.service");o=await n(aY)&&l}let s=await(t.configured??AY)(e),i=await(t.hasNodeKey??(()=>hY(yY(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}},CY=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),sR=(e,t)=>{let n=mg(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]===`
|
|
723
|
+
`&&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},kY=(e,t)=>{let n=sR(e,t);return n===null?e:e.slice(0,n.start)+e.slice(n.end)},U0=(e,t,n)=>{let r=`
|
|
724
724
|
<key>${t}</key>
|
|
725
|
-
<string>${
|
|
725
|
+
<string>${CY(n)}</string>`,o=sR(e,t);if(o!==null)return e.slice(0,o.start)+r+e.slice(o.end);let a=mg(e,"EnvironmentVariables"),s=a===null?-1:e.indexOf("<dict>",a.end);if(a===null||s<0)throw new de("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)},vY=(e,t,n=Zi)=>{let r=kY(e,"ORBIT_USE_SYSTEM_CONFIGURATION");return r=U0(r,"ORBIT_FLEET_URL",t),U0(r,"ORBIT_ENROLL_SECRET_PATH",n)},SY=(e,t,n=Zi)=>{let r=new Set(["ORBIT_FLEET_URL","ORBIT_ENROLL_SECRET","ORBIT_ENROLL_SECRET_PATH","ORBIT_USE_SYSTEM_CONFIGURATION"]);return`${e.split(`
|
|
726
726
|
`).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(`
|
|
727
727
|
`).trimEnd()}
|
|
728
728
|
|
|
@@ -732,17 +732,17 @@ available; on Windows, run it from a shell started as Administrator.`,pg=e=>!!(e
|
|
|
732
732
|
# file, never in this world-readable one.
|
|
733
733
|
ORBIT_FLEET_URL=${t}
|
|
734
734
|
ORBIT_ENROLL_SECRET_PATH=${n}
|
|
735
|
-
`},iR=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}},
|
|
735
|
+
`},iR=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}},EY=Me.object({code:Me.string().min(1).optional(),message:Me.string().min(1).optional()}).passthrough(),H0=e=>{let t=e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/ {2,}/g," ").trim();return t.length>300?`${t.slice(0,299)}\u2026`:t},IY=(e,t)=>{let n=`The gateway rejected endpoint enrollment (${e}).`,r=EY.safeParse(t);if(!r.success)return n;let o=H0(r.data.message??""),a=H0(r.data.code??"");return o?a?`${n} ${o} [${a}]`:`${n} ${o}`:a?`${n} [${a}]`:n},G0=async(e,t,n={})=>{let r=new AbortController,o=setTimeout(()=>r.abort(),n.timeoutMs??tY),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":Ee},body:"{}",signal:r.signal})}catch{throw new de("Could not reach the gateway for endpoint enrollment.")}finally{clearTimeout(o)}if(!a.ok){if(a.status===404)throw new de("This gateway does not provide endpoint enrollment yet.");let c;try{c=await a.json()}catch{c=void 0}throw new de(IY(a.status,c))}let s;try{s=await a.json()}catch{throw new de("The gateway returned malformed endpoint enrollment data.")}let i=Me.object({fleetUrl:Me.string().min(1).max(2048),enrollSecret:Me.string().min(1).max(4096)}).strict().safeParse(s);if(!i.success||!iR(i.data.fleetUrl))throw new de("The gateway returned invalid endpoint enrollment data.");return i.data},xY=async(e={})=>{let t=e.exists??fg;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 de("Linux endpoint installation requires either dpkg or rpm.")},RY=async e=>e==="darwin"?"pkg":e==="win32"?"msi":xY(),hg=e=>`fleetd.${e}`,OY=(e,t)=>e==="darwin"?t==="pkg":e==="win32"?t==="msi":t==="deb"||t==="rpm",TY=async(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),eY);try{return await t(e,{signal:n.signal})}finally{clearTimeout(r)}},_Y=async(e,t={})=>{let n=hg(e),r=t.fetchResponse??fetch,o;try{o=await TY(`${M0}/SHA256SUMS`,r)}catch{throw new de("Could not read the endpoint package checksums from GitHub.")}if(o.status===404)return;if(!o.ok)throw new de(`GitHub could not provide the endpoint package checksums (${o.status}).`);let a=Iy(await o.text(),n);if(!a)return;let s=t.makeTempDir?await t.makeTempDir():await X0(Eu(XZ(),"anyray-endpoint-")),i=Eu(s,n);try{await sg(s,448),await(t.download??Oy)(`${M0}/${n}`,i,a)}catch(c){if(await Wr(s,{recursive:!0,force:!0}).catch(()=>{}),c instanceof Mi&&c.status===404)return;throw new de("The endpoint package download or checksum verification failed.")}return{kind:e,path:i,sha256:a,cleanup:()=>Wr(s,{recursive:!0,force:!0})}},PY=async(e,t,n)=>{await jZ(zZ(e),{recursive:!0,mode:493});let r=`${e}.anyray-${process.pid}`;await Wr(r,{force:!0});try{await JZ(r,t,{encoding:"utf8",mode:n,flag:"wx"}),await ZZ(r,e)}catch(o){throw await Wr(r,{force:!0}).catch(()=>{}),o}},V0=async e=>{let t=GZ("sha256");for await(let n of HZ(e))t.update(n);return t.digest("hex")},DY=async(e,t={})=>{let n=await KZ(e.path).catch(()=>{});if(!n?.isFile()||n.isSymbolicLink())throw new de("The verified endpoint package staging file is no longer available.");if(e.kind==="msi"){if(await V0(e.path)!==e.sha256)throw new de("The endpoint package changed after verification; installation was refused.");return{package:e,cleanup:async()=>{}}}let r=t.makeTempDir?await t.makeTempDir():await X0(Eu(oY,"anyray-endpoint-root-")),o=Eu(r,hg(e.kind));try{if(await sg(r,448),await VZ(e.path,o),await sg(o,384),await V0(o)!==e.sha256)throw new de("The endpoint package changed after verification; installation was refused.");return{package:{...e,path:o},cleanup:()=>Wr(r,{recursive:!0,force:!0})}}catch(a){throw await Wr(r,{recursive:!0,force:!0}).catch(()=>{}),a}},za=(e,t)=>{if(e.status!==0)throw new de(t)},K0="com.fleetdm.fleetd.config",LY="com.fleetdm.fleetd.enroll.secret",NY=["/opt/orbit/secret.txt","/opt/orbit/fleet_url.txt",Q0],$Y=[iY,eR],MY=e=>{let t=e("/usr/bin/profiles",["show","-type","configuration"]);if(t.status===0&&t.stdout.includes(K0))throw new de(`This machine already receives its endpoint configuration from an MDM profile (${K0}), which takes precedence over anything installed here. Enrollment is managed by that profile; remove it first if this machine should enroll directly.`)},j0=async(e,t,n)=>{let r=n.removeFile??(o=>Wr(o,{force:!0}));for(let o of e==="win32"?$Y:NY)await r(o).catch(()=>{});e==="darwin"&&t("/usr/bin/security",["delete-generic-password","-s",LY,"/Library/Keychains/System.keychain"])},BY=e=>{e(Su,[ji,"/inheritance:r"]),e(Su,[ji,"/grant:r","*S-1-5-18:(F)"]),e(Su,[ji,"/grant:r","*S-1-5-32-544:(F)"]),e(Su,[ji,"/remove:g","*S-1-5-32-545"])},FY=(e,t,n)=>{if(e.kind==="pkg"){za(t("/usr/sbin/installer",["-pkg",e.path,"-target","/"]),"The macOS endpoint package installer failed.");return}if(e.kind==="deb"){za(t("dpkg",["-i",e.path]),"The Debian endpoint package installer failed.");return}if(e.kind==="rpm"){za(t("rpm",["-U",e.path]),"The RPM endpoint package installer failed.");return}za(t(cY,["/i",e.path,"/qn","/norestart",`FLEET_URL=${n}`,"ENABLE_SCRIPTS=true"]),"The Windows endpoint package installer failed.")},WY=(e,t)=>{if(e==="darwin"){t("/bin/launchctl",["bootout","system/com.fleetdm.orbit"]);let n;for(let r=0;r<og;r++){if(n=t("/bin/launchctl",["bootstrap","system",qa]),n.status===0)return;t("/bin/sleep",[rY])}throw new de(`Orbit was configured, but launchd could not load the updated service definition${n?.stdout.trim()?`: ${n.stdout.trim()}`:""}.`)}if(e==="win32"){t(ig,["stop",xu]);for(let n=0;n<og;n++){let r=dg(t);if(r==="Stopped"||r==="absent")break;t(cg,F0)}for(let n=0;n<og;n++){if(t(ig,["start",xu]).status===0||dg(t)==="Running")return;t(cg,F0)}throw new de("Orbit was configured, but the Windows service could not be started.")}za(t("systemctl",["daemon-reload"]),"Orbit was configured, but systemd could not reload its units."),za(t("systemctl",["restart","orbit"]),"Orbit was configured, but systemd could not restart it.")},UY=e=>new Promise(t=>setTimeout(t,e)),cR=async(e,t={})=>{let n=t.command??Ji,r=t.readText??(c=>Ru(c,"utf8")),o=t.writeText??PY,a=t.removeSecret??(()=>Wr(W0(e.os),{force:!0})),s=!1,i;try{if(e.action==="configure"){if(e.os==="darwin"&&MY(n),e.package&&!OY(e.os,e.package.kind))throw new de("The endpoint package does not match this operating system.");if(e.os==="win32"&&!e.package)throw new de("Reconfiguring the Windows endpoint agent requires the installer package.");if(e.os==="win32"&&await j0(e.os,n,t),e.package){let d=await(t.preparePackage??DY)(e.package);i=d.cleanup,FY(d.package,n,e.fleetUrl)}if(e.os==="darwin"){let d=await r(qa);await o(qa,vY(d,e.fleetUrl),420)}else if(e.os==="linux"){let d=await r(Iu);await o(Iu,SY(d,e.fleetUrl),420)}else await o(tR,`anyray
|
|
736
736
|
`,384);e.os!=="win32"&&await j0(e.os,n,t),await o(W0(e.os),`${e.enrollSecret}
|
|
737
|
-
`,384),e.os==="win32"&&
|
|
738
|
-
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??
|
|
739
|
-
sudo anyray-connect endpoint install`),"deferred"},
|
|
740
|
-
`;if(Buffer.byteLength(t)>q0)throw new de("The privileged endpoint plan is unexpectedly large.");let n=an(["__anyray-endpoint-install"]);return Y0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},
|
|
741
|
-
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Qa()==="darwin"?`/Users/${e}`:`/home/${e}`;let n=process.env.HOME,r=process.env.USERPROFILE;process.env.HOME=t,process.env.USERPROFILE=t;try{return await P()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},lR=async(e={},t={})=>{let n=t.os??Qa();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new de("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??aR)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??Z0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??wY)(r);if(!l||!d||u===void 0)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};let f=await(t.fetchEnrollment??G0)(l,d);if(u===f.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};L("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new de("This machine is already enrolled in a different Fleet configuration; it was left unchanged.");let s,i;if(o.installed&&o.configured&&o.checkedIn&&!a)s={action:"restart",os:r};else{let c=e.gateway&&e.clientKey?void 0:await(t.profile??Z0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new de("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??G0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>xY(r)))();if(i=await(t.stagePackage??TY)(f),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${hg(f)} is not published yet; skipping.`}}s={action:"configure",os:r,...u,...i?{package:{kind:i.kind,path:i.path,sha256:i.sha256}}:{}}}try{return await(t.execute??jY)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},yg=e=>e instanceof de?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",dR=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return A(lY),0;if(e.length!==1||e[0]!=="install")return R("Usage: anyray-connect endpoint install"),1;try{let t=await lR();return t.message&&(t.outcome==="installed"?M(t.message):L(t.message)),0}catch(t){return R(yg(t)),1}},ZY=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>q0)throw new de("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new de("The privileged endpoint plan is malformed.")}let r=fY.safeParse(n);if(!r.success||r.data.os!==Qa()||r.data.action==="configure"&&!iR(r.data.fleetUrl))throw new de("The privileged endpoint plan is invalid.");return r.data},uR=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 cR(await ZY()),0}catch(t){return R(yg(t)),1}},pR=async(e,t=lR)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?M(n.message):L(n.message)),n.outcome}catch(n){L(`Endpoint agent: ${yg(n)} Tool routing remains configured.`);return}};var JY=new Set(["darwin","win32","linux"]),XY=new Set(["S-1-5-18","S-1-5-19","S-1-5-20"]),zY=e=>{let t=e.match(/S-\d(?:-\d+)+/i)?.[0]?.toUpperCase();return t!==void 0&&!XY.has(t)},fR=(e,t)=>{let n=new Set(t);return e.filter(r=>!n.has(r.id))},gg=async e=>{try{if(!JY.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}},mR=async(e,t)=>{if(e!=="not-enrolled")return e;try{return!t.readManagedEnrollment().enrollmentUrl||(await t.loadProfile()).managedEnrollmentDisabled===!0||await gg(t)!==0?e:await t.refresh()}catch{return e}},wg=e=>({platform:process.platform,readManagedEnrollment:To,loadProfile:P,isUserSession:()=>{try{if(process.platform==="win32"){let t=YY(ug,["/user","/fo","csv","/nh"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return zY(t)}return process.getuid?.()!==0}catch{return!1}},runApply:e});var Xi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},bg=e=>typeof e=="string"&&e.trim()?e.trim():void 0,qY=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Xi(n,"deviceCode"),o=Xi(n,"privateKeyPem"),a=Xi(n,"publicKeyPem"),s=Xi(n,"cpOrigin"),i=Xi(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=bg(n.gatewayUrl),f=bg(n.gatewayOverride),m=bg(n.team);return{deviceCode:r,privateKeyPem:o,publicKeyPem:a,cpOrigin:s,tenantId:i,intervalMs:c,grantExpiresAt:l,startedAt:d,...u?{gatewayUrl:u}:{},...f?{gatewayOverride:f}:{},...m?{team:m}:{}}}catch{return null}},QY=e=>new Promise(t=>setTimeout(t,e)),eJ=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})},tJ=async(e,t={})=>{let n=t.poll??Rd,r=t.verify??tn,o=t.loadProfile??P,a=t.saveProfile??ce,s=t.saveDevKey??ac,i=t.readGateState??Ja,c=t.writeGateState??vu,l=t.clearGateState??b0,d=t.sleep??QY,u=t.now??Date.now,f=t.recordMint??Fa,m=t.reserveMint??xo,p=t.applyClaudeCode??(async I=>{await lr.apply(I,{dryRun:!1})}),h=I=>eJ(I,{readGateState:i,writeGateState:c,now:u}),w={cpOrigin:e.cpOrigin,tenantId:e.tenantId,deviceCode:e.deviceCode,userCode:"",verificationUriComplete:"",intervalMs:e.intervalMs,grantExpiresAt:e.grantExpiresAt,startedAt:e.startedAt,privateKeyPem:e.privateKeyPem,publicKeyPem:e.publicKeyPem,gatewayUrl:e.gatewayUrl},y;try{y=await n(w,{gatewayUrl:e.gatewayOverride})}catch(I){let _=I instanceof Ft?I.kind:"cp-unreachable";return await h(_),_}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 m();let S=(t.resolveMachineUuid??Ut)()||void 0;for(let I=0;I<3;I++)try{C=await r(g,y.cert,y.privateKeyPem,{timeoutMs:1e4,machineUuid:S});break}catch(_){if(_ instanceof lt||I===2)break;await d(1e3)}if(!C)return await h("gateway-unreachable"),"gateway-unreachable";let E={...k,gateway:g,name:C.user,team:e.team??C.team??k.team,clientKey:C.key,clientKeyExpiresAt:C.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:C.expiresAt});let I=Re({origin:g,clientKey:C.key,subscription:!0,user:E.name,team:E.team});return await p(I),await l(),"enrolled"}catch{return await h("gateway-unreachable"),"failed"}},nJ=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},hR=async()=>{let e=qY(await nJ());if(e)try{await tJ(e)}catch{}return 0};var rJ=1e4,Ag=/^[\w.:-]{1,64}$/,Gt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},Cg=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,yR=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),rJ);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 Gt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},oJ=e=>{let t=Cg(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}},aJ=e=>{let t=Cg(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&Ag.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&Ag.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},sJ=e=>{let t=Cg(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ae(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!Ag.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}}},iJ=e=>new Promise(t=>setTimeout(t,e)),cJ=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Gt("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 Wa("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 Gt("invalid-team","Choose one of the teams shown above.");return s},lJ=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??iJ,a=t.loadProfile??P,s=t.saveProfile??ce,i=t.clearDevKey??ss,c=t.chooseTeam??cJ,l=t.apply??(async y=>{await lr.apply(y,{dryRun:!1})}),d=t.log??L,u=await a(),f=Nr(e.gateway,u),m=await yR(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),p=oJ(m.body);if(m.status!==200||!p)throw new Gt("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${p.browser_url}`),d(`Enter this code in the browser: ${p.user_code}`),(t.openBrowser??Va)(p.browser_url);let h=r()+p.expires_in*1e3,w=e.team?.trim()||void 0;for(;r()<h;){let y=await yR(`${f}/sso/cli/poll/${encodeURIComponent(p.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":p.poll_secret,...w?{"x-anyray-team":w}:{}}},n);if(y.status===202){await o(p.interval*1e3);continue}if(y.status===401)throw new Gt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(y.status===410)throw new Gt("expired","SSO login expired before it completed. Run anyray-connect login again.");let g=aJ(y.body);if(y.status===200&&g){if(w&&!g.teams.includes(w))throw new Gt("invalid-team",`Team ${w} is not available for this account.`);w=await c(g.teams,g.default_team,e.interactive??ht());continue}let b=sJ(y.body);if(y.status!==200||!b)throw new Gt("login-failed","SSO login could not be completed.");let k={...u,gateway:f,name:b.user,team:b.team,clientKey:b.key,clientKeyExpiresAt:b.expires_at,enrolledCert:void 0,enrolledCertExpiry:void 0,enrolledTokenHash:void 0,ssoLink:void 0,authMode:"subscription"};return await i(),await s(k),await l(Re({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Gt("expired","SSO login expired before it completed. Run anyray-connect login again.")},dJ=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
737
|
+
`,384),e.os==="win32"&&BY(n),s=e.os!=="win32"}WY(e.os,n);let c=t.checkIn??(async d=>{let u=await aR(d);return u.running&&u.checkedIn}),l=t.wait??UY;for(let d=0;d<(t.attempts??B0);d++){if(await c(e.os))return;d+1<(t.attempts??B0)&&await l(nY)}throw new de("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(()=>{})}},HY=async()=>{try{return await J0("/dev/tty",z0.R_OK),!0}catch{return!1}},GY=12288,VY=e=>{let t=e(ug,["/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>=GY},KY=async(e,t={})=>{if((t.os??Qa())==="win32")return(t.elevated??(()=>VY(t.command??Ji)))()?(await e(),"direct"):((t.print??A)(`Administrator access is required. Open Windows Terminal or PowerShell as Administrator and run:
|
|
738
|
+
anyray-connect endpoint install`),"deferred");if((t.uid??(()=>process.getuid?.()??-1))()===0)return await e(),"direct";if(await(t.ttyReadable??HY)()){if(await(t.reexec??(async()=>1))()!==0)throw new de("Administrator access did not complete; the endpoint agent was not enrolled.");return"sudo"}return(t.print??A)(`Administrator access is required. Run:
|
|
739
|
+
sudo anyray-connect endpoint install`),"deferred"},jY=async e=>{let t=`${JSON.stringify(e)}
|
|
740
|
+
`;if(Buffer.byteLength(t)>q0)throw new de("The privileged endpoint plan is unexpectedly large.");let n=an(["__anyray-endpoint-install"]);return Y0("sudo",[n.command,...n.args],{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"}).status??1},ZY=async(e,t={})=>(t.withRoot??KY)(()=>(t.apply??cR)(e),{...t.root,reexec:()=>(t.sudo??jY)(e)}),Z0=async()=>{if((process.getuid?.()??-1)!==0||!process.env.SUDO_USER)return P();let e=process.env.SUDO_USER;if(!/^[A-Za-z0-9._-]{1,64}$/.test(e))return P();let t;try{let s=(await Ru("/etc/passwd","utf8")).split(`
|
|
741
|
+
`).find(i=>i.split(":")[0]===e)?.split(":")[5];s?.startsWith("/")&&(t=s)}catch{}t??=Qa()==="darwin"?`/Users/${e}`:`/home/${e}`;let n=process.env.HOME,r=process.env.USERPROFILE;process.env.HOME=t,process.env.USERPROFILE=t;try{return await P()}finally{n===void 0?delete process.env.HOME:process.env.HOME=n,r===void 0?delete process.env.USERPROFILE:process.env.USERPROFILE=r}},lR=async(e={},t={})=>{let n=t.os??Qa();if(n!=="darwin"&&n!=="linux"&&n!=="win32")throw new de("`anyray-connect endpoint install` supports macOS, Linux and Windows only.");let r=n,o=await(t.probe??aR)(r),a=!1;if(o.installed&&o.configured&&o.running&&o.checkedIn){let c=e.gateway&&e.clientKey?void 0:await(t.profile??Z0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey,u=await(t.readFleetUrl??bY)(r);if(!l||!d||u===void 0)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};let f=await(t.fetchEnrollment??G0)(l,d);if(u===f.fleetUrl)return{outcome:"already-enrolled",message:"Endpoint agent already running and enrolled; nothing to do."};L("This machine points at a different Anyray endpoint server; re-pointing it."),a=!0}if(o.installed&&o.checkedIn&&!o.configured)throw new de("This machine is already enrolled in a different Fleet configuration; it was left unchanged.");let s,i;if(o.installed&&o.configured&&o.checkedIn&&!a)s={action:"restart",os:r};else{let c=e.gateway&&e.clientKey?void 0:await(t.profile??Z0)(),l=e.gateway??c?.gateway,d=e.clientKey??c?.clientKey;if(!l||!d)throw new de("No enrolled seat key is available. Run anyray-connect with --sso first, then retry endpoint install.");let u=await(t.fetchEnrollment??G0)(l.replace(/\/$/,""),d);if(!o.installed||r==="win32"){let f=await(t.packageKind??(()=>RY(r)))();if(i=await(t.stagePackage??_Y)(f),!i)return{outcome:"release-unavailable",message:`Endpoint agent package ${hg(f)} is not published yet; skipping.`}}s={action:"configure",os:r,...u,...i?{package:{kind:i.kind,path:i.path,sha256:i.sha256}}:{}}}try{return await(t.execute??ZY)(s)==="deferred"?{outcome:"needs-root"}:{outcome:"installed",message:"Endpoint agent is running and enrolled."}}finally{await i?.cleanup().catch(()=>{})}},yg=e=>e instanceof de?e.publicMessage:"Endpoint agent installation failed locally; no enrollment was confirmed.",dR=async e=>{if(e.length===1&&(e[0]==="--help"||e[0]==="-h"))return A(dY),0;if(e.length!==1||e[0]!=="install")return R("Usage: anyray-connect endpoint install"),1;try{let t=await lR();return t.message&&(t.outcome==="installed"?M(t.message):L(t.message)),0}catch(t){return R(yg(t)),1}},YY=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>q0)throw new de("The privileged endpoint plan is unexpectedly large.");e.push(a)}let n;try{n=JSON.parse(Buffer.concat(e).toString("utf8"))}catch{throw new de("The privileged endpoint plan is malformed.")}let r=mY.safeParse(n);if(!r.success||r.data.os!==Qa()||r.data.action==="configure"&&!iR(r.data.fleetUrl))throw new de("The privileged endpoint plan is invalid.");return r.data},uR=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 cR(await YY()),0}catch(t){return R(yg(t)),1}},pR=async(e,t=lR)=>{try{let n=await t(e);return n.message&&(n.outcome==="installed"?M(n.message):L(n.message)),n.outcome}catch(n){L(`Endpoint agent: ${yg(n)} Tool routing remains configured.`);return}};var XY=new Set(["darwin","win32","linux"]),zY=new Set(["S-1-5-18","S-1-5-19","S-1-5-20"]),qY=e=>{let t=e.match(/S-\d(?:-\d+)+/i)?.[0]?.toUpperCase();return t!==void 0&&!zY.has(t)},fR=(e,t)=>{let n=new Set(t);return e.filter(r=>!n.has(r.id))},gg=async e=>{try{if(!XY.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}},mR=async(e,t)=>{if(e!=="not-enrolled")return e;try{return!t.readManagedEnrollment().enrollmentUrl||(await t.loadProfile()).managedEnrollmentDisabled===!0||await gg(t)!==0?e:await t.refresh()}catch{return e}},wg=e=>({platform:process.platform,readManagedEnrollment:To,loadProfile:P,isUserSession:()=>{try{if(process.platform==="win32"){let t=JY(ug,["/user","/fo","csv","/nh"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return qY(t)}return process.getuid?.()!==0}catch{return!1}},runApply:e});var Xi=(e,t)=>{let n=e[t];return typeof n=="string"&&n?n:void 0},bg=e=>typeof e=="string"&&e.trim()?e.trim():void 0,QY=e=>{try{let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t,r=Xi(n,"deviceCode"),o=Xi(n,"privateKeyPem"),a=Xi(n,"publicKeyPem"),s=Xi(n,"cpOrigin"),i=Xi(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=bg(n.gatewayUrl),f=bg(n.gatewayOverride),m=bg(n.team);return{deviceCode:r,privateKeyPem:o,publicKeyPem:a,cpOrigin:s,tenantId:i,intervalMs:c,grantExpiresAt:l,startedAt:d,...u?{gatewayUrl:u}:{},...f?{gatewayOverride:f}:{},...m?{team:m}:{}}}catch{return null}},eJ=e=>new Promise(t=>setTimeout(t,e)),tJ=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})},nJ=async(e,t={})=>{let n=t.poll??Rd,r=t.verify??tn,o=t.loadProfile??P,a=t.saveProfile??ce,s=t.saveDevKey??ac,i=t.readGateState??Ja,c=t.writeGateState??vu,l=t.clearGateState??b0,d=t.sleep??eJ,u=t.now??Date.now,f=t.recordMint??Fa,m=t.reserveMint??xo,p=t.applyClaudeCode??(async I=>{await lr.apply(I,{dryRun:!1})}),h=I=>tJ(I,{readGateState:i,writeGateState:c,now:u}),g={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(g,{gatewayUrl:e.gatewayOverride})}catch(I){let _=I instanceof Ft?I.kind:"cp-unreachable";return await h(_),_}let w=e.gatewayOverride??y.gatewayUrl,b=await o(),k={...b,gateway:w??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(!w)return await h("gateway-unreachable"),"gateway-unreachable";let C;await m();let S=(t.resolveMachineUuid??Ut)()||void 0;for(let I=0;I<3;I++)try{C=await r(w,y.cert,y.privateKeyPem,{timeoutMs:1e4,machineUuid:S});break}catch(_){if(_ instanceof lt||I===2)break;await d(1e3)}if(!C)return await h("gateway-unreachable"),"gateway-unreachable";let E={...k,gateway:w,name:C.user,team:e.team??C.team??k.team,clientKey:C.key,clientKeyExpiresAt:C.expiresAt,authMode:"subscription"};try{await a(E),await f({expiresAt:C.expiresAt});let I=Re({origin:w,clientKey:C.key,subscription:!0,user:E.name,team:E.team});return await p(I),await l(),"enrolled"}catch{return await h("gateway-unreachable"),"failed"}},rJ=async()=>{let e=[];try{for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}catch{return""}},hR=async()=>{let e=QY(await rJ());if(e)try{await nJ(e)}catch{}return 0};var oJ=1e4,Ag=/^[\w.:-]{1,64}$/,Gt=class extends Error{kind;constructor(t,n){super(n),this.kind=t,this.name="LoginError"}},Cg=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,yR=async(e,t,n)=>{let r=new AbortController,o=setTimeout(()=>r.abort(),oJ);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 Gt("gateway-unreachable","Could not reach the Anyray gateway to sign in.")}finally{clearTimeout(o)}},aJ=e=>{let t=Cg(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}},sJ=e=>{let t=Cg(e);if(t?.status!=="team_selection"||typeof t.user!="string"||!Array.isArray(t.teams))return;let n=t.teams.filter(o=>typeof o=="string"&&Ag.test(o));if(n.length===0||n.length!==t.teams.length)return;let r=typeof t.default_team=="string"&&Ag.test(t.default_team)?t.default_team:void 0;return{status:"team_selection",user:t.user,teams:n,...r&&{default_team:r}}},iJ=e=>{let t=Cg(e);if(!(t?.status!=="complete"||typeof t.key!="string"||!Ae(t.key)||typeof t.user!="string"||!t.user||typeof t.team!="string"||!Ag.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}}},cJ=e=>new Promise(t=>setTimeout(t,e)),lJ=async(e,t,n)=>{if(e.length===1)return e[0];if(!n){if(t&&e.includes(t))return t;throw new Gt("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 Wa("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 Gt("invalid-team","Choose one of the teams shown above.");return s},dJ=async(e,t={})=>{let n=t.fetch??fetch,r=t.now??Date.now,o=t.sleep??cJ,a=t.loadProfile??P,s=t.saveProfile??ce,i=t.clearDevKey??ss,c=t.chooseTeam??lJ,l=t.apply??(async y=>{await lr.apply(y,{dryRun:!1})}),d=t.log??L,u=await a(),f=Nr(e.gateway,u),m=await yR(`${f}/sso/cli/start`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"},n),p=aJ(m.body);if(m.status!==200||!p)throw new Gt("login-failed","The gateway could not start SSO login.");d("Open this URL to sign in with your organization:"),d(` ${p.browser_url}`),d(`Enter this code in the browser: ${p.user_code}`),(t.openBrowser??Va)(p.browser_url);let h=r()+p.expires_in*1e3,g=e.team?.trim()||void 0;for(;r()<h;){let y=await yR(`${f}/sso/cli/poll/${encodeURIComponent(p.id)}`,{method:"GET",headers:{"x-anyray-poll-secret":p.poll_secret,...g?{"x-anyray-team":g}:{}}},n);if(y.status===202){await o(p.interval*1e3);continue}if(y.status===401)throw new Gt("wrong-poll-secret","The gateway rejected this login session. Start a new login.");if(y.status===410)throw new Gt("expired","SSO login expired before it completed. Run anyray-connect login again.");let w=sJ(y.body);if(y.status===200&&w){if(g&&!w.teams.includes(g))throw new Gt("invalid-team",`Team ${g} is not available for this account.`);g=await c(w.teams,w.default_team,e.interactive??ht());continue}let b=iJ(y.body);if(y.status!==200||!b)throw new Gt("login-failed","SSO login could not be completed.");let k={...u,gateway:f,name:b.user,team:b.team,clientKey:b.key,clientKeyExpiresAt:b.expires_at,enrolledCert:void 0,enrolledCertExpiry:void 0,enrolledTokenHash:void 0,ssoLink:void 0,authMode:"subscription"};return await i(),await s(k),await l(Re({origin:f,clientKey:b.key,subscription:!0,user:b.user,team:b.team})),b}throw new Gt("expired","SSO login expired before it completed. Run anyray-connect login again.")},uJ=`anyray-connect login [--gateway <url>] [--team <name>]
|
|
742
742
|
|
|
743
743
|
Start browser SSO, choose a team, mint a personal gateway key, and configure
|
|
744
744
|
the subscription-backed Connect lane. In a non-interactive shell, --team may be
|
|
745
|
-
omitted only when the identity authority supplies a default or sole team.`,gR=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(
|
|
745
|
+
omitted only when the identity authority supplies a default or sole team.`,gR=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(uJ),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 dJ({gateway:n,team:r},t);return M(`Signed in as ${o.user} for team ${o.team}. Your personal key was saved and configured.`),0}catch(o){if(o instanceof mt)throw o;return R(o instanceof Gt?o.message:"SSO login failed."),1}};var wR=`anyray-connect update [--check] [--auto on|off] [--json]
|
|
746
746
|
|
|
747
747
|
Keep this machine's anyray-connect binary on the published release. Runs
|
|
748
748
|
automatically about every 30 minutes; this command forces it now.
|
|
@@ -753,34 +753,34 @@ Options:
|
|
|
753
753
|
Off still accepts a release the Anyray team marks mandatory.
|
|
754
754
|
--json Emit the result as JSON.
|
|
755
755
|
--help Show this help.
|
|
756
|
-
`,
|
|
756
|
+
`,pJ=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},fJ=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"fleet-directed":return"Your organization applies Connect updates centrally. This machine does not update on its own; an administrator pushes new versions.";case"fleet-off":return"Your organization manages Connect updates outside Anyray. This machine does not download binaries; new versions arrive through your own deployment tooling.";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}.`}},bR=async e=>{let t;try{t=pJ(e)}catch(o){return R(o.message),process.stderr.write(wR),1}if(t.help)return process.stdout.write(wR),0;if(t.auto!==void 0){let o=await P();if(o.autoUpdate!==!1!==t.auto&&await ce({...o,autoUpdate:t.auto}),t.json||(M(`Automatic updates ${t.auto?"enabled":"disabled"}.`),t.auto||A("A release the Anyray team marks mandatory still installs \u2014 that lever is for security fixes.")),!t.auto)return t.json&&process.stdout.write(`${JSON.stringify({autoUpdate:!1},null,2)}
|
|
757
757
|
`),0}let n=await Za({checkOnly:t.check,force:!t.check,allowNpmMigration:!0,initiator:"human"});if(t.json){let o=await _o();return process.stdout.write(`${JSON.stringify({...n,autoUpdate:o.autoUpdate,path:o.path,selfUpdateAvailable:o.available,selfUpdateState:o.state,fleetUpdateMode:o.fleetMode},null,2)}
|
|
758
|
-
`),n.outcome==="failed"?1:0}let r=
|
|
758
|
+
`),n.outcome==="failed"?1:0}let r=fJ(n);switch(n.outcome){case"updated":case"migrated":M(r);break;case"current":M(r);break;case"available":case"migration-available":A(r),t.check&&A(`Run ${K("anyray-connect update")} to install it.`);break;case"migration-deferred":O(r),A(v("Use the newer npm runtime until that standalone release is published."));break;case"disabled":O(r),A(`Run ${K("anyray-connect update")} to install it now, or ${K("--auto on")} to resume.`);break;case"fleet-directed":case"fleet-off":A(r),A(v("Ask your Anyray administrator if you need a newer version."));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":O(r),A(v("Keep using `npx anyray-connect@latest` on this platform."));break;case"unavailable":O(r);break;case"failed":return R(r),1}return 0};var mJ=3e3,AR=async(e={})=>{let t=e.stdout??(i=>process.stdout.write(i)),n=e.stderr??(i=>process.stderr.write(i)),r=e.latestVersion??(()=>Ry(mJ)),o=e.updateStatus??_o;t(`anyray-connect ${Ee}
|
|
759
759
|
`);let[a,s]=await Promise.all([r().catch(()=>{}),o().catch(()=>{})]);if(a&&ja(a,Ee)>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: ${Ee} \u2192 ${a}
|
|
760
760
|
${i}
|
|
761
|
-
`)}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
|
|
762
|
-
`),0};import
|
|
763
|
-
`)},
|
|
764
|
-
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,
|
|
761
|
+
`)}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 hJ=e=>{if(typeof e!="string"||e.length===0||e.length>512)return!1;try{return new URL(e).protocol==="https:"}catch{return!1}},yJ=e=>typeof e=="string"&&/^[A-Za-z0-9-]{4,16}$/.test(e),gJ=async(e={})=>{try{let t=await(e.readBootstrap??Pr)().catch(()=>{});if(!t)return{status:"noop"};await(e.refreshIfDue??Ht)().catch(()=>{});let n=await(e.loadProfile??P)();if(Ae(n.clientKey))return{status:"enrolled"};let r=await(e.ssoGate??Lo)({sso:t.sso,gateway:t.gateway??n.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(r.exitCode===0)return n=await(e.loadProfile??P)(),Ae(n.clientKey)?{status:"enrolled"}:{status:"noop"};if(r.exitCode!==2||!r.stderr)return{status:"noop"};let o=await(e.readState??Ja)().catch(()=>{}),a=o?.verificationUriComplete,s=o?.userCode;if(!hJ(a)||!yJ(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"}}},CR=async(e={})=>{let t=await gJ(e);return process.stdout.write(`${JSON.stringify(t)}
|
|
762
|
+
`),0};import wJ from"node:path";var bJ="2025-06-18",AJ={name:"anyray",version:"1"},kR={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}},CJ=20,vR={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}},RR=gy,kJ=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,RR)},vJ=e=>e==="paths"||e==="lines"||e==="full"?e:"full",SR={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-${RR}). 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}},ER={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}},SJ=8,EJ=3,IR={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}},IJ=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(`
|
|
763
|
+
`)},xJ=(e,t)=>{if(t.matches.length===0)return`No imported conversation mentions "${e}".
|
|
764
|
+
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,SJ).map(([a,s])=>{let i=s.slice(0,EJ).map(c=>` ${c.text.trim()}`);return[` ${a}`,...i].join(`
|
|
765
765
|
`)});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(`
|
|
766
766
|
`)},Ce=(e,t)=>({jsonrpc:"2.0",id:e,result:t}),kg=(e,t,n)=>({jsonrpc:"2.0",id:e,error:{code:t,message:n}}),xR=e=>e?.name??"error",ge=(e,t=!1)=>{let n=e;if(n.length>4e4){let r=t?`
|
|
767
767
|
|
|
768
768
|
[anyray: error output cut to fit the tool-result limit \u2014 ${n.length} chars total.]`:`
|
|
769
769
|
|
|
770
770
|
[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(`
|
|
771
|
-
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},
|
|
772
|
-
`+y.content))}let
|
|
773
|
-
${p.content}`))}return Ce(n??null,ge(p.content))}if(a.name===vR.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Ce(n??null,ge("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 Ce(n??null,l.ok?ge(
|
|
774
|
-
`),!0}catch{return!1}},l,d=()=>{
|
|
775
|
-
`))>=0;){let
|
|
771
|
+
`);n=(a>0?o.slice(0,a):o)+r}return{content:[{type:"text",text:n}],...t?{isError:!0}:{}}},OR=e=>{try{e.heartbeat?.().catch(()=>{})}catch{}},RJ=async(e,t)=>{let n=e?.id,r=n===void 0,o=typeof e?.method=="string"?e.method:"";switch(o){case"initialize":return OR(t),Ce(n??null,{protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:bJ,capabilities:{tools:{}},serverInfo:AJ});case"notifications/initialized":case"notifications/cancelled":return null;case"ping":return Ce(n??null,{});case"tools/list":{let a=[kR,vR];t.advertiseContextTools!==!1&&a.push(SR,ER);let s=!1;try{s=await t.historyAvailable()}catch{s=!1}return s&&a.push(IR),Ce(n??null,{tools:a})}case"tools/call":{let a=e.params??{},s=a.arguments??{};if(a.name===kR.name){let i=typeof s.handle=="string"?s.handle.trim():"";if(!i)return Ce(n??null,ge("handle is required",!0));let c=g=>{if(g!==void 0)return typeof g!="number"||!Number.isFinite(g)?null:Math.max(Math.round(g),1)},l=c(s.startLine),d=c(s.endLine);if(l===null||d===null)return Ce(n??null,ge("startLine/endLine must be numbers",!0));let u;if(s.grep!==void 0){if(typeof s.grep!="string"||s.grep.trim()==="")return Ce(n??null,ge("grep must be non-empty",!0));if(s.grep.length>256)return Ce(n??null,ge("grep is limited to 256 characters",!0));u=s.grep}let f=l!==void 0||d!==void 0||u!==void 0,m=Yy(i);if(m){let g=await Jy(m);if(u!==void 0)return Ce(n??null,ge(`${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 ${g??"the path in the footer"} directly.`,!0));let y=t.readTee?await t.readTee(m,{startLine:l,endLine:d}).catch(b=>({ok:!1,content:"",path:g??m,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 Ce(n??null,ge(`[anyray: ${i} is a local hook-tee file, not a stash handle \u2014 served ${b} from ${y.teePath??g}.${k} Read that path directly next time.]
|
|
772
|
+
`+y.content))}let w=y!==null;return Ce(n??null,ge(`${i} is a hook-tee file id, not a stash handle`+(w&&g?`, and ${g} 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 ${g??"the path in its footer"} directly.`),!0))}let p;try{p=await t.retrieve(i,f?{startLine:l,endLine:d,grep:u}:void 0)}catch(g){p={ok:!1,message:g instanceof Error?g.message:"retrieve failed"}}let h="this gateway does not support partial retrieval yet \u2014 call again without startLine/endLine/grep for the full content";if(!p.ok)return Ce(n??null,ge(p.kind==="slice-unsupported"?h:p.message,!0));if(f&&(p.partial===void 0||typeof p.totalLines!="number"))return Ce(n??null,ge(h,!0));if(p.partial===!0&&typeof p.totalLines=="number"){let g=p.grepMatches!==void 0?`[anyray: partial \u2014 ${p.grepMatches} matching line(s) in lines ${p.startLine}-${p.endLine} of ${p.totalLines}`+(p.grepTruncated?`, windows around the first ${CJ} matches shown \u2014 narrow the range or grep`:"")+` \xB7 retrieve ${i} again with startLine/endLine, another grep, or no params for full]`:`[anyray: partial \u2014 lines ${p.startLine}-${p.endLine} of ${p.totalLines} \xB7 retrieve ${i} again with other lines, grep, or no params for full]`;return Ce(n??null,ge(`${g}
|
|
773
|
+
${p.content}`))}return Ce(n??null,ge(p.content))}if(a.name===vR.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Ce(n??null,ge("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 Ce(n??null,l.ok?ge(IJ(l.matches)):ge(l.message,!0))}if(a.name===SR.name){let i=typeof s.query=="string"?s.query.trim():"";if(!i)return Ce(n??null,ge("query is required",!0));let c=Array.isArray(s.globs)?s.globs.filter(f=>typeof f=="string"):void 0,l=kJ(s.maxResults),d=vJ(s.resultShape),u;try{u=await t.search(i,c,l)}catch(f){u={ok:!1,matches:[],truncated:!1,engine:"ripgrep",message:f instanceof Error?f.message:"search failed"}}return Ce(n??null,u.ok?ge(zI(i,u,d)):ge(u.message??"search failed",!0))}if(a.name===IR.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 Ce(n??null,d.ok?ge(my(d)):ge(d.message??"history open failed",!0))}let c=typeof s.query=="string"?s.query.trim():"";if(!c)return Ce(n??null,ge("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 Ce(n??null,l.ok?ge(xJ(c,l)):ge(l.message??"history search failed",!0))}if(a.name===ER.name){let i=typeof s.path=="string"?s.path.trim():"";if(!i)return Ce(n??null,ge("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 Ce(n??null,l.ok?ge(my(l)):ge(l.message??"read failed",!0))}return kg(n??null,-32602,`unknown tool: ${String(a.name)}`)}default:return r?null:kg(n??null,-32601,`method not found: ${o}`)}},OJ=async(e,t=fetch)=>{if(!e)return!1;let n=new AbortController,r=setTimeout(()=>n.abort(),Nd);try{return(await t(`${e.origin}/connect/mcp-heartbeat`,{method:"POST",headers:Yt(e),signal:n.signal})).ok}catch{return!1}finally{clearTimeout(r)}},TJ=(e,t=!0)=>({retrieve:async(n,r)=>Ma(await e(),n,r),recall:async(n,r)=>$d(await e(),n,r),search:(n,r,o)=>ru(n,{globs:r,...o?{maxMatches:o}:{}}),read:(n,r)=>Di(n,r),readTee:async(n,r)=>{if(jy())return{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"the hook tee is off (ANYRAY_HOOK_TEE=off)"};let o=await Jy(n);return o?{...await Di(o,{cwd:wJ.dirname(o),...r}),teePath:o}:{ok:!1,content:"",path:n,lines:0,truncated:!1,message:"not a tee id"}},historySearch:n=>ex(n),historyOpen:n=>tx(n),historyAvailable:async()=>await Ga()>0,advertiseContextTools:t,heartbeat:async()=>{try{return await OJ(await e())}catch{return!1}}}),_J=5*6e4,TR=async(e="auto",t={})=>{let n=TJ(()=>nt(e),e!=="claude");t.heartbeat&&(n.heartbeat=t.heartbeat);let r=t.stdin??process.stdin,o=t.stdout??process.stdout,a=0,s=t.refreshTick??(()=>{let p=Date.now();p<a||(a=p+6e4,Lr().catch(()=>{}))}),i=()=>{try{s()}catch{}},c=p=>{try{return o.write(JSON.stringify(p)+`
|
|
774
|
+
`),!0}catch{return!1}},l,d=()=>{l||!n.heartbeat||(l=setInterval(()=>OR(n),_J),l.unref())},u=async p=>{let h=p.trim();if(!h)return;let g;try{g=JSON.parse(h)}catch{console.error("anyray mcp: dropping unparseable frame");return}let y;try{y=await RJ(g,n)}catch(b){console.error("anyray mcp: dispatch error",xR(b)),y=g?.id===void 0?null:kg(g.id,-32603,"internal error")}let w=y?c(y):!1;g.method==="initialize"&&y&&!y.error&&w&&d(),i()};i();let f=setInterval(i,30*6e4);f.unref();let m="";try{for await(let p of r){m+=p.toString("utf-8");let h;for(;(h=m.indexOf(`
|
|
775
|
+
`))>=0;){let g=m.slice(0,h);m=m.slice(h+1),await u(g)}}m.trim()&&await u(m)}catch(p){console.error("anyray mcp: stdin error",xR(p))}finally{clearInterval(f),l&&clearInterval(l)}return 0};import{spawn as PJ}from"node:child_process";var DJ=e=>e==="jetbrains"||e==="windsurf"?e:void 0,LJ=async(e,t,n,r=1e4)=>{let o=await new Promise(a=>{let s="",i=!1,c=m=>{i||(i=!0,clearTimeout(l),t.off("data",d),t.off("error",u),t.off("end",f),a(m))},l=setTimeout(()=>c(void 0),r),d=m=>{s+=m.toString();let p=s.indexOf(`
|
|
776
776
|
`);p!==-1?c(s.slice(0,p)):s.length>65536&&c(void 0)},u=()=>c(void 0),f=()=>c(s.length>0?s:void 0);t.on("data",d),t.once("error",u),t.once("end",f)});if(o===void 0)return!1;try{let s=JSON.parse(o)?.id;return typeof s!="number"&&typeof s!="string"?!1:(n.write(`${JSON.stringify({jsonrpc:"2.0",id:s,error:{code:-32e3,message:e}})}
|
|
777
|
-
`),!0)}catch{return!1}},
|
|
777
|
+
`),!0)}catch{return!1}},NJ={claude:["ANTHROPIC_AUTH_TOKEN","ANTHROPIC_API_KEY"],codex:["OPENAI_API_KEY"]},$J=(e,t,n)=>{let r=new Set(NJ[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}},_R=async(e,t,n={})=>{let r=n.stderr??process.stderr;if(e!=="claude"&&e!=="codex")return r.write(`Unknown ACP agent.
|
|
778
778
|
`),1;let o=n.platform??process.platform,a=n.environment??process.env;if(!t||!hd(t,o))return r.write(`Anyray ACP prerequisite is invalid; re-run anyray-connect with Node.js/npm available.
|
|
779
|
-
`),1;await(n.refreshIfDue??Ht)().catch(()=>{});let s=await(n.loadProfile??P)(),i=await(n.readBootstrap??Pr)().catch(()=>{});if(i){let
|
|
780
|
-
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??wn)():void 0,d=Re({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=
|
|
781
|
-
`),1;
|
|
782
|
-
`),
|
|
783
|
-
`,"utf8"),await a.chmod(384),await Qn(a),await a.close(),a=void 0,await(t.publish??ye)(o,r)}catch(s){throw a&&await a.close().catch(()=>{}),await
|
|
779
|
+
`),1;await(n.refreshIfDue??Ht)().catch(()=>{});let s=await(n.loadProfile??P)(),i=await(n.readBootstrap??Pr)().catch(()=>{});if(i){let w=await(n.ssoGate??Lo)({sso:i.sso,gateway:i.gateway??s.gateway},{routingIntact:async()=>!0,applyClaudeCode:async()=>{}});if(w.exitCode===2&&w.stderr)return await LJ(w.stderr.trim(),n.stdin??process.stdin,n.stdout??process.stdout)||r.write(w.stderr),1;s=await(n.loadProfile??P)()}if(!s.gateway)return r.write(`Anyray ACP agent is not configured; run anyray-connect first.
|
|
780
|
+
`),1;let c=s.authMode??"auto",l=c==="auto"?await(n.detectSeatState??wn)():void 0,d=Re({origin:s.gateway,clientKey:s.clientKey,user:s.name,team:s.team,subscription:c==="subscription",placeholder:c==="placeholder",seat:l}),u=DJ(n.clientTool);u&&(d.metadata.tool=u);let f=e==="claude"?"Anyray \xB7 Claude":"Anyray \xB7 Codex",m=(n.hookBinaryIsDurable??oe)(),p=nS(d,t,{mcpServer:m?Ge("profile"):void 0})[f],h=n.spawn??PJ,g=p.command,y=p.args;if(o==="win32"){if(!p.args.every(w=>w==="--yes"||/^@agentclientprotocol\/(claude-agent-acp|codex-acp)@[0-9]+(?:\.[0-9]+){2}$/.test(w)))return r.write(`Anyray ACP adapter arguments are invalid.
|
|
781
|
+
`),1;g=n.comSpec??a.ComSpec??"cmd.exe",y=["/d","/s","/c",`"${p.command}" ${p.args.join(" ")}`]}return await new Promise(w=>{let b=$J(e,a,p.env),k=h(g,y,{env:b,stdio:"inherit",windowsHide:!0});k.once("error",()=>{r.write(`Could not start the ${e} ACP adapter.
|
|
782
|
+
`),w(1)}),k.once("exit",(C,S)=>{w(typeof C=="number"?C:S?1:0)})})};import{randomUUID as MJ}from"node:crypto";import{open as BJ,rm as FJ}from"node:fs/promises";import{join as WJ}from"node:path";import{z as _e}from"zod";var Ou=_e.string().min(1).refine(e=>Number.isFinite(Date.parse(e)),"expected an ISO-8601 timestamp"),UJ=_e.enum(["reconcile","refresh","repair","status","offboard"]),vg=_e.union([_e.literal(0),_e.literal(1),_e.literal(2),_e.literal(3),_e.literal(4)]),HJ=_e.enum(["locked","required","recommended","optional"]),Tu=_e.object({schemaVersion:_e.literal(1),generatedAt:Ou,connectVersion:_e.string().min(1),fleetManaged:_e.boolean(),enrollment:_e.object({state:_e.enum(["enrolled","degraded","broken","none"]),lastRefreshAt:Ou.optional(),lastRefreshOutcome:_e.enum(["ok","failed"]).optional()}).strict(),keyExpiresAt:Ou.optional(),tools:_e.array(_e.object({id:_e.string().min(1),tier:HJ,routed:_e.boolean()}).strict()),lastVerb:_e.object({verb:UJ,exitCode:vg,at:Ou}).strict()}).strict(),PR=(e,t)=>{if(!e)return!1;let n=Date.parse(e);return Number.isFinite(n)&&n>t},GJ=(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||!PR(o,n)?"broken":!e.clientKey||e.clientKeyExpiresAt&&!PR(e.clientKeyExpiresAt,n)?"degraded":"enrolled"},VJ=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"}},DR=(e,t)=>e.fleetToolPolicy?.tiers?.[t]??"required",KJ=async(e,t)=>{let n=new Set(e.managedTools??[]),r=new Set(e.revertedTools??[]),o=(e.fleetToolPolicy?.enabled??[]).filter(c=>{let l=DR(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:DR(e,c),routed:d})}return i},LR=async(e,t={})=>{let n=t.now??Date.now,r=await(t.loadProfile??P)(),o=await(t.loadDevKey??Fe)().catch(()=>{}),a=await(t.readRefreshState??It)().catch(()=>({})),s={schemaVersion:1,generatedAt:new Date(n()).toISOString(),connectVersion:Ee,fleetManaged:r.anyrayFleetManaged===!0,enrollment:{state:GJ(r,!!o,n()),...VJ(a)},...r.clientKeyExpiresAt&&Number.isFinite(Date.parse(r.clientKeyExpiresAt))?{keyExpiresAt:r.clientKeyExpiresAt}:{},tools:await KJ(r,t.toolById??pt),lastVerb:e};return Tu.parse(s)},jJ=()=>WJ(ee(),"status.json"),NR=async(e,t={})=>{let n=Tu.parse(e);await(t.ensureStateDir??et)();let r=jJ(),o=`${r}.${process.pid}.${MJ()}.tmp`,a;try{a=await BJ(o,"wx",384),await a.writeFile(`${JSON.stringify(n,null,2)}
|
|
783
|
+
`,"utf8"),await a.chmod(384),await Qn(a),await a.close(),a=void 0,await(t.publish??ye)(o,r)}catch(s){throw a&&await a.close().catch(()=>{}),await FJ(o,{force:!0}).catch(()=>{}),s}},Sg=e=>e.enrollment.state==="none"||e.enrollment.state==="broken"?3:e.enrollment.state==="degraded"?4:e.tools.every(t=>t.routed)?0:4;var ZJ=1e4,es=e=>e?.name??"Error",Eg=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(ZJ)})}catch(o){console.error(`anyray seat offboard report: ${es(o)}`)}},YJ=e=>e==="reverted"||e==="queued",_u=async(e={})=>{let t=e.loadProfile??P,n=e.clearDeviceTokenState??Vd,r=e.reportSeatOffboarded??Eg,o=e.clearEnrollment??sc,a=e.recordManagedTools??er,s=e.markSeatOffboarded??ic,i=e.adapterById??pt,c=e.uninstallScheduler??_n,l=e.unitsPresent??Dc,d=e.saveProfile??ce,u=await t(),f=u.managedTools??[];await r(u).catch(()=>{}),await n().catch(()=>{});let m=!1,p=!1;try{m=await o()}catch(C){p=!0,console.error(`anyray offboard: clearing enrollment: ${es(C)}`)}let h=[],g=[],y=[];for(let C of f){let S=i(C);if(!S){y.push(C);continue}try{let E=await S.revert({dryRun:!1,fullRevert:!0});h.push({id:C,status:E.status}),YJ(E.status)?g.push(C):y.push(C)}catch(E){console.error(`anyray offboard: reverting ${C}: ${es(E)}`),y.push(C)}}let w=!0;try{await a(h,!0,!0)}catch(C){w=!1,console.error(`anyray offboard: recording managed tools: ${es(C)}`)}let b=y.length===0&&w,k=!1;if(b)try{await s(),k=!0}catch(C){console.error(`anyray offboard: stamping offboard: ${es(C)}`)}try{((await t()).refreshSchedulerEnabled||await l())&&await c(),await d({...await t(),refreshSchedulerEnabled:!1})}catch(C){console.error(`anyray offboard: unit teardown: ${es(C)}`)}return{reverted:g,unresolved:y,enrollmentCleared:m,credentialHeld:p,recordPersisted:w,offboardMarked:k,ok:y.length===0&&!p&&w&&k}};var ue={success:0,unexpected:1,usage:2,authBroken:3,partial:4},JJ=`Stable non-interactive runtime commands:
|
|
784
784
|
anyray-connect reconcile
|
|
785
785
|
anyray-connect refresh
|
|
786
786
|
anyray-connect repair
|
|
@@ -796,12 +796,12 @@ Exit codes:
|
|
|
796
796
|
1 unexpected error
|
|
797
797
|
2 usage error (unknown flag or argument)
|
|
798
798
|
3 authentication broken; re-enrollment required
|
|
799
|
-
4 partial; the command ran but drift remains`,
|
|
799
|
+
4 partial; the command ran but drift remains`,XJ={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"},zJ=e=>e.replaceAll("-","_"),BR=e=>{let t=e[0];if(!t)return;let n=XJ[zJ(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}},Ig=e=>{let t=e?.name;return typeof t=="string"&&/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(t)?t:"Error"},qJ=async(e=P,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 La(n.gateway,n.clientKey);return await Na(i)}catch(i){if(Oh(i))return o?"credential-degraded":"auth-broken";throw i}},QJ=e=>e==="auth-broken"?ue.authBroken:e==="credential-degraded"||e.toolsApplied<e.toolsRequested||e.toolsTombstoned.length>0?ue.partial:ue.success,e5=e=>e.refresh==="not-enrolled"||e.refresh==="cert-expired"||e.refresh==="cert-rejected"?ue.authBroken:e.refresh==="failed"?ue.unexpected:e.partial||e.refresh==="disabled"||e.refresh==="backoff"||e.refresh==="throttled"||e.refresh==="gateway-incompatible"?ue.partial:ue.success,t5=e=>!e.enrollment.enrolled||e.enrollment.expired===!0||e.verify?.kind==="enrollment-required",$R=async e=>{let t;return{code:await yu({repair:e,quick:!e,silent:!0},{captureReport:r=>t=r}),authBroken:t?t5(t):!1}},MR=e=>typeof e!="number"&&e.authBroken?ue.authBroken:(typeof e=="number"?e:e.code)===0?ue.success:ue.partial,n5=(e,t)=>{let n=Sg(t);return n===ue.authBroken?n:e!==0||n===ue.partial?ue.partial:ue.success},r5=async(e,t)=>{if(e==="reconcile")return QJ(await(t.reconcile??(()=>qJ(t.loadProfile)))());if(e==="refresh"){if(!t.refresh)throw new Error("refresh runtime is unavailable");return e5(await t.refresh())}return e==="repair"?MR(await(t.repair??(()=>$R(!0)))()):e==="status"?MR(await(t.status??(()=>$R(!1)))()):(await(t.offboard??_u)()).ok?ue.success:ue.partial},xg=(e,t)=>Tu.parse({...e,lastVerb:{...e.lastVerb,exitCode:t}}),FR=async(e,t={})=>{let n=t.stdout??console.log,r=t.stderr??console.error;if(e.help)return n(JJ),ue.success;let o=t.now??Date.now,a=new Date(o()).toISOString(),s=t.withProfileLock??is,i=t.buildStatus??LR,c=t.writeStatus??NR,l,d=e.usageError?ue.usage:ue.unexpected;e.usageError&&r(`anyray-connect ${e.verb}: UsageError`);try{await s(async()=>{if(!e.usageError)try{d=vg.parse(await r5(e.verb,t))}catch(u){d=Oh(u)?ue.authBroken:ue.unexpected,r(`anyray-connect ${e.verb}: ${Ig(u)}`)}if(l=await i({verb:e.verb,exitCode:d,at:a},{now:o}),(e.verb==="repair"||e.verb==="status")&&d!==ue.unexpected&&d!==ue.usage&&d!==ue.authBroken)d=n5(d===0?0:1,l);else if(e.verb!=="offboard"&&d!==ue.unexpected&&d!==ue.usage){let u=Sg(l);(u===ue.authBroken||d===ue.success)&&(d=u)}l=xg(l,d);try{await c(l)}catch(u){d=ue.unexpected,l=xg(l,d),r(`anyray-connect ${e.verb}: ${Ig(u)}`)}})}catch(u){d=ue.unexpected,r(`anyray-connect ${e.verb}: ${Ig(u)}`);try{l=xg(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 WR=new Set(["not-due","repaired","cert-renewed","heartbeat-refreshed","refreshed"]),UR=async(e,t={})=>await(t.fleetdPresent??Do)()?WR.has(e)?{retired:!0,messages:(await(t.uninstallScheduler??_n)()).messages}:{retired:!1,reason:"refresh-unhealthy",messages:[]}:{retired:!1,reason:"no-fleetd",messages:[]},HR=async(e,t={})=>{if(!WR.has(e))return{retired:!1,reason:"refresh-unhealthy",messages:[]};let r=await(t.load??P)().catch(()=>{});if(!r)return{retired:!1,reason:"no-profile",messages:[]};if(!r.refreshSchedulerEnabled||r.persistenceOwner==="tray")return{retired:!1,reason:"not-installed",messages:[]};if(Je(r,{},t.now??Date.now()))return{retired:!1,reason:"still-needed",messages:[]};let o=await(t.uninstallScheduler??_n)();if(!o.ok)return{retired:!1,reason:"uninstall-failed",messages:o.messages};if(await(t.schedulerInstalled??Pn)().catch(()=>!0))return{retired:!1,reason:"uninstall-failed",messages:o.messages};let s=t.mutate??nw;return await s(l=>!l.refreshSchedulerEnabled||l.persistenceOwner==="tray"||Je(l,{},t.now??Date.now())?{result:!1}:{next:{...l,refreshSchedulerEnabled:!1,refreshSchedulerInstalledOnce:!1},result:!0}).catch(()=>!1)?await(t.schedulerInstalled??Pn)().catch(()=>!1)?(await s(l=>({next:{...l,refreshSchedulerEnabled:!0,refreshSchedulerInstalledOnce:!0},result:void 0})).catch(()=>{}),{retired:!1,reason:"raced-reinstall",messages:o.messages}):{retired:!0,messages:o.messages}:{retired:!1,reason:"clear-failed",messages:o.messages}};var GR=["reapply_config","remint","revert","revert_tool","update"],o5=/^[a-z0-9][a-z0-9-]{0,31}$/;var a5=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id!="string"||t.id.length===0||typeof t.kind!="string"||!GR.includes(t.kind)?!1:t.kind==="revert_tool"?typeof t.tool=="string"&&o5.test(t.tool):t.tool===void 0},Rg=e=>e?.name??"error",VR=async(e,t,n)=>{let r=n.fetchImpl??fetch,o=e.replace(/\/$/,""),a;try{let i=await r(`${o}/connect/directive`,{method:"GET",headers:{"x-anyray-api-key":t,"x-anyray-directive-kinds":GR.join(",")},signal:AbortSignal.timeout(1e4)});if(i.status===404||!i.ok)return null;let c=await i.json();if(!a5(c.directive))return null;a=c.directive}catch(i){return console.error("connect directive pull skipped:",Rg(i)),null}let s;try{s=await n.execute(a.kind,a.tool)}catch(i){console.error("connect directive execution failed:",Rg(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:",Rg(i))}return a.kind};var KR=e=>e?.name??"Error",jR=async(e,t={})=>{if(!e)return"failed";let n=t.loadProfile??P,r=t.recordManagedTools??er,o=t.adapterById??pt,a=t.isLocked??bi,s=await n().catch(()=>{});if(!s)return"failed";if(!(s.managedTools??[]).includes(e))return"ok";if(a(s,e))return console.error(`anyray revert-tool: ${e} is locked by fleet policy`),"failed";let i=o(e);if(!i)return"failed";let c;try{c=(await i.revert({dryRun:!1,fullRevert:!1})).status}catch(l){return console.error(`anyray revert-tool: reverting ${e}: ${KR(l)}`),"failed"}try{await r([{id:e,status:c}],!0,!1)}catch(l){return console.error(`anyray revert-tool: recording ${e}: ${KR(l)}`),"failed"}return c==="reverted"||c==="queued"?"ok":"failed"};import{basename as s5}from"node:path";import{join as ZR}from"node:path";var i5="history.recentlyOpenedPathsList",c5={"ssh-remote":"ssh","dev-container":"devcontainer","attached-container":"attached-container",wsl:"wsl",codespaces:"codespace",tunnel:"tunnel"},l5=e=>{try{let t=JSON.parse(Buffer.from(e,"hex").toString("utf-8"));if(typeof t.hostPath=="string"&&t.hostPath)return{name:s5(t.hostPath),hostPath:t.hostPath};if(typeof t.containerName=="string"&&t.containerName)return{name:t.containerName.replace(/^\//,"")}}catch{}return{name:"container"}},d5=e=>{let t=/^vscode-remote:\/\/([^/]+)/.exec(e);if(!t)return;let n;try{n=decodeURIComponent(t[1])}catch{return}let r=n.indexOf("+");if(r<=0)return;let o=c5[n.slice(0,r)];if(!o)return;let a=n.slice(r+1);if(a){if(o==="devcontainer"||o==="attached-container"){let s=l5(a);return{kind:o,name:s.name,...o==="devcontainer"&&s.hostPath?{ref:s.hostPath}:{}}}return{kind:o,name:a}}},u5=e=>{let t;try{t=JSON.parse(e).entries}catch{return[]}if(!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){if(typeof o!="object"||o===null)continue;let a=o,s=[a.folderUri,a.fileUri,a.workspace?.configPath].filter(i=>typeof i=="string");for(let i of s){let c=d5(i);if(!c)continue;let l=`${c.kind}|${c.ref??c.name}`;r.has(l)||(r.add(l),n.push(c))}}return n},p5=()=>[...ro.map(e=>ZR(ul(e),"User","globalStorage","state.vscdb")),ZR(Ne("Cursor"),"User","globalStorage","state.vscdb")],Og=async(e={})=>{let t=e.readItem??(()=>{let o=mr();return o?o.readItem.bind(o):void 0})();if(!t)return[];let n=[],r=new Set;for(let o of e.dbPaths??p5()){let a;try{a=t(o,i5)}catch{continue}if(a)for(let s of u5(a)){let i=`${s.kind}|${s.ref??s.name}`;r.has(i)||(r.add(i),n.push(s))}}return n};import{execFile as f5,spawn as m5}from"node:child_process";import{promisify as h5}from"node:util";var y5="https://app.anyray.ai/connect.sh",g5=".anyray/bin/anyray-connect",ts=e=>`'${e.replaceAll("'",`'"'"'`)}'`,w5=e=>{let n=`${["set -eu","if command -v anyray-connect >/dev/null 2>&1; then"," command -v anyray-connect"," exit 0","fi",`ANYRAY_CONNECT_TAG=${ts(`connect-v${Ee}`)} \\`,` sh -c ${ts(`curl -fsSL ${y5} | sh`)} >&2 </dev/null`,`echo "$HOME/${g5}"`].join(`
|
|
800
800
|
`)}
|
|
801
|
-
`;switch(e.kind){case"ssh":return{command:"ssh",args:["-T","--",e.name,"sh","-s"],stdin:n};case"devcontainer":return{command:"docker",args:["exec","-i",e.name,"sh","-s"],stdin:n};case"wsl":return{command:"wsl.exe",args:["-d",e.name,"--","sh","-s"],stdin:n};case"codespace":return{command:"gh",args:["codespace","ssh","-c",e.name,"--","sh -s"],stdin:n}}},
|
|
802
|
-
`;switch(e.kind){case"ssh":return{command:"ssh",args:["-T","--",e.name,o],stdin:a};case"devcontainer":return{command:"docker",args:["exec","-i",e.name,...r],stdin:a};case"wsl":return{command:"wsl.exe",args:["-d",e.name,"--",...r],stdin:a};case"codespace":return{command:"gh",args:["codespace","ssh","-c",e.name,"--",o],stdin:a}}},
|
|
803
|
-
`).map(s=>s.trim()).filter(Boolean);if(a.length===0)throw new Error("No running dev container matches the discovered workspace.");if(a.length>1)throw new Error(`${a.length} running dev containers match this workspace; stop the stale one (docker ps --filter label=devcontainer.local_folder=...) and re-run.`);return a[0]},
|
|
804
|
-
`).map(c=>c.trim()).filter(Boolean).at(-1);return s?(await
|
|
801
|
+
`;switch(e.kind){case"ssh":return{command:"ssh",args:["-T","--",e.name,"sh","-s"],stdin:n};case"devcontainer":return{command:"docker",args:["exec","-i",e.name,"sh","-s"],stdin:n};case"wsl":return{command:"wsl.exe",args:["-d",e.name,"--","sh","-s"],stdin:n};case"codespace":return{command:"gh",args:["codespace","ssh","-c",e.name,"--","sh -s"],stdin:n}}},b5=(e,t,n)=>{let r=[n,"--yes","--key-stdin","--gateway",t.gateway,...t.user!==void 0?["--user",t.user]:[],...t.team!==void 0?["--team",t.team]:[]],o=[ts(n),"--yes","--key-stdin","--gateway",ts(t.gateway),...t.user!==void 0?["--user",ts(t.user)]:[],...t.team!==void 0?["--team",ts(t.team)]:[]].join(" "),a=`${t.clientKey}
|
|
802
|
+
`;switch(e.kind){case"ssh":return{command:"ssh",args:["-T","--",e.name,o],stdin:a};case"devcontainer":return{command:"docker",args:["exec","-i",e.name,...r],stdin:a};case"wsl":return{command:"wsl.exe",args:["-d",e.name,"--",...r],stdin:a};case"codespace":return{command:"gh",args:["codespace","ssh","-c",e.name,"--",o],stdin:a}}},A5=h5(f5),C5=async(e,t)=>(await A5(e,[...t],{encoding:"utf8"})).stdout.toString(),Tg=async(e,t={})=>{let n=typeof e=="string"?{name:e}:e,r=n.ref??(/[/\\]/.test(n.name)?n.name:void 0);if(!r)throw new Error("Cannot resolve a dev container by its bare name; use its full host path.");let a=(await(t.exec??C5)("docker",["ps","--filter",`label=devcontainer.local_folder=${r}`,"--format","{{.ID}}"])).split(`
|
|
803
|
+
`).map(s=>s.trim()).filter(Boolean);if(a.length===0)throw new Error("No running dev container matches the discovered workspace.");if(a.length>1)throw new Error(`${a.length} running dev containers match this workspace; stop the stale one (docker ps --filter label=devcontainer.local_folder=...) and re-run.`);return a[0]},YR=(e,t,n)=>new Promise(r=>{let o;try{o=t(e.command,e.args,{stdio:["pipe",n?"pipe":"inherit","inherit"]})}catch{r({code:1,stdout:""});return}let a="",s=!1,i=c=>{s||(s=!0,r({code:c,stdout:a}))};if(o.stdout?.on("data",c=>{a+=c.toString("utf-8")}),o.once("error",()=>i(1)),o.once("close",c=>i(c??1)),!o.stdin){i(1);return}o.stdin.end(e.stdin)}),_g=async(e,t,n={})=>{let r=n.spawn??m5,o=e.kind==="devcontainer"&&e.ref?{...e,name:await Tg(e,n)}:e,a=await YR(w5(o),r,!0);if(a.code!==0)return a.code;let s=a.stdout.split(`
|
|
804
|
+
`).map(c=>c.trim()).filter(Boolean).at(-1);return s?(await YR(b5(o,t,s),r,!1)).code:1};import{spawnSync as k5}from"node:child_process";import{platform as Lu}from"node:os";import{basename as v5}from"node:path";import{createInterface as S5}from"node:readline";var XR=`${K("anyray-connect")} \u2014 point your local coding tools at the Anyray gateway
|
|
805
805
|
|
|
806
806
|
${K("Usage")}
|
|
807
807
|
npx anyray-connect [options]
|
|
@@ -1058,22 +1058,22 @@ ${K("What it does")}
|
|
|
1058
1058
|
key stays server-side (ANYRAY_PROVIDER_KEY_*); your tools never hold it. Only
|
|
1059
1059
|
metadata (user/team) is attached \u2014 never prompt content.
|
|
1060
1060
|
~/.anyray (mode 600) remembers your gateway, name/team, personal key, and the
|
|
1061
|
-
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,
|
|
1062
|
-
${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?`}`,
|
|
1063
|
-
${o} ${n} tool target(s)?`;return await(r.confirm??Oo)(a)?"proceed":"declined"},J5=async(e=Za)=>{let t=await e({force:!0,respectFailureBackoff:!0,allowNpmMigration:!0,initiator:"directive"});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";case"fleet-off":return"failed";case"fleet-directed":return"failed";default:return t.outcome}},tO=(e,t)=>oO(e,!1,{managedEnrollmentRevertedTools:t}),X5=()=>gg(wg(tO)),z5=async()=>{let e=!1,t=await mR(await Ht({runAmbientSelfcheck:!0}),{...wg(tO),refresh:()=>Ht({})});await Ep(),await KE(),await jE()==="retry"&&(e=!0);let n=await P().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await ce(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await Do().catch(()=>!1);if(n&&(await WR(t,{fleetdPresent:async()=>r}).catch(()=>{}),await UR(t).catch(()=>{}),r&&n.gateway&&n.clientKey)){let o=n.gateway,a=n.clientKey,s=Ut(),i=n.enrolledCert;if(s&&i){let l=await Fe().catch(()=>{});l&&await LS(o,a,i,l,s).catch(()=>{})}await GR(o,a,{execute:async(l,d)=>{let u;return l==="remint"||l==="reapply_config"?u=await Ht({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?u=await KR(d):l==="update"?u=await J5():u=(await _u()).ok?"ok":"failed",u==="failed"&&(e=!0),u}}).catch(()=>{})}return r||await Za(),{refresh:t,...e?{partial:!0}:{}}},q5=async e=>{if(e[0]==="__anyray-hook"){let r=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return y0(r)}if(e[0]==="__anyray-codex-hook")return g0();if(e[0]==="__anyray-prompt-hook")return S0();if(e[0]==="__anyray-shell-pretool")return R0();if(e[0]==="__anyray-shell-run")return x0(e.slice(1));if(e[0]==="__anyray-read-pretool")return $0();if(e[0]==="__anyray-sso-gate")return v0(e.slice(1));if(e[0]==="__anyray-sso-poll")return hR();if(e[0]==="__anyray-managed-enroll")try{return await is(X5,{waitMs:eO})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return CR();if(e[0]==="__anyray-spawn-refresh")return await Lr(),0;if(e[0]==="__anyray-mcp-server"){let r=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return OR(r)}if(e[0]==="__anyray-acp-agent")return TR(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return uR(e.slice(1));let t=MR(e);if(t)return BR(t,{refresh:z5});if(e[0]==="__anyray-persistence")return Kw(e.slice(1));if(e[0]==="__anyray-quit-watch")return hS(e.slice(1));if(e[0]===xr)return gI(e.slice(1));if(e[0]===Qs)return bI(e.slice(1));if(e[0]===zr){let r=e[1];return r&&await Qd(r),0}if(e[0]==="--version"||e[0]==="-V")return AR();try{let r=await lw(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(j5(e)){let r=K5(await vx());r?.level==="warn"?O(r.message):r&&console.error(r.message)}if(e[0]==="managed")return eE(e.slice(1));if(e[0]==="endpoint")return dR(e.slice(1));if(e[0]==="print-key")return XE(e.slice(1));if(e[0]==="models")return qE(e.slice(1));if(e[0]==="copilot-login")return QE(e.slice(1));if(e[0]==="desktop"){let r=e.slice(1),o=uy(r);return o?Dg(o,!1):HI(r)}if(e[0]==="retrieve")return VI(e.slice(1));if(e[0]==="recall")return KI(e.slice(1));if(e[0]==="history")return rx(e.slice(1));if(e[0]==="migrate")return ax(e.slice(1));if(e[0]==="login")return gR(e.slice(1));if(e[0]==="update")return bR(e.slice(1));if(e[0]==="remote")return iX(e.slice(1));let n=e[0];if(n&&G5.has(n)){let r=e.slice(1),o;try{o=Lg(r)}catch(a){return R(a.message),A("\nRun `npx anyray-connect --help` for usage."),1}return o.help?(A(o.helpAll?Du:JR),0):n==="status"?Tx({gateway:o.gateway}):n==="doctor"?yu({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"?oI():Dg(r,!0)}return Dg(e,!1)},nO=async e=>{try{return await q5(e)}catch(t){if(t instanceof mt)return console.error(v("Cancelled.")),130;throw t}},Q5=e=>{let t=process.platform==="win32"?"where":"which";try{return C5(t,[e],{stdio:"ignore"}).status===0}catch{return!1}},eX=(e,t={})=>{let n=t.which??Q5,r=t.platform??Lu;switch(e.kind){case"ssh":return!0;case"devcontainer":return n("docker");case"wsl":return r()==="win32"&&n("wsl.exe");case"codespace":return n("gh")}},tX=e=>{switch(e.kind){case"ssh":case"devcontainer":case"wsl":case"codespace":return{kind:e.kind,name:e.name,...e.kind==="devcontainer"&&e.ref?{ref:e.ref}:{}};case"attached-container":case"tunnel":return}},nX=(e,t)=>{switch(e.kind){case"ssh":return`Configure \`${t}\` over SSH now?`;case"devcontainer":return`Configure \`${t}\` in this dev container now?`;case"wsl":return`Configure \`${t}\` in WSL now?`;case"codespace":return`Configure Codespace \`${t}\` now?`}},rX=e=>e.interactive&&!e.managed&&!e.yes&&!e.revert&&!e.dryRun,oX=async(e,t={})=>{if(!rX(e)||!Ae(e.clientKey))return;let n=t.discoverRemoteEnvironments??Og,r;try{r=await n()}catch{return}let o=t.confirm??Oo,a=t.runRemoteApply??_g,s=t.isCarrierAvailable??eX,i=t.resolveDevcontainer??Tg;for(let c of r){let l=tX(c);if(!l)continue;let d=l;try{if(!await s(d))continue;d.kind==="devcontainer"&&(d={kind:"devcontainer",name:await i(d)})}catch{continue}if(!await o(nX(d,c.name)))continue;let u=await a(d,{gateway:e.gateway,user:e.user,team:e.team,clientKey:e.clientKey});if(u===0){L(`Remote \`${c.name}\` exited with code 0.`);continue}O(`Remote \`${c.name}\` exited with code ${u}.`),L(rO(d.kind))}},rO=e=>{switch(e){case"ssh":return"Fix: ssh in and run `anyray-connect doctor`.";case"devcontainer":return"Fix: open a shell in the container and run `anyray-connect doctor`.";case"wsl":return"Fix: open the distro and run `anyray-connect doctor`.";case"codespace":return"Fix: `gh codespace ssh` in and run `anyray-connect doctor`."}},aX="usage: anyray-connect remote <ssh-host> [--yes] [--dry-run] | remote --devcontainer <host-path> | --wsl <distro> | --codespace <name> [--yes] [--dry-run]",sX=e=>{let t=/[/\\]/.test(e);return{kind:"devcontainer",name:t?k5(e.replaceAll("\\","/")):e,...t?{ref:e}:{}}},iX=async(e,t={})=>{if(e[0]==="--help"||e[0]==="-h")return console.log(Du),0;let n=e[0]&&!e[0].startsWith("-")?e[0]:void 0,r;try{r=Lg(n?e.slice(1):e)}catch(h){return R(h instanceof Error?h.message:String(h)),1}if(r.help)return console.log(Du),0;let o=[r.devcontainer,r.wsl,r.codespace].filter(h=>h!==void 0);if(n&&o.length>0||!n&&o.length!==1)return R(aX),1;let a=n?{kind:"ssh",name:n}:r.devcontainer!==void 0?sX(r.devcontainer):r.wsl!==void 0?{kind:"wsl",name:r.wsl}:{kind:"codespace",name:r.codespace};if(a.kind==="devcontainer"&&!a.ref)return R("Cannot resolve a dev container by its bare name; use its full host path."),1;if(a.kind==="wsl"&&(t.platform??Lu)()!=="win32")return R("--wsl is available only on Windows (win32)."),1;let s=t.isInteractive??ht;if(!r.yes&&!s())return R("remote requires a TTY; pass --yes only when you explicitly intend to configure that target."),1;if(r.revert||r.enroll||r.sso||r.claim||r.project||r.upstream||r.upstreamKey)return R("remote supports --gateway, --user, --team, --yes, --dry-run, and --key-stdin only."),1;if(r.dryRun)return L(`Dry run: would configure \`${a.name}\` remotely.`),0;let i;if(r.keyStdin)try{i=await XR()}catch{return R("could not read the personal gateway key from stdin."),1}let c=await(t.loadProfile??P)(),l=!r.gateway&&!process.env.ANYRAY_GATEWAY_URL?c.gateway:void 0,d=jt(r.gateway??l),u=i||process.env.ANYRAY_CLIENT_KEY?.trim()||zR(c);if(!Ae(u))return R("A personal gateway key is required. Enroll locally first or provide ANYRAY_CLIENT_KEY (or --key-stdin)."),1;let f=await Qh(r.user,c.name,r.yes),m=await ey(r.team,c.team,r.yes),p;try{p=await(t.runRemoteApply??_g)(a,{gateway:d,user:f,team:m,clientKey:u})}catch(h){return R(h instanceof Error?h.message:String(h)),1}return p===0?L(`Remote \`${a.name}\` exited with code 0.`):(O(`Remote \`${a.name}\` exited with code ${p}.`),L(rO(a.kind))),p},oO=async(e,t,n={})=>{let r=n.isInteractive??ht,o;try{o=Lg(e)}catch(D){return R(D.message),A("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return A(o.helpAll?Du:JR),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):hI({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 D;try{D=new URL(o.upstream.trim())}catch{return R(`invalid --upstream URL: "${o.upstream}"`),1}if(D.protocol!=="http:"&&D.protocol!=="https:")return R(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let N=o.upstreamKey.trim();if(!N)return R("--upstream-key must not be empty."),1;a={url:Kt(o.upstream),key:N}}let s=await P(),i;if(o.keyStdin)try{i=await XR()}catch{return R("could not read the personal gateway key from stdin."),1}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream);let c=!t&&ht()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,l=!1;(t||c)&&r()&&(o=await(n.runWizard??W5)(o,s),l=!0);let d;try{if(d=E5(o.tools),n.managedEnrollmentRevertedTools){let D=[...n.managedEnrollmentRevertedTools,...s.revertedTools??[]];d=fR(d,D)}}catch(D){return R(D.message),1}A(K(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&gi(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,A("That looks like an enrollment link \u2014 treating it as --enroll."));let u,f,m,p,h=!1;if(o.enroll){let D=Ed(o.enroll);if(D&&(!o.gateway||s.enrolledCert||fh(D.token)))try{let N=await Ni("Resolving enrollment link\u2026",()=>xS(D)),j=!o.gateway;j&&(o.gateway=N.gatewayUrl),u=N.deploymentId,f=N.email,m=N.provisioningKind,p=N.allowedDomains,h=!0,j&&L(`Enrollment link${N.org?` for ${N.org}`:""}: gateway ${N.gatewayUrl}`),N.seatMode&&!o.subscription&&(o.subscription=!0,L("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(N){if(fh(D.token))return R(N instanceof Error?N.message:String(N)),1;let j=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(j)L(`Could not resolve the gateway from the enrollment link \u2014 using ${j}.`);else return R(N instanceof Error?N.message:String(N)),1}}let w,y;if(o.claim&&!o.revert)if(o.dryRun)L("dry run: not enrolled (skipped redeeming the enrollment link).");else{let D=FS(o.claim);if(!D)return R("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let N=await Ni("Connecting this machine\u2026",()=>WS({cpOrigin:D.cpOrigin,claim:D.claim,gatewayUrl:o.gateway}));w={cert:N.cert,privateKeyPem:N.privateKeyPem},N.deploymentId&&(u=N.deploymentId),!o.gateway&&N.gatewayUrl&&(o.gateway=N.gatewayUrl),y=N.ssoLink}catch(N){return R(N instanceof Error?N.message:String(N)),1}}if(o.sso&&!w&&!o.revert)if(o.dryRun)L("dry run: not enrolled via SSO (skipped minting a personal key).");else{let D=Et(o.sso);if(!D)return R(gi(o.sso)?"that is an enrollment link, not an SSO link \u2014 re-run with --enroll instead of --sso.":"invalid --sso value: expected a https://\u2026/sso/<tenantId> link or a tnt_ id."),1;try{let N=await xd({cpOrigin:D.cpOrigin,tenantId:D.tenantId,gatewayUrl:o.gateway,log:on=>L(on),open:r()?Va:void 0}),j=await Ni("Waiting for SSO sign-in\u2026",()=>Rd(N,{gatewayUrl:o.gateway}));w={cert:j.cert,privateKeyPem:j.privateKeyPem},j.deploymentId&&(u=j.deploymentId),!o.gateway&&j.gatewayUrl&&(o.gateway=j.gatewayUrl)}catch(N){return R(N instanceof Error?N.message:String(N)),1}}let g=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;g&&(o.gateway=g);let b;try{b=jt(o.gateway)}catch(D){return R(D.message),1}let k,C;g&&!o.revert&&L(`Gateway: ${b} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&$g(b)&&O(`${b} 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 S=i??process.env.ANYRAY_CLIENT_KEY?.trim(),E=S||zR(s),I,_,T,W,Q,G,ne=async D=>{await xo();let N=TS(D.token),j=NS(s.enrolledCert,s.enrolledCertExpiry,D.deploymentId,Date.now(),N,s.enrolledTokenHash,D.expectedUser),on=j?await Fe():void 0,ve=Ut()||void 0,Vt=j&&on&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:on,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,J=yt=>$S({cpOrigin:D.cpOrigin,token:D.token,gatewayOrigin:b,email:D.email,team:D.team,machineId:D.machineId,deploymentId:D.deploymentId,machineUuid:ve,reuse:yt?Vt:void 0}),pe=!!Vt,Be=await(async()=>{try{return await J(pe)}catch(yt){if(Vt&&yt instanceof lt&&yt.policyCode!=="managed_device_required")return L("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),pe=!1,await J(!1);throw yt}})();E=Be.clientKey,o.user=Pu(o.user,Be.user),o.team=Pu(o.team,Be.team),I=Be.cert,_=Be.cert.payload.expiresAt,G=Be.expiresAt,Q=void 0,pe||(T=Be.privateKeyPem),pe||(W=N),M(`Enrolled${Be.user?` as ${Be.user}`:""}${pe?" (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)L("dry run: not enrolled (skipped minting a personal key).");else{let D=Ed(o.enroll);if(!D){let N=IS(o.enroll);return R(N?`that is ${N.what}, not an enrollment link \u2014 re-run with ${N.flag} instead of --enroll.`:Et(o.enroll)?"that is an SSO link, not an enrollment link \u2014 re-run with --sso instead of --enroll.":"invalid --enroll value: expected a https://\u2026/enroll/<token> link or a bare token."),1}try{let N=o.machine?Md():void 0,j=m==="mdm"&&!f?fx():void 0,on=m==="mdm"&&!f&&!j?px(p,Kd()):void 0,ve=j??on;if(ve){let pe=j?"the email your MDM assigned to this machine":`${ve} (this Mac's login name at the first allowed domain)`;A(o.user?.trim()&&o.user.trim()!==ve?`Ignoring --user: enrolling as ${pe}.`:`Enrolling as ${pe}.`)}let Vt=f??ve??S5(o.user);if(!o.machine&&!o.user&&!f&&!ve){let pe=cI();pe.distinct||(O(` Enrolling as "${pe.identity}" \u2014 this may not be unique to you.`),O(pe.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"),O(pe.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."),O(" Re-run with `--user you@company.com` (or set `git config --global"),O(" user.email`) so your usage is attributed to you."))}let J=o.machine?`machine:${N}`:h?Vt:void 0;await ne({cpOrigin:D.cpOrigin,token:D.token,email:Vt,team:o.team,machineId:N,deploymentId:u,expectedUser:J})}catch(N){return R(N instanceof Error?N.message:String(N)),N instanceof lt&&N.policyCode!=="managed_device_required"&&L("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."),PS(N)?3:1}}if(w){await xo();try{let D=Ut()||void 0,N=await tn(b,w.cert,w.privateKeyPem,{machineUuid:D});E=N.key,o.user=Pu(o.user,N.user),o.team=Pu(o.team,N.team),I=w.cert,_=w.cert.payload.expiresAt,T=w.privateKeyPem,G=N.expiresAt;let j=o.sso?Et(o.sso):void 0;Q=j?`${j.cpOrigin}/sso/${j.tenantId}`:y,M(`Enrolled${N.user?` as ${N.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(D){return R(D instanceof Error?D.message:String(D)),D instanceof lt&&D.policyCode!=="managed_device_required"&&L("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 D=o.yes;k=await Qh(o.user,s.name,D),C=await ey(o.team,s.team,D)}if(!o.revert&&!o.dryRun){let D=Ix(await Ex(b,E),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if(D.lane){let N=D.lane==="subscription";o.subscription=N,o.placeholder=!N;let j=N?"your own subscription seat":"the organization's provider account";D.overrodeFlag?L(`Your administrator assigns this machine to ${j}, so that is what was applied (it overrides the lane flag you passed).`):L(`Billing lane set by your administrator: ${j}.`)}}let z;!o.revert&&!o.subscription&&!o.placeholder&&(z=await wn(),H("Detecting your sign-ins"),A(` Claude (Anthropic): ${a?qe("BYO upstream key (passthrough)"):z.anthropic?qe("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),A(` Codex (ChatGPT): ${z.openai?qe("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),(!z.anthropic||!z.openai)&&E&&await Ox(Re({origin:b,placeholderKey:o.key,clientKey:E,subscription:!1,placeholder:!0,byoUpstream:a,user:k,team:C,intent:o.intent}))===!1&&(O(" This gateway holds NO server-side provider key, so the org-key"),O(" fallback above cannot serve a request \u2014 it answers 424, not 401."),z.copilot?(O(" Your Copilot seat DOES work and never touches the org key: prefer"),O(" `github-copilot/...` models in OpenCode and Copilot Chat until an"),O(" admin adds a provider key in the console \u2192 Providers.")):(O(" No subscription seat here works either. Sign in to Copilot or"),O(" Claude, or have an admin add a provider key in console \u2192 Providers."))),!z.anthropic&&!z.openai&&!z.copilot&&Zr()&&(O(" No subscription sign-ins found on this host. Sign-ins do not cross the"),O(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),O(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),O(" and re-run, or everything below routes on the org key instead.")));let Z=Re({origin:b,placeholderKey:o.key,clientKey:E,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:z,user:k,team:C,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),le=o.revert===!0&&(o.tools?.length??0)===0,U={dryRun:o.dryRun,fullRevert:le};if(!o.revert&&Z.clientKey&&!Ae(Z.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&&!Z.clientKey){H("Enrollment required");let D="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(O(` ${D}`),L(" Dry run only \u2014 no placeholder configuration will be written."),await YR(d,"after-enrollment"),L(`
|
|
1064
|
-
Dry run complete \u2014 no files were written.`),0):(R(` ${D}`),1)}o.revert||
|
|
1065
|
-
Dry run \u2014 no files will be written.`);let re=await
|
|
1061
|
+
per-skill versions ${v("sync")} last wrote \u2014 for zero-question re-runs.`,E5=e=>{let t=e?.trim();return t||zh()},zR=(e=process.stdin)=>new Promise((t,n)=>{let r=S5({input:e,crlfDelay:1/0}),o=!1,a=i=>{o||(o=!0,e.removeListener("error",s),r.close(),t(i))},s=i=>{o||(o=!0,r.close(),n(i))};r.once("line",i=>a(i.trim())),r.once("close",()=>a("")),e.once("error",s)}),Pu=(e,t)=>t||e,Lg=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"--key-stdin":t.keyStdin=!0;break;case"--devcontainer":t.devcontainer=o();break;case"--wsl":t.wsl=o();break;case"--codespace":t.codespace=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},I5=e=>!e||e.length===0?fe:e.map(t=>{let n=pt(t);if(!n)throw new Error(`unknown tool "${t}". Known: ${fe.map(r=>r.id).join(", ")}`);return n}),x5=(e,t)=>{if(H("Gateway target"),A(` Origin: ${qe(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 (${Dt(e.clientKey)}) ${v("rides x-anyray-api-key")}`);else if(e.authMode==="auto"){let n=te(e,"anthropic")?qe("your subscription"):"org key",r=te(e,"openai")?qe("your subscription"):"org key";A(` Auth: auto ${v("(per tool)")} \u2014 Claude: ${n}, Codex: ${r}`),e.clientKey&&A(` Client key: personal gateway key (${Dt(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 (${Dt(e.clientKey)}) ${v("rides x-anyray-api-key")}`)):e.clientKey?A(` Auth: personal gateway key (${Dt(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: ${qe("native Team subscription")} ${v("(Claude/Opus inference remains Cursor-hosted; Anyray hooks/MCP optimize supported local context)")}`),t.some(n=>n.id==="claude-desktop")&&(te(e,"anthropic")?(A(` Claude Desktop: ${qe("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: ${qe("third-party API lane")} ${v("(API-billed; switches the active local inference profile)")}`),A(` ${v("The first-party Claude subscription remains untouched.")}`))),A(` Attribution: ${me(e.metadata)??v("(none \u2014 pass --user)")}`)},R5=e=>{switch(e.kind){case"ssh":return`SSH remote \`${e.name}\``;case"devcontainer":return`dev container \`${e.name}\``;case"attached-container":return`attached container \`${e.name}\``;case"wsl":return`WSL distro \`${e.name}\``;case"codespace":return`Codespace \`${e.name}\``;case"tunnel":return`remote tunnel \`${e.name}\``}},O5=async()=>{let[e,t]=await Promise.all([fu().catch(()=>[]),Og().catch(()=>[])]);for(let n of e)A(` Bind-mounted config file: ${n} ${v("(cannot be replaced atomically; connect writes it in place, verified)")}`);if(t.length>0){H("Other environments you work in");for(let n of t)L(` ${R5(n)}`);A(v(" This run configures only this machine. Run `anyray-connect` inside each of these too \u2014 see docs.anyray.ai/get-started/remote-environments."))}},JR=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}`:""}`):L(` ${n.title} ${v(`(${n.id})`)} \u2014 not found${r.detail?`; ${r.detail}`:""}`)}},qR=(e,t=Date.now())=>{let n=e.clientKey?.trim();if(!Ae(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},T5={loadDevKey:Fe,saveDevKey:ac,clearDevKey:ss,saveProfile:ce},_5=async(e,t,n,r=T5,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}},P5=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 m=r?await u.revert(n):await u.apply(t,{...n,explicit:o?.has(u.id)===!0,reportsToUser:!0});for(let p of m.messages)A(` ${p}`);a+=m.changedFiles?.length??0,l.push({id:u.id,status:m.status}),m.status==="configured"||m.status==="reverted"?M(` ${m.status}`):m.status==="manual"?(s.push(u.title),m.manualAudience==="admin"?(i.push(u.title),c.push(u.id),O(" blocked by machine policy \u2014 your IT team owns this one")):O(" manual step required (see above)")):m.status==="held"?L(" left on its own plan (no change)"):L(` ${m.status}`)}catch(m){l.push({id:u.id,status:"failed"}),R(` failed: ${m instanceof Error?m.message:String(m)}`)}}if(d.length>0&&L(`Skipped ${d.length} not installed (${d.join(", ")})`),!n.dryRun){let u=await uc().catch(()=>[]);u.length&&L(` Removed ${u.length} unused Anyray runtime copies.`)}return{changes:a,manual:s,manualAdminOnly:i,manualAdminOnlyIds:c,results:l}},D5=(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},L5=(e,t,n)=>{if(t.revert)return[];if((t.tools?.length??0)>0)return[];let r=new Set(n??[]);return e.filter(o=>QR(o)&&!r.has(o.id))},N5=async e=>{let t=WI(e,process.platform,ee());if(t){await we(t.path,t.content);for(let n of UI(t,process.platform))A(` ${n}`)}},$5=async(e,t,n=Lu())=>{let r=[],o=new Set;for(let a of e){let s=a.quitGated,i=s?.quitTarget;if(!s||!i||!Nb(i,n)||!Lb(i,n))continue;let c=Pb(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},M5=(e,t)=>e.noQuitApps===!0||e.dryRun?!1:e.quitApps===!0?!0:!e.yes&&t,B5=e=>`
|
|
1062
|
+
${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?`}`,F5=async(e,t={})=>{let n=t.requestQuit??(a=>Mb(a)),r=t.waitFor??(a=>Bb(a)),o=[];for(let a of e){if(n(a.quitTarget)&&await r(a.isRunning)){o.push(a),M(` Closed ${a.title}.`);continue}O(` ${a.title} is still open \u2014 leaving it alone.`),L(` Its configuration is written either way; ${a.title} picks it up the next time you close it.`)}return o},W5=(e,t={})=>{let n=t.relaunch??(o=>Fb(o)),r=[];for(let o of e)n(o.quitTarget)?(r.push(o.title),M(` Reopened ${o.title}.`)):O(` Could not reopen ${o.title} \u2014 start it when you're ready.`);return r},QR=e=>e.changesBilling===!0||e.changesOrgManagement===!0,eO=e=>e.changesBilling===!0?"moves inference spend from your subscription to the org API bill":e.changesOrgManagement===!0?"switches the app to third-party mode; claude.ai Enterprise org settings stop applying":void 0,Pg=e=>!QR(e),U5=async(e,t,n={})=>{let r=n.hasEnrollment??zu,o=n.canMultiSelect??hx,a=n.multiSelect??yx,s=n.prompt??Wa,i=n.registry??fe;if(A(K("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 mt;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||O("Choose one of the three connection methods.")}if(!c)throw new mt;for(let l=0;l<3;l++)if(c==="enroll"){let d=await s("? Enrollment link or token");if(d&&gi(d)&&Ed(d)){e.enroll=d;break}O("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&&Et(d)){e.sso=d;break}O("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&&gi(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=jt(d);break}catch{O("That is not a valid http(s) gateway URL. Try again.")}}if(!e.enroll&&!e.sso&&!e.gateway)throw new mt}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=>Pg(u)).map(u=>u.id);if(c.length>0){for(let u=0;u<3&&!e.tools;u++){let f;if(o()){let m=await a({title:"Tools to configure",items:c.map(p=>({value:p.id,label:`${p.title} (${p.id})`,hint:eO(p),selected:Pg(p),requiresExplicitChoice:!Pg(p)}))});if(m.kind==="cancelled")throw new mt;f=m.values}else{f=(await s("? Tools to configure (comma-separated, blank = all suggested)",d.join(",")||void 0)??"").split(",").map(g=>g.trim()).filter(Boolean);let p=new Set(c.map(g=>g.id)),h=f.filter(g=>!p.has(g));if(h.length>0){O(`Unknown or unavailable tool id${h.length===1?"":"s"}. Choose from: ${c.map(g=>g.id).join(", ")}.`);continue}}if(f.length===0){O("Choose at least one installed tool.");continue}e.tools=f}if(!e.tools)throw new mt}l.length>0&&L(`${l.length} others not installed (${l.map(u=>u.id).join(", ")})`)}return e},H5=async(e,t)=>{H("Verifying the connection");let n=await Ni("Checking the gateway\u2026",()=>Ya(e,{tools:t}));n.kind==="ok"?M(` ${n.detail}`):n.kind==="unreachable"||n.kind==="unknown"||n.kind==="enrollment-required"||n.kind==="provider-rejected"?O(` ${n.detail}`):R(` ${n.detail}`);for(let r of n.remedy)A(v(` ${r}`))},G5=async(e,t={})=>{if(e.dryRun)return;let n=t.install??ur,r=t.uninstall??_n;if(e.want&&e.trayManaged){H("Automatic key refresh"),M(" Managed by the Anyray Connect app \u2014 it triggers the ~30-min key refresh.");return}if(e.want){let o=await n();H("Automatic key refresh");for(let a of o.messages)A(` ${a}`);o.ok&&M(" Your gateway key now renews every ~30 min \u2014 no tool will 401 on a stale key mid-session."),o.ok?await ce({...await P(),refreshSchedulerInstalledOnce:!0}):await ce({...await P(),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 ce({...await P(),refreshSchedulerEnabled:!1,refreshSchedulerInstalledOnce:!1}),M(" Removed the automatic key-refresh schedule.")}},V5=new Set(["login","wizard","status","doctor","sync","device-url"]),K5=new Set(["managed","print-key","device-url","status","update","retrieve","recall","history","migrate","endpoint","remote"]),j5=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==="fleet-off"||e.outcome==="fleet-directed")return{level:"warn",message:"Your organization manages anyray-connect updates, so this run did not download a binary; continuing with the current runtime."};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."}},Z5=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=uy(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]||!K5.has(e[0])},Dg=async(e,t)=>{try{return await aO(e,t)}catch(n){if(n instanceof mt)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}},tO=12e4,Y5=async(e,t,n,r=is)=>e&&!t?r(n,{waitMs:tO}):n(),J5=async(e,t,n,r={})=>{if(e.yes||e.dryRun)return"proceed";if(!(r.isInteractive??ht)())return"non-interactive";let o=e.revert?"remove Anyray config from":"configure",a=t?"Apply this configuration?":`
|
|
1063
|
+
${o} ${n} tool target(s)?`;return await(r.confirm??Oo)(a)?"proceed":"declined"},X5=async(e=Za)=>{let t=await e({force:!0,respectFailureBackoff:!0,allowNpmMigration:!0,initiator:"directive"});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";case"fleet-off":return"failed";case"fleet-directed":return"failed";default:return t.outcome}},nO=(e,t)=>aO(e,!1,{managedEnrollmentRevertedTools:t}),z5=()=>gg(wg(nO)),q5=async()=>{let e=!1,t=await mR(await Ht({runAmbientSelfcheck:!0}),{...wg(nO),refresh:()=>Ht({})});await Ep(),await KE(),await jE()==="retry"&&(e=!0);let n=await P().catch(()=>{});if(n&&process.env.ANYRAY_FLEET_MANAGED==="1"&&!n.anyrayFleetManaged){n.anyrayFleetManaged=!0;try{await ce(n)}catch{e=!0}}let r=n?.anyrayFleetManaged===!0&&await Do().catch(()=>!1);if(n&&(await UR(t,{fleetdPresent:async()=>r}).catch(()=>{}),await HR(t).catch(()=>{}),r&&n.gateway&&n.clientKey)){let o=n.gateway,a=n.clientKey,s=Ut(),i=n.enrolledCert;if(s&&i){let l=await Fe().catch(()=>{});l&&await LS(o,a,i,l,s).catch(()=>{})}await VR(o,a,{execute:async(l,d)=>{let u;return l==="remint"||l==="reapply_config"?u=await Ht({force:!0})==="failed"?"failed":"ok":l==="revert_tool"?u=await jR(d):l==="update"?u=await X5():u=(await _u()).ok?"ok":"failed",u==="failed"&&(e=!0),u}}).catch(()=>{})}return r||await Za(),{refresh:t,...e?{partial:!0}:{}}},Q5=async e=>{if(e[0]==="__anyray-hook"){let r=e[1]==="cursor"||e[1]==="opencode"?e[1]:"claude";return y0(r)}if(e[0]==="__anyray-codex-hook")return g0();if(e[0]==="__anyray-prompt-hook")return S0();if(e[0]==="__anyray-shell-pretool")return R0();if(e[0]==="__anyray-shell-run")return x0(e.slice(1));if(e[0]==="__anyray-read-pretool")return $0();if(e[0]==="__anyray-sso-gate")return v0(e.slice(1));if(e[0]==="__anyray-sso-poll")return hR();if(e[0]==="__anyray-managed-enroll")try{return await is(z5,{waitMs:tO})}catch{return 1}if(e[0]==="__anyray-vscode-gate")return CR();if(e[0]==="__anyray-spawn-refresh")return await Lr(),0;if(e[0]==="__anyray-mcp-server"){let r=e[1]==="claude"||e[1]==="profile"?e[1]:"auto";return TR(r)}if(e[0]==="__anyray-acp-agent")return _R(e[1],e[2],{clientTool:e[3]});if(e[0]==="__anyray-endpoint-install")return uR(e.slice(1));let t=BR(e);if(t)return FR(t,{refresh:q5});if(e[0]==="__anyray-persistence")return Kw(e.slice(1));if(e[0]==="__anyray-quit-watch")return hS(e.slice(1));if(e[0]===xr)return gI(e.slice(1));if(e[0]===Qs)return bI(e.slice(1));if(e[0]===zr){let r=e[1];return r&&await Qd(r),0}if(e[0]==="--version"||e[0]==="-V")return AR();try{let r=await lw(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(Z5(e)){let r=j5(await vx());r?.level==="warn"?O(r.message):r&&console.error(r.message)}if(e[0]==="managed")return eE(e.slice(1));if(e[0]==="endpoint")return dR(e.slice(1));if(e[0]==="print-key")return XE(e.slice(1));if(e[0]==="models")return qE(e.slice(1));if(e[0]==="copilot-login")return QE(e.slice(1));if(e[0]==="desktop"){let r=e.slice(1),o=uy(r);return o?Dg(o,!1):HI(r)}if(e[0]==="retrieve")return VI(e.slice(1));if(e[0]==="recall")return KI(e.slice(1));if(e[0]==="history")return rx(e.slice(1));if(e[0]==="migrate")return ax(e.slice(1));if(e[0]==="login")return gR(e.slice(1));if(e[0]==="update")return bR(e.slice(1));if(e[0]==="remote")return cX(e.slice(1));let n=e[0];if(n&&V5.has(n)){let r=e.slice(1),o;try{o=Lg(r)}catch(a){return R(a.message),A("\nRun `npx anyray-connect --help` for usage."),1}return o.help?(A(o.helpAll?Du:XR),0):n==="status"?Tx({gateway:o.gateway}):n==="doctor"?yu({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"?oI():Dg(r,!0)}return Dg(e,!1)},rO=async e=>{try{return await Q5(e)}catch(t){if(t instanceof mt)return console.error(v("Cancelled.")),130;throw t}},eX=e=>{let t=process.platform==="win32"?"where":"which";try{return k5(t,[e],{stdio:"ignore"}).status===0}catch{return!1}},tX=(e,t={})=>{let n=t.which??eX,r=t.platform??Lu;switch(e.kind){case"ssh":return!0;case"devcontainer":return n("docker");case"wsl":return r()==="win32"&&n("wsl.exe");case"codespace":return n("gh")}},nX=e=>{switch(e.kind){case"ssh":case"devcontainer":case"wsl":case"codespace":return{kind:e.kind,name:e.name,...e.kind==="devcontainer"&&e.ref?{ref:e.ref}:{}};case"attached-container":case"tunnel":return}},rX=(e,t)=>{switch(e.kind){case"ssh":return`Configure \`${t}\` over SSH now?`;case"devcontainer":return`Configure \`${t}\` in this dev container now?`;case"wsl":return`Configure \`${t}\` in WSL now?`;case"codespace":return`Configure Codespace \`${t}\` now?`}},oX=e=>e.interactive&&!e.managed&&!e.yes&&!e.revert&&!e.dryRun,aX=async(e,t={})=>{if(!oX(e)||!Ae(e.clientKey))return;let n=t.discoverRemoteEnvironments??Og,r;try{r=await n()}catch{return}let o=t.confirm??Oo,a=t.runRemoteApply??_g,s=t.isCarrierAvailable??tX,i=t.resolveDevcontainer??Tg;for(let c of r){let l=nX(c);if(!l)continue;let d=l;try{if(!await s(d))continue;d.kind==="devcontainer"&&(d={kind:"devcontainer",name:await i(d)})}catch{continue}if(!await o(rX(d,c.name)))continue;let u=await a(d,{gateway:e.gateway,user:e.user,team:e.team,clientKey:e.clientKey});if(u===0){L(`Remote \`${c.name}\` exited with code 0.`);continue}O(`Remote \`${c.name}\` exited with code ${u}.`),L(oO(d.kind))}},oO=e=>{switch(e){case"ssh":return"Fix: ssh in and run `anyray-connect doctor`.";case"devcontainer":return"Fix: open a shell in the container and run `anyray-connect doctor`.";case"wsl":return"Fix: open the distro and run `anyray-connect doctor`.";case"codespace":return"Fix: `gh codespace ssh` in and run `anyray-connect doctor`."}},sX="usage: anyray-connect remote <ssh-host> [--yes] [--dry-run] | remote --devcontainer <host-path> | --wsl <distro> | --codespace <name> [--yes] [--dry-run]",iX=e=>{let t=/[/\\]/.test(e);return{kind:"devcontainer",name:t?v5(e.replaceAll("\\","/")):e,...t?{ref:e}:{}}},cX=async(e,t={})=>{if(e[0]==="--help"||e[0]==="-h")return console.log(Du),0;let n=e[0]&&!e[0].startsWith("-")?e[0]:void 0,r;try{r=Lg(n?e.slice(1):e)}catch(h){return R(h instanceof Error?h.message:String(h)),1}if(r.help)return console.log(Du),0;let o=[r.devcontainer,r.wsl,r.codespace].filter(h=>h!==void 0);if(n&&o.length>0||!n&&o.length!==1)return R(sX),1;let a=n?{kind:"ssh",name:n}:r.devcontainer!==void 0?iX(r.devcontainer):r.wsl!==void 0?{kind:"wsl",name:r.wsl}:{kind:"codespace",name:r.codespace};if(a.kind==="devcontainer"&&!a.ref)return R("Cannot resolve a dev container by its bare name; use its full host path."),1;if(a.kind==="wsl"&&(t.platform??Lu)()!=="win32")return R("--wsl is available only on Windows (win32)."),1;let s=t.isInteractive??ht;if(!r.yes&&!s())return R("remote requires a TTY; pass --yes only when you explicitly intend to configure that target."),1;if(r.revert||r.enroll||r.sso||r.claim||r.project||r.upstream||r.upstreamKey)return R("remote supports --gateway, --user, --team, --yes, --dry-run, and --key-stdin only."),1;if(r.dryRun)return L(`Dry run: would configure \`${a.name}\` remotely.`),0;let i;if(r.keyStdin)try{i=await zR()}catch{return R("could not read the personal gateway key from stdin."),1}let c=await(t.loadProfile??P)(),l=!r.gateway&&!process.env.ANYRAY_GATEWAY_URL?c.gateway:void 0,d=jt(r.gateway??l),u=i||process.env.ANYRAY_CLIENT_KEY?.trim()||qR(c);if(!Ae(u))return R("A personal gateway key is required. Enroll locally first or provide ANYRAY_CLIENT_KEY (or --key-stdin)."),1;let f=await Qh(r.user,c.name,r.yes),m=await ey(r.team,c.team,r.yes),p;try{p=await(t.runRemoteApply??_g)(a,{gateway:d,user:f,team:m,clientKey:u})}catch(h){return R(h instanceof Error?h.message:String(h)),1}return p===0?L(`Remote \`${a.name}\` exited with code 0.`):(O(`Remote \`${a.name}\` exited with code ${p}.`),L(oO(a.kind))),p},aO=async(e,t,n={})=>{let r=n.isInteractive??ht,o;try{o=Lg(e)}catch(D){return R(D.message),A("\nRun `npx anyray-connect --help` for usage."),1}if(o.help)return A(o.helpAll?Du:XR),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):hI({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 D;try{D=new URL(o.upstream.trim())}catch{return R(`invalid --upstream URL: "${o.upstream}"`),1}if(D.protocol!=="http:"&&D.protocol!=="https:")return R(`invalid --upstream URL: "${o.upstream}" \u2014 must start with http:// or https://`),1;let N=o.upstreamKey.trim();if(!N)return R("--upstream-key must not be empty."),1;a={url:Kt(o.upstream),key:N}}let s=await P(),i;if(o.keyStdin)try{i=await zR()}catch{return R("could not read the personal gateway key from stdin."),1}!a&&!o.subscription&&!o.placeholder&&!o.revert&&(a=s.byoUpstream);let c=!t&&ht()&&!o.gateway&&!o.revert&&!o.yes&&!o.dryRun&&!o.enroll&&!o.sso,l=!1;(t||c)&&r()&&(o=await(n.runWizard??U5)(o,s),l=!0);let d;try{if(d=I5(o.tools),n.managedEnrollmentRevertedTools){let D=[...n.managedEnrollmentRevertedTools,...s.revertedTools??[]];d=fR(d,D)}}catch(D){return R(D.message),1}A(K(o.revert?"Anyray connect \u2014 revert":"Anyray connect")),o.gateway&&!o.enroll&&gi(o.gateway)&&(o.enroll=o.gateway,o.gateway=void 0,A("That looks like an enrollment link \u2014 treating it as --enroll."));let u,f,m,p,h=!1;if(o.enroll){let D=Ed(o.enroll);if(D&&(!o.gateway||s.enrolledCert||fh(D.token)))try{let N=await Ni("Resolving enrollment link\u2026",()=>xS(D)),j=!o.gateway;j&&(o.gateway=N.gatewayUrl),u=N.deploymentId,f=N.email,m=N.provisioningKind,p=N.allowedDomains,h=!0,j&&L(`Enrollment link${N.org?` for ${N.org}`:""}: gateway ${N.gatewayUrl}`),N.seatMode&&!o.subscription&&(o.subscription=!0,L("Subscription org: using pass-through auth (--subscription) \u2014 your own seat sign-in is used."))}catch(N){if(fh(D.token))return R(N instanceof Error?N.message:String(N)),1;let j=o.gateway||process.env.ANYRAY_GATEWAY_URL?.trim()||s.gateway;if(j)L(`Could not resolve the gateway from the enrollment link \u2014 using ${j}.`);else return R(N instanceof Error?N.message:String(N)),1}}let g,y;if(o.claim&&!o.revert)if(o.dryRun)L("dry run: not enrolled (skipped redeeming the enrollment link).");else{let D=FS(o.claim);if(!D)return R("invalid --claim value: expected the sdc_ code from your organization's Anyray page."),1;try{let N=await Ni("Connecting this machine\u2026",()=>WS({cpOrigin:D.cpOrigin,claim:D.claim,gatewayUrl:o.gateway}));g={cert:N.cert,privateKeyPem:N.privateKeyPem},N.deploymentId&&(u=N.deploymentId),!o.gateway&&N.gatewayUrl&&(o.gateway=N.gatewayUrl),y=N.ssoLink}catch(N){return R(N instanceof Error?N.message:String(N)),1}}if(o.sso&&!g&&!o.revert)if(o.dryRun)L("dry run: not enrolled via SSO (skipped minting a personal key).");else{let D=Et(o.sso);if(!D)return R(gi(o.sso)?"that is an enrollment link, not an SSO link \u2014 re-run with --enroll instead of --sso.":"invalid --sso value: expected a https://\u2026/sso/<tenantId> link or a tnt_ id."),1;try{let N=await xd({cpOrigin:D.cpOrigin,tenantId:D.tenantId,gatewayUrl:o.gateway,log:on=>L(on),open:r()?Va:void 0}),j=await Ni("Waiting for SSO sign-in\u2026",()=>Rd(N,{gatewayUrl:o.gateway}));g={cert:j.cert,privateKeyPem:j.privateKeyPem},j.deploymentId&&(u=j.deploymentId),!o.gateway&&j.gatewayUrl&&(o.gateway=j.gatewayUrl)}catch(N){return R(N instanceof Error?N.message:String(N)),1}}let w=!o.gateway&&!process.env.ANYRAY_GATEWAY_URL?s.gateway:void 0;w&&(o.gateway=w);let b;try{b=jt(o.gateway)}catch(D){return R(D.message),1}let k,C;w&&!o.revert&&L(`Gateway: ${b} ${v("(cached in ~/.anyray \u2014 pass a URL to change)")}`),!o.revert&&$g(b)&&O(`${b} 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 S=i??process.env.ANYRAY_CLIENT_KEY?.trim(),E=S||qR(s),I,_,T,W,Q,G,ne=async D=>{await xo();let N=TS(D.token),j=NS(s.enrolledCert,s.enrolledCertExpiry,D.deploymentId,Date.now(),N,s.enrolledTokenHash,D.expectedUser),on=j?await Fe():void 0,ve=Ut()||void 0,Vt=j&&on&&s.enrolledCert?{cert:s.enrolledCert,privateKeyPem:on,publicKeyPem:s.enrolledCert.payload.devPublicKey}:void 0,J=yt=>$S({cpOrigin:D.cpOrigin,token:D.token,gatewayOrigin:b,email:D.email,team:D.team,machineId:D.machineId,deploymentId:D.deploymentId,machineUuid:ve,reuse:yt?Vt:void 0}),pe=!!Vt,Be=await(async()=>{try{return await J(pe)}catch(yt){if(Vt&&yt instanceof lt&&yt.policyCode!=="managed_device_required")return L("your saved certificate was rejected by the gateway (it may have been rebuilt) \u2014 re-enrolling from scratch\u2026"),pe=!1,await J(!1);throw yt}})();E=Be.clientKey,o.user=Pu(o.user,Be.user),o.team=Pu(o.team,Be.team),I=Be.cert,_=Be.cert.payload.expiresAt,G=Be.expiresAt,Q=void 0,pe||(T=Be.privateKeyPem),pe||(W=N),M(`Enrolled${Be.user?` as ${Be.user}`:""}${pe?" (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)L("dry run: not enrolled (skipped minting a personal key).");else{let D=Ed(o.enroll);if(!D){let N=IS(o.enroll);return R(N?`that is ${N.what}, not an enrollment link \u2014 re-run with ${N.flag} instead of --enroll.`:Et(o.enroll)?"that is an SSO link, not an enrollment link \u2014 re-run with --sso instead of --enroll.":"invalid --enroll value: expected a https://\u2026/enroll/<token> link or a bare token."),1}try{let N=o.machine?Md():void 0,j=m==="mdm"&&!f?fx():void 0,on=m==="mdm"&&!f&&!j?px(p,Kd()):void 0,ve=j??on;if(ve){let pe=j?"the email your MDM assigned to this machine":`${ve} (this Mac's login name at the first allowed domain)`;A(o.user?.trim()&&o.user.trim()!==ve?`Ignoring --user: enrolling as ${pe}.`:`Enrolling as ${pe}.`)}let Vt=f??ve??E5(o.user);if(!o.machine&&!o.user&&!f&&!ve){let pe=cI();pe.distinct||(O(` Enrolling as "${pe.identity}" \u2014 this may not be unique to you.`),O(pe.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"),O(pe.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."),O(" Re-run with `--user you@company.com` (or set `git config --global"),O(" user.email`) so your usage is attributed to you."))}let J=o.machine?`machine:${N}`:h?Vt:void 0;await ne({cpOrigin:D.cpOrigin,token:D.token,email:Vt,team:o.team,machineId:N,deploymentId:u,expectedUser:J})}catch(N){return R(N instanceof Error?N.message:String(N)),N instanceof lt&&N.policyCode!=="managed_device_required"&&L("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."),PS(N)?3:1}}if(g){await xo();try{let D=Ut()||void 0,N=await tn(b,g.cert,g.privateKeyPem,{machineUuid:D});E=N.key,o.user=Pu(o.user,N.user),o.team=Pu(o.team,N.team),I=g.cert,_=g.cert.payload.expiresAt,T=g.privateKeyPem,G=N.expiresAt;let j=o.sso?Et(o.sso):void 0;Q=j?`${j.cpOrigin}/sso/${j.tenantId}`:y,M(`Enrolled${N.user?` as ${N.user}`:""} via SSO \u2014 personal gateway key minted (not shown; it lands in your tool configs).`)}catch(D){return R(D instanceof Error?D.message:String(D)),D instanceof lt&&D.policyCode!=="managed_device_required"&&L("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 D=o.yes;k=await Qh(o.user,s.name,D),C=await ey(o.team,s.team,D)}if(!o.revert&&!o.dryRun){let D=Ix(await Ex(b,E),{subscription:o.subscription,org:o.placeholder,byoUpstream:!!a});if(D.lane){let N=D.lane==="subscription";o.subscription=N,o.placeholder=!N;let j=N?"your own subscription seat":"the organization's provider account";D.overrodeFlag?L(`Your administrator assigns this machine to ${j}, so that is what was applied (it overrides the lane flag you passed).`):L(`Billing lane set by your administrator: ${j}.`)}}let z;!o.revert&&!o.subscription&&!o.placeholder&&(z=await wn(),H("Detecting your sign-ins"),A(` Claude (Anthropic): ${a?qe("BYO upstream key (passthrough)"):z.anthropic?qe("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),A(` Codex (ChatGPT): ${z.openai?qe("signed in \u2192 your subscription"):v("not signed in \u2192 org key")}`),(!z.anthropic||!z.openai)&&E&&await Ox(Re({origin:b,placeholderKey:o.key,clientKey:E,subscription:!1,placeholder:!0,byoUpstream:a,user:k,team:C,intent:o.intent}))===!1&&(O(" This gateway holds NO server-side provider key, so the org-key"),O(" fallback above cannot serve a request \u2014 it answers 424, not 401."),z.copilot?(O(" Your Copilot seat DOES work and never touches the org key: prefer"),O(" `github-copilot/...` models in OpenCode and Copilot Chat until an"),O(" admin adds a provider key in the console \u2192 Providers.")):(O(" No subscription seat here works either. Sign in to Copilot or"),O(" Claude, or have an admin add a provider key in console \u2192 Providers."))),!z.anthropic&&!z.openai&&!z.copilot&&Zr()&&(O(" No subscription sign-ins found on this host. Sign-ins do not cross the"),O(" Remote-SSH hop \u2014 your laptop's are invisible here, and these tools run"),O(" HERE. Sign in on this machine (`copilot` \u2192 /login, Claude Code, Codex)"),O(" and re-run, or everything below routes on the org key instead.")));let Z=Re({origin:b,placeholderKey:o.key,clientKey:E,subscription:o.subscription,placeholder:o.placeholder,byoUpstream:a,seat:z,user:k,team:C,intent:o.intent,intentLabel:o.intentLabel,session:o.session}),le=o.revert===!0&&(o.tools?.length??0)===0,U={dryRun:o.dryRun,fullRevert:le};if(!o.revert&&Z.clientKey&&!Ae(Z.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&&!Z.clientKey){H("Enrollment required");let D="A real apply requires a personal ark_ gateway key. Run with --enroll <link> or --sso <link>, then re-run Connect.";return o.dryRun?(O(` ${D}`),L(" Dry run only \u2014 no placeholder configuration will be written."),await JR(d,"after-enrollment"),L(`
|
|
1064
|
+
Dry run complete \u2014 no files were written.`),0):(R(` ${D}`),1)}o.revert||x5(Z,d);let Y=!o.revert&&!o.yes&&r();(l||Y)&&!o.revert&&await JR(d,"plan"),Y&&await O5(),o.dryRun&&L(`
|
|
1065
|
+
Dry run \u2014 no files will be written.`);let re=await J5(o,l,d.length,{isInteractive:r,confirm:n.confirm});if(re==="non-interactive")return R(`
|
|
1066
1066
|
Non-interactive session \u2014 cannot ask for confirmation. Pass --yes to proceed.`),1;if(re==="declined")return L(l?"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 D=await su(Z.origin);if(!D.reachable)return R(`
|
|
1067
1067
|
Gateway ${Z.origin} is not reachable (${D.detail}).`),A(v(` Refusing to repoint your tools at a gateway that isn\u2019t responding \u2014
|
|
1068
1068
|
that would break them until you re-run with --revert.`)),A(`
|
|
1069
|
-
Start the gateway and try again, or pass --force to configure anyway.`),1;M(`Gateway reachable (${D.detail}).`)}let Qe=o.revert?[]:await
|
|
1070
|
-
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),A("Run --revert with no --tools to remove it."));let pe=d,Be=
|
|
1069
|
+
Start the gateway and try again, or pass --force to configure anyway.`),1;M(`Gateway reachable (${D.detail}).`)}let Qe=o.revert?[]:await $5(d,Z.origin),Ie=[],ke=()=>{Ie.length!==0&&(H("Reopening"),W5(Ie),Ie=[])};if(Qe.length>0){let D=Qe.map(j=>j.title),N=D.length===1?"it":"them";if(H("Open apps"),M5(o,ht()))o.quitApps===!0||await Oo(B5(D))?Ie=await F5(Qe):L(` Leaving ${N} open \u2014 restart when convenient.`);else{let j=o.noQuitApps===!0?"":" (or pass --quit-apps)";L(o.dryRun?` Would offer to quit ${D.join(", ")} \u2014 dry run, nothing was closed.`:` ${D.join(", ")} ${D.length===1?"is":"are"} open; restart ${N} to pick this up${j}.`)}}let Rt=async()=>{if(!o.dryRun)try{await et()}catch{return R("Could not prepare the owner-only Anyray state directory."),1}let D=s.anyrayFleetManaged===!0&&await Do().catch(()=>!1),N=rR(o,Lu(),D),j=!!(S&&Z.clientKey===S&&!I),on=Je({...s,enrolledCert:I??s.enrolledCert},{toolIds:d.map(xe=>xe.id),keyExpiresAt:G}),ve=!o.revert&&o.noKeyRefresh!==!0&&!j&&on,Vt=o.dryRun?await jo(s):await Ep(),J=Vt==="healthy";if(Vt==="healed"&&(delete s.persistenceOwner,delete s.trayAppPath),!o.revert&&!o.dryRun){let xe={...s,managedEnrollmentDisabled:void 0,gateway:Z.origin,name:k,team:C,clientKey:Z.clientKey??s.clientKey,enrolledCert:j?void 0:I??s.enrolledCert,enrolledCertExpiry:j?void 0:_??s.enrolledCertExpiry,enrolledTokenHash:j?void 0:W??s.enrolledTokenHash,ssoLink:j?void 0:g?Q:I?void 0:s.ssoLink,clientKeyExpiresAt:j?void 0:G??(Z.clientKey===s.clientKey?.trim()?s.clientKeyExpiresAt:void 0),authMode:Z.authMode,byoUpstream:Z.byoUpstream,refreshSchedulerEnabled:ve};try{await _5(s,xe,T,void 0,j)}catch{return R("Could not save the owner-only Anyray runtime profile. No tool configuration was changed."),1}G&&!j&&await Fa({expiresAt:G})}if(le)if(o.dryRun)await zu()&&(H("Enrollment"),A(" would remove the stored gateway credential"));else{await Eg(s),await Vd().catch(()=>{});try{await sc()&&(H("Enrollment"),M(" Removed the stored gateway credential."),L(" Reconnect any time with `npx anyray-connect@latest --sso`."))}catch(xe){H("Enrollment"),O(" Could not remove the stored gateway credential."),O(` Delete ${ee()} by hand, or a credential refresh may restore your tool config.`)}}else o.revert&&!o.dryRun&&(A(`
|
|
1070
|
+
Keeping the stored enrollment \u2014 the tools you did not name still need it.`),A("Run --revert with no --tools to remove it."));let pe=d,Be=L5(pe,o,s.managedTools);if(Be.length>0){H("Not configured \u2014 needs your say-so");for(let be of Be)O(` ${be.id}: ${eO(be)??"changes where inference is billed"}.`),A(` Configure it deliberately with \`npx anyray-connect --tools ${be.id}\`.`);let xe=new Set(Be.map(be=>be.id));pe=pe.filter(be=>!xe.has(be.id))}if(o.revert&&!le){let xe=d.filter(be=>bi(s,be.id));if(xe.length>0){H("Fleet policy");for(let be of xe)O(` ${be.id}: locked by your admin's fleet policy \u2014 leaving it configured. Ask an admin to change the tool's tier.`);pe=d.filter(be=>!bi(s,be.id))}}let{changes:yt,manual:No,manualAdminOnly:$o,manualAdminOnlyIds:zi,results:qi}=await P5(pe,Z,U,o.revert,new Set(o.tools??[])),Qi;if(pg(o)){H("Endpoint agent");try{Qi=await(n.installEndpointAfterEnrollment??pR)({gateway:b,clientKey:Z.clientKey})}catch{L("Endpoint agent setup did not complete. Tool routing remains configured.")}}let Mo=N&&nR(Qi),ns=ve&&!Mo;if(N&&!Mo&&ve&&!o.dryRun&&L(" The machine is not under endpoint policy, so automatic key refresh stays on this seat."),Mo&&!o.dryRun&&await ce({...await P(),refreshSchedulerEnabled:!1}).catch(()=>{}),o.dryRun||(await er(qi,o.revert,le).catch(()=>{}),le&&await ic().catch(()=>{})),await G5({want:ns,scopedRevert:!!o.revert&&!le,dryRun:!!o.dryRun,wasEnabled:!!s.refreshSchedulerEnabled||!ns&&await Dc(),trayManaged:J}),!o.revert&&!o.dryRun&&!j){let xe=T??await Fe();xe&&await Kh(await P(),xe).catch(()=>{})}if(ke(),H("Summary"),o.dryRun)L("Dry run complete \u2014 re-run without --dry-run to apply.");else if(o.revert){M(`Reverted (${yt} file(s) touched).`),L("Restart any editor or agent that was running \u2014 it loaded our hooks at startup.");let xe=await mI();xe.length>0&&(H("This repo carries its own Anyray routing"),O(` Committed here: ${xe.join(", ")}`),O(" Those are tracked files, so they route every checkout of this"),O(" repo \u2014 this machine included, and your teammates' too. This"),O(" revert only removed THIS machine's own configuration."),A(`
|
|
1071
1071
|
Remove them from the repo (then commit):`),A(v(" anyray-connect --project --revert")));let be=jc(Z);be.length>0&&(H("This terminal still points at the gateway"),O(` Still exported here: ${be.join(", ")}`),O(" Removing the block from your shell profile cannot reach a shell"),O(" that already ran it. Until these are gone, your tools keep"),O(" reaching the gateway and now fail with 401."),A(`
|
|
1072
1072
|
Fix this terminal:`),A(v(` unset ${be.join(" ")}`)),A(`
|
|
1073
|
-
Every other open terminal needs the same \u2014 or just open a new one.`),A(" VS Code injects a copy it captured when IT launched, so its"),A(" terminals stay stale even if you open a new one: quit the app"),A(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(M(`Done (${yt} file(s) written).`),No.length>0){let Ot=$o.length===No.length;H(Ot?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let Ng of
|
|
1074
|
-
Skipped the connection smoke test (--skip-verify).`):await
|
|
1073
|
+
Every other open terminal needs the same \u2014 or just open a new one.`),A(" VS Code injects a copy it captured when IT launched, so its"),A(" terminals stay stale even if you open a new one: quit the app"),A(" entirely (Cmd+Q). Reloading the window keeps the old copy."))}else{if(M(`Done (${yt} file(s) written).`),No.length>0){let Ot=$o.length===No.length;H(Ot?"Blocked by machine policy \u2014 nothing for you to do":"Action required \u2014 manual steps");for(let Ng of D5(No,$o,zi.includes("claude-desktop")?process.platform:void 0))O(Ng);if(zi.includes("claude-desktop")&&!o.dryRun)try{await N5(Z)}catch{O(" Could not write the administrator profile locally. Your admin can generate it with `anyray-connect desktop fleet static macos <helper-path> --gateway <url>`.")}ht()&&!o.yes&&!Ot&&(await Oo("Have you applied the manual settings shown above?")?M("Acknowledged."):O("Apply them before using the tool, or it will keep sending traffic straight to the provider (unattributed)."))}o.skipVerify?L(`
|
|
1074
|
+
Skipped the connection smoke test (--skip-verify).`):await H5(Z,d.map(Ot=>Ot.id)),H("What's next");let xe=new Set(qi.filter(Ot=>Ot.status==="configured").map(Ot=>Ot.id)),be=d.filter(Ot=>xe.has(Ot.id)).map(Ot=>Ot.title);if(A(be.length>0?` Connected: ${be.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"),Ae(Z.clientKey)&&await aX({interactive:ht(),managed:n.managedEnrollmentRevertedTools!==void 0,yes:!!o.yes,revert:!!o.revert,dryRun:!!o.dryRun,gateway:Z.origin,user:Z.metadata.user,team:Z.metadata.team,clientKey:Z.clientKey}),!o.verbose)return 0;A(`
|
|
1075
1075
|
Re-test by hand any time:`),Z.authMode!=="placeholder"&&d.length===1&&d[0]?.id==="cursor"?(A(v(` curl -sS ${Z.origin}/connect/savings \\
|
|
1076
1076
|
-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 ${Z.openaiBaseUrl}/chat/completions \\
|
|
1077
1077
|
-H "Content-Type: application/json" \\
|
|
1078
1078
|
-H "Authorization: Bearer ${Z.clientKey?`<your personal key (${Dt(Z.clientKey)}) \u2014 see your tool config>`:"<enrollment required>"}" \\
|
|
1079
|
-
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),A(v(" Revert: npx anyray-connect --revert"))}return 0};try{return await
|
|
1079
|
+
-d '{"model":"anyray-default","messages":[{"role":"user","content":"ping"}],"max_tokens":16}'`)),A(v(" Revert: npx anyray-connect --revert"))}return 0};try{return await Y5(o.revert,o.dryRun,Rt,n.withProfileLock)}catch(D){if(D instanceof Error&&D.message==="connect profile is busy; retry the command")return R("Another Connect update is in progress. Try again."),1;throw D}finally{ke()}};rO(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e),process.exitCode=1});
|