@cortexkit/opencode-anthropic-auth 1.1.3 → 1.2.0
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/README.md +19 -0
- package/dist/cli.js +6 -254
- package/dist/index-sebye7nt.js +318 -0
- package/dist/index.js +5 -1039
- package/package.json +5 -4
- package/dist/prompt-context.js +0 -98
- package/dist/transform.js +0 -498
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
var y="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Of={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.ai/oauth/authorize"},Ef="https://platform.claude.com/oauth/code/callback",Ff="https://platform.claude.com/v1/oauth/token",qf=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],k$="mcp_";var hf="fast-mode-2026-02-01";function R$(f,$){let _=(f??"").split(",").map((m)=>m.trim()).filter(Boolean);return[...new Set([..._,...$])].join(",")}function i$(f){return typeof f==="string"&&(f.startsWith("claude-opus-4-6")||f.startsWith("claude-opus-4-7"))}var c$="You are OpenCode",u$="You are a Claude agent, built on Anthropic's Claude Agent SDK.";var Z="2.1.141",Mf="67b",wf="sdk-cli",xf="0.94.0",Pf="v24.3.0",kf="claude-cli/2.1.141 (external, sdk-cli)",Rf=["explicit","automatic","hybrid"],p="explicit",n$=["github.com/anomalyco/opencode","opencode.ai/docs"],l$=[{match:"if OpenCode honestly",replacement:"if the assistant honestly"},{match:"Here is some useful information about the environment you are running in:",replacement:"Environment context you are running in:"}];function cf(f){let $="";for(let _ of f)$+=String.fromCharCode(_);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function uf(){let f=new Uint8Array(64);crypto.getRandomValues(f);let $=cf(f),_=await crypto.subtle.digest("SHA-256",new TextEncoder().encode($));return{verifier:$,challenge:cf(new Uint8Array(_)),method:"S256"}}class h extends Error{status;body;constructor(f,$){super(`Claude OAuth refresh failed: ${f} — ${$}`);this.status=f,this.body=$,this.name="ClaudeOAuthRefreshError"}}function l0(f){if(!(f instanceof Error))return!1;let $=f.code;return f.message.includes("fetch failed")||$==="ECONNRESET"||$==="ECONNREFUSED"||$==="ETIMEDOUT"||$==="UND_ERR_CONNECT_TIMEOUT"}async function nf(f){let $=f.fetchImpl??fetch,_=f.maxRetries??2,m=f.baseDelayMs??500;for(let D=0;D<=_;D++)try{if(D>0){let C=m*2**(D-1);await new Promise((N)=>setTimeout(N,C))}let H=await $(Ff,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:f.refreshToken,client_id:y})});if(!H.ok){if(H.status>=500&&D<_){await H.body?.cancel().catch(()=>{});continue}let C=await H.text().catch(()=>"");throw new h(H.status,C)}let E=await H.json(),F=f.now?.()??Date.now();return{access:E.access_token,refresh:E.refresh_token??f.refreshToken,expires:F+E.expires_in*1000,expiresIn:E.expires_in}}catch(H){if(H instanceof h)throw H;if(D<_&&l0(H))continue;throw H}throw Error("Token refresh exhausted all retries")}function y0(){return crypto.randomUUID().replace(/-/g,"")}function p0(f){let $=f.trim();try{let E=new URL($),F=E.searchParams.get("code"),C=E.searchParams.get("state");if(F&&C)return{code:F,state:C}}catch{}let _=$.split("#");if(_.length===2&&_[0]&&_[1])return{code:_[0],state:_[1]};let m=new URLSearchParams($),D=m.get("code"),H=m.get("state");if(D&&H)return{code:D,state:H};return null}async function v0(f,$,_){let m=await fetch(Ff,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":"axios/1.13.6"},body:JSON.stringify({code:f.code,state:f.state,grant_type:"authorization_code",client_id:y,redirect_uri:_,code_verifier:$})});if(!m.ok)return{type:"failed"};let D=await m.json();return{type:"success",refresh:D.refresh_token,access:D.access_token,expires:Date.now()+D.expires_in*1000}}async function t$(f){let $=await uf(),_=y0(),m=new URL(Of[f],import.meta.url);return m.searchParams.set("code","true"),m.searchParams.set("client_id",y),m.searchParams.set("response_type","code"),m.searchParams.set("redirect_uri",Ef),m.searchParams.set("scope",qf.join(" ")),m.searchParams.set("code_challenge",$.challenge),m.searchParams.set("code_challenge_method","S256"),m.searchParams.set("state",_),{url:m.toString(),redirectUri:Ef,state:_,verifier:$.verifier}}async function g$(f,$,_,m){let D=p0(f);if(!D)return{type:"failed"};if(m&&D.state!==m)return{type:"failed"};return v0(D,$,_)}import*as lf from"node:fs";import*as yf from"node:os";import*as pf from"node:path";var d0=pf.join(yf.tmpdir(),"opencode-anthropic-auth.log"),vf=!1,t0=500,g0=50,P=[],w=null;function Cf(){if(w)clearTimeout(w),w=null;if(P.length===0)return;let f=P.join("");P=[];try{lf.appendFileSync(d0,f)}catch{}}function s0(){if(w)return;w=setTimeout(()=>{w=null,Cf()},t0)}function r0(f){if(f===void 0)return"";if(f instanceof Error)return` ${f.message}${f.stack?`
|
|
2
|
+
${f.stack}`:""}`;return` ${JSON.stringify(f)}`}function A(f,$){if(vf)return;try{if(P.push(`[${new Date().toISOString()}] ${f}${r0($)}
|
|
3
|
+
`),P.length>=g0)Cf();else s0()}catch{}}function J(f,$){A(`[relay] ${f}`,$)}if(!vf)process.on("exit",Cf);import{createHash as o0,randomUUID as Kf}from"node:crypto";import{mkdir as $0,readFile as d,rename as a0,rm as df,writeFile as _0}from"node:fs/promises";import{homedir as e0}from"node:os";import{dirname as f1,join as t}from"node:path";var $1="anthropic-auth.json",_1="https://api.anthropic.com/api/oauth/usage",m1=[401,403,429],m0=240,D1=m0;var H1=300000,E1=3600000,F1=86400000,M1=5,tf={five_hour:0,seven_day:0},C1=!0,K1=60000;function j1(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return t(process.env.XDG_CONFIG_HOME||t(e0(),".config"),"opencode")}function B(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||t(j1(),$1)}function G(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function N1(f){if(!G(f))return null;if(f.type!=="oauth")return null;if(typeof f.refresh!=="string"||!f.refresh.trim())return null;return{id:typeof f.id==="string"&&f.id.trim()?f.id.trim():Kf(),label:typeof f.label==="string"?f.label:void 0,type:"oauth",access:typeof f.access==="string"?f.access:void 0,refresh:f.refresh,expires:typeof f.expires==="number"?f.expires:void 0,enabled:typeof f.enabled==="boolean"?f.enabled:void 0,addedAt:typeof f.addedAt==="number"?f.addedAt:void 0,lastUsed:typeof f.lastUsed==="number"?f.lastUsed:void 0,lastRefreshedAt:typeof f.lastRefreshedAt==="number"?f.lastRefreshedAt:void 0,lastRefreshError:gf(f.lastRefreshError),lastQuotaRefreshError:gf(f.lastQuotaRefreshError),quota:J1(f.quota)}}function gf(f){if(!G(f))return;if(typeof f.message!=="string")return;let $=Number(f.checkedAt);if(!Number.isFinite($))return;let _=Number(f.nextRetryAt),m=Number(f.retryCount);return{message:f.message,checkedAt:$,nextRetryAt:Number.isFinite(_)?_:void 0,retryCount:Number.isFinite(m)?m:void 0,tokenHash:typeof f.tokenHash==="string"?f.tokenHash:void 0}}function J1(f){if(!G(f))return;let $={};for(let _ of["five_hour","seven_day"]){let m=f[_];if(!G(m))continue;let D=Number(m.usedPercent),H=Number(m.remainingPercent),E=Number(m.checkedAt);if(!Number.isFinite(D)||!Number.isFinite(H)||!Number.isFinite(E))continue;$[_]={usedPercent:D,remainingPercent:H,checkedAt:E,resetsAt:typeof m.resetsAt==="string"?m.resetsAt:void 0}}return Object.keys($).length?$:void 0}function b1(f){if(!G(f)||!Array.isArray(f.accounts))return null;return{version:1,main:{type:"opencode",provider:"anthropic"},fallbackOn:Array.isArray(f.fallbackOn)?f.fallbackOn.filter(($)=>Number.isInteger($)):void 0,refresh:G(f.refresh)?f.refresh:void 0,quota:G(f.quota)?f.quota:void 0,claudeCache:G(f.claudeCache)?f.claudeCache:void 0,dump:G(f.dump)?f.dump:void 0,claudeFast:G(f.claudeFast)?f.claudeFast:void 0,cacheKeep:G(f.cacheKeep)?f.cacheKeep:void 0,relay:G(f.relay)?f.relay:void 0,accounts:f.accounts.map(N1).filter(($)=>$!=null)}}async function V(f=B()){try{let $=await d(f,"utf8");return b1(JSON.parse($))}catch($){if($.code==="ENOENT")return null;return null}}async function I1(f){try{let $=await d(f,"utf8"),_=JSON.parse($);return G(_)?_:{}}catch{return{}}}function G1(f){return Object.fromEntries(Object.entries(f).filter(([,$])=>$!==void 0))}async function Y(f,$=B()){await $0(f1($),{recursive:!0});let m={...await I1($),...G1(f)},D=`${$}.${Kf()}.tmp`;await _0(D,`${JSON.stringify(m,null,2)}
|
|
4
|
+
`,{encoding:"utf8",mode:384}),await a0(D,$)}async function D_(f){let _=`${f.path??B()}.${f.name}.lock`,m=t(_,"owner.json"),D=Kf(),H=f.now??Date.now;async function E(){try{return await $0(_,{mode:448}),await _0(m,`${JSON.stringify({ownerId:D,expiresAt:H()+f.ttlMs})}
|
|
5
|
+
`,{encoding:"utf8",mode:384}),!0}catch(F){if(F.code!=="EEXIST")throw F;return!1}}if(!await E()){try{let F=JSON.parse(await d(m,"utf8"));if(Number(F?.expiresAt)>H())return null}catch{}if(await df(_,{recursive:!0,force:!0}).catch(()=>{}),!await E())return null}return{release:async()=>{try{if(JSON.parse(await d(m,"utf8"))?.ownerId!==D)return}catch{return}await df(_,{recursive:!0,force:!0}).catch(()=>{})}}}function H_(f){return f?.claudeCache?.enabled===!0}function S1(f){return typeof f==="string"&&Rf.includes(f)?f:p}function W1(f){return S1(f?.claudeCache?.mode)}async function E_(f,$,_=B()){let m=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return m.claudeCache={...m.claudeCache??{},enabled:f,mode:$??W1(m)},await Y(m,_),m}async function F_(f,$=B()){let _=await V($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return _.claudeCache={..._.claudeCache??{},enabled:_.claudeCache?.enabled===!0,mode:f},await Y(_,$),_}function M_(f){return f?.dump?.enabled===!0}async function C_(f,$=B()){let _=await V($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return _.dump={..._.dump??{},enabled:f},await Y(_,$),_}function K_(f){return f?.claudeFast?.enabled===!0}async function j_(f,$=B()){let _=await V($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return _.claudeFast={..._.claudeFast??{},enabled:f},await Y(_,$),_}async function N_(f,$,_=B()){let m=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return m.cacheKeep={enabled:!0,startHour:f,endHour:$},await Y(m,_),m}async function J_(f,$=B()){let _=await V($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return _.cacheKeep={..._.cacheKeep??{},enabled:f},await Y(_,$),_}function L1(f){return f?.fallbackOn?.length?f.fallbackOn:m1}function b_(f,$){return L1($).includes(f)}function D0(f){let $=f?.quota?.minimumRemaining||{};return{five_hour:$.five_hour??$["5h"]??tf.five_hour,seven_day:$.seven_day??$["1w"]??tf.seven_day}}function i(f){return f?.quota?.enabled!==!1}function B1(f){return f?.refresh?.enabled!==!1}function Q1(f){let $=f?.refresh?.refreshBeforeExpiryMinutes??D1;return Math.max(m0,$)*60000}function H0(f){return o0("sha256").update(f).digest("hex")}function U1(f){if(f instanceof h)return f.status===429||f.status>=500;if(!(f instanceof Error))return!1;return f.message.includes("fetch failed")||"code"in f&&(f.code==="ECONNRESET"||f.code==="ECONNREFUSED"||f.code==="ETIMEDOUT"||f.code==="UND_ERR_CONNECT_TIMEOUT")}function Z1(f){let $=H0(f.refreshToken),m=(f.previous?.tokenHash===$?f.previous.retryCount??0:0)+1,D=U1(f.error)?Math.min(E1,H1*2**Math.min(m-1,6)):F1;return{message:jf(f.error),checkedAt:f.now,nextRetryAt:f.now+D,retryCount:m,tokenHash:$}}function v(f,$,_){if(!f?.nextRetryAt||f.nextRetryAt<=_)return!1;if(!$)return!0;return f.tokenHash===H0($)}function sf(f,$){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??$)-$)/1000))}s after: ${f.message}`}function R(f){let $=f?.quota?.checkIntervalMinutes??M1;return Math.max(1,$)*60000}function E0(f){return f?.quota?.failClosedOnUnknownQuota??C1}function X1(f,$){if(!i($))return!0;let _=D0($);for(let m of["five_hour","seven_day"]){let D=f?.[m];if(!D)return!E0($);if(D.remainingPercent<_[m])return!1}return!0}function I_(f,$,_){if(!i($))return _+R($);let m=D0($),D=[];for(let H of["five_hour","seven_day"]){let E=f?.[H];if(!E)return _+R($);if(E.remainingPercent>=m[H])continue;let F=E.resetsAt?Date.parse(E.resetsAt):Number.NaN;if(!Number.isFinite(F)||F<=_)return _+R($);D.push(F)}if(!D.length)return _+R($);return Math.min(...D)+60000}function k(f,$,_){return!f.access||!f.expires||f.expires-_<=Q1($)}function rf(f,$,_){if(!i($))return!1;let m=R($);return["five_hour","seven_day"].some((D)=>{let H=f.quota?.[D];return!H||_-H.checkedAt>=m})}function of(f){if(!Number.isFinite(f))return 0;if(f<0)return 0;if(f>100)return 100;return f}function af(f,$){if(typeof f?.utilization!=="number")return;let _=of(f.utilization);return{usedPercent:_,remainingPercent:of(100-_),resetsAt:f.resets_at,checkedAt:$}}async function ef(f){let _=await(f.fetchImpl??fetch)(_1,{method:"GET",headers:{Authorization:`Bearer ${f.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${Z}`}});if(!_.ok){let H=await _.text().catch(()=>"");throw Error(`Claude quota check failed: ${_.status} — ${H}`)}let m=f.now?.()??Date.now(),D=await _.json();return{five_hour:af(D.five_hour,m),seven_day:af(D.seven_day,m)}}function X(f,$){let _=f.accounts.findIndex((m)=>m.id===$.id);if(_>=0)f.accounts[_]=$}function jf(f){return f instanceof Error?f.message:String(f)}function F0(f,$,_){f.lastRefreshError=Z1({error:$,now:_,refreshToken:f.refresh,previous:f.lastRefreshError})}function f0(f,$,_){if(f.lastQuotaRefreshError={message:jf($),checkedAt:_},$ instanceof h)F0(f,$,_)}class z1{now;fetchImpl;configPath;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;constructor(f={}){this.now=f.now??Date.now,this.fetchImpl=f.fetchImpl??fetch,this.configPath=f.configPath??B()}async load(){return V(this.configPath)}async save(f){await Y(f,this.configPath)}startBackgroundRefresh(){let f=async()=>{await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()};if(f().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{f().catch(()=>{})},K1),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts(f){let $=f!==void 0?f:await this.load();if(!$)return[];let _=[],m=!1;for(let D of $.accounts){if(D.enabled===!1)continue;try{let H=D;if(k(H,$,this.now())){let E=H.lastRefreshError;if(E&&v(E,H.refresh,this.now()))throw Error(sf(E,this.now()));H=await this.refreshAccount(H,$),m=!0}if(rf(H,$,this.now()))H=await this.refreshAccountQuota(H,$),m=!0;if(this.accountPassesQuotaPolicy(H,$))_.push(H)}catch{if(!E0($))_.push(D)}}if(m)await this.save($);return _}async markUsed(f){let $=await this.load();if(!$)return;let _=$.accounts.find((m)=>m.id===f.id);if(!_)return;_.lastUsed=this.now(),await this.save($)}accountPassesQuotaPolicy(f,$){return X1(f.quota,$)}async refreshDueAccounts(){let f=await this.load();if(!f||!B1(f))return;let $=!1;for(let _ of f.accounts){if(_.enabled===!1)continue;if(!k(_,f,this.now()))continue;if(v(_.lastRefreshError,_.refresh,this.now())){A("[refresh] fallback oauth skipped backoff",{accountId:_.id,nextRetryAt:_.lastRefreshError?.nextRetryAt,retryCount:_.lastRefreshError?.retryCount});continue}try{A("[refresh] fallback oauth background due",{accountId:_.id,expiresInMs:_.expires?_.expires-this.now():void 0}),await this.refreshAccount(_,f),$=!0}catch(m){A("[refresh] fallback oauth background failed",{accountId:_.id,error:m instanceof Error?m.message:String(m)}),F0(_,m,this.now()),X(f,_),$=!0}}if($)await this.save(f)}async refreshQuotaForDueAccounts(){let f=await this.load();if(!f||!i(f))return;let $=!1;for(let _ of f.accounts){if(_.enabled===!1)continue;let m=_;try{if(k(m,f,this.now())){if(v(m.lastRefreshError,m.refresh,this.now()))continue;m=await this.refreshAccount(m,f),$=!0}if(!rf(m,f,this.now()))continue;await this.refreshAccountQuota(m,f),$=!0}catch(D){f0(_,D,this.now()),X(f,_),$=!0}}if($)await this.save(f)}async refreshQuotaForAllAccounts(){let f=await this.load(),$=[];if(!f||!i(f))return{storage:f,errors:$};let _=!1;for(let m of f.accounts){if(m.enabled===!1)continue;let D=m;try{if(k(D,f,this.now())){let H=D.lastRefreshError;if(H&&v(H,D.refresh,this.now()))throw Error(sf(H,this.now()));D=await this.refreshAccount(D,f),_=!0}await this.refreshAccountQuota(D,f),_=!0}catch(H){f0(m,H,this.now()),X(f,m),_=!0,$.push({accountId:m.id,message:jf(H)})}}if(_)await this.save(f);return{storage:f,errors:$}}async refreshAccount(f,$,_={}){let m=this.refreshPromises.get(f.id);if(m){let E=await m;return X($,E),E}let D=this.refreshAccountNow(f,$,_).finally(()=>{this.refreshPromises.delete(f.id)});this.refreshPromises.set(f.id,D);let H=await D;return X($,H),H}async refreshAccountNow(f,$,_){let m=await this.load(),D=m?.accounts.find((C)=>C.id===f.id);if(D&&!_.force&&!k(D,m,this.now()))return X($,D),D;let H=D??f,E=H.refresh;A("[refresh] fallback oauth refresh request start",{accountId:H.id,force:_.force===!0,expiresInMs:H.expires?H.expires-this.now():void 0});let F=await nf({refreshToken:E,fetchImpl:this.fetchImpl,now:this.now});return H.access=F.access,H.refresh=F.refresh,H.expires=F.expires,H.lastRefreshedAt=F.expires-F.expiresIn*1000,H.lastRefreshError=void 0,X($,H),A("[refresh] fallback oauth refresh succeeded",{accountId:H.id,expiresInMs:H.expires?H.expires-this.now():void 0}),H}async refreshAccountQuota(f,$){let _=f;if(!_.access)throw Error(`Fallback account ${f.id} has no access token`);try{_.quota=await ef({accessToken:_.access,fetchImpl:this.fetchImpl,now:this.now})}catch(m){if(!(m instanceof Error?m.message:String(m)).includes("Claude quota check failed: 401"))throw m;if(_=await this.refreshAccount(f,$,{force:!0}),!_.access)throw m;_.quota=await ef({accessToken:_.access,fetchImpl:this.fetchImpl,now:this.now})}return _.lastQuotaRefreshError=void 0,X($,_),_}}var W_="claude-cache",M0="## Claude Cache Status",A1="## Claude Cache Enabled",V1="## Claude Cache Disabled",Y1="## Claude Cache Usage",T1="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",g=!1,s=p;function L_(){return g}function B_(){return s}function Q_(f){g=f.enabled,s=f.mode}function O1(f){let $=f.trim().split(/\s+/).filter(Boolean);if($.length===0)return{type:"status"};if($.length===1&&$[0]==="on")return{type:"enable"};if($.length===1&&$[0]==="off")return{type:"disable"};if($.length===2&&$[0]==="mode"&&($[1]==="explicit"||$[1]==="automatic"||$[1]==="hybrid"))return{type:"mode",mode:$[1]};return{type:"usage"}}function c(f){let $=f?.enabled??g,_=f?.mode??s;return[M0,"",`- Enabled: ${$?"enabled":"disabled"}`,`- Mode: ${_}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Scope: main sessions only; subagent sessions keep default ephemeral cache behavior","- Modes: explicit = existing OpenCode breakpoints; automatic = top-level cache_control only; hybrid = system + messages[0] + top-level cache_control","- TTL: 1h when enabled for main sessions; default ephemeral cache behavior otherwise"].join(`
|
|
6
|
+
`)}function U_(f){let $=O1(f.argumentsText),_=f.enabled??g,m=f.mode??s;if($.type==="status")return c({enabled:_,mode:m});if($.type==="enable")return[A1,"",c({enabled:!0,mode:m})].join(`
|
|
7
|
+
`);if($.type==="disable")return[V1,"",c({enabled:!1,mode:m})].join(`
|
|
8
|
+
`);if($.type==="mode")return[M0,"",`Mode updated to \`${$.mode}\`.`,"",c({enabled:_,mode:$.mode})].join(`
|
|
9
|
+
`);return[Y1,"",T1,"",c({enabled:_,mode:m})].join(`
|
|
10
|
+
`)}import{randomBytes as q1,randomUUID as K0}from"node:crypto";var h1=1000,u=new Map;function Jf(f,$,_){if(!f.has($)&&f.size>=h1){let m=f.keys().next().value;if(m!==void 0)f.delete(m)}f.set($,_)}function j0(f){let $=f||"anonymous",_=u.get($);if(_)return _;let m={deviceId:q1(32).toString("hex"),sessionId:K0()};return Jf(u,$,m),m}var Nf=new Map;async function w1(f,$){if(!f.startsWith("sk-ant-oat"))return null;let _=new AbortController,m=setTimeout(()=>_.abort(),5000);try{let D=new URL("https://api.anthropic.com/api/claude_cli/bootstrap");if(D.searchParams.set("entrypoint",wf),$)D.searchParams.set("model",$);let H=await fetch(D,{method:"GET",headers:{accept:"application/json, text/plain, */*",authorization:`Bearer ${f}`,"content-type":"application/json","anthropic-beta":"oauth-2025-04-20","user-agent":`claude-code/${Z}`},signal:_.signal});if(!H.ok)return null;let F=(await H.json().catch(()=>null))?.oauth_account?.account_uuid;return typeof F==="string"&&F?F:null}catch{return null}finally{clearTimeout(m)}}async function A_(f,$){let _=j0(f);if(!f.startsWith("sk-ant-oat"))return _;let m=Nf.get(f);if(!m)m=w1(f,$),Nf.set(f,m);let D=await m;if(!D)return Nf.delete(f),_;let H=`account:${D}`,E=u.get(H);if(E)return Jf(u,f,E),E;return _.accountUuid=D,Jf(u,H,_),_}function T(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function x1(f){if(!f.accountUuid)return null;return JSON.stringify({device_id:f.deviceId,account_uuid:f.accountUuid,session_id:f.sessionId})}function V_(f,$){let _=x1($);if(!_){if(T(f.metadata))delete f.metadata.user_id;return!1}if(!T(f.metadata))f.metadata={};let m=f.metadata;if(T(m))m.user_id=_;return!0}var P1=["claude-code-20250219","oauth-2025-04-20","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advisor-tool-2026-03-01","advanced-tool-use-2025-11-20","context-1m-2025-08-07","effort-2025-11-24","extended-cache-ttl-2025-04-11","cache-diagnosis-2026-04-07"],k1=["oauth-2025-04-20","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advisor-tool-2026-03-01","structured-outputs-2025-12-15","cache-diagnosis-2026-04-07"],C0=["oauth-2025-04-20","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advisor-tool-2026-03-01","cache-diagnosis-2026-04-07"];function R1(f){return f.output_config?.format?.type==="json_schema"}function i1(f){return Array.isArray(f.tools)&&f.tools.length>0&&Array.isArray(f.system)&&T(f.thinking)&&T(f.context_management)&&T(f.output_config)&&T(f.diagnostics)}function c1(f,$=[]){let _=f?i1(f)?[...P1]:R1(f)?[...k1]:[...C0]:[...C0];if(f?.speed==="fast")_.push(hf);for(let m of $){let D=m.trim();if(D)_.push(D)}return[...new Set(_)].join(",")}function u1(){switch(process.platform){case"darwin":return"MacOS";case"win32":return"Windows";case"linux":return"Linux";case"freebsd":return"FreeBSD";default:return"Unknown"}}function n1(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";case"ia32":return"x32";default:return process.arch}}function Y_(f,$,_={}){let m=_.identity??j0($),H=[...(f.get("anthropic-beta")??"").split(",").map((E)=>E.trim()).filter(Boolean),..._.extraBetas??[]];return f.set("accept","application/json"),f.set("authorization",`Bearer ${$}`),f.set("content-type","application/json"),f.set("user-agent",kf),f.set("anthropic-beta",c1(_.body,H)),f.set("anthropic-dangerous-direct-browser-access","true"),f.set("anthropic-version","2023-06-01"),f.set("x-app","cli"),f.set("x-client-request-id",K0()),f.set("x-claude-code-session-id",m.sessionId),f.set("x-stainless-arch",n1()),f.set("x-stainless-lang","js"),f.set("x-stainless-os",u1()),f.set("x-stainless-package-version",xf),f.set("x-stainless-retry-count","0"),f.set("x-stainless-runtime","node"),f.set("x-stainless-runtime-version",Pf),f.set("x-stainless-timeout","600"),f.delete("x-api-key"),f}var l1=["model","messages","system","tools","tool_choice","metadata","max_tokens","temperature","thinking","context_management","output_config","diagnostics","stream","speed"];function N0(f){let $={};for(let _ of l1)if(Object.hasOwn(f,_))$[_]=f[_];for(let[_,m]of Object.entries(f))if(!Object.hasOwn($,_))$[_]=m;return $}import{createHash as p1}from"node:crypto";var y1=new Uint8Array([0,97,115,109,1,0,0,0,1,48,8,96,3,127,127,127,1,127,96,3,127,127,127,0,96,2,127,127,0,96,1,127,1,127,96,3,127,127,126,1,126,96,3,126,127,127,1,126,96,2,127,126,0,96,1,127,1,126,3,11,10,0,0,2,1,3,4,5,6,1,7,5,3,1,0,1,7,85,9,3,109,101,109,2,0,5,120,120,104,51,50,0,0,6,105,110,105,116,51,50,0,2,8,117,112,100,97,116,101,51,50,0,3,8,100,105,103,101,115,116,51,50,0,4,5,120,120,104,54,52,0,5,6,105,110,105,116,54,52,0,7,8,117,112,100,97,116,101,54,52,0,8,8,100,105,103,101,115,116,54,52,0,9,10,251,22,10,242,1,1,4,127,32,0,32,1,106,33,3,32,1,65,16,79,4,127,32,3,65,16,107,33,6,32,2,65,168,136,141,161,2,106,33,3,32,2,65,137,235,208,208,7,107,33,4,32,2,65,207,140,162,142,6,106,33,5,3,64,32,3,32,0,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,3,32,4,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,4,32,2,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,2,32,5,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,5,32,6,32,0,65,4,106,34,0,79,13,0,11,32,2,65,12,119,32,5,65,18,119,106,32,4,65,7,119,106,32,3,65,1,119,106,5,32,2,65,177,207,217,178,1,106,11,32,1,106,32,0,32,1,65,15,113,16,1,11,146,1,0,32,1,32,2,106,33,2,3,64,32,1,65,4,106,32,2,75,69,4,64,32,0,32,1,40,2,0,65,189,220,202,149,124,108,106,65,17,119,65,175,214,211,190,2,108,33,0,32,1,65,4,106,33,1,12,1,11,11,3,64,32,1,32,2,79,69,4,64,32,0,32,1,45,0,0,65,177,207,217,178,1,108,106,65,11,119,65,177,243,221,241,121,108,33,0,32,1,65,1,106,33,1,12,1,11,11,32,0,32,0,65,15,118,115,65,247,148,175,175,120,108,34,0,65,13,118,32,0,115,65,189,220,202,149,124,108,34,0,65,16,118,32,0,115,11,63,0,32,0,65,8,106,32,1,65,168,136,141,161,2,106,54,2,0,32,0,65,12,106,32,1,65,137,235,208,208,7,107,54,2,0,32,0,65,16,106,32,1,54,2,0,32,0,65,20,106,32,1,65,207,140,162,142,6,106,54,2,0,11,195,4,1,6,127,32,1,32,2,106,33,6,32,0,65,24,106,33,4,32,0,65,40,106,40,2,0,33,3,32,0,32,0,40,2,0,32,2,106,54,2,0,32,0,65,4,106,34,5,32,5,40,2,0,32,2,65,16,79,32,0,40,2,0,65,16,79,114,114,54,2,0,32,2,32,3,106,65,16,73,4,64,32,3,32,4,106,32,1,32,2,252,10,0,0,32,0,65,40,106,32,2,32,3,106,54,2,0,15,11,32,3,4,64,32,3,32,4,106,32,1,65,16,32,3,107,34,2,252,10,0,0,32,0,65,8,106,34,3,32,3,40,2,0,32,4,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,54,2,0,32,0,65,12,106,34,3,32,3,40,2,0,32,4,65,4,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,54,2,0,32,0,65,16,106,34,3,32,3,40,2,0,32,4,65,8,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,54,2,0,32,0,65,20,106,34,3,32,3,40,2,0,32,4,65,12,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,54,2,0,32,0,65,40,106,65,0,54,2,0,32,1,32,2,106,33,1,11,32,1,32,6,65,16,107,77,4,64,32,6,65,16,107,33,8,32,0,65,8,106,40,2,0,33,2,32,0,65,12,106,40,2,0,33,3,32,0,65,16,106,40,2,0,33,5,32,0,65,20,106,40,2,0,33,7,3,64,32,2,32,1,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,2,32,3,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,3,32,5,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,5,32,7,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,7,32,8,32,1,65,4,106,34,1,79,13,0,11,32,0,65,8,106,32,2,54,2,0,32,0,65,12,106,32,3,54,2,0,32,0,65,16,106,32,5,54,2,0,32,0,65,20,106,32,7,54,2,0,11,32,1,32,6,73,4,64,32,4,32,1,32,6,32,1,107,34,1,252,10,0,0,32,0,65,40,106,32,1,54,2,0,11,11,97,1,1,127,32,0,65,16,106,40,2,0,33,1,32,0,65,4,106,40,2,0,4,127,32,1,65,12,119,32,0,65,20,106,40,2,0,65,18,119,106,32,0,65,12,106,40,2,0,65,7,119,106,32,0,65,8,106,40,2,0,65,1,119,106,5,32,1,65,177,207,217,178,1,106,11,32,0,40,2,0,106,32,0,65,24,106,32,0,65,40,106,40,2,0,16,1,11,255,3,2,3,126,1,127,32,0,32,1,106,33,6,32,1,65,32,79,4,126,32,6,65,32,107,33,6,32,2,66,214,235,130,238,234,253,137,245,224,0,124,33,3,32,2,66,177,169,172,193,173,184,212,166,61,125,33,4,32,2,66,249,234,208,208,231,201,161,228,225,0,124,33,5,3,64,32,3,32,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,3,32,4,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,4,32,2,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,2,32,5,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,5,32,6,32,0,65,8,106,34,0,79,13,0,11,32,2,66,12,137,32,5,66,18,137,124,32,4,66,7,137,124,32,3,66,1,137,124,32,3,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,4,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,2,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,5,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,5,32,2,66,197,207,217,178,241,229,186,234,39,124,11,32,1,173,124,32,0,32,1,65,31,113,16,6,11,134,2,0,32,1,32,2,106,33,2,3,64,32,2,32,1,65,8,106,79,4,64,32,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,32,0,133,66,27,137,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,33,0,32,1,65,8,106,33,1,12,1,11,11,32,1,65,4,106,32,2,77,4,64,32,0,32,1,53,2,0,66,135,149,175,175,152,182,222,155,158,127,126,133,66,23,137,66,207,214,211,190,210,199,171,217,66,126,66,249,243,221,241,153,246,153,171,22,124,33,0,32,1,65,4,106,33,1,11,3,64,32,1,32,2,73,4,64,32,0,32,1,49,0,0,66,197,207,217,178,241,229,186,234,39,126,133,66,11,137,66,135,149,175,175,152,182,222,155,158,127,126,33,0,32,1,65,1,106,33,1,12,1,11,11,32,0,32,0,66,33,136,133,66,207,214,211,190,210,199,171,217,66,126,34,0,32,0,66,29,136,133,66,249,243,221,241,153,246,153,171,22,126,34,0,32,0,66,32,136,133,11,77,0,32,0,65,8,106,32,1,66,214,235,130,238,234,253,137,245,224,0,124,55,3,0,32,0,65,16,106,32,1,66,177,169,172,193,173,184,212,166,61,125,55,3,0,32,0,65,24,106,32,1,55,3,0,32,0,65,32,106,32,1,66,249,234,208,208,231,201,161,228,225,0,124,55,3,0,11,244,4,2,3,127,4,126,32,1,32,2,106,33,5,32,0,65,40,106,33,4,32,0,65,200,0,106,40,2,0,33,3,32,0,32,0,41,3,0,32,2,173,124,55,3,0,32,2,32,3,106,65,32,73,4,64,32,3,32,4,106,32,1,32,2,252,10,0,0,32,0,65,200,0,106,32,2,32,3,106,54,2,0,15,11,32,3,4,64,32,3,32,4,106,32,1,65,32,32,3,107,34,2,252,10,0,0,32,0,65,8,106,34,3,32,3,41,3,0,32,4,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,55,3,0,32,0,65,16,106,34,3,32,3,41,3,0,32,4,65,8,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,55,3,0,32,0,65,24,106,34,3,32,3,41,3,0,32,4,65,16,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,55,3,0,32,0,65,32,106,34,3,32,3,41,3,0,32,4,65,24,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,55,3,0,32,0,65,200,0,106,65,0,54,2,0,32,1,32,2,106,33,1,11,32,1,65,32,106,32,5,77,4,64,32,5,65,32,107,33,2,32,0,65,8,106,41,3,0,33,6,32,0,65,16,106,41,3,0,33,7,32,0,65,24,106,41,3,0,33,8,32,0,65,32,106,41,3,0,33,9,3,64,32,6,32,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,7,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,7,32,8,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,8,32,9,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,9,32,2,32,1,65,8,106,34,1,79,13,0,11,32,0,65,8,106,32,6,55,3,0,32,0,65,16,106,32,7,55,3,0,32,0,65,24,106,32,8,55,3,0,32,0,65,32,106,32,9,55,3,0,11,32,1,32,5,73,4,64,32,4,32,1,32,5,32,1,107,34,1,252,10,0,0,32,0,65,200,0,106,32,1,54,2,0,11,11,188,2,1,5,126,32,0,65,24,106,41,3,0,33,1,32,0,41,3,0,34,2,66,32,90,4,126,32,0,65,8,106,41,3,0,34,3,66,1,137,32,0,65,16,106,41,3,0,34,4,66,7,137,124,32,1,66,12,137,32,0,65,32,106,41,3,0,34,5,66,18,137,124,124,32,3,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,4,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,1,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,5,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,5,32,1,66,197,207,217,178,241,229,186,234,39,124,11,32,2,124,32,0,65,40,106,32,2,66,31,131,167,16,6,11]);async function J0(){return function(f){let{exports:{mem:$,xxh32:_,xxh64:m,init32:D,update32:H,digest32:E,init64:F,update64:C,digest64:N}}=f,j=new Uint8Array($.buffer);function b(M,I){if($.buffer.byteLength<M+I){let Df=Math.ceil((M+I-$.buffer.byteLength)/65536);$.grow(Df),j=new Uint8Array($.buffer)}}function U(M,I,Df,c0,u0,n0){b(M);let x=new Uint8Array(M);return j.set(x),Df(0,I),x.set(j.subarray(0,M)),{update(q){let Hf;return j.set(x),typeof q=="string"?(b(3*q.length,M),Hf=L.encodeInto(q,j.subarray(M)).written):(b(q.byteLength,M),j.set(q,M),Hf=q.byteLength),c0(0,M,Hf),x.set(j.subarray(0,M)),this},digest:()=>(j.set(x),n0(u0(0)))}}function Q(M){return M>>>0}let K=2n**64n-1n;function W(M){return M&K}let L=new TextEncoder,n=0,l=0n;function Yf(M,I=n){return b(3*M.length,0),Q(_(0,L.encodeInto(M,j).written,I))}function Tf(M,I=l){return b(3*M.length,0),W(m(0,L.encodeInto(M,j).written,I))}return{h32:Yf,h32ToString:(M,I=n)=>Yf(M,I).toString(16).padStart(8,"0"),h32Raw:(M,I=n)=>(b(M.byteLength,0),j.set(M),Q(_(0,M.byteLength,I))),create32:(M=n)=>U(48,M,D,H,E,Q),h64:Tf,h64ToString:(M,I=l)=>Tf(M,I).toString(16).padStart(16,"0"),h64Raw:(M,I=l)=>(b(M.byteLength,0),j.set(M),W(m(0,M.byteLength,I))),create64:(M=l)=>U(88,M,F,C,N,W)}}((await WebAssembly.instantiate(y1)).instance)}var v1=0x6e52736ac806831en,r=/\bcch=([0-9a-f]{5});/,b0=null,bf=null;async function d1(){if(bf)return;b0??=(async()=>{bf=(await J0()).h64Raw})(),await b0}async function t1(f){return await d1(),((bf?.(f,v1)??0n)&0xfffffn).toString(16).padStart(5,"0")}async function I0(f){if(!r.test(f))return f;let $=await t1(new TextEncoder().encode(f));return f.replace(r,`cch=${$};`)}function g1(f=Z,$=new Date){if(f===Z)return Mf;let _=$.toISOString().slice(0,10);return p1("sha256").update(`${_}${f}`).digest("hex").slice(0,3)}function x_(f,$=Z,_,m=new Date){let D=g1($,m);return`x-anthropic-billing-header: cc_version=${$}.${D}; cc_entrypoint=${_}; cch=00000;`}var i_="claude-cachekeep",G0=3600000,If=300000,s1=60000,c_="extended-cache-ttl-2025-04-11",r1="## Claude Cache Keep Status",o1="## Claude Cache Keep Enabled",a1="## Claude Cache Keep Disabled",e1="## Claude Cache Keep Usage",f$="Usage: `/claude-cachekeep`, `/claude-cachekeep off`, or `/claude-cachekeep HH-HH`.";function a(f){return String(f).padStart(2,"0")}function $$(f){let $=f.trim();if(!$)return{type:"status"};if($==="off")return{type:"disable"};let _=/^(\d{1,2})-(\d{1,2})$/.exec($);if(!_)return{type:"usage"};let m=Number(_[1]),D=Number(_[2]);if(!Number.isInteger(m)||!Number.isInteger(D)||m<0||m>23||D<0||D>23||m===D)return{type:"usage"};return{type:"window",startHour:m,endHour:D}}function Sf(f){let $=Number(f?.cacheKeep?.startHour),_=Number(f?.cacheKeep?.endHour);if(!Number.isInteger($)||!Number.isInteger(_)||$<0||$>23||_<0||_>23||$===_)return;return{startHour:$,endHour:_}}function L0(f){return f?.cacheKeep?.enabled===!0&&!!Sf(f)}function _$(f){return L0(f)&&f?.claudeCache?.enabled===!0&&f.claudeCache.mode==="hybrid"}function S0(f,$=new Date){if(!f)return!1;let _=$.getHours();if(f.startHour<f.endHour)return _>=f.startHour&&_<f.endHour;return _>=f.startHour||_<f.endHour}function W0(f=new Date){return`${f.getFullYear()}-${a(f.getMonth()+1)}-${a(f.getDate())}`}function Gf(f,$=new Date){if(f&&f.startHour>f.endHour&&$.getHours()<f.endHour){let _=new Date($);return _.setDate(_.getDate()-1),W0(_)}return W0($)}function o(f){let $=f.window?`${a(f.window.startHour)}-${a(f.window.endHour)}`:"not configured",_=[`Cache keep: ${f.enabled?"enabled":"disabled"}`,`Window: ${$}`,"Mode requirement: `/claude-cache mode hybrid` must be active."];if(typeof f.hybridActive==="boolean")_.push(`Hybrid active: ${f.hybridActive?"yes":"no"}`);if(typeof f.trackedSessions==="number")_.push(`Tracked sessions: ${f.trackedSessions}`);if(f.nextPrewarmAt)_.push(`Next prewarm: ${new Date(f.nextPrewarmAt).toLocaleString()}`);return _.join(`
|
|
11
|
+
`)}function u_(f){let $=$$(f.argumentsText),_={enabled:f.enabled??!1,window:f.window,trackedSessions:f.trackedSessions,nextPrewarmAt:f.nextPrewarmAt,hybridActive:f.hybridActive};if($.type==="status")return[r1,"",o(_)].join(`
|
|
12
|
+
`);if($.type==="disable")return[a1,"",o({..._,enabled:!1})].join(`
|
|
13
|
+
`);if($.type==="window")return[o1,"",o({..._,enabled:!0,window:{startHour:$.startHour,endHour:$.endHour}})].join(`
|
|
14
|
+
`);return[e1,"",f$,"",o(_)].join(`
|
|
15
|
+
`)}function Wf(f){if(!f||typeof f!=="object")return!1;if(Array.isArray(f))return f.some(Wf);let $=f,_=$.cache_control;if(_&&typeof _==="object"&&_.type==="ephemeral")return!0;return Object.values($).some(Wf)}async function m$(f){let $;try{$=JSON.parse(f)}catch{return{ok:!1,reason:"body is not valid JSON"}}if(!Wf($))return{ok:!1,reason:"body has no explicit cache breakpoints"};let _=structuredClone($);if(_.max_tokens=0,delete _.stream,_.thinking?.type==="enabled")delete _.thinking;if(_.output_config?.format)delete _.output_config;let H=_.tool_choice;if(H?.type==="tool"||H?.type==="any")delete _.tool_choice;let E=JSON.stringify(N0(_)).replace(r,"cch=00000;");return{ok:!0,bodyText:await I0(E)}}class D${options;targets=new Map;timer=null;constructor(f){this.options=f}start(){if(this.timer)return;if(this.timer=setInterval(()=>{this.tick().catch((f)=>{this.options.log?.("[cachekeep] tick failed",{error:f instanceof Error?f.message:String(f)})})},s1),"unref"in this.timer)this.timer.unref()}stop(){if(this.timer)clearInterval(this.timer);this.timer=null}stats(f,$=this.options.now?.()??Date.now()){let _=Gf(f,new Date($)),m=[...this.targets.values()].filter((H)=>H.dayKey===_),D=m.length?Math.min(...m.map((H)=>H.cacheExpiresAt-If)):void 0;return{trackedSessions:m.length,nextPrewarmAt:D}}track(f){if(!f.sessionId)return{tracked:!1,reason:"missing session id"};if(!L0(f.storage))return{tracked:!1,reason:"cachekeep disabled"};if(f.cacheMode!=="hybrid")return{tracked:!1,reason:"cache mode is not hybrid"};let $=this.options.now?.()??Date.now(),_=Sf(f.storage);if(!S0(_,new Date($)))return{tracked:!1,reason:"outside configured window"};let m={};return f.headers.forEach((D,H)=>{m[H]=D}),this.targets.set(f.sessionId,{id:f.sessionId,url:f.url,headers:m,bodyText:f.bodyText,cacheExpiresAt:$+G0,dayKey:Gf(_,new Date($))}),this.start(),{tracked:!0}}async tick(){let f=await this.options.loadStorage(),$=Sf(f),_=this.options.now?.()??Date.now(),m=Gf($,new Date(_));for(let[H,E]of this.targets)if(E.dayKey!==m)this.targets.delete(H);if(!this.targets.size){this.stop();return}if(!_$(f))return;if(!S0($,new Date(_)))return;let D=_+If;for(let H of this.targets.values()){if(H.cacheExpiresAt>D)continue;await this.prewarm(H,_)}}async prewarm(f,$){let _=await m$(f.bodyText);if(!_.ok){this.options.log?.("[cachekeep] prewarm skipped",{session:f.id,reason:_.reason}),this.targets.delete(f.id);return}let m=this.options.fetchImpl??fetch,D={...f,bodyText:_.bodyText},H=this.options.prepareHeaders?await this.options.prepareHeaders(new Headers(f.headers),D):new Headers(f.headers);H.delete("content-length"),H.delete("transfer-encoding");let E=await m(f.url,{method:"POST",headers:H,body:_.bodyText});if(!E.ok){this.options.log?.("[cachekeep] prewarm failed",{session:f.id,status:E.status,body:await E.text().catch(()=>"")}),f.cacheExpiresAt=$+If+300000;return}await E.body?.cancel().catch(()=>{}),f.cacheExpiresAt=$+G0,this.options.log?.("[cachekeep] prewarm succeeded",{session:f.id})}}import{createHash as H$}from"node:crypto";import{mkdir as E$,writeFile as Lf}from"node:fs/promises";import{tmpdir as F$}from"node:os";import{join as U0}from"node:path";var t_="claude-dump",M$="## Claude Dump Status",C$="## Claude Dump Enabled",K$="## Claude Dump Disabled",j$="## Claude Dump Usage",N$="Usage: `/claude-dump`, `/claude-dump on`, or `/claude-dump off`.",Qf=U0(F$(),"opencode-anthropic-auth-dumps"),ff=!1,B0=0;function g_(f){ff=f}function J$(f){let $=f.trim().split(/\s+/).filter(Boolean);if($.length===0)return{type:"status"};if($.length===1&&$[0]==="on")return{type:"enable"};if($.length===1&&$[0]==="off")return{type:"disable"};return{type:"usage"}}function e(f){let $=f?.enabled??ff;return[M$,"",`- Enabled: ${$?"enabled":"disabled"}`,`- Directory: ${Qf}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Captures: final rewritten Anthropic body plus redacted relay payload metadata","- Warning: body dumps may contain prompt/session content; turn this off after debugging"].join(`
|
|
16
|
+
`)}function s_(f){let $=J$(f.argumentsText),_=f.enabled??ff;if($.type==="status")return e({enabled:_});if($.type==="enable")return[C$,"",e({enabled:!0})].join(`
|
|
17
|
+
`);if($.type==="disable")return[K$,"",e({enabled:!1})].join(`
|
|
18
|
+
`);return[j$,"",N$,"",e({enabled:_})].join(`
|
|
19
|
+
`)}function Q0(f){return f.length<=16?f:`${f.slice(0,12)}…`}function Z0(f){return H$("sha256").update(f).digest("hex")}function b$(f){return f.match(/\bcch=([0-9a-f]{5});/)?.[1]??null}function I$(f,$){if(f==null)return null;if(f===$)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:f.length,currentBytes:$.length};let _=0;while(_<f.length&&_<$.length&&f[_]===$[_])_+=1;let m=f.length-1,D=$.length-1;while(m>=_&&D>=_&&f[m]===$[D])m-=1,D-=1;return{changed:!0,firstByte:_,lastPreviousByte:m,lastCurrentByte:D,changedPreviousBytes:m-_+1,changedCurrentBytes:D-_+1,previousBytes:f.length,currentBytes:$.length}}function G$(f){try{let $=JSON.parse(f);return $!=null&&typeof $==="object"&&!Array.isArray($)?$:null}catch($){return J(`dump body parse failed: ${$ instanceof Error?$.message:String($)}`),null}}function Bf(f){return Z0(JSON.stringify(f))}function S$(f){let $=G$(f);if(!$)return{parseable:!1};let _=Array.isArray($.messages)?$.messages:[],m=Array.isArray($.system)?$.system:[],D=_[0],H=_.slice(1);return{parseable:!0,model:typeof $.model==="string"?$.model:void 0,stream:$.stream,systemCount:m.length,messagesCount:_.length,systemHash:Bf(m),message0Hash:D===void 0?null:Bf(D),message0Bytes:D===void 0?0:JSON.stringify(D).length,messagesAfter0Hash:Bf(H),messagesAfter0Bytes:JSON.stringify(H).length,cch:b$(f)}}function Uf(f){if(Array.isArray(f))return f.map(Uf);if(f==null||typeof f!=="object")return f;let $={};for(let[_,m]of Object.entries(f)){let D=_.toLowerCase();if(D==="authorization"||D==="x-api-key"||D==="cookie"||D==="set-cookie"){$[_]="[redacted]";continue}$[_]=Uf(m)}return $}async function X0(f){if(!ff)return;B0+=1;let $=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(B0).padStart(5,"0")}-${f.transport}-p${f.protocol}-${f.mode}`,_=U0(Qf,$);try{await E$(Qf,{recursive:!0});let m={id:$,createdAt:new Date().toISOString(),session:Q0(f.affinity),transport:f.transport,protocol:f.protocol,mode:f.mode,status:f.status,bodyBytes:f.bodyText.length,relayBytes:f.relayBytes,bodyHash:Z0(f.bodyText),diff:I$(f.previousBodyText,f.bodyText),body:S$(f.bodyText),files:{body:`${_}.body.json`,relay:`${_}.relay.json`,metadata:`${_}.meta.json`}};await Promise.all([Lf(`${_}.body.json`,f.bodyText,"utf8"),Lf(`${_}.relay.json`,`${JSON.stringify(Uf(f.payload),null,2)}
|
|
20
|
+
`,"utf8"),Lf(`${_}.meta.json`,`${JSON.stringify(m,null,2)}
|
|
21
|
+
`,"utf8")]),J(`dumped request id=${$} session=${Q0(f.affinity)} body=${_}.body.json meta=${_}.meta.json`)}catch(m){J(`dump failed: ${m instanceof Error?m.message:String(m)}`)}}var o_="claude-fast";var _f=!1;function a_(){return _f}function e_(f){_f=f}function W$(f){let $=f.trim().split(/\s+/).filter(Boolean);if($.length===0)return{type:"status"};if($.length===1&&$[0]==="on")return{type:"enable"};if($.length===1&&$[0]==="off")return{type:"disable"};return{type:"usage"}}function $f(f){return["## Claude Fast Mode Status","",`- Enabled: ${f?.enabled??_f?"enabled":"disabled"}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Scope: adds Anthropic fast mode to supported Opus requests","- Supported models: claude-opus-4-6 and claude-opus-4-7",'- Request changes: adds `speed: "fast"` and the `fast-mode-2026-02-01` beta header',"- Note: fast and standard speeds do not share prompt-cache prefixes"].join(`
|
|
22
|
+
`)}function fm(f){let $=W$(f.argumentsText),_=f.enabled??_f;if($.type==="status")return $f({enabled:_});if($.type==="enable")return["## Claude Fast Mode Enabled","",$f({enabled:!0})].join(`
|
|
23
|
+
`);if($.type==="disable")return["## Claude Fast Mode Disabled","",$f({enabled:!1})].join(`
|
|
24
|
+
`);return["## Claude Fast Mode Usage","","Usage: `/claude-fast`, `/claude-fast on`, or `/claude-fast off`.","",$f({enabled:_})].join(`
|
|
25
|
+
`)}var _m="claude-quota",z0={five_hour:"5h",seven_day:"1w"};function A0(f){return`${Math.round(f*10)/10}%`}function Zf(f,$){let _=Math.max(0,$-f),m=Math.floor(_/60000);if(m<1)return"just now";if(m===1)return"1m ago";if(m<60)return`${m}m ago`;let D=Math.floor(m/60),H=m%60;if(H===0)return`${D}h ago`;return`${D}h ${H}m ago`}function L$(f,$){let _=Date.parse(f);if(!Number.isFinite(_))return f;let m=_-$;if(m<=0)return"now";let D=Math.max(1,Math.ceil(m/60000));if(D<60)return`in ${D}m`;let H=Math.floor(D/60),E=D%60;if(E===0)return`in ${H}h`;return`in ${H}h ${E}m`}function B$(f,$){if(!f)return"";return`, resets ${L$(f,$)}`}function V0(f,$,_){if(!$)return` - ${z0[f]}: unknown`;return[` - ${z0[f]}: ${A0($.remainingPercent)} remaining`,` (${A0($.usedPercent)} used`,`${B$($.resetsAt,_)}, checked ${Zf($.checkedAt,_)})`].join("")}function Q$(f){return f.label?.trim()||f.id}function U$(f){return f.lastQuotaRefreshError?.message??f.lastRefreshError?.message}function mm(f,$=new Map){if(!f?.accounts.length)return[];return f.accounts.map((_)=>{let m=$.get(_.id)??U$(_);return{name:Q$(_),role:"fallback",enabled:_.enabled!==!1,quota:_.quota,lastRefreshedAt:_.lastRefreshedAt,...m&&{error:m}}})}function Dm(f){let $=f.now??Date.now(),_=["## Claude Quotas",""];if(f.refreshedAt)_.push(`Refreshed: ${Zf(f.refreshedAt,$)}`,"");if(!f.accounts.length)return _.push("No Claude OAuth accounts found yet."),_.join(`
|
|
26
|
+
`);for(let m of f.accounts){let D=m.role==="main"?"main":"fallback",H=m.enabled===!1?" disabled":"";if(_.push(`### ${m.name} (${D}${H})`),m.lastRefreshedAt)_.push(` - Last token refresh: ${Zf(m.lastRefreshedAt,$)}`);if(m.error)_.push(` - Error: ${m.error}`);_.push(V0("five_hour",m.quota?.five_hour,$)),_.push(V0("seven_day",m.quota?.seven_day,$)),_.push("")}return _.join(`
|
|
27
|
+
`).trimEnd()}import{Buffer as P0}from"node:buffer";import{createHash as Z$,randomBytes as X$}from"node:crypto";class zf extends Error{}var Vf=new Map,Y0=new Map,T0=new Set,O0=0;function Xf(){return O0+=1,`req_${Date.now().toString(36)}_${O0.toString(36)}`}function mf(f){if(T0.has(f))return;T0.add(f),J(f)}function Km(f){let $=f?.relay;if(!$)return mf("disabled: no relay config found"),null;if($.enabled!==!0)return mf("disabled: relay.enabled is not true"),null;if(!$.url?.trim()||!$.token?.trim())return mf("disabled: missing relay url or token"),null;let _=$.transport==="http"?"http":"websocket";return mf(`configured transport=${_} protocol=${_==="websocket"?2:1} url=${$.url.trim()} fallbackToDirect=${$.fallbackToDirect!==!1}`),{enabled:!0,url:$.url.trim(),token:$.token.trim(),fallbackToDirect:$.fallbackToDirect!==!1,transport:_}}function jm(){return X$(32).toString("base64url")}function z$(f){return`sha256:${Z$("sha256").update(f).digest("hex")}`}function q0(f,$){let _=0,m=Math.min(f.length,$.length);while(_<m&&f.charCodeAt(_)===$.charCodeAt(_))_++;let D=f.length,H=$.length;while(D>_&&H>_&&f.charCodeAt(D-1)===$.charCodeAt(H-1))D--,H--;return{start:_,deleteCount:D-_,insert:$.slice(_,H)}}function A$(f){return f.deleteCount===0&&f.insert.length===0}function h0(f){let $=f.match(/\bcch=([0-9a-f]{5});/),_=$?.[1];if(!_||$.index==null)return null;let m=$.index+4;return{start:m,end:m+_.length,token:_}}function V$(f,$,_,m){return`${f.slice(0,$)}${m}${f.slice(_)}`}function k0(f,$){let _=h0(f),m=h0($);if(_&&m&&_.start===m.start&&_.end-_.start===m.end-m.start&&_.token!==m.token){let D={start:_.start,deleteCount:_.end-_.start,insert:m.token},H=V$(f,_.start,_.end,m.token),E=q0(H,$);return A$(E)?D:[D,E]}return q0(f,$)}function Y$(f,$){if(typeof $!=="string")return!1;try{let _=f instanceof Request?new URL(f.url):new URL(f.toString());return _.pathname==="/v1/messages"||_.pathname==="/messages"}catch{return!1}}function T$(f){let $={};for(let[_,m]of f.entries()){if(_==="x-session-affinity"||_==="x-opencode-session")continue;$[_]=m}return $}async function w0(f,$){return fetch(f.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":f.token},body:JSON.stringify($)})}function S(f){return f.length>12?`${f.slice(0,12)}…`:f}function z(){return performance.now()}function O(f){return Math.round(f*10)/10}function O$(f){let{input:$,init:_,headers:m,bodyText:D,affinity:H,previous:E,nextHash:F}=f,C=$ instanceof Request?$.url:$.toString(),N={protocol:1,type:"request",affinity:H,upstream:{url:C,method:_?.method||($ instanceof Request?$.method:"POST"),headers:T$(m)},next_hash:F};return E?{...N,mode:"patch",base_hash:E.hash,revision:E.revision+1,patch:k0(E.body,D)}:{...N,mode:"full_sync",revision:1,body:D}}function Af(f,$){return{protocol:f.protocol,type:"request",affinity:f.affinity,upstream:f.upstream,next_hash:f.next_hash,mode:"full_sync",revision:1,body:$}}function R0(f,$,_,m){Vf.set(f,{body:$,hash:_,revision:m})}async function x0(f){let{config:$,payload:_,bodyText:m,fallback:D}=f,H=_,E=await w0($,H);if(E.status===409&&H.mode==="patch")J(`state mismatch from relay session=${S(H.affinity)}; retrying full_sync`),await E.body?.cancel().catch(()=>{}),H=Af(H,m),E=await w0($,H);if(!E.ok&&E.status>=500&&$.fallbackToDirect)return J(`relay returned ${E.status}; falling back direct session=${S(H.affinity)}`),await E.body?.cancel().catch(()=>{}),{response:await D(),payload:H,transport:"http",protocol:H.protocol,usedRelay:!1};return{response:E,payload:H,transport:"http",protocol:H.protocol,usedRelay:!0}}function q$(f,$){let _=new URL(f);return _.protocol=_.protocol==="http:"?"ws:":"wss:",_.pathname="/ws",_.searchParams.set("token",$),_.toString()}function h$(f){return new Uint8Array(P0.from(f,"base64"))}function w$(f){if(f instanceof Uint8Array)return f;if(f instanceof ArrayBuffer)return new Uint8Array(f);if(ArrayBuffer.isView(f))return new Uint8Array(f.buffer,f.byteOffset,f.byteLength);return new Uint8Array(P0.from(String(f)))}function x$(f){return JSON.parse(f)}class i0{config;affinity;socket;connecting;queue=Promise.resolve();pending;serverState;constructor(f,$){this.config=f,this.affinity=$}send(f,$,_=!1){let m=z(),D=this.queue.catch(()=>{}).then(()=>this.startQueued(f,$,m,_)),H=D.then(async({response:E,getPayload:F})=>({response:await E,payload:F(),transport:"websocket",protocol:2,usedRelay:!0}));return this.queue=D.then(({done:E})=>E.catch(()=>{}),()=>{}),H}async startQueued(f,$,_,m){let D=z();await this.ensureConnected();let H=z(),E=Vf.get(this.affinity),F=this.serverState?.hash,C={...f,protocol:2,id:Xf()};if(C.mode==="patch"&&(!F||F!==C.base_hash))C.mode="full_sync",C.revision=(this.serverState?.revision??0)+1,delete C.base_hash,delete C.patch,C.body=$;if(C.mode==="patch"&&E)C.patch=k0(E.body,$);J(`perf websocket send_start session=${S(this.affinity)} request=${C.id} mode=${C.mode} queueMs=${O(H-_)} connectMs=${O(H-D)} bodyBytes=${$.length} relayBytes=${JSON.stringify(C).length}`);let N=C,j=this.sendPayload(C,$,m);j.done.catch(()=>{});let b=j.done,U=j.response.catch((K)=>{if(!(K instanceof zf)||C.mode!=="patch")throw K;let W=Af(C,$);W.protocol=2,W.id=Xf(),W.revision=(this.serverState?.revision??0)+1,N=W;let L=this.sendPayload(W,$,m);return L.done.catch(()=>{}),b=L.done,L.response}),Q=U.then(()=>b,()=>b.catch(()=>{}));return{response:U,done:Q,getPayload:()=>N}}async ensureConnected(){if(this.socket?.readyState===WebSocket.OPEN&&this.serverState!==void 0)return;if(this.connecting)return await this.connecting;this.connecting=new Promise((f,$)=>{let _=q$(this.config.url,this.config.token),m=new URL(_);m.searchParams.set("affinity",this.affinity);let D=new WebSocket(m.toString());this.socket=D,this.serverState=void 0;let H=setTimeout(()=>{D.close(),$(Error("relay websocket ready timed out"))},15000);D.addEventListener("message",(E)=>{try{if(typeof E.data!=="string"){this.handleBinaryChunk(E.data);return}let F=x$(E.data);if(F.type==="ready"){clearTimeout(H),this.serverState=F.state,f();return}this.handleMessage(F)}catch(F){clearTimeout(H),$(F),this.failPending(F),D.close()}}),D.addEventListener("error",()=>{clearTimeout(H);let E=Error("relay websocket error");$(E),this.failPending(E)}),D.addEventListener("close",()=>{if(clearTimeout(H),this.socket===D)this.socket=void 0,this.serverState=void 0,this.connecting=void 0;if(this.pending){if(this.pending.retryingBeforeResponse)return;if(this.retryPendingBeforeResponse(this.pending,"closed before response"))return;let E=Error("relay websocket closed before response");this.failPending(E)}})}).finally(()=>{this.connecting=void 0}),await this.connecting}sendPayload(f,$,_){let m=this.socket;if(!m||m.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");let D=z(),H,E,F=new Promise((N,j)=>{H=N,E=j});return{response:new Promise((N,j)=>{let b={payload:f,bodyText:$,resolve:N,reject:j,streamDone:!1,accepted:!1,responseStarted:!1,resolveDone:H,rejectDone:E,sentAt:D,optimisticResponse:_,retryAttempts:0,retryingBeforeResponse:!1};if(this.pending=b,this.resetPendingTimeout(b),m.send(JSON.stringify(f)),_)this.resolvePendingResponse(b,200,"OK",{"content-type":"text/event-stream","x-cortexkit-relay-optimistic":"true"})}),done:F}}resetPendingTimeout(f){clearTimeout(f.timeout),f.timeout=setTimeout(()=>{if(this.pending!==f)return;if(this.retryPendingBeforeResponse(f,"response timed out"))return;this.failPending(Error("relay websocket response timed out")),this.socket?.close()},45000)}retryPendingBeforeResponse(f,$){if(f.responseStartedAt!=null)return!1;if(f.streamDone)return!1;if(f.retryAttempts>=1)return!1;f.retryAttempts+=1,f.retryingBeforeResponse=!0,clearTimeout(f.timeout);let _=f.retryAttempts,m=f.payload.id;return J(`websocket ${$}; reconnecting and retrying full_sync session=${S(this.affinity)} request=${m} retry=${_}`),this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0,(async()=>{try{if(await this.ensureConnected(),this.pending!==f)return;let D=Af(f.payload,f.bodyText);D.protocol=2,D.id=Xf(),D.revision=(this.serverState?.revision??0)+1,f.payload=D,f.accepted=!1,f.acceptedAt=void 0,f.responseStartedAt=void 0,f.sentAt=z(),f.retryingBeforeResponse=!1;let H=this.socket;if(!H||H.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");this.resetPendingTimeout(f),J(`perf websocket retry_send session=${S(this.affinity)} request=${D.id} previous=${m} mode=full_sync retry=${_} bodyBytes=${f.bodyText.length} relayBytes=${JSON.stringify(D).length}`),H.send(JSON.stringify(D))}catch(D){if(f.retryingBeforeResponse=!1,this.pending===f)this.failPending(D)}})(),!0}handleBinaryChunk(f){let $=this.pending;if(!$?.responseStarted)return;$.streamController?.enqueue(w$(f))}resolvePendingResponse(f,$,_,m){if(f.responseStarted)return;f.responseStarted=!0;let D=new ReadableStream({start:(H)=>{f.streamController=H},cancel:()=>{this.socket?.close()}});f.resolve(new Response(D,{status:$,statusText:_,headers:m}))}handleMessage(f){if(f.type==="keepalive"){if(this.pending)this.resetPendingTimeout(this.pending);return}let $=this.pending;if(!$)return;if("id"in f&&f.id&&f.id!==$.payload.id)return;if(f.type==="accepted"){let _=z();$.accepted=!0,$.acceptedAt=_,J(`perf websocket accepted session=${S(this.affinity)} request=${$.payload.id} sentMs=${O(_-$.sentAt)} mode=${$.payload.mode}`),this.serverState={hash:f.hash,revision:f.revision},R0(this.affinity,$.bodyText,f.hash,f.revision),this.resetPendingTimeout($);return}if(f.type==="response_start"){let _=z();if($.responseStartedAt=_,J(`perf websocket response_start session=${S(this.affinity)} request=${$.payload.id} sentMs=${O(_-$.sentAt)} upstreamMs=${$.acceptedAt==null?"unknown":O(_-$.acceptedAt)} status=${f.status}`),clearTimeout($.timeout),this.resolvePendingResponse($,f.status,f.statusText,f.headers),$.optimisticResponse&&f.status>=400)$.streamController?.enqueue(new TextEncoder().encode(`event: error
|
|
28
|
+
data: ${JSON.stringify({type:"error",error:{type:"relay_upstream_error",message:`Relay upstream returned HTTP ${f.status}`}})}
|
|
29
|
+
|
|
30
|
+
`)),this.finishPending();return}if(f.type==="chunk"){$.streamController?.enqueue(h$(f.base64));return}if(f.type==="done"){this.finishPending();return}if(f.type==="error"){if($.optimisticResponse&&$.responseStartedAt!=null){J(`websocket relay error during optimistic response session=${S(this.affinity)} request=${$.payload.id} status=${f.status} message=${f.message||"unknown"}`),$.streamController?.enqueue(new TextEncoder().encode(`event: error
|
|
31
|
+
data: ${JSON.stringify({type:"error",error:{type:"relay_error",message:f.message||"relay error"}})}
|
|
32
|
+
|
|
33
|
+
`)),this.finishPending(),this.socket?.close();return}if(f.status===409&&this.retryPendingBeforeResponse($,f.message||"state mismatch"))return;let _=f.status===409?new zf(f.message||"state mismatch"):Error(f.message||"relay websocket error");this.failPending(_)}}finishPending(){let f=this.pending;if(!f)return;let $=z();if(J(`perf websocket done session=${S(this.affinity)} request=${f.payload.id} sentMs=${O($-f.sentAt)} streamMs=${f.responseStartedAt==null?"unknown":O($-f.responseStartedAt)}`),clearTimeout(f.timeout),!f.streamDone)f.streamDone=!0,f.streamController?.close();f.resolveDone(),this.pending=void 0}failPending(f){let $=this.pending;if(!$)return;if(clearTimeout($.timeout),this.pending=void 0,$.responseStarted)$.streamController?.error(f);else $.reject(f);$.rejectDone(f)}}function P$(f,$){let _=Y0.get($);if(_)return _;let m=new i0(f,$);return Y0.set($,m),m}async function Nm(f){let{config:$,input:_,init:m,headers:D,body:H,fallback:E,affinity:F,optimisticResponse:C}=f;if(!$||!Y$(_,H))return E();let N=F||D.get("x-session-affinity")||D.get("x-opencode-session");if(!N)return J("skipping relay: missing x-session-affinity header"),E();let j=H,b=z$(j),U=Vf.get(N),Q=O$({input:_,init:m,headers:D,bodyText:j,affinity:N,previous:U,nextHash:b});try{let K;if($.transport==="websocket")try{K=await P$($,N).send(Q,j,C===!0)}catch(L){J(`websocket relay failed session=${S(N)}; trying http relay: ${L instanceof Error?L.message:String(L)}`),K=await x0({config:$,payload:Q,bodyText:j,fallback:E})}else K=await x0({config:$,payload:Q,bodyText:j,fallback:E});if(!K.usedRelay)return K.response;if(K.transport==="http")R0(N,j,K.payload.next_hash,K.payload.revision);let W=JSON.stringify(K.payload).length;return J(`used relay transport=${K.transport} protocol=${K.protocol} mode=${K.payload.mode} status=${K.response.status} session=${S(N)} bodyBytes=${j.length} relayBytes=${W}`),await X0({affinity:N,transport:K.transport,protocol:K.protocol,mode:K.payload.mode,status:K.response.status,bodyText:j,previousBodyText:U?.body,payload:K.payload,relayBytes:W}),K.response}catch(K){if(!$.fallbackToDirect)throw J(`relay failed session=${S(N)} and fallbackToDirect=false: ${K instanceof Error?K.message:String(K)}`),K;return J(`relay failed; falling back direct session=${S(N)}: ${K instanceof Error?K.message:String(K)}`),E()}}var Jm=`
|
|
34
|
+
async function hashBody(body) {
|
|
35
|
+
const bytes = new TextEncoder().encode(body)
|
|
36
|
+
const digest = await crypto.subtle.digest('SHA-256', bytes)
|
|
37
|
+
const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
38
|
+
return 'sha256:' + hex
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function applyPatch(base, patch) {
|
|
42
|
+
return base.slice(0, patch.start) + patch.insert + base.slice(patch.start + patch.deleteCount)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function applyPatchSet(base, patch) {
|
|
46
|
+
if (!Array.isArray(patch)) return applyPatch(base, patch)
|
|
47
|
+
if (patch.length === 0) return base
|
|
48
|
+
|
|
49
|
+
let result = ''
|
|
50
|
+
let cursor = 0
|
|
51
|
+
for (const item of patch) {
|
|
52
|
+
if (item.start < cursor) return { error: 'overlapping patch', status: 400 }
|
|
53
|
+
result += base.slice(cursor, item.start)
|
|
54
|
+
result += item.insert
|
|
55
|
+
cursor = item.start + item.deleteCount
|
|
56
|
+
}
|
|
57
|
+
return result + base.slice(cursor)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function readState(env, affinity) {
|
|
61
|
+
const raw = await env.RELAY_STATE.get('session:' + affinity)
|
|
62
|
+
return raw ? JSON.parse(raw) : null
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function writeState(env, affinity, state) {
|
|
66
|
+
await env.RELAY_STATE.put('session:' + affinity, JSON.stringify(state), { expirationTtl: 86400 })
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function resolveBody(env, payload) {
|
|
70
|
+
if (payload.mode === 'full_sync') return payload.body
|
|
71
|
+
if (payload.mode === 'patch') {
|
|
72
|
+
const state = await readState(env, payload.affinity)
|
|
73
|
+
if (!state || state.hash !== payload.base_hash) {
|
|
74
|
+
return { error: 'state mismatch', status: 409 }
|
|
75
|
+
}
|
|
76
|
+
return applyPatchSet(state.body, payload.patch)
|
|
77
|
+
}
|
|
78
|
+
return { error: 'unknown mode', status: 400 }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function prepareUpstream(env, payload) {
|
|
82
|
+
if ((payload.protocol !== 1 && payload.protocol !== 2) || payload.type !== 'request' || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
|
|
83
|
+
return { error: 'invalid payload', status: 400 }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const body = await resolveBody(env, payload)
|
|
87
|
+
if (body && typeof body === 'object' && 'error' in body) return body
|
|
88
|
+
|
|
89
|
+
if (typeof body !== 'string' || (await hashBody(body)) !== payload.next_hash) {
|
|
90
|
+
return { error: 'hash mismatch', status: 409 }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const stateWrite = writeState(env, payload.affinity, { body, hash: payload.next_hash, revision: payload.revision }).catch(() => {})
|
|
94
|
+
console.log(JSON.stringify({
|
|
95
|
+
relay: 'opencode-anthropic-auth',
|
|
96
|
+
transport: 'relay',
|
|
97
|
+
mode: payload.mode,
|
|
98
|
+
revision: payload.revision,
|
|
99
|
+
affinity: String(payload.affinity).slice(0, 12),
|
|
100
|
+
bodyBytes: body.length,
|
|
101
|
+
}))
|
|
102
|
+
|
|
103
|
+
return { body, stateWrite }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function resolveBodyFromState(state, payload) {
|
|
107
|
+
if (payload.mode === 'full_sync') return payload.body
|
|
108
|
+
if (payload.mode === 'patch') {
|
|
109
|
+
if (!state || state.hash !== payload.base_hash) {
|
|
110
|
+
return { error: 'state mismatch', status: 409 }
|
|
111
|
+
}
|
|
112
|
+
return applyPatchSet(state.body, payload.patch)
|
|
113
|
+
}
|
|
114
|
+
return { error: 'unknown mode', status: 400 }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function deferWorkerTask(task) {
|
|
118
|
+
return new Promise((resolve) => setTimeout(resolve, 0)).then(task)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function checkpointWebSocketState(env, payload, body, nextState) {
|
|
122
|
+
return deferWorkerTask(async () => {
|
|
123
|
+
try {
|
|
124
|
+
if ((await hashBody(body)) !== payload.next_hash) {
|
|
125
|
+
throw new Error('hash mismatch')
|
|
126
|
+
}
|
|
127
|
+
await writeState(env, payload.affinity, nextState)
|
|
128
|
+
} catch (error) {
|
|
129
|
+
console.log(JSON.stringify({
|
|
130
|
+
relay: 'opencode-anthropic-auth',
|
|
131
|
+
transport: 'websocket',
|
|
132
|
+
event: 'checkpoint_write_failed',
|
|
133
|
+
affinity: String(payload.affinity).slice(0, 12),
|
|
134
|
+
message: error instanceof Error ? error.message : String(error),
|
|
135
|
+
}))
|
|
136
|
+
}
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function prepareWebSocketUpstream(env, state, payload) {
|
|
141
|
+
if (payload.protocol !== 2 || payload.type !== 'request' || !payload.id || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
|
|
142
|
+
return { error: 'invalid payload', status: 400 }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const body = resolveBodyFromState(state, payload)
|
|
146
|
+
if (body && typeof body === 'object' && 'error' in body) return body
|
|
147
|
+
if (typeof body !== 'string') return { error: 'invalid body', status: 400 }
|
|
148
|
+
if ((await hashBody(body)) !== payload.next_hash) {
|
|
149
|
+
return { error: 'hash mismatch', status: 409 }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const nextState = { body, hash: payload.next_hash, revision: payload.revision }
|
|
153
|
+
const checkpoint = checkpointWebSocketState(env, payload, body, nextState)
|
|
154
|
+
const logAccepted = () => console.log(JSON.stringify({
|
|
155
|
+
relay: 'opencode-anthropic-auth',
|
|
156
|
+
transport: 'websocket',
|
|
157
|
+
mode: payload.mode,
|
|
158
|
+
revision: payload.revision,
|
|
159
|
+
affinity: String(payload.affinity).slice(0, 12),
|
|
160
|
+
bodyBytes: body.length,
|
|
161
|
+
}))
|
|
162
|
+
|
|
163
|
+
return { body, state: nextState, checkpoint, logAccepted }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function headersToObject(headers) {
|
|
167
|
+
const result = {}
|
|
168
|
+
for (const [key, value] of headers.entries()) result[key] = value
|
|
169
|
+
return result
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function handleRelayPayload(env, payload) {
|
|
173
|
+
const prepared = await prepareUpstream(env, payload)
|
|
174
|
+
if (prepared.error) return prepared
|
|
175
|
+
const upstream = await fetch(payload.upstream.url, {
|
|
176
|
+
method: payload.upstream.method || 'POST',
|
|
177
|
+
headers: payload.upstream.headers,
|
|
178
|
+
body: prepared.body,
|
|
179
|
+
})
|
|
180
|
+
return { upstream, stateWrite: prepared.stateWrite }
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function handleWebSocket(socket, env, ctx, payload, getState, setState) {
|
|
184
|
+
const heartbeat = setInterval(() => {
|
|
185
|
+
try {
|
|
186
|
+
socket.send(JSON.stringify({ protocol: 2, type: 'keepalive' }))
|
|
187
|
+
} catch {
|
|
188
|
+
clearInterval(heartbeat)
|
|
189
|
+
}
|
|
190
|
+
}, 15000)
|
|
191
|
+
try {
|
|
192
|
+
const result = await prepareWebSocketUpstream(env, getState(), payload)
|
|
193
|
+
if (result.error) {
|
|
194
|
+
socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: result.status, message: result.error }))
|
|
195
|
+
return
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
setState(result.state)
|
|
199
|
+
socket.send(JSON.stringify({ protocol: 2, type: 'accepted', id: payload.id, hash: result.state.hash, revision: result.state.revision }))
|
|
200
|
+
ctx?.waitUntil?.(deferWorkerTask(result.logAccepted))
|
|
201
|
+
|
|
202
|
+
const upstreamPromise = fetch(payload.upstream.url, {
|
|
203
|
+
method: payload.upstream.method || 'POST',
|
|
204
|
+
headers: payload.upstream.headers,
|
|
205
|
+
body: result.body,
|
|
206
|
+
})
|
|
207
|
+
ctx?.waitUntil?.(result.checkpoint)
|
|
208
|
+
const upstream = await upstreamPromise
|
|
209
|
+
socket.send(JSON.stringify({
|
|
210
|
+
protocol: 2,
|
|
211
|
+
type: 'response_start',
|
|
212
|
+
id: payload.id,
|
|
213
|
+
status: upstream.status,
|
|
214
|
+
statusText: upstream.statusText,
|
|
215
|
+
headers: headersToObject(upstream.headers),
|
|
216
|
+
}))
|
|
217
|
+
|
|
218
|
+
const reader = upstream.body?.getReader()
|
|
219
|
+
if (reader) {
|
|
220
|
+
while (true) {
|
|
221
|
+
const { done, value } = await reader.read()
|
|
222
|
+
if (done) break
|
|
223
|
+
socket.send(value)
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
socket.send(JSON.stringify({ protocol: 2, type: 'done', id: payload.id }))
|
|
227
|
+
} catch (error) {
|
|
228
|
+
socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: 500, message: error instanceof Error ? error.message : String(error) }))
|
|
229
|
+
} finally {
|
|
230
|
+
clearInterval(heartbeat)
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export default {
|
|
235
|
+
async fetch(request, env, ctx) {
|
|
236
|
+
if (request.headers.get('Upgrade') === 'websocket') {
|
|
237
|
+
const url = new URL(request.url)
|
|
238
|
+
const token = url.searchParams.get('token')
|
|
239
|
+
const affinity = url.searchParams.get('affinity')
|
|
240
|
+
if (token !== env.RELAY_TOKEN) return new Response('unauthorized', { status: 401 })
|
|
241
|
+
if (!affinity) return new Response('missing affinity', { status: 400 })
|
|
242
|
+
const pair = new WebSocketPair()
|
|
243
|
+
const client = pair[0]
|
|
244
|
+
const server = pair[1]
|
|
245
|
+
server.binaryType = 'arraybuffer'
|
|
246
|
+
let state = null
|
|
247
|
+
let ready = false
|
|
248
|
+
server.accept()
|
|
249
|
+
const loadState = readState(env, affinity).then((loadedState) => {
|
|
250
|
+
state = loadedState
|
|
251
|
+
ready = true
|
|
252
|
+
server.send(JSON.stringify({
|
|
253
|
+
protocol: 2,
|
|
254
|
+
type: 'ready',
|
|
255
|
+
state: state ? { hash: state.hash, revision: state.revision } : null,
|
|
256
|
+
}))
|
|
257
|
+
}).catch((error) => {
|
|
258
|
+
server.send(JSON.stringify({ protocol: 2, type: 'error', status: 500, message: error instanceof Error ? error.message : String(error) }))
|
|
259
|
+
server.close(1011, 'state load failed')
|
|
260
|
+
})
|
|
261
|
+
ctx?.waitUntil?.(loadState)
|
|
262
|
+
if (!ctx?.waitUntil) void loadState
|
|
263
|
+
let busy = false
|
|
264
|
+
server.addEventListener('message', (event) => {
|
|
265
|
+
if (!ready) {
|
|
266
|
+
server.send(JSON.stringify({ protocol: 2, type: 'error', status: 425, message: 'relay state is not ready' }))
|
|
267
|
+
return
|
|
268
|
+
}
|
|
269
|
+
if (busy) {
|
|
270
|
+
server.send(JSON.stringify({ protocol: 2, type: 'error', status: 429, message: 'request already in flight' }))
|
|
271
|
+
return
|
|
272
|
+
}
|
|
273
|
+
let payload
|
|
274
|
+
try {
|
|
275
|
+
payload = JSON.parse(event.data)
|
|
276
|
+
} catch {
|
|
277
|
+
server.send(JSON.stringify({ protocol: 2, type: 'error', status: 400, message: 'invalid JSON payload' }))
|
|
278
|
+
return
|
|
279
|
+
}
|
|
280
|
+
payload.affinity = affinity
|
|
281
|
+
busy = true
|
|
282
|
+
const run = handleWebSocket(server, env, ctx, payload, () => state, (nextState) => { state = nextState }).finally(() => { busy = false })
|
|
283
|
+
ctx?.waitUntil?.(run)
|
|
284
|
+
if (!ctx?.waitUntil) void run
|
|
285
|
+
})
|
|
286
|
+
return new Response(null, { status: 101, webSocket: client })
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (request.method === 'GET') {
|
|
290
|
+
return Response.json({ status: 'ok', transports: ['http', 'websocket'] })
|
|
291
|
+
}
|
|
292
|
+
if (request.method !== 'POST') return new Response('method not allowed', { status: 405 })
|
|
293
|
+
if (request.headers.get('x-relay-token') !== env.RELAY_TOKEN) {
|
|
294
|
+
return new Response('unauthorized', { status: 401 })
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
try {
|
|
298
|
+
const payload = await request.json()
|
|
299
|
+
const result = await handleRelayPayload(env, payload)
|
|
300
|
+
if (result.error) return Response.json({ error: result.error }, { status: result.status })
|
|
301
|
+
|
|
302
|
+
if (result.stateWrite) ctx.waitUntil(result.stateWrite)
|
|
303
|
+
|
|
304
|
+
const upstream = result.upstream
|
|
305
|
+
return new Response(upstream.body, {
|
|
306
|
+
status: upstream.status,
|
|
307
|
+
statusText: upstream.statusText,
|
|
308
|
+
headers: upstream.headers,
|
|
309
|
+
})
|
|
310
|
+
} catch (error) {
|
|
311
|
+
return Response.json(
|
|
312
|
+
{ error: error instanceof Error ? error.message : 'internal relay error' },
|
|
313
|
+
{ status: 502 },
|
|
314
|
+
)
|
|
315
|
+
}
|
|
316
|
+
},
|
|
317
|
+
}
|
|
318
|
+
`;export{k$ as a,hf as b,R$ as c,i$ as d,c$ as e,u$ as f,wf as g,n$ as h,l$ as i,h as j,nf as k,t$ as l,g$ as m,A as n,B as o,V as p,Y as q,D_ as r,H_ as s,W1 as t,E_ as u,F_ as v,M_ as w,C_ as x,K_ as y,j_ as z,N_ as A,J_ as B,b_ as C,H0 as D,Z1 as E,v as F,sf as G,R as H,X1 as I,I_ as J,ef as K,z1 as L,W_ as M,L_ as N,B_ as O,Q_ as P,O1 as Q,U_ as R,I0 as S,x_ as T,A_ as U,V_ as V,Y_ as W,N0 as X,i_ as Y,c_ as Z,$$ as _,Sf as $,L0 as aa,_$ as ba,u_ as ca,D$ as da,t_ as ea,g_ as fa,J$ as ga,s_ as ha,o_ as ia,a_ as ja,e_ as ka,W$ as la,fm as ma,_m as na,mm as oa,Dm as pa,Km as qa,jm as ra,Nm as sa,Jm as ta};
|