@cortexkit/opencode-anthropic-auth 1.11.0 → 1.12.1

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.
@@ -0,0 +1,417 @@
1
+ import{sb as j0,wb as I,xb as g,yb as L}from"./index-z86v5q5a.js";import{Qb as i0}from"./index-ptdkq8gx.js";var Hf="9d1c250a-e61b-44d9-88ed-5944d1962f5e",B_={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.com/cai/oauth/authorize"},xf="https://platform.claude.com/oauth/code/callback",Tf="https://platform.claude.com/v1/oauth/token",hf="axios/1.15.2",H_=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],M_="user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload",PD="mcp_";var j_="fast-mode-2026-02-01";function ID(f,_){let $=(f??"").split(",").map((D)=>D.trim()).filter(Boolean);return[...new Set([...$,..._])].join(",")}function xD(f){return typeof f==="string"&&(f.startsWith("claude-opus-4-6")||f.startsWith("claude-opus-4-7")||f.startsWith("claude-opus-4-8"))}var TD="You are OpenCode",hD="You are Claude Code, Anthropic's official CLI for Claude.",wD=["<use_parallel_tool_calls>","For maximum efficiency, whenever you perform multiple independent operations, invoke all relevant tools simultaneously rather than sequentially. Prioritize calling independent tools in parallel whenever possible. For example, when reading 3 known files, run 3 tool calls in parallel to read all 3 files into context at the same time. When running multiple independent read-only commands like `ls` or `list_dir`, run all of those commands in parallel. Err on the side of maximizing parallel tool calls for independent work rather than running too many tools sequentially.","","Do not parallelize tool calls when one call depends on the output of another call. If a tool call needs an ID, filename, search result, or any other value returned by a previous tool call, run the first call, wait for its result, then run the dependent call using the real returned value. Never invent placeholder IDs, guessed task IDs, or other guessed values for dependent tool calls just to place them in the same parallel block.","</use_parallel_tool_calls>"].join(`
2
+ `);var v="2.1.177",wf="3bf",L_="cli",O_="0.94.0",z_="v24.3.0",S_="claude-cli/2.1.177 (external, cli)",J_=["explicit","automatic","hybrid"],Mf="explicit",yD=["github.com/anomalyco/opencode","opencode.ai/docs"],lD=[{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 W_(f){let _="";for(let $ of f)_+=String.fromCharCode($);return btoa(_).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function Y_(){let f=new Uint8Array(64);crypto.getRandomValues(f);let _=W_(f),$=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(_));return{verifier:_,challenge:W_(new Uint8Array($)),method:"S256"}}function lf(f){if(!f)return;let _=Number(f);if(Number.isFinite(_)&&_>0)return Math.ceil(_);let $=Date.parse(f);if(Number.isFinite($)){let D=Math.ceil(($-Date.now())/1000);return D>0?D:void 0}return}class yf extends Error{status;body;retryAfter;isRefreshError=!0;constructor(f,_,$){super(`Claude OAuth refresh failed: ${f} — ${_}`);this.status=f,this.body=_,this.name="ClaudeOAuthRefreshError",this.retryAfter=lf($??void 0)}}function k0(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 Z_(f){let _=f.fetchImpl??fetch,$=f.maxRetries??2,D=f.baseDelayMs??500;for(let C=0;C<=$;C++)try{if(C>0){let b=D*2**(C-1);await new Promise((K)=>setTimeout(K,b))}let m=await _(Tf,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":hf},body:JSON.stringify({grant_type:"refresh_token",refresh_token:f.refreshToken,client_id:Hf,scope:M_})});if(!m.ok){if(m.status>=500&&C<$){await m.body?.cancel().catch(()=>{});continue}let b=await m.text().catch(()=>"");throw new yf(m.status,b,m.headers.get("retry-after"))}let N=await m.json(),E=f.now?.()??Date.now();return{access:N.access_token,refresh:N.refresh_token??f.refreshToken,expires:E+N.expires_in*1000,expiresIn:N.expires_in}}catch(m){if(m instanceof yf)throw m;if(C<$&&k0(m))continue;throw m}throw Error("Token refresh exhausted all retries")}function p0(){return crypto.randomUUID().replace(/-/g,"")}function v0(f){let _=f.trim();try{let N=new URL(_),E=N.searchParams.get("code"),b=N.searchParams.get("state");if(E&&b)return{code:E,state:b}}catch{}let $=_.split("#");if($.length===2&&$[0]&&$[1])return{code:$[0],state:$[1]};let D=new URLSearchParams(_),C=D.get("code"),m=D.get("state");if(C&&m)return{code:C,state:m};return null}async function d0(f,_,$){let D=await fetch(Tf,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":hf},body:JSON.stringify({code:f.code,state:f.state,grant_type:"authorization_code",client_id:Hf,redirect_uri:$,code_verifier:_})});if(!D.ok)return{type:"failed"};let C=await D.json();return{type:"success",refresh:C.refresh_token,access:C.access_token,expires:Date.now()+C.expires_in*1000}}async function iD(f){let _=await Y_(),$=p0(),D=new URL(B_[f],import.meta.url);return D.searchParams.set("code","true"),D.searchParams.set("client_id",Hf),D.searchParams.set("response_type","code"),D.searchParams.set("redirect_uri",xf),D.searchParams.set("scope",H_.join(" ")),D.searchParams.set("code_challenge",_.challenge),D.searchParams.set("code_challenge_method","S256"),D.searchParams.set("state",$),{url:D.toString(),redirectUri:xf,state:$,verifier:_.verifier}}async function uD(f,_,$,D){let C=v0(f);if(!C)return{type:"failed"};if(D&&C.state!==D)return{type:"failed"};return d0(C,_,$)}import{createHash as x_,randomUUID as Df}from"node:crypto";import{mkdir as T_,readFile as jf,rename as h_,rm as t,stat as X_,writeFile as Lf}from"node:fs/promises";import{homedir as u0}from"node:os";import{dirname as w_,join as o}from"node:path";var g0=globalThis.setTimeout.bind(globalThis),n0=globalThis.clearTimeout.bind(globalThis),y_="anthropic-auth.json",s0="anthropic-auth-state.json",r0="https://api.anthropic.com/api/oauth/usage";function h(f){return f.type==="oauth"}function aD(f){return f.type==="api"}function c0(f){let _=f?.trim();if(!_)return!1;try{let $=new URL(_);return($.protocol==="http:"||$.protocol==="https:")&&!$.username&&!$.password}catch{return!1}}function fC(f){return f.costZeroing?.enabled!==!1}var t0=[401,403,429],l_=240,o0=l_;var e0=300000,a0=3600000,k_=86400000,f1=60000,_1=900000,$1=300000,D1=5,F_={five_hour:0,seven_day:0},C1=!0,m1=60000,N1=60000,E1=600000,b1=1e4,K1=100;function U1(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return o(process.env.XDG_CONFIG_HOME||o(u0(),".config"),"opencode")}function O(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||o(U1(),y_)}function p_(f=O()){let _=process.env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim();if(_)return _;return f.endsWith(y_)?o(w_(f),s0):`${f}.state.json`}function H(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function V_(f){return{id:typeof f.id==="string"&&f.id.trim()?f.id.trim():Df(),label:typeof f.label==="string"?f.label: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}}function G1(f){if(!H(f))return null;if(f.type==="api"){let _=typeof f.baseURL==="string"?f.baseURL.trim():"",$=typeof f.apiKey==="string"?f.apiKey.trim():"";if(!c0(_))return null;let D=f.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...V_(f),type:"api",apiKey:$||void 0,baseURL:_,authHeader:D}}if(f.type!=="oauth")return null;if(typeof f.refresh!=="string"||!f.refresh.trim())return null;return{...V_(f),type:"oauth",access:typeof f.access==="string"?f.access:void 0,refresh:f.refresh,expires:typeof f.expires==="number"?f.expires:void 0,lastRefreshedAt:typeof f.lastRefreshedAt==="number"?f.lastRefreshedAt:void 0,lastRefreshError:A_(f.lastRefreshError),lastQuotaRefreshError:A_(f.lastQuotaRefreshError),quota:B1(f.quota)}}function A_(f){if(!H(f))return;if(typeof f.message!=="string")return;let _=Number(f.checkedAt);if(!Number.isFinite(_))return;let $=Number(f.nextRetryAt),D=Number(f.retryCount),C=Number(f.status);return{message:f.message,checkedAt:_,nextRetryAt:Number.isFinite($)?$:void 0,retryCount:Number.isFinite(D)?D:void 0,tokenHash:typeof f.tokenHash==="string"?f.tokenHash:void 0,status:Number.isFinite(C)?C:void 0,permanent:typeof f.permanent==="boolean"?f.permanent:void 0}}function B1(f){if(!H(f))return;let _={};for(let $ of["five_hour","seven_day"]){let D=f[$];if(!H(D))continue;let C=Number(D.usedPercent),m=Number(D.remainingPercent),N=Number(D.checkedAt);if(!Number.isFinite(C)||!Number.isFinite(m)||!Number.isFinite(N))continue;_[$]={usedPercent:C,remainingPercent:m,checkedAt:N,resetsAt:typeof D.resetsAt==="string"?D.resetsAt:void 0}}return Object.keys(_).length?_:void 0}function Q(){return{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]}}function H1(f){if(!H(f)||!Array.isArray(f.accounts))return null;return{version:1,main:{type:"opencode",provider:"anthropic"},routing:H(f.routing)?f.routing:void 0,fallbackOn:Array.isArray(f.fallbackOn)?f.fallbackOn.filter((_)=>Number.isInteger(_)):void 0,refresh:H(f.refresh)?f.refresh:void 0,quota:H(f.quota)?f.quota:void 0,claudeCache:H(f.claudeCache)?f.claudeCache:void 0,dump:H(f.dump)?f.dump:void 0,claudeFast:H(f.claudeFast)?f.claudeFast:void 0,costZeroing:H(f.costZeroing)?f.costZeroing:void 0,cacheKeep:H(f.cacheKeep)?f.cacheKeep:void 0,relay:H(f.relay)?f.relay:void 0,logging:H(f.logging)?f.logging:void 0,killswitch:H(f.killswitch)?f.killswitch:void 0,accounts:f.accounts.map(G1).filter((_)=>_!=null)}}async function Of(f){try{return{exists:!0,value:JSON.parse(await jf(f,"utf8"))}}catch(_){if(_.code==="ENOENT")return{exists:!1,value:null};let $=_ instanceof Error?_.message:String(_);throw Error(`account store at ${f} is corrupt or unreadable (${$}) — fix or remove it`)}}function n(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function M1(f,_){if(!H(f))return f;let $=H(_)?_:{},D=H($.main)?$.main:void 0,C=H($.accounts)?$.accounts:{},m=H(f.quota)?f.quota:{},N=H(f.refresh)?f.refresh:{},E=D??m,b=D??N,K=Array.isArray(f.accounts)?f.accounts.map((U)=>{if(!H(U))return U;let j=typeof U.id==="string"&&H(C[U.id])?C[U.id]:{};return{...U,...j}}):[];return{...f,refresh:n({...N,mainLastRefreshError:b.lastRefreshError,mainRefreshLeaseId:b.refreshLeaseId,mainRefreshLeaseUntil:b.refreshLeaseUntil,mainRefreshLeaseTokenHash:b.refreshLeaseTokenHash}),quota:n({...m,mainQuota:E.quota,mainQuotaCheckedAt:E.quotaCheckedAt,mainQuotaToken:E.quotaToken,mainLastQuotaApiError:E.lastQuotaApiError}),accounts:K}}async function X(f=O()){let _=await Of(f),$=await Of(p_(f));if(!_.exists&&!$.exists)return null;let D=_.exists?_.value:Q();return H1(M1(D,$.value))}async function j1(f){let _=await Of(f);return H(_.value)?_.value:{}}function L1(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function O1(f){return n({id:f.id,label:f.label,type:f.type,enabled:f.enabled,addedAt:f.addedAt,baseURL:f.type==="api"?f.baseURL:void 0,authHeader:f.type==="api"?f.authHeader:void 0})}function z1(f){if(f.type==="api")return n({apiKey:f.apiKey,lastUsed:f.lastUsed});return n({access:f.access,refresh:f.refresh,expires:f.expires,lastUsed:f.lastUsed,lastRefreshedAt:f.lastRefreshedAt,lastRefreshError:f.lastRefreshError,lastQuotaRefreshError:f.lastQuotaRefreshError,quota:f.quota})}function Cf(f){return Math.max(f?.five_hour?.checkedAt??0,f?.seven_day?.checkedAt??0)}function S1(f,_){if(!H(f))return _;let $=f,D=Cf($.quota),C=Cf(_.quota);if(D>C){let N=Boolean($.access&&_.access&&$.access!==_.access),E=$.lastRefreshedAt??0,b=_.lastRefreshedAt??0;if(N&&b<=E){let K={...$};if(typeof _.lastUsed==="number"&&(typeof $.lastUsed!=="number"||_.lastUsed>$.lastUsed))K.lastUsed=_.lastUsed;return K}return{...$,..._,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}}let m={...$,..._};if(!("lastQuotaRefreshError"in _))delete m.lastQuotaRefreshError;if(!("lastRefreshError"in _))delete m.lastRefreshError;return m}function J1(f){let _=f.refresh?n({enabled:f.refresh.enabled,intervalMinutes:f.refresh.intervalMinutes,refreshBeforeExpiryMinutes:f.refresh.refreshBeforeExpiryMinutes}):void 0,$=f.quota?n({enabled:f.quota.enabled,checkIntervalMinutes:f.quota.checkIntervalMinutes,refreshEveryNRequests:f.quota.refreshEveryNRequests,minimumRemaining:f.quota.minimumRemaining,failClosedOnUnknownQuota:f.quota.failClosedOnUnknownQuota,showToasts:f.quota.showToasts}):void 0;return L1({version:1,main:f.main,routing:f.routing,fallbackOn:f.fallbackOn,refresh:_,quota:$,claudeCache:f.claudeCache,dump:f.dump,logging:f.logging,claudeFast:f.claudeFast,costZeroing:f.costZeroing,cacheKeep:f.cacheKeep,relay:f.relay,killswitch:f.killswitch,accounts:f.accounts.map(O1)})}var Q_=Promise.resolve();function v_(f){return new Promise((_,$)=>{Q_=Q_.then(()=>f().then(_,$),()=>f().then(_,$))})}async function d_(f,_){await T_(w_(f),{recursive:!0});let $=`${f}.${Df()}.tmp`;await Lf($,`${JSON.stringify(_,null,2)}
3
+ `,{encoding:"utf8",mode:384});try{await h_($,f)}catch(D){throw await t($,{force:!0}).catch(()=>{}),D}}function V(f,_=O()){let $=_;return v_(()=>W1(f,$))}async function W1(f,_){let D={...await j1(_),...J1(f)};await d_(_,D),await i_(f,_,{mainQuota:!0,mainRefresh:!0,accounts:!0})}function Y1(f,_){f.main=f.main??{};let $=typeof f.main.quotaCheckedAt==="number"?f.main.quotaCheckedAt:Cf(f.main.quota),D=typeof _.quota?.mainQuotaCheckedAt==="number"?_.quota.mainQuotaCheckedAt:Cf(_.quota?.mainQuota);if($>D)return;f.main.quota=_.quota?.mainQuota,f.main.quotaCheckedAt=_.quota?.mainQuotaCheckedAt,f.main.quotaToken=_.quota?.mainQuotaToken,f.main.lastQuotaApiError=_.quota?.mainLastQuotaApiError}function Z1(f,_){f.main=f.main??{},f.main.lastRefreshError=_.refresh?.mainLastRefreshError,f.main.refreshLeaseId=_.refresh?.mainRefreshLeaseId,f.main.refreshLeaseUntil=_.refresh?.mainRefreshLeaseUntil,f.main.refreshLeaseTokenHash=_.refresh?.mainRefreshLeaseTokenHash}function vf(f){if(Array.isArray(f))return f.map(vf);if(!H(f))return f;return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0).map(([_,$])=>[_,vf($)]))}function X1(f,_=O(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let D=_;return v_(()=>i_(f,D,$))}async function i_(f,_,$){let D=p_(_),C=(await Of(D)).value,m=H(C)?{...C,version:1}:{version:1};if($.mainQuota)Y1(m,f);if($.mainRefresh)Z1(m,f);if($.accounts){let N=$.accounts===!0?null:new Set($.accounts);m.accounts={...H(m.accounts)?m.accounts:{}};for(let E of f.accounts){if(N&&!N.has(E.id))continue;m.accounts[E.id]=S1(m.accounts[E.id],z1(E))}if(N){for(let E of N)if(!f.accounts.some((b)=>b.id===E))delete m.accounts[E]}else{let E=new Set(f.accounts.map((b)=>b.id));for(let b of Object.keys(m.accounts))if(!E.has(b))delete m.accounts[b]}}await d_(D,vf(m))}async function Sf(f){let $=`${f.path??O()}.${f.name}.lock`,D=o($,"owner.json"),C=Df(),m=f.now??Date.now,N=null,E=!1;async function b(){try{return JSON.parse(await jf($,"utf8"))}catch(M){if(M.code!=="EISDIR")throw M;return JSON.parse(await jf(D,"utf8"))}}async function K(){await Lf($,`${JSON.stringify({ownerId:C,expiresAt:m()+f.ttlMs})}
4
+ `,{encoding:"utf8",mode:384})}async function U(){try{return await Lf($,`${JSON.stringify({ownerId:C,expiresAt:m()+f.ttlMs})}
5
+ `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(M){let Z=M.code;if(Z==="EEXIST"||Z==="EISDIR")return!1;throw M}}function j(){if(!f.renew||E)return;let M=f.renewIntervalMs??Math.max(1000,Math.floor(f.ttlMs/3));if(N=g0(()=>{(async()=>{try{let Z=await b(),J=m();if(E||Z?.ownerId!==C||Number(Z?.expiresAt)<=J)return;await K(),j()}catch{}})()},M),"unref"in N)N.unref()}let Y=await U();if(!Y){let M=`${$}.evicting`,Z=o(M,"owner.json"),J=Df(),B=5000,i=8;async function P(){await new Promise((F)=>setTimeout(F,Math.floor(Math.random()*4)))}async function l(){try{let F=await b();return Number(F?.expiresAt)>m()}catch{try{return(await X_($)).mtimeMs+f.ttlMs>m()}catch{return!1}}}async function T(){try{return JSON.parse(await jf(Z,"utf8"))?.ownerId===J}catch{return!1}}async function G(){await T_(M);try{await Lf(Z,`${JSON.stringify({ownerId:J,createdAt:m()})}
6
+ `,{encoding:"utf8",mode:384,flag:"wx"})}catch(F){if(F.code==="ENOENT")return!1;throw await W(),F}return await f.onStep?.("eviction-marker-acquired"),!0}async function W(){if(await T())await t(M,{recursive:!0,force:!0}).catch(()=>{})}for(let F=0;F<8;F++){if(Y=await U(),Y)break;if(await l())return null;try{if(!await G()){await P();continue}}catch(Gf){if(Gf.code!=="EEXIST")throw Gf;let Bf;try{Bf=await X_(M)}catch(R){if(R.code==="ENOENT"){await P();continue}throw R}if(Bf.mtimeMs+5000>m())return null;await f.onStep?.("stale-marker-stat");let p=`${M}.${Df()}`;try{await h_(M,p)}catch(R){if(R.code==="ENOENT"){await P();continue}throw R}await f.onStep?.("stale-marker-claimed"),await t(p,{recursive:!0,force:!0}).catch(()=>{}),await P();continue}try{if(await l())return null;if(!await T())return null;if(await f.onStep?.("stale-lock-confirmed"),!await T())return null;if(await t($,{recursive:!0,force:!0}).catch(()=>{}),!await T())return null;if(Y=await U(),!Y)return null;if(!await T())return await t($,{recursive:!0,force:!0}).catch(()=>{}),Y=!1,null;break}finally{await W()}}}if(!Y)return null;return j(),{release:async()=>{if(E=!0,N)n0(N),N=null;try{if((await b())?.ownerId!==C)return}catch{return}await t($,{recursive:!0,force:!0}).catch(()=>{})}}}function _C(f){return f?.claudeCache?.enabled===!0}function F1(f){return typeof f==="string"&&J_.includes(f)?f:Mf}function V1(f){return F1(f?.claudeCache?.mode)}async function $C(f,_,$=O()){let D=await X($)??Q();return D.claudeCache={...D.claudeCache??{},enabled:f,mode:_??V1(D)},await V(D,$),D}async function DC(f,_=O()){let $=await X(_)??Q();return $.claudeCache={...$.claudeCache??{},enabled:$.claudeCache?.enabled===!0,mode:f},await V($,_),$}function CC(f){return f?.dump?.enabled===!0}async function mC(f,_=O()){let $=await X(_)??Q();return $.dump={...$.dump??{},enabled:f},await V($,_),$}function NC(f){return f?.claudeFast?.enabled===!0}async function EC(f,_=O()){let $=await X(_)??Q();return $.claudeFast={...$.claudeFast??{},enabled:f},await V($,_),$}async function bC(f,_,$=O()){let D=await X($)??Q();return D.cacheKeep={enabled:!0,startHour:f,endHour:_},await V(D,$),D}async function KC(f,_=O()){let $=await X(_)??Q();return $.cacheKeep={...$.cacheKeep??{},enabled:f},await V($,_),$}function UC(f){return f?.cacheKeep?.subagents===!0}async function GC(f,_=O()){let $=await X(_)??Q();return $.cacheKeep={...$.cacheKeep??{},subagents:f},await V($,_),$}function A1(f){return f?.fallbackOn?.length?f.fallbackOn:t0}function BC(f,_){return A1(_).includes(f)}function u_(f){let _=f?.quota?.minimumRemaining||{};return{five_hour:_.five_hour??_["5h"]??F_.five_hour,seven_day:_.seven_day??_["1w"]??F_.seven_day}}function mf(f){return f?.quota?.enabled!==!1}function Q1(f){return f?.refresh?.enabled!==!1}function q1(f){return Math.floor(Math.random()*Math.max(0,f))}function R1(f){let _=f?.refresh?.refreshBeforeExpiryMinutes??o0;return Math.max(l_,_)*60000}function g_(f){return x_("sha256").update(f).digest("hex")}function P1(f){let _=f.status;if(typeof _==="number"&&Number.isFinite(_))return _===429||_>=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 I1(f){let _=g_(f.refreshToken),D=(f.previous?.tokenHash===_?f.previous.retryCount??0:0)+1,C=f.error.retryAfter,m;if(typeof C==="number"&&C>0)m=C*1000;else if(P1(f.error))m=Math.min(a0,e0*2**Math.min(D-1,6));else m=k_;let N=f.error.status,E=typeof N==="number"&&Number.isFinite(N)?N:void 0,b=a(f.error),U=(typeof f.error.body==="string"?f.error.body:"").includes("invalid_grant")||b.includes("invalid_grant");return{message:b,checkedAt:f.now,nextRetryAt:f.now+m,retryCount:D,tokenHash:_,status:E,permanent:E===400&&U}}function HC(f){if(!f)return!1;if(typeof f.permanent==="boolean")return f.permanent;if(typeof f.status==="number")return f.status===400;if(typeof f.nextRetryAt==="number")return f.nextRetryAt-f.checkedAt>=k_;return!1}function $f(f,_,$){if(!f?.nextRetryAt||f.nextRetryAt<=$)return!1;if(!_)return!0;return f.tokenHash===g_(_)}function kf(f,_){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function df(f){if(f.status===403)return!0;return/Claude quota check failed: 403\b/.test(a(f))}function Jf(f){let $=(f.previous?.retryCount??0)+1,D=t_(f.error)?Math.min(_1,f1*2**Math.min($-1,6)):$1;return{message:a(f.error),checkedAt:f.now,nextRetryAt:f.now+D,retryCount:$}}function e(f,_){if(!f?.nextRetryAt||f.nextRetryAt<=_)return!1;return!0}function MC(f,_){return`Quota API backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function w(f){let _=f?.quota?.checkIntervalMinutes??D1;return Math.max(1,_)*60000}function jC(f){return f?.logging?.level}async function LC(f,_=O()){let{setLogLevel:$}=await import("./logger-59cepv7b.js"),D=await X(_)??Q();D.logging={...D.logging??{},level:f},await V(D,_),$(f)}function n_(f){if(!f?.quota?.mainQuota||!f.quota.mainQuotaCheckedAt)return null;return{quota:f.quota.mainQuota,checkedAt:f.quota.mainQuotaCheckedAt,tokenFingerprint:f.quota.mainQuotaToken}}function s_(f){let _=f?.quota?.refreshEveryNRequests;return typeof _==="number"&&Number.isFinite(_)&&_>0?Math.floor(_):0}function zf(f){return f?.quota?.failClosedOnUnknownQuota??C1}function r_(f,_){if(!mf(_))return!0;let $=u_(_);for(let D of["five_hour","seven_day"]){let C=f?.[D];if(!C)return!zf(_);if(!Number.isFinite(C.remainingPercent))return!zf(_);if(C.remainingPercent<$[D])return!1}return!0}var y={five_hour:5,seven_day:10};function q_(f){let _=f?.five_hour??f?.["5h"],$=f?.seven_day??f?.["1w"];return{five_hour:typeof _==="number"&&Number.isFinite(_)?_:y.five_hour,seven_day:typeof $==="number"&&Number.isFinite($)?$:y.seven_day}}function x1(f){return f?.killswitch?.enabled===!0}function T1(f,_){if(!f?.killswitch)return y;if(_&&f.killswitch.accounts?.[_])return q_(f.killswitch.accounts[_]);return q_(f.killswitch.main)}function OC(f,_,$){if(!x1(_))return!0;let D=T1(_,$),C=!1;for(let m of["five_hour","seven_day"]){let N=f?.[m];if(!N){C=!0;continue}if(!Number.isFinite(N.remainingPercent)){C=!0;continue}if(N.remainingPercent<D[m])return!1}if(C)return!zf(_);return!0}function zC(f,_,$){let D=[],C=[f,..._.map((m)=>m.quota)];for(let m of C)for(let N of["five_hour","seven_day"]){let E=m?.[N]?.resetsAt;if(!E)continue;let b=Date.parse(E);if(Number.isFinite(b)&&b>$)D.push(b)}if(!D.length)return 300;return Math.max(1,Math.ceil((Math.min(...D)-$)/1000))+60}function SC(f){return f?.killswitch??{enabled:!1}}async function JC(f,_=O()){let $=await X(_)??Q();return $.killswitch=f,await V($,_),$}async function WC(f,_=O()){let $=await X(_);if(!$)return!1;let D=k1($,f);if(D)await V($,_);return D}async function YC(f,_=O()){let $=await X(_);if(!$)return;p1($,f),await V($,_)}async function ZC(f,_,$=O()){let D=await X($);if(!D)return!1;let C=v1(D,f,_);if(C)await V(D,$);return C}async function XC(f,_=O()){let $=await X(_)??Q();l1($,f),await V($,_)}function uf(f,_,$){if(!mf(_))return $+w(_);let D=u_(_),C=[];for(let m of["five_hour","seven_day"]){let N=f?.[m];if(!N)return $+w(_);if(N.remainingPercent>=D[m])continue;let E=N.resetsAt?Date.parse(N.resetsAt):Number.NaN;if(!Number.isFinite(E)||E<=$)return $+w(_);C.push(E)}if(!C.length)return $+w(_);return Math.min(...C)+60000}function u(f,_,$){return!f.access||!f.expires||f.expires-$<=R1(_)}function c_(f,_,$){if(!mf(_))return!0;let D=w(_);return["five_hour","seven_day"].every((C)=>{let m=f?.[C];return Boolean(m&&$-m.checkedAt<D)})}function pf(f,_,$){return!c_(f.quota,_,$)}function h1(f,_){if(!f)return!1;if(!f.resetsAt)return!0;let $=Date.parse(f.resetsAt);return!Number.isFinite($)||$>_}function w1(f,_){return["five_hour","seven_day"].every(($)=>h1(f?.[$],_))}function t_(f){let _=f.status;if(typeof _==="number"&&Number.isFinite(_)){if(_===429||_>=500)return!0}let $=a(f);if(/Claude quota check failed: (429|5\d\d)\b/.test($))return!0;if($.includes("Quota refresh is already in progress"))return!0;if(!(f instanceof Error))return!1;let{message:D,code:C}=f;return D.includes("fetch failed")||C==="ECONNRESET"||C==="ECONNREFUSED"||C==="ETIMEDOUT"||C==="UND_ERR_CONNECT_TIMEOUT"}function y1(f,_,$,D){return t_($)&&r_(f.quota,_)&&w1(f.quota,D)}function R_(f){if(!Number.isFinite(f))return 0;if(f<0)return 0;if(f>100)return 100;return f}function P_(f,_){if(typeof f?.utilization!=="number")return;if(!Number.isFinite(f.utilization))return;let $=R_(f.utilization);return{usedPercent:$,remainingPercent:R_(100-$),resetsAt:f.resets_at,checkedAt:_}}async function Wf(f){let $=await(f.fetchImpl??fetch)(r0,{method:"GET",headers:{Authorization:`Bearer ${f.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${v}`}});if(!$.ok){let m=await $.text().catch(()=>"");throw Object.assign(Error(`Claude quota check failed: ${$.status} — ${m}`),{status:$.status,retryAfter:lf($.headers.get("Retry-After"))})}let D=f.now?.()??Date.now(),C=await $.json();return{five_hour:P_(C.five_hour,D),seven_day:P_(C.seven_day,D)}}function A(f,_){let $=f.accounts.findIndex((D)=>D.id===_.id);if($>=0)f.accounts[$]=_}function l1(f,_){let $=f.accounts.findIndex((D)=>D.id===_.id||_.label&&D.label===_.label);if($>=0){f.accounts[$]={...f.accounts[$],..._,addedAt:f.accounts[$]?.addedAt??_.addedAt,..._.type==="oauth"&&{quota:_.quota,lastRefreshedAt:_.lastRefreshedAt,lastRefreshError:_.lastRefreshError,lastQuotaRefreshError:_.lastQuotaRefreshError}};return}f.accounts.push(_)}function k1(f,_){let $=f.accounts.findIndex((D)=>D.id===_);if($<0)return!1;return f.accounts.splice($,1),!0}function p1(f,_){let $=new Map(_.map((m,N)=>[m,N])),D=f.accounts.filter((m)=>$.has(m.id)),C=f.accounts.filter((m)=>!$.has(m.id));D.sort((m,N)=>($.get(m.id)??0)-($.get(N.id)??0)),f.accounts=[...D,...C]}function v1(f,_,$){let D=f.accounts.find((C)=>C.id===_);if(!D)return!1;return D.enabled=$,!0}function a(f){return f instanceof Error?f.message:String(f)}function o_(f,_,$){f.lastRefreshError=I1({error:_,now:$,refreshToken:f.refresh,previous:f.lastRefreshError})}function I_(f,_,$){if(df(_))return;if(f.lastQuotaRefreshError=Jf({error:_,now:$,previous:f.lastQuotaRefreshError}),_.isRefreshError)o_(f,_,$)}function d1(f){return`fallback-oauth-refresh-${x_("sha256").update(f).digest("hex").slice(0,16)}`}class i1{now;fetchImpl;configPath;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;constructor(f={}){this.now=f.now??Date.now,this.fetchImpl=f.fetchImpl??fetch,this.configPath=f.configPath??O(),this.quotaManager=f.quotaManager??null,this.onFallbackStorageChanged=f.onFallbackStorageChanged}seedFallbackQuota(f,_){if(!this.quotaManager)return;if(!f.quota)return;let $=Math.max(f.quota.five_hour?.checkedAt??0,f.quota.seven_day?.checkedAt??0);if($<=0)return;let D=this.quotaManager.getFallback(f.id,f.access);if(D&&D.checkedAt>=$)return;let C=w(_);this.quotaManager.setFallback(f.id,{quota:f.quota,refreshAfter:$+C,checkedAt:$},f.access)}async load(){return X(this.configPath)}async save(f,_){await X1(f,this.configPath,{accounts:_??!0})}startBackgroundRefresh(){let f=async()=>{await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()};if(f().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{f().catch(()=>{})},m1+q1(N1)),"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 $=[],D=!1;for(let C of _.accounts){if(C.enabled===!1||!h(C))continue;try{let m=C;if(u(m,_,this.now())){let E=m.lastRefreshError;if(E&&$f(E,m.refresh,this.now()))throw Error(kf(E,this.now()));m=await this.refreshAccount(m,_),D=!0}if(this.seedFallbackQuota(m,_),(this.quotaManager?this.quotaManager.isFallbackStale(m.id,m.access):pf(m,_,this.now()))&&!e(m.lastQuotaRefreshError,this.now()))m=await this.refreshAccountQuota(m,_),D=!0;if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount(m),_))$.push(m)}catch(m){if(y1(C,_,m,this.now()))g("[refresh] fallback quota using cached quota after refresh error",{accountId:C.id,error:a(m)}),$.push(C);else if(!zf(_))$.push(C)}}if(D)await this.save(_);return $}async markUsed(f){let _=await this.load();if(!_)return;let $=_.accounts.find((D)=>D.id===f.id);if(!$)return;$.lastUsed=this.now(),await this.save(_)}accountPassesQuotaPolicy(f,_){return r_(f.quota,_)}quotaPolicyAccount(f){if(!this.quotaManager)return f;let _=this.quotaManager.getFallback(f.id,f.access)?.quota;return _?{...f,quota:_}:f}async refreshDueAccounts(){let f=await this.load();if(!f||!Q1(f))return;let _=!1;for(let $ of f.accounts){if($.enabled===!1||!h($))continue;if(!u($,f,this.now()))continue;if($f($.lastRefreshError,$.refresh,this.now()))continue;try{g("[refresh] fallback oauth background due",{accountId:$.id,expiresInMs:$.expires?$.expires-this.now():void 0}),await this.refreshAccount($,f),_=!0}catch(D){I.warn("refresh","fallback oauth background failed",{accountId:$.id,error:D instanceof Error?D.message:String(D)}),o_($,D,this.now()),A(f,$),_=!0}}if(_)await this.save(f)}async refreshQuotaForDueAccounts(){let f=await this.load();if(!f||!mf(f))return;let _=!1;for(let $ of f.accounts){if($.enabled===!1||!h($))continue;let D=$;try{if(u(D,f,this.now())){if($f(D.lastRefreshError,D.refresh,this.now()))continue;D=await this.refreshAccount(D,f),_=!0}if(e(D.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(D,f),!(this.quotaManager?this.quotaManager.isFallbackStale(D.id,D.access):pf(D,f,this.now())))continue;await this.refreshAccountQuota(D,f),_=!0}catch(C){I_($,C,this.now()),A(f,$),_=!0}}if(_)await this.save(f),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(f={}){let _=await this.load(),$=[];if(!_||!mf(_))return{storage:_,errors:$};let D=f.force??!1,C=!1;for(let m of _.accounts){if(m.enabled===!1||!h(m))continue;let N=m;try{if(u(N,_,this.now())){let E=N.lastRefreshError;if(E&&$f(E,N.refresh,this.now()))throw Error(kf(E,this.now()));N=await this.refreshAccount(N,_),C=!0}if(!D&&!pf(N,_,this.now())){if(N.lastQuotaRefreshError)N.lastQuotaRefreshError=void 0,A(_,N),C=!0;continue}await this.refreshAccountQuota(N,_),C=!0}catch(E){I_(m,E,this.now()),A(_,m),C=!0,$.push({accountId:m.id,message:a(E)})}}if(C)await this.save(_);return{storage:_,errors:$}}async refreshAccount(f,_,$={}){let D=this.refreshPromises.get(f.id);if(D){let N=await D;return A(_,N),N}let C=this.refreshAccountNow(f,_,$).finally(()=>{this.refreshPromises.delete(f.id)});this.refreshPromises.set(f.id,C);let m=await C;return A(_,m),m}async waitForConcurrentFallbackRefresh(f,_,$,D){let C=Date.now()+b1;while(Date.now()<C){await new Promise((K)=>setTimeout(K,K1));let m=await this.load(),N=m?.accounts.find((K)=>K.id===f.id&&h(K));if(!N)continue;if((N.access!==$.access||N.refresh!==$.refresh||(N.expires??0)>($.expires??0)+60000)&&(D.force||!u(N,m,this.now())))return A(_,N),g("[refresh] fallback oauth joined concurrent refresh",{accountId:N.id,expiresInMs:N.expires?N.expires-this.now():void 0}),N;let b=N.lastRefreshError;if(b&&$f(b,N.refresh,this.now()))throw A(_,N),Error(kf(b,this.now()))}return null}async refreshAccountNow(f,_,$){let D=await this.load(),C=D?.accounts.find((E)=>E.id===f.id&&h(E));if(C&&!$.force&&!u(C,D,this.now()))return A(_,C),C;let m=C??f,N=await Sf({name:d1(m.id),ttlMs:E1,path:this.configPath,now:this.now,renew:!0});if(!N){g("[refresh] fallback oauth refresh skipped file lock",{accountId:m.id});let E=await this.waitForConcurrentFallbackRefresh(f,_,m,$);if(E)return E;throw Error("Fallback OAuth refresh is already in progress")}try{if(D=await this.load(),C=D?.accounts.find((K)=>K.id===f.id&&h(K)),C&&!$.force&&!u(C,D,this.now()))return A(_,C),C;m=C??m;let E=m.refresh;g("[refresh] fallback oauth refresh request start",{accountId:m.id,force:$.force===!0,expiresInMs:m.expires?m.expires-this.now():void 0});let b=await Z_({refreshToken:E,fetchImpl:this.fetchImpl,now:this.now});return m.access=b.access,m.refresh=b.refresh,m.expires=b.expires,m.lastRefreshedAt=b.expires-b.expiresIn*1000,m.lastRefreshError=void 0,A(_,m),await this.save(_),g("[refresh] fallback oauth refresh succeeded",{accountId:m.id,expiresInMs:m.expires?m.expires-this.now():void 0}),m}finally{await N.release()}}async refreshAccountQuota(f,_){let $=f;if(!$.access)throw Error(`Fallback account ${f.id} has no access token`);let D=(E)=>this.quotaManager?this.quotaManager.refreshFallback($.id,E):Wf({accessToken:E,fetchImpl:this.fetchImpl,now:this.now}),C=this.now();try{$.quota=await D($.access)}catch(E){if(!(E instanceof Error?E.message:String(E)).includes("Claude quota check failed: 401"))throw E;if($=await this.refreshAccount(f,_,{force:!0}),!$.access)throw E;$.quota=await D($.access)}let m=await this.load(),N=m?.accounts.find((E)=>E.id===$.id&&h(E));if(m&&N&&N.access!==$.access)return this.seedFallbackQuota(N,m),A(_,N),N;if(m&&N?.access===$.access&&N.quota&&Cf(N.quota)>=C&&c_(N.quota,m,this.now()))return this.seedFallbackQuota(N,m),A(_,N),N;if($.lastQuotaRefreshError=void 0,A(_,$),this.quotaManager&&$.quota){let E=this.now();this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:E+w(_),checkedAt:E},$.access)}return $}}var AC="claude-cache",e_="## Claude Cache Status",u1="## Claude Cache Enabled",g1="## Claude Cache Disabled",n1="## Claude Cache Usage",s1="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",Yf=!1,Zf=Mf;function QC(){return Yf}function qC(){return Zf}function RC(f){Yf=f.enabled,Zf=f.mode}function r1(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 Nf(f){let _=f?.enabled??Yf,$=f?.mode??Zf;return[e_,"",`- 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(`
7
+ `)}function PC(f){let _=r1(f.argumentsText),$=f.enabled??Yf,D=f.mode??Zf;if(_.type==="status")return Nf({enabled:$,mode:D});if(_.type==="enable")return[u1,"",Nf({enabled:!0,mode:D})].join(`
8
+ `);if(_.type==="disable")return[g1,"",Nf({enabled:!1,mode:D})].join(`
9
+ `);if(_.type==="mode")return[e_,"",`Mode updated to \`${_.mode}\`.`,"",Nf({enabled:$,mode:_.mode})].join(`
10
+ `);return[n1,"",s1,"",Nf({enabled:$,mode:D})].join(`
11
+ `)}import{randomBytes as c1,randomUUID as _0}from"node:crypto";var t1=1000,s=new Map;function Ef(f,_,$){if(!f.has(_)&&f.size>=t1){let D=f.keys().next().value;if(D!==void 0)f.delete(D)}f.set(_,$)}function $0(f){let _=f||"anonymous",$=s.get(_);if($)return $;let D={deviceId:c1(32).toString("hex"),sessionId:_0()};return Ef(s,_,D),D}var o1=86400000,e1=300000,gf=new Map,a_=new Map;async function a1(f,_){if(!f.startsWith("sk-ant-oat"))return null;let $=new AbortController,D=setTimeout(()=>$.abort(),5000);try{let C=new URL("https://api.anthropic.com/api/claude_cli/bootstrap");if(C.searchParams.set("entrypoint",L_),_)C.searchParams.set("model",_);let m=await fetch(C,{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/${v}`},signal:$.signal});if(!m.ok)return null;let E=(await m.json().catch(()=>null))?.oauth_account?.account_uuid;return typeof E==="string"&&E?E:null}catch{return null}finally{clearTimeout(D)}}async function hC(f,_){let $=$0(f);if(!f.startsWith("sk-ant-oat"))return $;let D=Date.now(),C=a_.get(f);if(C&&C.expiresAt>D){if(!C.accountUuid)return $;let K=`account:${C.accountUuid}`,U=s.get(K);if(U)return Ef(s,f,U),U}let m=gf.get(f);if(!m)m=a1(f,_),gf.set(f,m);let N=await m.finally(()=>{gf.delete(f)});if(Ef(a_,f,{accountUuid:N,expiresAt:D+(N?o1:e1)}),!N)return $;let E=`account:${N}`,b=s.get(E);if(b)return Ef(s,f,b),b;return $.accountUuid=N,Ef(s,E,$),$}function r(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function f$(f){if(!f.accountUuid)return null;return JSON.stringify({device_id:f.deviceId,account_uuid:f.accountUuid,session_id:f.sessionId})}function wC(f,_){let $=f$(_);if(!$){if(r(f.metadata))delete f.metadata.user_id;return!1}if(!r(f.metadata))f.metadata={};let D=f.metadata;if(r(D))D.user_id=$;return!0}var _$=["oauth-2025-04-20","interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13","context-management-2025-06-27","prompt-caching-scope-2026-01-05","claude-code-20250219","advisor-tool-2026-03-01","advanced-tool-use-2025-11-20","extended-cache-ttl-2025-04-11","cache-diagnosis-2026-04-07"],$$=["oauth-2025-04-20","interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13","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"],f0=["oauth-2025-04-20","interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advisor-tool-2026-03-01","advanced-tool-use-2025-11-20","extended-cache-ttl-2025-04-11","cache-diagnosis-2026-04-07"];function D$(f){return f.output_config?.format?.type==="json_schema"}function C$(f){return Array.isArray(f.tools)&&f.tools.length>0&&Array.isArray(f.system)&&r(f.thinking)&&r(f.context_management)&&r(f.output_config)&&r(f.diagnostics)}function m$(f,_=[]){let $=f?C$(f)?[..._$]:D$(f)?[...$$]:[...f0]:[...f0];if(f?.speed==="fast")$.push(j_);for(let D of _){let C=D.trim();if(C)$.push(C)}return[...new Set($)].join(",")}function N$(){switch(process.platform){case"darwin":return"MacOS";case"win32":return"Windows";case"linux":return"Linux";case"freebsd":return"FreeBSD";default:return"Unknown"}}function E$(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";case"ia32":return"x32";default:return process.arch}}function yC(f,_,$={}){let D=$.identity??$0(_),m=[...(f.get("anthropic-beta")??"").split(",").map((N)=>N.trim()).filter(Boolean),...$.extraBetas??[]];return f.set("accept","application/json"),f.set("authorization",`Bearer ${_}`),f.set("content-type","application/json"),f.set("user-agent",S_),f.set("anthropic-beta",m$($.body,m)),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",_0()),f.set("x-claude-code-session-id",D.sessionId),f.set("x-stainless-arch",E$()),f.set("x-stainless-lang","js"),f.set("x-stainless-os",N$()),f.set("x-stainless-package-version",O_),f.set("x-stainless-retry-count","0"),f.set("x-stainless-runtime","node"),f.set("x-stainless-runtime-version",z_),f.set("x-stainless-timeout","600"),f.delete("x-api-key"),f}var b$=["model","messages","system","tools","tool_choice","metadata","max_tokens","temperature","thinking","context_management","output_config","diagnostics","stream","speed"];function D0(f){let _={};for(let $ of b$)if(Object.hasOwn(f,$))_[$]=f[$];for(let[$,D]of Object.entries(f))if(!Object.hasOwn(_,$))_[$]=D;return _}import{createHash as U$}from"node:crypto";var K$=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 C0(){return function(f){let{exports:{mem:_,xxh32:$,xxh64:D,init32:C,update32:m,digest32:N,init64:E,update64:b,digest64:K}}=f,U=new Uint8Array(_.buffer);function j(G,W){if(_.buffer.byteLength<G+W){let F=Math.ceil((G+W-_.buffer.byteLength)/65536);_.grow(F),U=new Uint8Array(_.buffer)}}function Y(G,W,F,Gf,G_,Bf){j(G);let p=new Uint8Array(G);return U.set(p),F(0,W),p.set(U.subarray(0,G)),{update(R){let If;return U.set(p),typeof R=="string"?(j(3*R.length,G),If=B.encodeInto(R,U.subarray(G)).written):(j(R.byteLength,G),U.set(R,G),If=R.byteLength),Gf(0,G,If),p.set(U.subarray(0,G)),this},digest:()=>(U.set(p),Bf(G_(0)))}}function M(G){return G>>>0}let Z=2n**64n-1n;function J(G){return G&Z}let B=new TextEncoder,i=0,P=0n;function l(G,W=i){return j(3*G.length,0),M($(0,B.encodeInto(G,U).written,W))}function T(G,W=P){return j(3*G.length,0),J(D(0,B.encodeInto(G,U).written,W))}return{h32:l,h32ToString:(G,W=i)=>l(G,W).toString(16).padStart(8,"0"),h32Raw:(G,W=i)=>(j(G.byteLength,0),U.set(G),M($(0,G.byteLength,W))),create32:(G=i)=>Y(48,G,C,m,N,M),h64:T,h64ToString:(G,W=P)=>T(G,W).toString(16).padStart(16,"0"),h64Raw:(G,W=P)=>(j(G.byteLength,0),U.set(G),J(D(0,G.byteLength,W))),create64:(G=P)=>Y(88,G,E,b,K,J)}}((await WebAssembly.instantiate(K$)).instance)}var G$=0x6e52736ac806831en,B$="cch=00000;";var sf=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=([0-9a-f]{5});/,H$=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=00000;/,m0=null,nf=null;async function M$(){if(nf)return;m0??=(async()=>{nf=(await C0()).h64Raw})(),await m0}async function j$(f){return await M$(),((nf?.(f,G$)??0n)&0xfffffn).toString(16).padStart(5,"0")}function L$(f){return f.replace(sf,`$1${B$}`)}function N0(f){return sf.exec(f)?.[2]??null}async function E0(f){if(!sf.test(f))return f;let _=L$(f),$=await j$(new TextEncoder().encode(_));return _.replace(H$,`$1cch=${$};`)}function O$(f=v,_=new Date){if(f===v)return wf;return U$("sha256").update(f).digest("hex").slice(0,3)}function iC(f,_=v,$,D=new Date){let C=O$(_,D);return`x-anthropic-billing-header: cc_version=${_}.${C}; cc_entrypoint=${$}; cch=00000;`}var rC="claude-cachekeep",tf=3600000,rf=300000,z$=60000,cC="extended-cache-ttl-2025-04-11",S$=32,b0=16777216,J$=2*tf,K0="## Claude Cache Keep Status",W$="## Claude Cache Keep Enabled",Y$="## Claude Cache Keep Disabled",Z$="## Claude Cache Keep Usage",X$="Usage: `/claude-cachekeep`, `/claude-cachekeep off`, or `/claude-cachekeep HH-HH`.";function Xf(f){return String(f).padStart(2,"0")}function F$(f){let _=f.trim();if(!_)return{type:"status"};if(_==="off")return{type:"disable"};if(_==="subagents on")return{type:"subagents",enabled:!0};if(_==="subagents off")return{type:"subagents",enabled:!1};let $=/^(\d{1,2})-(\d{1,2})$/.exec(_);if(!$)return{type:"usage"};let D=Number($[1]),C=Number($[2]);if(!Number.isInteger(D)||!Number.isInteger(C)||D<0||D>23||C<0||C>23||D===C)return{type:"usage"};return{type:"window",startHour:D,endHour:C}}function of(f){let _=Number(f?.cacheKeep?.startHour),$=Number(f?.cacheKeep?.endHour);if(!Number.isInteger(_)||!Number.isInteger($)||_<0||_>23||$<0||$>23||_===$)return;return{startHour:_,endHour:$}}function B0(f){return f?.cacheKeep?.enabled===!0&&!!of(f)}function V$(f){return B0(f)&&f?.claudeCache?.enabled===!0&&f.claudeCache.mode==="hybrid"}function U0(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 G0(f=new Date){return`${f.getFullYear()}-${Xf(f.getMonth()+1)}-${Xf(f.getDate())}`}function cf(f,_=new Date){if(f&&f.startHour>f.endHour&&_.getHours()<f.endHour){let $=new Date(_);return $.setDate($.getDate()-1),G0($)}return G0(_)}function bf(f){let _=f.window?`${Xf(f.window.startHour)}-${Xf(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(`
12
+ `)}function tC(f){let _=F$(f.argumentsText),$={enabled:f.enabled??!1,window:f.window,trackedSessions:f.trackedSessions,nextPrewarmAt:f.nextPrewarmAt,hybridActive:f.hybridActive};if(_.type==="status")return[K0,"",bf($)].join(`
13
+ `);if(_.type==="disable")return[Y$,"",bf({...$,enabled:!1})].join(`
14
+ `);if(_.type==="window")return[W$,"",bf({...$,enabled:!0,window:{startHour:_.startHour,endHour:_.endHour}})].join(`
15
+ `);if(_.type==="subagents")return[K0,"",bf($),"",`Subagent tracking: ${_.enabled?"enabled":"disabled"}`].join(`
16
+ `);return[Z$,"",X$,"",bf($)].join(`
17
+ `)}function ef(f){if(!f||typeof f!=="object")return!1;if(Array.isArray(f))return f.some(ef);let _=f,$=_.cache_control;if($&&typeof $==="object"&&$.type==="ephemeral")return!0;return Object.values(_).some(ef)}async function A$(f){let _;try{_=JSON.parse(f)}catch{return{ok:!1,reason:"body is not valid JSON"}}if(!ef(_))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 m=$.tool_choice;if(m?.type==="tool"||m?.type==="any")delete $.tool_choice;return{ok:!0,bodyText:await E0(JSON.stringify(D0($)))}}class Q${options;targets=new Map;timer=null;constructor(f){this.options=f}start(){if(this.timer)return;if(I.debug("cachekeep","started"),this.timer=setInterval(()=>{this.tick().catch((f)=>{I.warn("cachekeep","tick failed",{error:f instanceof Error?f.message:String(f)})})},z$),"unref"in this.timer)this.timer.unref()}stop(){if(!this.timer)return;I.debug("cachekeep","stopped"),clearInterval(this.timer),this.timer=null}stats(f,_=this.options.now?.()??Date.now()){let $=cf(f,new Date(_)),D=[...this.targets.values()].filter((m)=>m.dayKey===$),C=D.length?Math.min(...D.map((m)=>m.cacheExpiresAt-rf)):void 0;return{trackedSessions:D.length,nextPrewarmAt:C}}trackedCount(){return this.targets.size}totalBodyBytes(){return[...this.targets.values()].reduce((f,_)=>f+_.bodyText.length,0)}evictOldestTarget(){let f=this.targets.keys().next().value;if(f!==void 0)this.targets.delete(f)}pruneTargets(f,_){for(let[$,D]of this.targets){if(_&&D.dayKey!==_){this.targets.delete($);continue}if(f-D.cacheExpiresAt>J$)this.targets.delete($)}while(this.targets.size>S$)this.evictOldestTarget();while(this.totalBodyBytes()>b0){let $=this.targets.size;if(this.evictOldestTarget(),this.targets.size===$)break}}track(f){if(!f.sessionId)return{tracked:!1,reason:"missing session id"};if(!B0(f.storage))return{tracked:!1,reason:"cachekeep disabled"};if(f.cacheMode!=="hybrid")return{tracked:!1,reason:"cache mode is not hybrid"};if(f.bodyText.length>b0)return{tracked:!1,reason:"body exceeds cachekeep memory budget"};let _=this.options.now?.()??Date.now(),$=of(f.storage);if(!U0($,new Date(_)))return{tracked:!1,reason:"outside configured window"};let D=cf($,new Date(_));if(this.pruneTargets(_,D),this.targets.has(f.sessionId))this.targets.delete(f.sessionId);let C={};return f.headers.forEach((m,N)=>{C[N]=m}),this.targets.set(f.sessionId,{id:f.sessionId,url:f.url,headers:C,bodyText:f.bodyText,cacheExpiresAt:_+tf,dayKey:D}),this.pruneTargets(_,D),this.start(),{tracked:!0}}async tick(){let f=await this.options.loadStorage(),_=of(f),$=this.options.now?.()??Date.now(),D=cf(_,new Date($));if(this.pruneTargets($,D),!this.targets.size){this.stop();return}if(!V$(f))return;if(!U0(_,new Date($)))return;I.debug("cachekeep","fired",{targets:this.targets.size});let C=$+rf;for(let m of this.targets.values()){if(m.cacheExpiresAt>C)continue;await this.prewarm(m,$)}}async prewarm(f,_){let $=await A$(f.bodyText);if(!$.ok){I.debug("cachekeep","prewarm skipped",{session:f.id,reason:$.reason}),this.targets.delete(f.id);return}let D=this.options.fetchImpl??fetch,C={...f,bodyText:$.bodyText},m=this.options.prepareHeaders?await this.options.prepareHeaders(new Headers(f.headers),C):new Headers(f.headers);m.delete("content-length"),m.delete("transfer-encoding");let N=await D(f.url,{method:"POST",headers:m,body:$.bodyText});if(!N.ok){I.warn("cachekeep","prewarm failed",{session:f.id,status:N.status,body:await N.text().catch(()=>"")}),f.cacheExpiresAt=_+rf+300000;return}let b=(await N.json().catch(()=>null))?.usage;if(f.cacheExpiresAt=_+tf,b)I.debug("cachekeep","prewarm succeeded",{session:f.id,usage:b});else I.debug("cachekeep","prewarm succeeded",{session:f.id})}}var eC="claude-account";function q$(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};let $=_[0],D=_.slice(1).join(" ");if($==="enable"&&D)return{type:"enable",id:D};if($==="disable"&&D)return{type:"disable",id:D};if($==="remove"&&D)return{type:"remove",id:D};if($==="move-up"&&D)return{type:"move-up",id:D};if($==="move-down"&&D)return{type:"move-down",id:D};if($==="add-apikey"&&D){let C=D,m,N,E=C.match(/--base-url\s+(\S+)/);if(E)m=E[1],C=C.replace(E[0],"").trim();let b=C.match(/--auth-header\s+(authorization-bearer|x-api-key)/);if(b)N=b[1],C=C.replace(b[0],"").trim();let K,U=C.match(/--label\s+(.+)/);if(U)K=U[1]?.trim()||void 0,C=C.replace(U[0],"").trim();let j=C.indexOf(" ");if(j===-1){if(!C)return{type:"usage"};return{type:"add-apikey",apiKey:C,baseURL:m,authHeader:N,label:K}}let Y=C.slice(0,j),M=C.slice(j+1).trim();return{type:"add-apikey",apiKey:Y,label:K??(M||void 0),baseURL:m,authHeader:N}}if($==="add-oauth-start")return{type:"add-oauth-start"};if($==="add-oauth-finish"&&D){let C=D,m,N=C.match(/--label\s+(.+)/);if(N)m=N[1]?.trim()||void 0,C=C.replace(N[0],"").trim();if(!C)return{type:"usage"};return{type:"add-oauth-finish",code:C,label:m}}return{type:"usage"}}function R$(f){let _=[],$=f.quota?.mainQuota?.five_hour;_.push({id:"main",label:f.main?.provider==="anthropic"?"OpenCode anthropic":"Main",role:"main",enabled:!0,quotaPercent:$?.usedPercent??null});for(let D of f.accounts){let C=D.quota?.five_hour;_.push({id:D.id,label:D.label??D.id,role:"fallback",enabled:D.enabled!==!1,quotaPercent:C?.usedPercent??null})}return _}var af=["Usage:"," /claude-account Show account list"," /claude-account enable <id> Enable a fallback account"," /claude-account disable <id> Disable a fallback account"," /claude-account remove <id> Remove a fallback account"," /claude-account move-up <id> Move a fallback account up"," /claude-account move-down <id> Move a fallback account down"," /claude-account add-apikey <key> Add an API key fallback account"," /claude-account add-oauth-start Start OAuth device flow"," /claude-account add-oauth-finish <code> Complete OAuth flow"].join(`
18
+ `);function aC(f){let _=q$(f.argumentsText),$=f.storage.accounts,D="main";if(_.type==="status"){let m=R$(f.storage),N=["## Claude Accounts",""];for(let E of m){let b=E.quotaPercent!=null?` ${Math.round(E.quotaPercent)}%`:"",K=!E.enabled?" (disabled)":"";N.push(`- **${E.label}** [${E.role}]${K}${b}`)}return N.push("",af),{text:N.join(`
19
+ `)}}if(_.type==="usage")return{text:af};if(_.type==="add-apikey")return{text:"add-apikey"};if(_.type==="add-oauth-start")return{text:"add-oauth-start"};if(_.type==="add-oauth-finish")return{text:"add-oauth-finish"};let C=_.id;if(C==="main")return{text:`Cannot ${_.type} the main account (OpenCode managed).`};if(_.type==="enable"||_.type==="disable"){let m=$.find((N)=>N.id===C);if(!m)return{text:`Account "${C}" not found.`};return{text:`Account "${m.label??C}" ${_.type}d.`,updated:{id:C,action:_.type,enabled:_.type==="enable"}}}if(_.type==="remove"){let m=$.find((N)=>N.id===C);if(!m)return{text:`Account "${C}" not found.`};return{text:`Account "${m.label??C}" removed.`,updated:{id:C,action:"remove"}}}if(_.type==="move-up"){let m=$.findIndex((K)=>K.id===C);if(m<0)return{text:`Account "${C}" not found.`};if(m===0)return{text:`Account "${$[m]?.label??C}" is already first.`};let N=$.map((K)=>K.id),E=[...$];[E[m-1],E[m]]=[E[m],E[m-1]];let b=E.map((K)=>K.id);return{text:`Account "${$[m]?.label??C}" moved up.`,updated:{id:C,action:"reorder",previousOrder:N,newOrder:b}}}if(_.type==="move-down"){let m=$.findIndex((K)=>K.id===C);if(m<0)return{text:`Account "${C}" not found.`};if(m===$.length-1)return{text:`Account "${$[m]?.label??C}" is already last.`};let N=$.map((K)=>K.id),E=[...$];[E[m],E[m+1]]=[E[m+1],E[m]];let b=E.map((K)=>K.id);return{text:`Account "${$[m]?.label??C}" moved down.`,updated:{id:C,action:"reorder",previousOrder:N,newOrder:b}}}return{text:af}}import{createHash as P$}from"node:crypto";import{mkdir as I$,writeFile as Ff}from"node:fs/promises";import{tmpdir as x$}from"node:os";import{join as L0}from"node:path";var Em="claude-dump",T$="## Claude Dump Status",h$="## Claude Dump Enabled",w$="## Claude Dump Disabled",y$="## Claude Dump Usage",l$="Usage: `/claude-dump`, `/claude-dump on`, or `/claude-dump off`.",k$="OPENCODE_ANTHROPIC_AUTH_DUMP_DIR",p$=L0(x$(),"opencode-anthropic-auth-dumps"),Kf=!1,H0=0,v$=100,ff=new Map;function bm(f){Kf=f}function O0(){return process.env[k$]||p$}function d$(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 Vf(f){let _=f?.enabled??Kf;return[T$,"",`- Enabled: ${_?"enabled":"disabled"}`,`- Directory: ${O0()}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Captures: final rewritten Anthropic body in direct and relay modes; request/relay metadata is redacted","- Warning: body dumps may contain prompt/session content; turn this off after debugging"].join(`
20
+ `)}function Km(f){let _=d$(f.argumentsText),$=f.enabled??Kf;if(_.type==="status")return Vf({enabled:$});if(_.type==="enable")return[h$,"",Vf({enabled:!0})].join(`
21
+ `);if(_.type==="disable")return[w$,"",Vf({enabled:!1})].join(`
22
+ `);return[y$,"",l$,"",Vf({enabled:$})].join(`
23
+ `)}function M0(f){return f.length<=16?f:`${f.slice(0,12)}…`}function z0(f){let _=f.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!_)return"session-unknown";return _.length<=80?_:_.slice(0,80)}function i$(f){if(f.transport!=="direct")return`${f.transport}-p${f.protocol}-${f.mode}`;return`direct${f.route?`-${z0(f.route)}`:""}`}function u$(f){let _=f.affinity?.trim();if(_)return`session:${_}`;return`request:${f.route??"direct"}:${f.url??""}`}function g$(f,_){if(!ff.has(f))while(ff.size>=v$){let $=ff.keys().next().value;if($===void 0)break;ff.delete($)}ff.set(f,_)}function n$(f){if(f==null)return;return Object.fromEntries(new Headers(f).entries())}function S0(f){return P$("sha256").update(f).digest("hex")}function s$(f){return N0(f)}function r$(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 D=f.length-1,C=_.length-1;while(D>=$&&C>=$&&f[D]===_[C])D-=1,C-=1;return{changed:!0,firstByte:$,lastPreviousByte:D,lastCurrentByte:C,changedPreviousBytes:D-$+1,changedCurrentBytes:C-$+1,previousBytes:f.length,currentBytes:_.length}}function c$(f){try{let _=JSON.parse(f);return _!=null&&typeof _==="object"&&!Array.isArray(_)?_:null}catch(_){return L(`dump body parse failed: ${_ instanceof Error?_.message:String(_)}`),null}}function f_(f){return S0(JSON.stringify(f))}function t$(f){let _=c$(f);if(!_)return{parseable:!1};let $=Array.isArray(_.messages)?_.messages:[],D=Array.isArray(_.system)?_.system:[],C=$[0],m=$.slice(1);return{parseable:!0,model:typeof _.model==="string"?_.model:void 0,stream:_.stream,systemCount:D.length,messagesCount:$.length,systemHash:f_(D),message0Hash:C===void 0?null:f_(C),message0Bytes:C===void 0?0:JSON.stringify(C).length,messagesAfter0Hash:f_(m),messagesAfter0Bytes:JSON.stringify(m).length,cch:s$(f)}}function Af(f){if(Array.isArray(f))return f.map(Af);if(f==null||typeof f!=="object")return f;let _={};for(let[$,D]of Object.entries(f)){let C=$.toLowerCase();if(C==="authorization"||C==="x-api-key"||C==="cookie"||C==="set-cookie"||j0($)){_[$]="[redacted]";continue}_[$]=Af(D)}return _}async function J0(f){if(!Kf)return;H0+=1;let _=f.affinity?.trim()||"session-unknown",$=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(H0).padStart(5,"0")}-${z0(_)}-${i$(f)}`,D=O0(),C=L0(D,$),m={body:`${C}.body.json`,metadata:`${C}.meta.json`};if(f.payload!==void 0)m.relay=`${C}.relay.json`;if(f.request!==void 0)m.request=`${C}.request.json`;try{await I$(D,{recursive:!0});let N={id:$,createdAt:new Date().toISOString(),session:M0(_),transport:f.transport,protocol:f.protocol,mode:f.mode,route:f.route,status:f.status,error:f.error,bodyBytes:f.bodyText.length,relayBytes:f.relayBytes,bodyHash:S0(f.bodyText),diff:r$(f.previousBodyText,f.bodyText),body:t$(f.bodyText),files:m},E=[Ff(m.body,f.bodyText,"utf8"),Ff(m.metadata,`${JSON.stringify(N,null,2)}
24
+ `,"utf8")];if(f.payload!==void 0&&m.relay)E.push(Ff(m.relay,`${JSON.stringify(Af(f.payload),null,2)}
25
+ `,"utf8"));if(f.request!==void 0&&m.request)E.push(Ff(m.request,`${JSON.stringify(Af({...f.request,headers:n$(f.request.headers)}),null,2)}
26
+ `,"utf8"));await Promise.all(E),L(`dumped request id=${$} session=${M0(_)} body=${m.body} meta=${m.metadata}`)}catch(N){L(`dump failed: ${N instanceof Error?N.message:String(N)}`)}}async function Um(f){if(!Kf)return;let _=u$(f),$=ff.get(_);await J0({affinity:f.affinity,transport:"direct",route:f.route,status:f.status,error:f.error,bodyText:f.bodyText,previousBodyText:$,request:{url:f.url,method:f.method,headers:f.headers}}),g$(_,f.bodyText)}async function W0(f){await J0({affinity:f.affinity,transport:f.transport,protocol:f.protocol,mode:f.mode,status:f.status,bodyText:f.bodyText,previousBodyText:f.previousBodyText,payload:f.payload,relayBytes:f.relayBytes})}var Bm="claude-fast";var qf=!1;function Hm(){return qf}function Mm(f){qf=f}function o$(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 Qf(f){return["## Claude Fast Mode Status","",`- Enabled: ${f?.enabled??qf?"enabled":"disabled"}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Scope: adds Anthropic fast mode to supported Opus requests","- Supported models: claude-opus-4-6, claude-opus-4-7, and claude-opus-4-8",'- 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(`
27
+ `)}function jm(f){let _=o$(f.argumentsText),$=f.enabled??qf;if(_.type==="status")return Qf({enabled:$});if(_.type==="enable")return["## Claude Fast Mode Enabled","",Qf({enabled:!0})].join(`
28
+ `);if(_.type==="disable")return["## Claude Fast Mode Disabled","",Qf({enabled:!1})].join(`
29
+ `);return["## Claude Fast Mode Usage","","Usage: `/claude-fast`, `/claude-fast on`, or `/claude-fast off`.","",Qf({enabled:$})].join(`
30
+ `)}var Uf="claude-killswitch";function e$(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&_[0]==="on")return{type:"on"};if(_.length===1&&_[0]==="off")return{type:"off"};if(_[0]==="set"){let $=[];for(let D=1;D<_.length;D++){let C=_[D]?.match(/^([^:]+):(\d+),(\d+)$/);if(!C)return{type:"usage"};let[,m,N,E]=C;$.push({account:m,fh:Number.parseInt(N,10),sd:Number.parseInt(E,10)})}if($.length===0)return{type:"usage"};return{type:"set",entries:$}}return{type:"usage"}}function Rf(f,_){let $=f.enabled===!0,D=["## Killswitch","",`Status: **${$?"ON":"OFF"}**`];if($){D.push(""),D.push("| Account | 5h threshold | 1w threshold |"),D.push("| ------- | ------------ | ------------ |");let C=f.main??{},m=C.five_hour??C["5h"]??y.five_hour,N=C.seven_day??C["1w"]??y.seven_day;D.push(`| main | ≥ ${m}% | ≥ ${N}% |`);for(let E of _){let b=f.accounts?.[E]??f.main??{},K=b.five_hour??b["5h"]??y.five_hour,U=b.seven_day??b["1w"]??y.seven_day;D.push(`| ${E} | ≥ ${K}% | ≥ ${U}% |`)}}return D.join(`
31
+ `)}var Y0=["## Killswitch Commands","","```",`/${Uf} — show status`,`/${Uf} on — enable with current or default thresholds`,`/${Uf} off — disable`,`/${Uf} set all:5,10 — set all accounts to 5h≥5%, 1w≥10%`,`/${Uf} set main:3,8 work-alt:5,10 — per-account`,"```"].join(`
32
+ `);function zm(f){let _=e$(f.argumentsText);if(_.type==="status")return{text:`${Rf(f.config,f.accountIds)}
33
+
34
+ ${Y0}`};if(_.type==="on"){let D={...f.config,enabled:!0,main:f.config.main??{five_hour:y.five_hour,seven_day:y.seven_day}};return{text:`## Killswitch Enabled
35
+
36
+ ${Rf(D,f.accountIds)}`,updatedConfig:D}}if(_.type==="off")return{text:"## Killswitch Disabled",updatedConfig:{...f.config,enabled:!1}};if(_.type==="set"){let D={...f.config.accounts??{}},C={...f.config,enabled:!0,accounts:D};for(let N of _.entries){let E={five_hour:N.fh,seven_day:N.sd};if(N.account==="main")C.main=E;else if(N.account==="all"){C.main=E;for(let b of f.accountIds)D[b]=E}else D[N.account]=E}return{text:`## Killswitch Updated
37
+
38
+ ${Rf(C,f.accountIds)}`,updatedConfig:C}}return{text:`${Rf(f.config,f.accountIds)}
39
+
40
+ ${Y0}`}}var Jm="claude-logging",a$=["error","warn","info","debug","trace"];function fD(f){let _=f.trim().toLowerCase().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&a$.includes(_[0]))return{type:"level",level:_[0]};return{type:"usage"}}function __(f){return["## Claude Log Level","",`Current log level: \`${f?.level??"info"}\``,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Valid levels: error, warn, info, debug, trace","","Usage: `/claude-logging`, `/claude-logging error|warn|info|debug|trace`."].join(`
41
+ `)}function Wm(f){let _=fD(f.argumentsText),$=f.level??"info";if(_.type==="status")return __({level:$});if(_.type==="level")return["## Claude Log Level Updated","",`Level set to \`${_.level}\`.`,"",...__({level:_.level}).split(`
42
+ `).slice(2)].join(`
43
+ `);return["## Claude Log Level Usage","","Usage: `/claude-logging`, `/claude-logging error|warn|info|debug|trace`.","",...__({level:$}).split(`
44
+ `).slice(2)].join(`
45
+ `)}var _D=["claude-fable-5","claude-mythos-5"],$D={type:"adaptive",display:"summarized"},Zm={input:10,output:50,cacheRead:1,cacheWrite5m:12.5,cacheWrite1h:20},Xm=1e6,Fm=128000,Vm="2026-06-09",Am={["claude-fable-5"]:{id:"claude-fable-5",name:"Claude Fable 5"},["claude-mythos-5"]:{id:"claude-mythos-5",name:"Claude Mythos 5",limited:!0}};function Qm(f){return typeof f==="string"&&_D.some((_)=>f===_||f.startsWith(`${_}-`))}var Z0="claude-sonnet-5",qm=$D;function Rm(f){return typeof f==="string"&&(f===Z0||f.startsWith(`${Z0}-`))}function Pm(f){if(typeof f!=="string")return!1;if(f.startsWith("gAAAA"))return!0;if(!f.startsWith("{"))return!1;try{let _=JSON.parse(f);return _.type==="reasoning"&&typeof _.id==="string"&&_.id.startsWith("rs_")&&typeof _.encrypted_content==="string"&&_.encrypted_content.startsWith("gAAAA")}catch{return!1}}import{createHash as DD}from"node:crypto";var CD=globalThis.setTimeout;function x(f){return DD("sha256").update(f).digest("hex").slice(0,16)}class d{main=null;mainTokenFp=null;fallbacks=new Map;fallbackTokenFps=new Map;inflightMain=null;inflightMainFp=null;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;fallbackErrorTokenFps=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;onMainQuotaFetched;onApiError;constructor(f){this.storage=f.storage,this.fetchImpl=f.fetchImpl??fetch,this.now=f.now??Date.now,this.onMainQuotaFetched=f.onMainQuotaFetched,this.onApiError=f.onApiError,this.seedMainFromStorage(f.storage),this.seedMainBackoffFromStorage(f.storage)}getMain(f){if(f&&this.main&&this.mainTokenFp&&this.mainTokenFp!==x(f))this.main=null,this.mainTokenFp=null;return this.main}getFallback(f,_){let $=this.fallbacks.get(f)??null;if(!_||!$)return $;if(this.fallbackTokenFps.get(f)!==x(_))return this.fallbacks.delete(f),this.fallbackTokenFps.delete(f),null;return $}getAllFallbacks(){return this.fallbacks}setMain(f,_){this.mainTokenFp=x(f),this.main=_}setFallback(f,_,$){if(this.fallbacks.set(f,_),$)this.fallbackTokenFps.set(f,x($));else this.fallbackTokenFps.delete(f)}async refreshMain(f){let _=x(f);if(this.mainTokenFp&&this.mainTokenFp!==_)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===_)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=_,this.inflightMain=this._fetchMain(f),this.inflightMain}async refreshFallback(f,_){let $=d.fallbackInflightKey(f,_),D=this.inflightFallbacks.get($);if(D)return D;if(this.isFallbackBackedOff(f,_)){let m=this.getFallback(f,_);if(m)return m.quota;throw Error("Quota API rate-limited — try again later")}let C=this._fetchFallback(f,_);return this.inflightFallbacks.set($,C),C}async refreshAllFallbacks(f){let _=this.now();for(let $ of f){if($.enabled===!1)continue;if(!$.access)continue;let D=this.getFallback($.id,$.access);if(D&&_<D.refreshAfter)continue;try{await this.refreshFallback($.id,$.access)}catch{}}}refreshMainInBackground(f){if(this.inflightMain)return;if(this.isBackedOff())return;this.refreshMain(f).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale(f,_){let $=this.getFallback(f,_);if(!$)return!0;return this.now()>=$.refreshAfter}shouldRefreshOnRequestCount(f){let _=s_(this.storage);if(_<=0)return!1;return f>0&&f%_===0}needsRefresh(f){return this.isMainStale()||this.shouldRefreshOnRequestCount(f)}updateStorage(f){this.storage=f,this.seedMainFromStorage(f),this.seedMainBackoffFromStorage(f)}seedMainFromStorage(f,_){let $=n_(f);if(!$)return;let D=_?x(_):null;if(D&&$.tokenFingerprint&&$.tokenFingerprint!==D)return;let C={quota:$.quota,refreshAfter:uf($.quota,f,$.checkedAt),checkedAt:$.checkedAt};if(this.main&&this.main.checkedAt>=C.checkedAt&&(!D||!this.mainTokenFp||this.mainTokenFp===D))return;this.main=C,this.mainTokenFp=$.tokenFingerprint??null}seedMainBackoffFromStorage(f){let _=f?.quota?.mainLastQuotaApiError;this.mainLastApiError=_&&e(_,this.now())?_:void 0}seedFallbacksFromAccounts(f){let _=w(this.storage);for(let $ of f){if($.enabled===!1)continue;if(!$.quota)continue;let D=Math.max($.quota.five_hour?.checkedAt??0,$.quota.seven_day?.checkedAt??0);if(D<=0)continue;let C=this.getFallback($.id,$.access);if(C&&C.checkedAt>=D)continue;this.setFallback($.id,{quota:$.quota,refreshAfter:D+_,checkedAt:D},$.access)}}isBackedOff(){return e(this.mainLastApiError,this.now())}isFallbackBackedOff(f,_){if(_){if(this.fallbackErrorTokenFps.get(f)!==x(_))return!1}return e(this.fallbackApiErrors.get(f),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(f,_){return JSON.stringify([f,x(_)])}static quotaLockName(f){return`opencode-fallback-quota-refresh-${f.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch(f){let _=async()=>{let D=this.now()-this.lastApiCallAt;if(D<d.API_CALL_GAP_MS)await new Promise((C)=>{let m=CD(C,d.API_CALL_GAP_MS-D);if(typeof m==="object"&&"unref"in m)m.unref()});return this.lastApiCallAt=this.now(),f()},$=this.apiGate.then(_,_);return this.apiGate=$.catch(()=>{}),$}async _fetchMain(f){let _=x(f);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let $=await Sf({name:"opencode-main-quota-refresh",ttlMs:30000});if(!$){let D=this.main;if(D&&this.now()<D.refreshAfter)return D.quota;throw Error("Quota refresh is already in progress")}try{let D=this.now(),C=await Wf({accessToken:f,fetchImpl:this.fetchImpl,now:this.now}),m=this.now();return this.mainTokenFp=x(f),this.main={quota:C,refreshAfter:uf(C,this.storage,m),checkedAt:m},this.mainLastApiError=void 0,this.onMainQuotaFetched?.(C,m,this.mainTokenFp,D),C}catch(D){throw this._handleMainFetchError(D),D}finally{await $.release()}}finally{if(this.inflightMainFp===_)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback(f,_){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff(f,_)){let D=this.getFallback(f,_);if(D)return D.quota;throw Error("Quota API rate-limited — try again later")}let $=await Sf({name:d.quotaLockName(f),ttlMs:30000});if(!$){let D=this.getFallback(f,_);if(D&&this.now()<D.refreshAfter)return D.quota;throw Error("Quota refresh is already in progress")}try{let D=await Wf({accessToken:_,fetchImpl:this.fetchImpl,now:this.now}),C=this.now();return this.setFallback(f,{quota:D,refreshAfter:C+w(this.storage),checkedAt:C},_),this.fallbackApiErrors.delete(f),this.fallbackErrorTokenFps.delete(f),D}finally{await $.release()}}catch($){throw this._handleFallbackFetchError(f,_,$),$}finally{this.inflightFallbacks.delete(d.fallbackInflightKey(f,_))}})}static isAuthError(f){if(f.status===401||df(f))return!0;let $=f instanceof Error?f.message:String(f);return/quota check failed: 401\b/.test($)}_handleMainFetchError(f){if(d.isAuthError(f))return;this.mainLastApiError=Jf({error:f,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(f,_,$){if(d.isAuthError($))return;let D=x(_),C=this.fallbackErrorTokenFps.get(f)===D?this.fallbackApiErrors.get(f):void 0;this.fallbackApiErrors.set(f,Jf({error:$,now:this.now(),previous:C})),this.fallbackErrorTokenFps.set(f,D)}}var ym="claude-quota",X0={five_hour:"5h",seven_day:"1w"};function F0(f){return`${Math.round(f*10)/10}%`}function $_(f,_){let $=Math.max(0,_-f),D=Math.floor($/60000);if(D<1)return"just now";if(D===1)return"1m ago";if(D<60)return`${D}m ago`;let C=Math.floor(D/60),m=D%60;if(m===0)return`${C}h ago`;return`${C}h ${m}m ago`}function mD(f,_){let $=Date.parse(f);if(!Number.isFinite($))return f;let D=$-_;if(D<=0)return"now";let C=Math.max(1,Math.ceil(D/60000));if(C<60)return`in ${C}m`;let m=Math.floor(C/60),N=C%60;if(N===0)return`in ${m}h`;return`in ${m}h ${N}m`}function ND(f,_){if(!f)return"";return`, resets ${mD(f,_)}`}function V0(f,_,$){if(!_)return` - ${X0[f]}: unknown`;return[` - ${X0[f]}: ${F0(_.remainingPercent)} remaining`,` (${F0(_.usedPercent)} used`,`${ND(_.resetsAt,$)}, checked ${$_(_.checkedAt,$)})`].join("")}function ED(f){return f.label?.trim()||f.id}function bD(f){return f.lastQuotaRefreshError?.message??f.lastRefreshError?.message}function lm(f,_=new Map){if(!f?.accounts.length)return[];return f.accounts.filter(h).map(($)=>{let D=_.get($.id)??bD($);return{name:ED($),role:"fallback",enabled:$.enabled!==!1,quota:$.quota,lastRefreshedAt:$.lastRefreshedAt,...D&&{error:D}}})}function km(f){let _=f.now??Date.now(),$=["## Claude Quotas",""];if(f.refreshedAt)$.push(`Refreshed: ${$_(f.refreshedAt,_)}`,"");if(!f.accounts.length)return $.push("No Claude OAuth accounts found yet."),$.join(`
46
+ `);for(let D of f.accounts){let C=D.role==="main"?"main":"fallback",m=D.enabled===!1?" disabled":"";if($.push(`### ${D.name} (${C}${m})`),D.lastRefreshedAt)$.push(` - Last token refresh: ${$_(D.lastRefreshedAt,_)}`);if(D.error)$.push(` - Error: ${D.error}`);$.push(V0("five_hour",D.quota?.five_hour,_)),$.push(V0("seven_day",D.quota?.seven_day,_)),$.push("")}return $.join(`
47
+ `).trimEnd()}import{Buffer as T0}from"node:buffer";import{createHash as KD,randomBytes as UD}from"node:crypto";class C_ extends Error{}class m_ extends Error{code="ECONNRESET";syscall="websocket";closeCode;closeReason;wasClean;constructor(f,_){super(f);this.name="RelayWebSocketConnectionResetError",this.closeCode=_?.code,this.closeReason=_?.reason,this.wasClean=_?.wasClean}}var k=new Map,c=new Map,A0=new Set,GD=7200000,BD=1800000,HD=128,MD=32,Q0=0;function D_(){return Q0+=1,`req_${Date.now().toString(36)}_${Q0.toString(36)}`}function Pf(f){if(A0.has(f))return;A0.add(f),L(f)}function gm(f){let _=f?.relay;if(!_)return Pf("disabled: no relay config found"),null;if(_.enabled!==!0)return Pf("disabled: relay.enabled is not true"),null;if(!_.url?.trim()||!_.token?.trim())return Pf("disabled: missing relay url or token"),null;let $=_.transport==="http"?"http":"websocket";return Pf(`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 nm(){return UD(32).toString("base64url")}function jD(f){return`sha256:${KD("sha256").update(f).digest("hex")}`}function q0(f,_){let $=0,D=Math.min(f.length,_.length);while($<D&&f.charCodeAt($)===_.charCodeAt($))$++;let C=f.length,m=_.length;while(C>$&&m>$&&f.charCodeAt(C-1)===_.charCodeAt(m-1))C--,m--;return{start:$,deleteCount:C-$,insert:_.slice($,m)}}function LD(f){return f.deleteCount===0&&f.insert.length===0}function R0(f){let _=f.match(/\bcch=([0-9a-f]{5});/),$=_?.[1];if(!$||_.index==null)return null;let D=_.index+4;return{start:D,end:D+$.length,token:$}}function OD(f,_,$,D){return`${f.slice(0,_)}${D}${f.slice($)}`}function h0(f,_){let $=R0(f),D=R0(_);if($&&D&&$.start===D.start&&$.end-$.start===D.end-D.start&&$.token!==D.token){let C={start:$.start,deleteCount:$.end-$.start,insert:D.token},m=OD(f,$.start,$.end,D.token),N=q0(m,_);return LD(N)?C:[C,N]}return q0(f,_)}function zD(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 SD(f){let _={};for(let[$,D]of f.entries()){if($==="x-session-affinity"||$==="x-opencode-session")continue;_[$]=D}return _}async function P0(f,_,$){let D=z(),C=JSON.stringify(_);return _f("http_payload_stringify",{session:S(_.affinity),ms:q(z()-D),relayBytes:C.length,mode:_.mode}),fetch(f.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":f.token},body:C,signal:$??void 0})}function S(f){return f.length>12?`${f.slice(0,12)}…`:f}function z(){return performance.now()}function q(f){return Math.round(f*10)/10}function JD(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function _f(f,_){if(!JD())return;L(`[perf] relay ${f} ${JSON.stringify(_)}`)}function WD(f){let{input:_,init:$,headers:D,bodyText:C,affinity:m,previous:N,nextHash:E}=f,b=_ instanceof Request?_.url:_.toString(),K={protocol:1,type:"request",affinity:m,upstream:{url:b,method:$?.method||(_ instanceof Request?_.method:"POST"),headers:SD(D)},next_hash:E};return N?{...K,mode:"patch",base_hash:N.hash,revision:N.revision+1,patch:h0(N.body,C)}:{...K,mode:"full_sync",revision:1,body:C}}function N_(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 w0(f,_,$,D){let C=Date.now();k.delete(f),k.set(f,{body:_,hash:$,revision:D,updatedAt:C}),E_(C)}async function I0(f){let{config:_,payload:$,bodyText:D,fallback:C,signal:m}=f,N=$,E=await P0(_,N,m);if(E.status===409&&N.mode==="patch")L(`state mismatch from relay session=${S(N.affinity)}; retrying full_sync`),await E.body?.cancel().catch(()=>{}),N=N_(N,D),E=await P0(_,N,m);if(!E.ok&&E.status>=500&&_.fallbackToDirect)return L(`relay returned ${E.status}; falling back direct session=${S(N.affinity)}`),await E.body?.cancel().catch(()=>{}),{response:await C(),payload:N,transport:"http",protocol:N.protocol,usedRelay:!1};return{response:E,payload:N,transport:"http",protocol:N.protocol,usedRelay:!0}}function YD(f,_){let $=new URL(f);return $.protocol=$.protocol==="http:"?"ws:":"wss:",$.pathname="/ws",$.searchParams.set("token",_),$.toString()}function ZD(f){return new Uint8Array(T0.from(f,"base64"))}function XD(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(T0.from(String(f)))}function FD(f){return JSON.parse(f)}function x0(f){let _=f,$=[`code=${_.code??"unknown"}`,`wasClean=${_.wasClean??"unknown"}`];if(_.reason)$.push(`reason=${JSON.stringify(_.reason)}`);return $.join(" ")}function VD(f){let _=f.message||"relay websocket error";return f.status?`relay websocket error ${f.status}: ${_}`:_}class y0{config;affinity;socket;connecting;queue=Promise.resolve();pending;serverState;lastUsedAt=Date.now();constructor(f,_){this.config=f,this.affinity=_}touch(f=Date.now()){this.lastUsedAt=f}canEvict(f=Date.now()){return!this.pending&&!this.connecting&&f-this.lastUsedAt>BD}dispose(){this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0}send(f,_,$=!1){this.touch();let D=z(),C=this.queue.catch(()=>{}).then(()=>this.startQueued(f,_,D,$)),m=C.then(async({response:N,getPayload:E})=>({response:await N,payload:E(),transport:"websocket",protocol:2,usedRelay:!0}));return this.queue=C.then(({done:N})=>N.catch(()=>{}),()=>{}),m}async startQueued(f,_,$,D){let C=z();await this.ensureConnected();let m=z(),N=k.get(this.affinity),E=this.serverState?.hash,b={...f,protocol:2,id:D_()};if(b.mode==="patch"&&(!E||E!==b.base_hash))b.mode="full_sync",b.revision=(this.serverState?.revision??0)+1,delete b.base_hash,delete b.patch,b.body=_;if(b.mode==="patch"&&N)b.patch=h0(N.body,_);L(`perf websocket send_start session=${S(this.affinity)} request=${b.id} mode=${b.mode} queueMs=${q(m-$)} connectMs=${q(m-C)} bodyBytes=${_.length} relayBytes=${JSON.stringify(b).length}`);let K=b,U=this.sendPayload(b,_,D);U.done.catch(()=>{});let j=U.done,Y=U.response.catch((Z)=>{if(!(Z instanceof C_)||b.mode!=="patch")throw Z;let J=N_(b,_);J.protocol=2,J.id=D_(),J.revision=(this.serverState?.revision??0)+1,K=J;let B=this.sendPayload(J,_,D);return B.done.catch(()=>{}),j=B.done,B.response}),M=Y.then(()=>j,()=>j.catch(()=>{}));return{response:Y,done:M,getPayload:()=>K}}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 $=YD(this.config.url,this.config.token),D=new URL($);D.searchParams.set("affinity",this.affinity);let C=new WebSocket(D.toString());this.socket=C,this.serverState=void 0;let m=setTimeout(()=>{C.close(),_(Error("relay websocket ready timed out"))},15000);C.addEventListener("message",(N)=>{try{if(typeof N.data!=="string"){this.handleBinaryChunk(N.data);return}let E=FD(N.data);if(E.type==="ready"){clearTimeout(m),this.serverState=E.state,f();return}this.handleMessage(E)}catch(E){clearTimeout(m),_(E),this.failPending(E),C.close()}}),C.addEventListener("error",()=>{clearTimeout(m);let N=new m_("relay websocket error");_(N),this.failPending(N)}),C.addEventListener("close",(N)=>{if(clearTimeout(m),this.socket===C)this.socket=void 0,this.serverState=void 0,this.connecting=void 0;if(this.pending){if(this.pending.retryingBeforeResponse)return;let E=this.pending.responseStartedAt!=null,b=E?"closed after response_start before stream bytes":"closed before response";if(this.retryPendingBeforeResponse(this.pending,b,N))return;let K=E?new m_("relay websocket closed during response stream",N):Error("relay websocket closed before response");L(`websocket ${E?"closed during response stream":"closed before response without retry"} session=${S(this.affinity)} request=${this.pending.payload.id} chunks=${this.pending.streamChunkCount} bytes=${this.pending.streamByteCount} ${x0(N)}`),this.failPending(K)}})}).finally(()=>{this.connecting=void 0}),await this.connecting}sendPayload(f,_,$){let D=this.socket;if(!D||D.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");let C=z(),m,N,E=new Promise((K,U)=>{m=K,N=U});return{response:new Promise((K,U)=>{let j={payload:f,bodyText:_,resolve:K,reject:U,streamDone:!1,accepted:!1,responseStarted:!1,resolveDone:m,rejectDone:N,sentAt:C,optimisticResponse:$,streamChunkCount:0,streamByteCount:0,retryAttempts:0,retryingBeforeResponse:!1};if(this.pending=j,this.resetPendingTimeout(j),D.send(JSON.stringify(f)),$)this.resolvePendingResponse(j,200,"OK",{"content-type":"text/event-stream","x-cortexkit-relay-optimistic":"true"})}),done:E}}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&&f.streamByteCount>0)return!1;if(f.streamDone)return!1;if(f.retryAttempts>=1)return!1;f.retryAttempts+=1,f.retryingBeforeResponse=!0,clearTimeout(f.timeout);let D=f.retryAttempts,C=f.payload.id;return L(`websocket ${_}; reconnecting and retrying full_sync session=${S(this.affinity)} request=${C} retry=${D} chunks=${f.streamChunkCount} bytes=${f.streamByteCount}${$?` ${x0($)}`:""}`),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 m=N_(f.payload,f.bodyText);m.protocol=2,m.id=D_(),m.revision=(this.serverState?.revision??0)+1,f.payload=m,f.accepted=!1,f.acceptedAt=void 0,f.responseStartedAt=void 0,f.sentAt=z(),f.retryingBeforeResponse=!1;let N=this.socket;if(!N||N.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");this.resetPendingTimeout(f),L(`perf websocket retry_send session=${S(this.affinity)} request=${m.id} previous=${C} mode=full_sync retry=${D} bodyBytes=${f.bodyText.length} relayBytes=${JSON.stringify(m).length}`),N.send(JSON.stringify(m))}catch(m){if(f.retryingBeforeResponse=!1,this.pending===f)this.failPending(m)}})(),!0}enqueueStreamChunk(f,_){f.streamChunkCount+=1,f.streamByteCount+=_.byteLength,f.streamController?.enqueue(_)}handleBinaryChunk(f){let _=this.pending;if(!_?.responseStarted)return;this.enqueueStreamChunk(_,XD(f))}resolvePendingResponse(f,_,$,D){if(f.responseStarted)return;f.responseStarted=!0;let C=new ReadableStream({start:(m)=>{f.streamController=m},cancel:()=>{this.socket?.close()}});f.resolve(new Response(C,{status:_,statusText:$,headers:D}))}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=$,L(`perf websocket accepted session=${S(this.affinity)} request=${_.payload.id} sentMs=${q($-_.sentAt)} mode=${_.payload.mode}`),this.serverState={hash:f.hash,revision:f.revision},w0(this.affinity,_.bodyText,f.hash,f.revision),this.resetPendingTimeout(_);return}if(f.type==="response_start"){let $=z();if(_.responseStartedAt=$,L(`perf websocket response_start session=${S(this.affinity)} request=${_.payload.id} sentMs=${q($-_.sentAt)} upstreamMs=${_.acceptedAt==null?"unknown":q($-_.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
48
+ data: ${JSON.stringify({type:"error",error:{type:"relay_upstream_error",message:`Relay upstream returned HTTP ${f.status}`}})}
49
+
50
+ `)),this.finishPending();return}if(f.type==="chunk"){this.enqueueStreamChunk(_,ZD(f.base64));return}if(f.type==="done"){this.finishPending(f);return}if(f.type==="error"){if(_.optimisticResponse&&_.responseStartedAt!=null){L(`websocket relay error during optimistic response session=${S(this.affinity)} request=${_.payload.id} status=${f.status} message=${f.message||"unknown"} chunks=${_.streamChunkCount} bytes=${_.streamByteCount}`),_.streamController?.enqueue(new TextEncoder().encode(`event: error
51
+ data: ${JSON.stringify({type:"error",error:{type:"relay_error",message:f.message||"relay error"}})}
52
+
53
+ `)),this.finishPending(),this.socket?.close();return}if(f.status===409&&this.retryPendingBeforeResponse(_,f.message||"state mismatch"))return;let $=f.status===409?new C_(f.message||"state mismatch"):Error(VD(f));this.failPending($)}}finishPending(f){let _=this.pending;if(!_)return;let $=z(),D=f&&"frames"in f?` upstreamChunks=${f.upstreamChunks??"unknown"} upstreamBytes=${f.upstreamBytes??"unknown"} frames=${f.frames} frameBytes=${f.frameBytes??"unknown"}`:"";if(L(`perf websocket done session=${S(this.affinity)} request=${_.payload.id} sentMs=${q($-_.sentAt)} streamMs=${_.responseStartedAt==null?"unknown":q($-_.responseStartedAt)} chunks=${_.streamChunkCount} bytes=${_.streamByteCount}${D}`),clearTimeout(_.timeout),!_.streamDone)_.streamDone=!0,_.streamController?.close();_.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 E_(f=Date.now()){for(let[_,$]of k)if(f-$.updatedAt>GD)k.delete(_);while(k.size>HD){let _=k.keys().next().value;if(_===void 0)break;k.delete(_)}for(let[_,$]of c)if($.canEvict(f))$.dispose(),c.delete(_);while(c.size>MD){let _=!1;for(let[$,D]of c){if(!D.canEvict(f))continue;D.dispose(),c.delete($),_=!0;break}if(!_)break}}function AD(f,_){E_();let $=c.get(_);if($)return $.touch(),$;let D=new y0(f,_);return c.set(_,D),E_(),D}async function sm(f){let{config:_,input:$,init:D,headers:C,body:m,fallback:N,affinity:E,optimisticResponse:b}=f;if(!_||!zD($,m))return N();let K=E||C.get("x-session-affinity")||C.get("x-opencode-session");if(!K)return L("skipping relay: missing x-session-affinity header"),N();let U=m,j=z(),Y=jD(U);_f("hash_body",{session:S(K),ms:q(z()-j),bodyBytes:U.length});let M=k.get(K),Z=z(),J=WD({input:$,init:D,headers:C,bodyText:U,affinity:K,previous:M,nextHash:Y});_f("create_payload",{session:S(K),ms:q(z()-Z),mode:J.mode,bodyBytes:U.length,previousBytes:M?.body.length});try{let B,i=z();if(_.transport==="websocket")try{B=await AD(_,K).send(J,U,b===!0)}catch(G){L(`websocket relay failed session=${S(K)}; trying http relay: ${G instanceof Error?G.message:String(G)}`),B=await I0({config:_,payload:J,bodyText:U,fallback:N,signal:D?.signal})}else B=await I0({config:_,payload:J,bodyText:U,fallback:N,signal:D?.signal});if(_f("send",{session:S(K),ms:q(z()-i),transport:B.transport,protocol:B.protocol,mode:B.payload.mode,status:B.response.status,usedRelay:B.usedRelay}),!B.usedRelay)return B.response;if(B.transport==="http")w0(K,U,B.payload.next_hash,B.payload.revision);let P=z(),l=JSON.stringify(B.payload).length;_f("payload_stringify",{session:S(K),ms:q(z()-P),relayBytes:l}),L(`used relay transport=${B.transport} protocol=${B.protocol} mode=${B.payload.mode} status=${B.response.status} session=${S(K)} bodyBytes=${U.length} relayBytes=${l}`);let T=z();return await W0({affinity:K,transport:B.transport,protocol:B.protocol,mode:B.payload.mode,status:B.response.status,bodyText:U,previousBodyText:M?.body,payload:B.payload,relayBytes:l}),_f("dump",{session:S(K),ms:q(z()-T),enabled:!0}),B.response}catch(B){if(!_.fallbackToDirect)throw L(`relay failed session=${S(K)} and fallbackToDirect=false: ${B instanceof Error?B.message:String(B)}`),B;return L(`relay failed; falling back direct session=${S(K)}: ${B instanceof Error?B.message:String(B)}`),N()}}var rm=`
54
+ async function hashBody(body) {
55
+ const bytes = new TextEncoder().encode(body)
56
+ const digest = await crypto.subtle.digest('SHA-256', bytes)
57
+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
58
+ return 'sha256:' + hex
59
+ }
60
+
61
+ function applyPatch(base, patch) {
62
+ return base.slice(0, patch.start) + patch.insert + base.slice(patch.start + patch.deleteCount)
63
+ }
64
+
65
+ function applyPatchSet(base, patch) {
66
+ if (!Array.isArray(patch)) return applyPatch(base, patch)
67
+ if (patch.length === 0) return base
68
+
69
+ let result = ''
70
+ let cursor = 0
71
+ for (const item of patch) {
72
+ if (item.start < cursor) return { error: 'overlapping patch', status: 400 }
73
+ result += base.slice(cursor, item.start)
74
+ result += item.insert
75
+ cursor = item.start + item.deleteCount
76
+ }
77
+ return result + base.slice(cursor)
78
+ }
79
+
80
+ async function readState(env, affinity) {
81
+ const raw = await env.RELAY_STATE.get('session:' + affinity)
82
+ return raw ? JSON.parse(raw) : null
83
+ }
84
+
85
+ async function writeState(env, affinity, state) {
86
+ await env.RELAY_STATE.put('session:' + affinity, JSON.stringify(state), { expirationTtl: 86400 })
87
+ }
88
+
89
+ async function resolveBody(env, payload) {
90
+ if (payload.mode === 'full_sync') return payload.body
91
+ if (payload.mode === 'patch') {
92
+ const state = await readState(env, payload.affinity)
93
+ if (!state || state.hash !== payload.base_hash) {
94
+ return { error: 'state mismatch', status: 409 }
95
+ }
96
+ return applyPatchSet(state.body, payload.patch)
97
+ }
98
+ return { error: 'unknown mode', status: 400 }
99
+ }
100
+
101
+ async function prepareUpstream(env, payload) {
102
+ if ((payload.protocol !== 1 && payload.protocol !== 2) || payload.type !== 'request' || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
103
+ return { error: 'invalid payload', status: 400 }
104
+ }
105
+
106
+ const body = await resolveBody(env, payload)
107
+ if (body && typeof body === 'object' && 'error' in body) return body
108
+
109
+ if (typeof body !== 'string' || (await hashBody(body)) !== payload.next_hash) {
110
+ return { error: 'hash mismatch', status: 409 }
111
+ }
112
+
113
+ const stateWrite = writeState(env, payload.affinity, { body, hash: payload.next_hash, revision: payload.revision }).catch(() => {})
114
+ console.log(JSON.stringify({
115
+ relay: 'opencode-anthropic-auth',
116
+ transport: 'relay',
117
+ mode: payload.mode,
118
+ revision: payload.revision,
119
+ affinity: String(payload.affinity).slice(0, 12),
120
+ bodyBytes: body.length,
121
+ }))
122
+
123
+ return { body, stateWrite }
124
+ }
125
+
126
+ function resolveBodyFromState(state, payload) {
127
+ if (payload.mode === 'full_sync') return payload.body
128
+ if (payload.mode === 'patch') {
129
+ if (!state || state.hash !== payload.base_hash) {
130
+ return { error: 'state mismatch', status: 409 }
131
+ }
132
+ return applyPatchSet(state.body, payload.patch)
133
+ }
134
+ return { error: 'unknown mode', status: 400 }
135
+ }
136
+
137
+ function deferWorkerTask(task) {
138
+ return new Promise((resolve) => setTimeout(resolve, 0)).then(task)
139
+ }
140
+
141
+ const WEBSOCKET_STREAM_FLUSH_BYTES = 1024
142
+ const WEBSOCKET_STREAM_FLUSH_MS = 20
143
+
144
+ function createWebSocketStreamCoalescer(socket, options = {}) {
145
+ const flushBytes = options.flushBytes || WEBSOCKET_STREAM_FLUSH_BYTES
146
+ const flushMs = options.flushMs ?? WEBSOCKET_STREAM_FLUSH_MS
147
+ let chunks = []
148
+ let byteLength = 0
149
+ let flushTimer = null
150
+ const stats = {
151
+ upstreamChunks: 0,
152
+ upstreamBytes: 0,
153
+ frames: 0,
154
+ frameBytes: 0,
155
+ }
156
+
157
+ const clearFlushTimer = () => {
158
+ if (flushTimer === null) return
159
+ clearTimeout(flushTimer)
160
+ flushTimer = null
161
+ }
162
+
163
+ const mergeChunks = () => {
164
+ if (chunks.length === 1) return chunks[0]
165
+ const frame = new Uint8Array(byteLength)
166
+ let offset = 0
167
+ for (const chunk of chunks) {
168
+ frame.set(chunk, offset)
169
+ offset += chunk.byteLength
170
+ }
171
+ return frame
172
+ }
173
+
174
+ const flush = () => {
175
+ clearFlushTimer()
176
+ if (byteLength === 0) return
177
+ const frame = mergeChunks()
178
+ chunks = []
179
+ byteLength = 0
180
+ socket.send(frame)
181
+ stats.frames += 1
182
+ stats.frameBytes += frame.byteLength
183
+ }
184
+
185
+ const scheduleFlush = () => {
186
+ if (flushTimer !== null) return
187
+ flushTimer = setTimeout(flush, flushMs)
188
+ }
189
+
190
+ return {
191
+ push(value) {
192
+ const chunk = value instanceof Uint8Array ? value : new Uint8Array(value)
193
+ if (chunk.byteLength === 0) return
194
+ stats.upstreamChunks += 1
195
+ stats.upstreamBytes += chunk.byteLength
196
+ chunks.push(chunk)
197
+ byteLength += chunk.byteLength
198
+ if (byteLength >= flushBytes) flush()
199
+ else scheduleFlush()
200
+ },
201
+ flush,
202
+ stats() {
203
+ return { ...stats, pendingBytes: byteLength }
204
+ },
205
+ }
206
+ }
207
+
208
+ function checkpointWebSocketState(env, payload, body, nextState) {
209
+ return deferWorkerTask(async () => {
210
+ try {
211
+ if ((await hashBody(body)) !== payload.next_hash) {
212
+ throw new Error('hash mismatch')
213
+ }
214
+ await writeState(env, payload.affinity, nextState)
215
+ } catch (error) {
216
+ console.log(JSON.stringify({
217
+ relay: 'opencode-anthropic-auth',
218
+ transport: 'websocket',
219
+ event: 'checkpoint_write_failed',
220
+ affinity: String(payload.affinity).slice(0, 12),
221
+ message: error instanceof Error ? error.message : String(error),
222
+ }))
223
+ }
224
+ })
225
+ }
226
+
227
+ async function prepareWebSocketUpstream(env, state, payload) {
228
+ if (payload.protocol !== 2 || payload.type !== 'request' || !payload.id || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
229
+ return { error: 'invalid payload', status: 400 }
230
+ }
231
+
232
+ const body = resolveBodyFromState(state, payload)
233
+ if (body && typeof body === 'object' && 'error' in body) return body
234
+ if (typeof body !== 'string') return { error: 'invalid body', status: 400 }
235
+ if ((await hashBody(body)) !== payload.next_hash) {
236
+ return { error: 'hash mismatch', status: 409 }
237
+ }
238
+
239
+ const nextState = { body, hash: payload.next_hash, revision: payload.revision }
240
+ const checkpoint = checkpointWebSocketState(env, payload, body, nextState)
241
+ const logAccepted = () => console.log(JSON.stringify({
242
+ relay: 'opencode-anthropic-auth',
243
+ transport: 'websocket',
244
+ mode: payload.mode,
245
+ revision: payload.revision,
246
+ affinity: String(payload.affinity).slice(0, 12),
247
+ bodyBytes: body.length,
248
+ }))
249
+
250
+ return { body, state: nextState, checkpoint, logAccepted }
251
+ }
252
+
253
+ function headersToObject(headers) {
254
+ const result = {}
255
+ for (const [key, value] of headers.entries()) result[key] = value
256
+ return result
257
+ }
258
+
259
+ async function handleRelayPayload(env, payload) {
260
+ const prepared = await prepareUpstream(env, payload)
261
+ if (prepared.error) return prepared
262
+ const upstream = await fetch(payload.upstream.url, {
263
+ method: payload.upstream.method || 'POST',
264
+ headers: payload.upstream.headers,
265
+ body: prepared.body,
266
+ })
267
+ return { upstream, stateWrite: prepared.stateWrite }
268
+ }
269
+
270
+ async function handleWebSocket(socket, env, ctx, payload, getState, setState) {
271
+ const heartbeat = setInterval(() => {
272
+ try {
273
+ socket.send(JSON.stringify({ protocol: 2, type: 'keepalive' }))
274
+ } catch {
275
+ clearInterval(heartbeat)
276
+ }
277
+ }, 15000)
278
+ let streamCoalescer = null
279
+ try {
280
+ const result = await prepareWebSocketUpstream(env, getState(), payload)
281
+ if (result.error) {
282
+ socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: result.status, message: result.error }))
283
+ return
284
+ }
285
+
286
+ setState(result.state)
287
+ socket.send(JSON.stringify({ protocol: 2, type: 'accepted', id: payload.id, hash: result.state.hash, revision: result.state.revision }))
288
+ ctx?.waitUntil?.(deferWorkerTask(result.logAccepted))
289
+
290
+ const upstreamPromise = fetch(payload.upstream.url, {
291
+ method: payload.upstream.method || 'POST',
292
+ headers: payload.upstream.headers,
293
+ body: result.body,
294
+ })
295
+ ctx?.waitUntil?.(result.checkpoint)
296
+ const upstream = await upstreamPromise
297
+ socket.send(JSON.stringify({
298
+ protocol: 2,
299
+ type: 'response_start',
300
+ id: payload.id,
301
+ status: upstream.status,
302
+ statusText: upstream.statusText,
303
+ headers: headersToObject(upstream.headers),
304
+ }))
305
+
306
+ const reader = upstream.body?.getReader()
307
+ if (reader) {
308
+ streamCoalescer = createWebSocketStreamCoalescer(socket)
309
+ while (true) {
310
+ const { done, value } = await reader.read()
311
+ if (done) break
312
+ streamCoalescer.push(value)
313
+ }
314
+ streamCoalescer.flush()
315
+ }
316
+ const stats = streamCoalescer?.stats?.() || {}
317
+ socket.send(JSON.stringify({ protocol: 2, type: 'done', id: payload.id, ...stats }))
318
+ } catch (error) {
319
+ try {
320
+ streamCoalescer?.flush?.()
321
+ } catch {}
322
+ socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: 500, message: error instanceof Error ? error.message : String(error) }))
323
+ } finally {
324
+ clearInterval(heartbeat)
325
+ }
326
+ }
327
+
328
+ export default {
329
+ async fetch(request, env, ctx) {
330
+ if (request.headers.get('Upgrade') === 'websocket') {
331
+ const url = new URL(request.url)
332
+ const token = url.searchParams.get('token')
333
+ const affinity = url.searchParams.get('affinity')
334
+ if (token !== env.RELAY_TOKEN) return new Response('unauthorized', { status: 401 })
335
+ if (!affinity) return new Response('missing affinity', { status: 400 })
336
+ const pair = new WebSocketPair()
337
+ const client = pair[0]
338
+ const server = pair[1]
339
+ server.binaryType = 'arraybuffer'
340
+ let state = null
341
+ let ready = false
342
+ server.accept()
343
+ const loadState = readState(env, affinity).then((loadedState) => {
344
+ state = loadedState
345
+ ready = true
346
+ server.send(JSON.stringify({
347
+ protocol: 2,
348
+ type: 'ready',
349
+ state: state ? { hash: state.hash, revision: state.revision } : null,
350
+ }))
351
+ }).catch((error) => {
352
+ server.send(JSON.stringify({ protocol: 2, type: 'error', status: 500, message: error instanceof Error ? error.message : String(error) }))
353
+ server.close(1011, 'state load failed')
354
+ })
355
+ ctx?.waitUntil?.(loadState)
356
+ if (!ctx?.waitUntil) void loadState
357
+ let busy = false
358
+ server.addEventListener('message', (event) => {
359
+ if (!ready) {
360
+ server.send(JSON.stringify({ protocol: 2, type: 'error', status: 425, message: 'relay state is not ready' }))
361
+ return
362
+ }
363
+ if (busy) {
364
+ server.send(JSON.stringify({ protocol: 2, type: 'error', status: 429, message: 'request already in flight' }))
365
+ return
366
+ }
367
+ let payload
368
+ try {
369
+ payload = JSON.parse(event.data)
370
+ } catch {
371
+ server.send(JSON.stringify({ protocol: 2, type: 'error', status: 400, message: 'invalid JSON payload' }))
372
+ return
373
+ }
374
+ payload.affinity = affinity
375
+ busy = true
376
+ const run = handleWebSocket(server, env, ctx, payload, () => state, (nextState) => { state = nextState }).finally(() => { busy = false })
377
+ ctx?.waitUntil?.(run)
378
+ if (!ctx?.waitUntil) void run
379
+ })
380
+ return new Response(null, { status: 101, webSocket: client })
381
+ }
382
+
383
+ if (request.method === 'GET') {
384
+ return Response.json({ status: 'ok', transports: ['http', 'websocket'] })
385
+ }
386
+ if (request.method !== 'POST') return new Response('method not allowed', { status: 405 })
387
+ if (request.headers.get('x-relay-token') !== env.RELAY_TOKEN) {
388
+ return new Response('unauthorized', { status: 401 })
389
+ }
390
+
391
+ try {
392
+ const payload = await request.json()
393
+ const result = await handleRelayPayload(env, payload)
394
+ if (result.error) return Response.json({ error: result.error }, { status: result.status })
395
+
396
+ if (result.stateWrite) ctx.waitUntil(result.stateWrite)
397
+
398
+ const upstream = result.upstream
399
+ return new Response(upstream.body, {
400
+ status: upstream.status,
401
+ statusText: upstream.statusText,
402
+ headers: upstream.headers,
403
+ })
404
+ } catch (error) {
405
+ return Response.json(
406
+ { error: error instanceof Error ? error.message : 'internal relay error' },
407
+ { status: 502 },
408
+ )
409
+ }
410
+ },
411
+ }
412
+ `;var om="claude-routing",K_=["main-first","fallback-first"],U_="main-first",l0="Usage: `/claude-routing`, `/claude-routing main-first`, or `/claude-routing fallback-first`.";function QD(f){return typeof f==="string"&&K_.includes(f)?f:U_}function em(f){return QD(f?.routing?.mode)}async function am(f,_=O()){let $=await X(_)??Q();return $.routing={...$.routing??{},mode:f},await V($,_),$}function qD(f){let _=f.trim().toLowerCase().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&K_.includes(_[0]))return{type:"mode",mode:_[0]};if(_.length===2&&_[0]==="mode"&&K_.includes(_[1]))return{type:"mode",mode:_[1]};return{type:"usage"}}function RD(f){if(f==="fallback-first")return"Try usable fallback accounts before the main account. If no fallback succeeds, try the main account.";return"Try the main account first. Use fallback accounts only when quota policy or fallback errors require it."}function b_(f){let _=f?.mode??U_;return["## Claude Routing Status","",`- Mode: \`${_}\``,`- Behavior: ${RD(_)}`,"",l0].join(`
413
+ `)}function fN(f){let _=qD(f.argumentsText),$=f.mode??U_;if(_.type==="status")return b_({mode:$});if(_.type==="mode")return["## Claude Routing Updated","",`Mode updated to \`${_.mode}\`.`,"",...b_({mode:_.mode}).split(`
414
+ `).slice(2)].join(`
415
+ `);return["## Claude Routing Usage","",l0,"",...b_({mode:$}).split(`
416
+ `).slice(2)].join(`
417
+ `)}export{PD as a,j_ as b,ID as c,xD as d,TD as e,hD as f,wD as g,L_ as h,yD as i,lD as j,Z_ as k,iD as l,uD as m,h as n,aD as o,c0 as p,fC as q,O as r,Q as s,X as t,V as u,X1 as v,Sf as w,_C as x,V1 as y,$C as z,DC as A,CC as B,mC as C,NC as D,EC as E,bC as F,KC as G,UC as H,GC as I,BC as J,g_ as K,I1 as L,HC as M,$f as N,kf as O,MC as P,jC as Q,LC as R,n_ as S,r_ as T,x1 as U,OC as V,zC as W,SC as X,JC as Y,WC as Z,YC as _,ZC as $,XC as aa,uf as ba,l1 as ca,i1 as da,AC as ea,QC as fa,qC as ga,RC as ha,r1 as ia,PC as ja,E0 as ka,iC as la,hC as ma,wC as na,yC as oa,D0 as pa,rC as qa,cC as ra,F$ as sa,of as ta,B0 as ua,V$ as va,tC as wa,Q$ as xa,eC as ya,q$ as za,R$ as Aa,aC as Ba,Em as Ca,bm as Da,d$ as Ea,Km as Fa,Um as Ga,Bm as Ha,Hm as Ia,Mm as Ja,o$ as Ka,jm as La,Uf as Ma,zm as Na,Jm as Oa,fD as Pa,Wm as Qa,$D as Ra,Zm as Sa,Xm as Ta,Fm as Ua,Vm as Va,Am as Wa,Qm as Xa,qm as Ya,Rm as Za,Pm as _a,d as $a,ym as ab,lm as bb,km as cb,gm as db,nm as eb,sm as fb,rm as gb,om as hb,em as ib,am as jb,qD as kb,fN as lb};