@cortexkit/opencode-anthropic-auth 1.17.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,422 @@
1
+ import{hc as e1,lc as P,mc as r,nc as b}from"./index-1ets4bf8.js";import{uc as gC}from"./index-9aeag0wm.js";var Q0="9d1c250a-e61b-44d9-88ed-5944d1962f5e",l$={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.com/cai/oauth/authorize"},$$="https://platform.claude.com/oauth/code/callback",C$="https://platform.claude.com/v1/oauth/token",_$="axios/1.15.2",p$=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],g$="user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload",mG="mcp_";var d$="fast-mode-2026-02-01";function vG($,C){let _=($??"").split(",").map((K)=>K.trim()).filter(Boolean);return[...new Set([..._,...C])].join(",")}function lG($){return typeof $==="string"&&($.startsWith("claude-opus-4-6")||$.startsWith("claude-opus-4-7")||$.startsWith("claude-opus-4-8")||$.startsWith("claude-opus-5"))}var pG="You are OpenCode",gG="You are Claude Code, Anthropic's official CLI for Claude.",dG=["<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 p="2.1.177",K$="3bf",u$="cli",i$="0.94.0",c$="v24.3.0",r$="claude-cli/2.1.177 (external, cli)",s$=["explicit","automatic","hybrid"],B0="explicit",uG=["github.com/anomalyco/opencode","opencode.ai/docs"],iG=[{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 n$($){let C="";for(let _ of $)C+=String.fromCharCode(_);return btoa(C).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function o$(){let $=new Uint8Array(64);crypto.getRandomValues($);let C=n$($),_=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(C));return{verifier:C,challenge:n$(new Uint8Array(_)),method:"S256"}}function j$($){if(!$)return;let C=Number($);if(Number.isFinite(C)&&C>0)return Math.ceil(C);let _=Date.parse($);if(Number.isFinite(_)){let K=Math.ceil((_-Date.now())/1000);return K>0?K:void 0}return}class G$ extends Error{status;body;retryAfter;isRefreshError=!0;constructor($,C,_){super(`Claude OAuth refresh failed: ${$} — ${C}`);this.status=$,this.body=C,this.name="ClaudeOAuthRefreshError",this.retryAfter=j$(_??void 0)}}function yC($){if(!($ instanceof Error))return!1;let C=$.code;return $.message.includes("fetch failed")||C==="ECONNRESET"||C==="ECONNREFUSED"||C==="ETIMEDOUT"||C==="UND_ERR_CONNECT_TIMEOUT"}async function a$($){let C=$.fetchImpl??fetch,_=$.maxRetries??2,K=$.baseDelayMs??500;for(let G=0;G<=_;G++)try{if(G>0){let z=K*2**(G-1);await new Promise((X)=>setTimeout(X,z))}let j=await C(C$,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":_$},body:JSON.stringify({grant_type:"refresh_token",refresh_token:$.refreshToken,client_id:Q0,scope:g$})});if(!j.ok){if(j.status>=500&&G<_){await j.body?.cancel().catch(()=>{});continue}let z=await j.text().catch(()=>"");throw new G$(j.status,z,j.headers.get("retry-after"))}let J=await j.json(),Z=$.now?.()??Date.now();return{access:J.access_token,refresh:J.refresh_token??$.refreshToken,expires:Z+J.expires_in*1000,expiresIn:J.expires_in}}catch(j){if(j instanceof G$)throw j;if(G<_&&yC(j))continue;throw j}throw Error("Token refresh exhausted all retries")}function mC(){return crypto.randomUUID().replace(/-/g,"")}function vC($){let C=$.trim();try{let J=new URL(C),Z=J.searchParams.get("code"),z=J.searchParams.get("state");if(Z&&z)return{code:Z,state:z}}catch{}let _=C.split("#");if(_.length===2&&_[0]&&_[1])return{code:_[0],state:_[1]};let K=new URLSearchParams(C),G=K.get("code"),j=K.get("state");if(G&&j)return{code:G,state:j};return null}async function lC($,C,_){let K=await fetch(C$,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":_$},body:JSON.stringify({code:$.code,state:$.state,grant_type:"authorization_code",client_id:Q0,redirect_uri:_,code_verifier:C})});if(!K.ok)return{type:"failed"};let G=await K.json();return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+G.expires_in*1000}}async function oG($){let C=await o$(),_=mC(),K=new URL(l$[$],import.meta.url);return K.searchParams.set("code","true"),K.searchParams.set("client_id",Q0),K.searchParams.set("response_type","code"),K.searchParams.set("redirect_uri",$$),K.searchParams.set("scope",p$.join(" ")),K.searchParams.set("code_challenge",C.challenge),K.searchParams.set("code_challenge_method","S256"),K.searchParams.set("state",_),{url:K.toString(),redirectUri:$$,state:_,verifier:C.verifier}}async function aG($,C,_,K){let G=vC($);if(!G)return{type:"failed"};if(K&&G.state!==K)return{type:"failed"};return lC(G,C,_)}import{createHash as pC}from"node:crypto";function D($){return pC("sha256").update($).digest("hex").slice(0,16)}import{createHash as Y1,randomUUID as N0}from"node:crypto";import{mkdir as X$,readFile as D0,rename as O1,rm as $0,stat as t$,writeFile as S0}from"node:fs/promises";import{homedir as dC}from"node:os";import{dirname as Y$,join as C0}from"node:path";var uC=globalThis.setTimeout.bind(globalThis),iC=globalThis.clearTimeout.bind(globalThis),N1="anthropic-auth.json",cC="anthropic-auth-state.json",rC="https://api.anthropic.com/api/oauth/usage";function k($){return $.type==="oauth"}function X2($){return $.type==="api"}function sC($){let C=$?.trim();if(!C)return!1;try{let _=new URL(C);return(_.protocol==="http:"||_.protocol==="https:")&&!_.username&&!_.password}catch{return!1}}function Y2($){return $.costZeroing?.enabled!==!1}var nC=[401,403,429],L1=240,oC=L1;var aC=300000,tC=3600000,W1=86400000,eC=60000,$6=900000,C6=300000,_6=5,e$={five_hour:0,seven_day:0},K6=!0,G6=60000,j6=60000,J6=600000,Z6=1e4,z6=100;function X6(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return C0(process.env.XDG_CONFIG_HOME||C0(dC(),".config"),"opencode")}function f(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||C0(X6(),N1)}function O$($=f()){let C=process.env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim();if(C)return C;return $.endsWith(N1)?C0(Y$($),cC):`${$}.state.json`}function U($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function $1($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():N0(),label:typeof $.label==="string"?$.label:void 0,enabled:typeof $.enabled==="boolean"?$.enabled:void 0,addedAt:typeof $.addedAt==="number"?$.addedAt:void 0,lastUsed:typeof $.lastUsed==="number"?$.lastUsed:void 0}}function Y6($){if(!U($))return null;if($.type==="api"){let C=typeof $.baseURL==="string"?$.baseURL.trim():"",_=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!sC(C))return null;let K=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...$1($),type:"api",apiKey:_||void 0,baseURL:C,authHeader:K}}if($.type!=="oauth")return null;if(typeof $.refresh!=="string"||!$.refresh.trim())return null;return{...$1($),type:"oauth",access:typeof $.access==="string"?$.access:void 0,refresh:$.refresh,expires:typeof $.expires==="number"?$.expires:void 0,lastRefreshedAt:typeof $.lastRefreshedAt==="number"?$.lastRefreshedAt:void 0,lastRefreshError:C1($.lastRefreshError),lastQuotaRefreshError:C1($.lastQuotaRefreshError),quota:O6($.quota),profile:L0($.profile)}}function L0($){if(!U($))return;if(typeof $.tier!=="string"||!$.tier.trim()||typeof $.orgType!=="string"||!$.orgType.trim()||typeof $.checkedAt!=="number"||!Number.isFinite($.checkedAt))return;return{tier:$.tier.trim(),orgType:$.orgType.trim(),checkedAt:$.checkedAt,...typeof $.tokenFingerprint==="string"&&$.tokenFingerprint.trim()&&{tokenFingerprint:$.tokenFingerprint.trim()}}}function C1($){if(!U($))return;if(typeof $.message!=="string")return;let C=Number($.checkedAt);if(!Number.isFinite(C))return;let _=Number($.nextRetryAt),K=Number($.retryCount),G=Number($.status);return{message:$.message,checkedAt:C,nextRetryAt:Number.isFinite(_)?_:void 0,retryCount:Number.isFinite(K)?K:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0,status:Number.isFinite(G)?G:void 0,permanent:typeof $.permanent==="boolean"?$.permanent:void 0}}function _1($){if(!U($))return;let C=Number($.usedPercent),_=Number($.remainingPercent),K=Number($.checkedAt);if(!Number.isFinite(C)||!Number.isFinite(_)||!Number.isFinite(K))return;return{usedPercent:C,remainingPercent:_,checkedAt:K,resetsAt:typeof $.resetsAt==="string"?$.resetsAt:void 0}}function O6($){if(!U($))return;let C={};for(let _ of["five_hour","seven_day"]){let K=_1($[_]);if(K)C[_]=K}if(typeof $.checkedAt==="number"&&Number.isFinite($.checkedAt))C.checkedAt=$.checkedAt;if(Array.isArray($.scoped)){let _=$.scoped.map((K)=>{if(!U(K))return;let G=_1(K);if(!G)return;if(typeof K.id!=="string"||!K.id.trim())return;if(typeof K.title!=="string"||!K.title.trim())return;if(typeof K.modelName!=="string"||!K.modelName.trim())return;let j=typeof K.modelId==="string"&&K.modelId.trim()?K.modelId.trim():void 0;return{...G,id:K.id.trim(),title:K.title.trim(),...j&&{modelId:j},modelName:K.modelName.trim()}}).filter((K)=>K!=null);C.scoped=_}if(U($.extraUsage)){let _=K1($.extraUsage.used),K=K1($.extraUsage.limit);if(_&&K&&typeof $.extraUsage.exhausted==="boolean")C.extraUsage={used:_,limit:K,...typeof $.extraUsage.utilizationPercent==="number"&&Number.isFinite($.extraUsage.utilizationPercent)&&{utilizationPercent:$.extraUsage.utilizationPercent},...typeof $.extraUsage.severity==="string"&&{severity:$.extraUsage.severity},exhausted:$.extraUsage.exhausted}}if(typeof $.bindingWindow==="string"&&$.bindingWindow.trim())C.bindingWindow=$.bindingWindow.trim();if($.bindingWindowSource==="poll"||$.bindingWindowSource==="headers")C.bindingWindowSource=$.bindingWindowSource;if(typeof $.fallbackAdvised==="boolean")C.fallbackAdvised=$.fallbackAdvised;if($.source==="poll"||$.source==="headers")C.source=$.source;return Object.keys(C).length?C:void 0}function K1($){if(!U($))return;if(typeof $.amountMinor!=="number"||!Number.isFinite($.amountMinor)||typeof $.currency!=="string"||!$.currency.trim()||typeof $.exponent!=="number"||!Number.isFinite($.exponent))return;return{amountMinor:$.amountMinor,currency:$.currency.trim(),exponent:$.exponent}}function I(){return{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]}}function N6($){if(!U($)||!Array.isArray($.accounts))return null;return{version:1,main:{type:"opencode",provider:"anthropic",profile:L0(U($.main)?$.main.profile:void 0)},routing:U($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((C)=>Number.isInteger(C)):void 0,refresh:U($.refresh)?$.refresh:void 0,quota:U($.quota)?$.quota:void 0,claudeCache:U($.claudeCache)?$.claudeCache:void 0,dump:U($.dump)?$.dump:void 0,claudeFast:U($.claudeFast)?$.claudeFast:void 0,costZeroing:U($.costZeroing)?$.costZeroing:void 0,cacheKeep:U($.cacheKeep)?$.cacheKeep:void 0,relay:U($.relay)?$.relay:void 0,logging:U($.logging)?$.logging:void 0,killswitch:U($.killswitch)?$.killswitch:void 0,accounts:$.accounts.map(Y6).filter((C)=>C!=null)}}async function W0($){try{return{exists:!0,value:JSON.parse(await D0($,"utf8"))}}catch(C){if(C.code==="ENOENT")return{exists:!1,value:null};let _=C instanceof Error?C.message:String(C);throw Error(`account store at ${$} is corrupt or unreadable (${_}) — fix or remove it`)}}function n($){return Object.fromEntries(Object.entries($).filter(([,C])=>C!==void 0))}function R0($){return typeof $==="number"&&Number.isFinite($)?$:0}function z$($){return Math.max(R0($.lastRefreshedAt),R0($.lastUsed),R0($.addedAt))}function L6($,C){if($.type!=="oauth")return!1;if(typeof $.refresh!=="string"||!$.refresh.trim())return!1;if(!Boolean(typeof $.access==="string"&&typeof C.access==="string"&&$.access!==C.access||typeof $.refresh==="string"&&typeof C.refresh==="string"&&$.refresh!==C.refresh))return!1;return z$($)>z$(C)}function W6($,C){if(L6($,C)){let _={...C,...$},K=z$($);if(K>R0(_.lastRefreshedAt))_.lastRefreshedAt=K;return delete _.quota,delete _.lastRefreshError,delete _.lastQuotaRefreshError,_}return{...$,...C}}function H6($,C){if(!U($))return $;let _=U(C)?C:{},K=U(_.main)?_.main:void 0,G=U(_.accounts)?_.accounts:{},j=U($.quota)?$.quota:{},J=U($.refresh)?$.refresh:{},Z=K??j,z=K??J,X=Array.isArray($.accounts)?$.accounts.map((Y)=>{if(!U(Y))return Y;let O=typeof Y.id==="string"&&U(G[Y.id])?G[Y.id]:{};return W6(Y,O)}):[];return{...$,main:{type:"opencode",provider:"anthropic",profile:L0(K?.profile)},refresh:n({...J,mainLastRefreshError:z.lastRefreshError,mainRefreshLeaseId:z.refreshLeaseId,mainRefreshLeaseUntil:z.refreshLeaseUntil,mainRefreshLeaseTokenHash:z.refreshLeaseTokenHash}),quota:n({...j,mainQuota:Z.quota,mainQuotaCheckedAt:Z.quotaCheckedAt,mainQuotaToken:Z.quotaToken,mainLastQuotaApiError:Z.lastQuotaApiError}),accounts:X}}async function S($=f()){let C=await W0($),_=await W0(O$($));if(!C.exists&&!_.exists)return null;let K=C.exists?C.value:I();return N6(H6(K,_.value))}async function F6($){let C=await W0($);return U(C.value)?C.value:{}}function U6($){return Object.fromEntries(Object.entries($).filter(([,C])=>C!==void 0))}function V6($){return n({id:$.id,label:$.label,type:$.type,enabled:$.enabled,addedAt:$.addedAt,baseURL:$.type==="api"?$.baseURL:void 0,authHeader:$.type==="api"?$.authHeader:void 0})}function M6($){if($.type==="api")return n({apiKey:$.apiKey,lastUsed:$.lastUsed});return n({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota,profile:$.profile})}function H0($){return Math.max($?.five_hour?.checkedAt??0,$?.seven_day?.checkedAt??0,...$?.scoped?.map((C)=>C.checkedAt)??[],$?.checkedAt??0)}function _0($){if($?.source==="poll")return 2;if($?.source==="headers")return 1;return 0}function f6($,C){if(!("scoped"in $))return C.scoped;if(!Array.isArray($.scoped)||$.scoped.length===0)return $.scoped;if(!Array.isArray(C.scoped)||C.scoped.length===0)return $.scoped;let _=new Map(C.scoped.map((K)=>[K.id,K]));for(let K of $.scoped){let G=_.get(K.id);if(!G||K.checkedAt>=G.checkedAt)_.set(K.id,K)}return[..._.values()]}function G1($,C,_){let K=$[_],G=C[_];if(!G)return K;if(!K)return G;if(G.checkedAt>K.checkedAt)return G;if(G.checkedAt<K.checkedAt)return K;return _0($)>_0(C)?K:G}function H1($,C){if(!$||C.source!=="headers")return C;let _=$.bindingWindowSource==="poll";return{...$,...C,five_hour:G1($,C,"five_hour"),seven_day:G1($,C,"seven_day"),scoped:f6($,C),extraUsage:$.extraUsage??C.extraUsage,bindingWindow:_?$.bindingWindow:C.bindingWindow??$.bindingWindow,bindingWindowSource:_?"poll":C.bindingWindowSource??$.bindingWindowSource}}function b6($,C){if(!U($))return C;let _=$,K=Boolean(_.access&&C.access&&_.access!==C.access||_.refresh&&C.refresh&&_.refresh!==C.refresh),G=Boolean(!K&&C.quota?.source==="headers"),j=G&&C.quota?{...C,quota:H1(_.quota,C.quota)}:C,J=H0(_.quota),Z=H0(j.quota),z=Boolean(J===Z&&_0(_.quota)>_0(j.quota));if(!G&&(J>Z||z)){let Y=_.lastRefreshedAt??0,O=j.lastRefreshedAt??0;if(K&&O<=Y){let W={..._};if(typeof j.lastUsed==="number"&&(typeof _.lastUsed!=="number"||j.lastUsed>_.lastUsed))W.lastUsed=j.lastUsed;return W}let L={..._,...j};if(K){if(!("profile"in j))delete L.profile;if(j.quota?.source)L.quota=j.quota;else delete L.quota;if(!("lastQuotaRefreshError"in j))delete L.lastQuotaRefreshError;if(!("lastRefreshError"in j))delete L.lastRefreshError;return L}return{...L,quota:_.quota,lastQuotaRefreshError:_.lastQuotaRefreshError}}let X={..._,...j};if(K){if(!("profile"in j))delete X.profile;if(!j.quota?.source)delete X.quota}if(!("lastQuotaRefreshError"in j))delete X.lastQuotaRefreshError;if(!("lastRefreshError"in j))delete X.lastRefreshError;return X}function E6($){let C=$.refresh?n({enabled:$.refresh.enabled,intervalMinutes:$.refresh.intervalMinutes,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,_=$.quota?n({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota,showToasts:$.quota.showToasts}):void 0;return U6({version:1,main:{type:"opencode",provider:"anthropic"},routing:$.routing,fallbackOn:$.fallbackOn,refresh:C,quota:_,claudeCache:$.claudeCache,dump:$.dump,logging:$.logging,claudeFast:$.claudeFast,costZeroing:$.costZeroing,cacheKeep:$.cacheKeep,relay:$.relay,killswitch:$.killswitch,accounts:$.accounts.map(V6)})}var j1=Promise.resolve();function N$($){return new Promise((C,_)=>{j1=j1.then(()=>$().then(C,_),()=>$().then(C,_))})}async function L$($,C){await X$(Y$($),{recursive:!0});let _=`${$}.${N0()}.tmp`;await S0(_,`${JSON.stringify(C,null,2)}
3
+ `,{encoding:"utf8",mode:384});try{await O1(_,$)}catch(K){throw await $0(_,{force:!0}).catch(()=>{}),K}}function J1($,C){return $.id===C.id||Boolean($.label&&C.label&&$.label===C.label)}function Q6($,C,_){let K=new Set(_.removedAccountIds??[]),G=$.filter((X)=>!K.has(X.id)),j=C.filter((X)=>!K.has(X.id)),J=G.filter((X)=>!j.some((Y)=>J1(Y,X)));if(!J.length)return[...j];if(_.preserveExistingAccountOrder===!1)return[...j,...J];let Z=new Set,z=G.map((X)=>{let Y=j.findIndex((L,W)=>!Z.has(W)&&J1(L,X)),O=j[Y];if(!O)return X;return Z.add(Y),O});for(let X=0;X<j.length;X++){let Y=j[X];if(!Z.has(X)&&Y)z.push(Y)}return z}var B6=1e4,D6=12000,S6=1e4,R6=12000;async function F1($){let{path:C,name:_,ttlMs:K,waitMs:G,description:j}=$;await X$(Y$(C),{recursive:!0});let J=Date.now()+G;while(!0){let Z=await o({name:_,ttlMs:K,path:C,renew:!0});if(Z)return Z;if(Date.now()>=J)throw Error(`Timed out waiting for the account ${j} lock`);await new Promise((z)=>setTimeout(z,25))}}function U1($){return F1({path:$,name:"config-write",ttlMs:B6,waitMs:D6,description:"configuration write"})}function W$($){return F1({path:$,name:"state-write",ttlMs:S6,waitMs:R6,description:"state write"})}function R($,C=f(),_={}){let K=C;return N$(()=>q6($,K,_))}async function q6($,C,_){let K=await U1(C);try{let G=await S(C),j={...$,accounts:Q6(G?.accounts??[],$.accounts,_)},Z={...await F6(C),...E6(j)};await L$(C,Z);let z=await W$(C);try{await V1(j,C,{mainQuota:!0,mainRefresh:!0,accounts:!0})}finally{await z.release()}}finally{await K.release()}}function A6($,C){$.main=$.main??{},$.main.profile=C.main?.profile}function P6($,C){$.main=$.main??{};let _=C.quota?.mainQuota,K=Boolean($.main.quotaToken&&C.quota?.mainQuotaToken&&$.main.quotaToken===C.quota.mainQuotaToken),G=K&&_?.source==="headers"?H1($.main.quota,_):_,j=Boolean(K&&_?.source==="headers"),J=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:H0($.main.quota),Z=typeof C.quota?.mainQuotaCheckedAt==="number"?C.quota.mainQuotaCheckedAt:H0(G);if(!j&&(J>Z||J===Z&&_0($.main.quota)>_0(G)))return;$.main.quota=G,$.main.quotaCheckedAt=j?Math.max(J,Z):C.quota?.mainQuotaCheckedAt,$.main.quotaToken=C.quota?.mainQuotaToken,$.main.lastQuotaApiError=C.quota?.mainLastQuotaApiError}function I6($,C){$.main=$.main??{},$.main.lastRefreshError=C.refresh?.mainLastRefreshError,$.main.refreshLeaseId=C.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=C.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=C.refresh?.mainRefreshLeaseTokenHash}function q0($){if(Array.isArray($))return $.map(q0);if(!U($))return $;return Object.fromEntries(Object.entries($).filter(([,C])=>C!==void 0).map(([C,_])=>[C,q0(_)]))}function h6($,C=f(),_={mainProfile:!0,mainQuota:!0,mainRefresh:!0,accounts:!0}){let K=C;return N$(async()=>{let G=await W$(K);try{await V1($,K,_)}finally{await G.release()}})}function O2($,C=f()){let _=C;return N$(async()=>{let K=await U1(_);try{let G=await W$(_);try{let j=await S(_),J=O$(_),Z=(await W0(J)).value,z=U(Z)?{...Z,version:1}:{version:1},{accountId:X,expectedTokenFingerprint:Y,profile:O}=$;if(O?.tokenFingerprint&&O.tokenFingerprint!==Y)return!1;if(X==="main"){z.main={...z.main??{}};let L=L0(z.main.profile),W=z.main.profileToken??L?.tokenFingerprint;if(!O&&L&&W===Y)return!1;if(O){if(W&&W!==Y)return!1;if(L&&L.checkedAt>O.checkedAt)return!1}z.main.profile=O,z.main.profileToken=Y}else{let L=j?.accounts.find((V)=>V.id===X&&k(V));if(!L?.access||D(L.access)!==Y)return!1;z.accounts={...U(z.accounts)?z.accounts:{}};let W=U(z.accounts[X])?{...z.accounts[X]}:{},F=L0(W.profile);if(!O&&F?.tokenFingerprint===Y)return!1;if(O&&F&&F.checkedAt>O.checkedAt)return!1;W.profile=O,z.accounts[X]=W}return await L$(J,q0(z)),!0}finally{await G.release()}}finally{await K.release()}})}async function V1($,C,_){let K=O$(C),G=(await W0(K)).value,j=U(G)?{...G,version:1}:{version:1};if(_.mainProfile)A6(j,$);if(_.mainQuota)P6(j,$);if(_.mainRefresh)I6(j,$);if(_.accounts){let J=_.accounts===!0?null:new Set(_.accounts);j.accounts={...U(j.accounts)?j.accounts:{}};for(let Z of $.accounts){if(J&&!J.has(Z.id))continue;j.accounts[Z.id]=b6(j.accounts[Z.id],M6(Z))}if(J){for(let Z of J)if(!$.accounts.some((z)=>z.id===Z))delete j.accounts[Z]}else{let Z=new Set($.accounts.map((z)=>z.id));for(let z of Object.keys(j.accounts))if(!Z.has(z))delete j.accounts[z]}}await L$(K,q0(j))}async function o($){let _=`${$.path??f()}.${$.name}.lock`,K=C0(_,"owner.json"),G=N0(),j=$.now??Date.now,J=null,Z=!1;async function z(){try{return JSON.parse(await D0(_,"utf8"))}catch(W){if(W.code!=="EISDIR")throw W;return JSON.parse(await D0(K,"utf8"))}}async function X(){await S0(_,`${JSON.stringify({ownerId:G,expiresAt:j()+$.ttlMs})}
4
+ `,{encoding:"utf8",mode:384})}async function Y(){try{return await S0(_,`${JSON.stringify({ownerId:G,expiresAt:j()+$.ttlMs})}
5
+ `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(W){let F=W.code;if(F==="EEXIST"||F==="EISDIR")return!1;throw W}}function O(){if(!$.renew||Z)return;let W=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(J=uC(()=>{(async()=>{try{let F=await z(),V=j();if(Z||F?.ownerId!==G||Number(F?.expiresAt)<=V)return;await X(),O()}catch{}})()},W),"unref"in J)J.unref()}let L=await Y();if(!L){let W=`${_}.evicting`,F=C0(W,"owner.json"),V=N0(),E=5000,N=8;async function x(){await new Promise((q)=>setTimeout(q,Math.floor(Math.random()*4)))}async function u(){try{let q=await z();return Number(q?.expiresAt)>j()}catch{try{return(await t$(_)).mtimeMs+$.ttlMs>j()}catch{return!1}}}async function T(){try{return JSON.parse(await D0(F,"utf8"))?.ownerId===V}catch{return!1}}async function H(){await X$(W);try{await S0(F,`${JSON.stringify({ownerId:V,createdAt:j()})}
6
+ `,{encoding:"utf8",mode:384,flag:"wx"})}catch(q){let i=q.code;if(i==="ENOENT"||i==="EINVAL")return!1;throw await M(),q}return await $.onStep?.("eviction-marker-acquired"),!0}async function M(){if(await T())await $0(W,{recursive:!0,force:!0}).catch(()=>{})}for(let q=0;q<8;q++){if(L=await Y(),L)break;if(await u())return null;try{if(!await H()){await x();continue}}catch(i){if(i.code!=="EEXIST")throw i;let E0;try{E0=await t$(W)}catch(w){if(w.code==="ENOENT"){await x();continue}throw w}if(E0.mtimeMs+5000>j())return null;await $.onStep?.("stale-marker-stat");let l=`${W}.${N0()}`;try{await O1(W,l)}catch(w){if(w.code==="ENOENT"){await x();continue}throw w}await $.onStep?.("stale-marker-claimed"),await $0(l,{recursive:!0,force:!0}).catch(()=>{}),await x();continue}try{if(await u())return null;if(!await T())return null;if(await $.onStep?.("stale-lock-confirmed"),!await T())return null;if(await $0(_,{recursive:!0,force:!0}).catch(()=>{}),!await T())return null;if(L=await Y(),!L)return null;if(!await T())return await $0(_,{recursive:!0,force:!0}).catch(()=>{}),L=!1,null;break}finally{await M()}}}if(!L)return null;return O(),{release:async()=>{if(Z=!0,J)iC(J),J=null;try{if((await z())?.ownerId!==G)return}catch{return}await $0(_,{recursive:!0,force:!0}).catch(()=>{})}}}function N2($){return $?.claudeCache?.enabled===!0}function T6($){return typeof $==="string"&&s$.includes($)?$:B0}function w6($){return T6($?.claudeCache?.mode)}async function L2($,C,_=f()){let K=await S(_)??I();return K.claudeCache={...K.claudeCache??{},enabled:$,mode:C??w6(K)},await R(K,_),K}async function W2($,C=f()){let _=await S(C)??I();return _.claudeCache={..._.claudeCache??{},enabled:_.claudeCache?.enabled===!0,mode:$},await R(_,C),_}function H2($){return $?.dump?.enabled===!0}async function F2($,C=f()){let _=await S(C)??I();return _.dump={..._.dump??{},enabled:$},await R(_,C),_}function U2($){return $?.claudeFast?.enabled===!0}async function V2($,C=f()){let _=await S(C)??I();return _.claudeFast={..._.claudeFast??{},enabled:$},await R(_,C),_}async function M2($,C,_=f()){let K=await S(_)??I();return K.cacheKeep={...K.cacheKeep??{},enabled:!0,always:!1,startHour:$,endHour:C},await R(K,_),K}async function f2($=f()){let C=await S($)??I();return C.cacheKeep={...C.cacheKeep??{},enabled:!0,always:!0},delete C.cacheKeep.startHour,delete C.cacheKeep.endHour,await R(C,$),C}async function b2($,C=f()){let _=await S(C)??I();return _.cacheKeep={..._.cacheKeep??{},enabled:$},await R(_,C),_}function E2($){return $?.cacheKeep?.subagents===!0}async function Q2($,C=f()){let _=await S(C)??I();return _.cacheKeep={..._.cacheKeep??{},subagents:$},await R(_,C),_}function x6($){return $?.fallbackOn?.length?$.fallbackOn:nC}function B2($,C){return x6(C).includes($)}function I0($){let C=$?.quota?.minimumRemaining||{};return{five_hour:C.five_hour??C["5h"]??e$.five_hour,seven_day:C.seven_day??C["1w"]??e$.seven_day}}function F0($){return $?.quota?.enabled!==!1}function k6($){return $?.refresh?.enabled!==!1}function y6($){return Math.floor(Math.random()*Math.max(0,$))}function m6($){let C=$?.refresh?.refreshBeforeExpiryMinutes??oC;return Math.max(L1,C)*60000}function M1($){return Y1("sha256").update($).digest("hex")}function v6($){let C=$.status;if(typeof C==="number"&&Number.isFinite(C))return C===429||C>=500;if(!($ instanceof Error))return!1;return $.message.includes("fetch failed")||"code"in $&&($.code==="ECONNRESET"||$.code==="ECONNREFUSED"||$.code==="ETIMEDOUT"||$.code==="UND_ERR_CONNECT_TIMEOUT")}function l6($){let C=M1($.refreshToken),K=($.previous?.tokenHash===C?$.previous.retryCount??0:0)+1,G=$.error.retryAfter,j;if(typeof G==="number"&&G>0)j=G*1000;else if(v6($.error))j=Math.min(tC,aC*2**Math.min(K-1,6));else j=W1;let J=$.error.status,Z=typeof J==="number"&&Number.isFinite(J)?J:void 0,z=G0($.error),Y=(typeof $.error.body==="string"?$.error.body:"").includes("invalid_grant")||z.includes("invalid_grant");return{message:z,checkedAt:$.now,nextRetryAt:$.now+j,retryCount:K,tokenHash:C,status:Z,permanent:Z===400&&Y}}function D2($){if(!$)return!1;if(typeof $.permanent==="boolean")return $.permanent;if(typeof $.status==="number")return $.status===400;if(typeof $.nextRetryAt==="number")return $.nextRetryAt-$.checkedAt>=W1;return!1}function O0($,C,_){if(!$?.nextRetryAt||$.nextRetryAt<=_)return!1;if(!C)return!0;return $.tokenHash===M1(C)}function J$($,C){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??C)-C)/1000))}s after: ${$.message}`}function H$($){if($.status===403)return!0;return/Claude quota check failed: 403\b/.test(G0($))}function h0($){let _=($.previous?.retryCount??0)+1,K=B1($.error)?Math.min($6,eC*2**Math.min(_-1,6)):C6;return{message:G0($.error),checkedAt:$.now,nextRetryAt:$.now+K,retryCount:_}}function K0($,C){if(!$?.nextRetryAt||$.nextRetryAt<=C)return!1;return!0}function S2($,C){return`Quota API backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??C)-C)/1000))}s after: ${$.message}`}function m($){let C=$?.quota?.checkIntervalMinutes??_6;return Math.max(1,C)*60000}function R2($){return $?.logging?.level}async function q2($,C=f()){let{setLogLevel:_}=await import("./logger-whpn7rjx.js"),K=await S(C)??I();K.logging={...K.logging??{},level:$},await R(K,C),_($)}function f1($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function b1($){let C=$?.quota?.refreshEveryNRequests;return typeof C==="number"&&Number.isFinite(C)&&C>0?Math.floor(C):0}function A0($){return $?.quota?.failClosedOnUnknownQuota??K6}function p6($){if(typeof $!=="string")return null;let C=$.toLowerCase();if(C.includes("fable"))return"fable";if(C.includes("mythos"))return"mythos";return null}function y($,C){let _=p6(C);if(!_)return;return $?.scoped?.find((K)=>{return[K.modelId,K.modelName,K.title].filter((j)=>typeof j==="string").join(" ").toLowerCase().includes(_)})}function g6($,C){let _=y($,C);return Boolean(_&&Number.isFinite(_.remainingPercent)&&_.remainingPercent<=0)}function Z1($,C){return!g6($,C)}function E1($,C){if(!F0(C))return!0;let _=I0(C);for(let K of["five_hour","seven_day"]){let G=$?.[K];if(!G)return!A0(C);if(!Number.isFinite(G.remainingPercent))return!A0(C);if(G.remainingPercent<_[K])return!1}return!0}var s={five_hour:5,seven_day:10,scoped:0};function U0($){let C=$?.five_hour??$?.["5h"],_=$?.seven_day??$?.["1w"],K=$?.scoped;return{five_hour:typeof C==="number"&&Number.isFinite(C)?C:s.five_hour,seven_day:typeof _==="number"&&Number.isFinite(_)?_:s.seven_day,scoped:typeof K==="number"&&Number.isFinite(K)?K:s.scoped}}function F$($){return $?.killswitch?.enabled===!0}function U$($,C){if(!$?.killswitch)return s;if(C&&$.killswitch.accounts?.[C])return U0($.killswitch.accounts[C]);return U0($.killswitch.main)}function A2($,C,_,K){if(!F$(C))return!0;let G=U$(C,_),j=!1;for(let J of["five_hour","seven_day"]){let Z=$?.[J];if(!Z){j=!0;continue}if(!Number.isFinite(Z.remainingPercent)){j=!0;continue}if(Z.remainingPercent<G[J])return!1}if(K){let J=y($,K);if(J&&Number.isFinite(J.remainingPercent)&&J.remainingPercent<=G.scoped)return!1}if(j)return!A0(C);return!0}function P2($,C,_,K){let G=[],j=[$,...C.map((J)=>J.quota)];for(let J of j)if(K){let z=y(J,K)?.resetsAt;if(!z)continue;let X=Date.parse(z);if(Number.isFinite(X)&&X>_)G.push(X)}else for(let Z of["five_hour","seven_day"]){let z=J?.[Z]?.resetsAt;if(!z)continue;let X=Date.parse(z);if(Number.isFinite(X)&&X>_)G.push(X)}if(!G.length)return 300;return Math.max(1,Math.ceil((Math.min(...G)-_)/1000))+60}function I2($){return $?.killswitch??{enabled:!1}}async function h2($,C=f()){let _=await S(C)??I();return _.killswitch=$,await R(_,C),_}async function T2($,C=f()){let _=await S(C);if(!_)return!1;let K=o6(_,$);if(K)await R(_,C,{removedAccountIds:[$]});return K}async function w2($,C=f()){let _=await S(C);if(!_)return;a6(_,$),await R(_,C,{preserveExistingAccountOrder:!1})}async function x2($,C,_=f()){let K=await S(_);if(!K)return!1;let G=t6(K,$,C);if(G)await R(K,_);return G}async function k2($,C=f()){let _=await S(C)??I();n6(_,$),await R(_,C)}function j0($,C,_){let K=m(C);if(!F0(C))return _+K;let G=Math.min(...[...["five_hour","seven_day"].map((z)=>$?.[z]?.checkedAt),...($?.scoped??[]).map((z)=>z.checkedAt)].filter((z)=>Number.isFinite(z)).map((z)=>z+K)),j=(z)=>Number.isFinite(G)?Math.min(z,G):z,J=I0(C),Z=[];for(let z of["five_hour","seven_day"]){let X=$?.[z];if(!X)return j(_+K);if(X.remainingPercent>=J[z])continue;let Y=X.resetsAt?Date.parse(X.resetsAt):Number.NaN;if(!Number.isFinite(Y)||Y<=_)return j(_+K);Z.push(Y)}if(!Z.length)return j(_+K);return j(Math.min(...Z)+60000)}function c($,C,_){return!$.access||!$.expires||$.expires-_<=m6(C)}function Q1($,C,_){if(!F0(C))return!0;let K=m(C);return["five_hour","seven_day"].every((G)=>{let j=$?.[G];return Boolean(j&&_-j.checkedAt<K)})}function Z$($,C,_,K){if(!Q1($.quota,C,_))return!0;let G=y($.quota,K);return Boolean(G&&_-G.checkedAt>=m(C))}function d6($,C){if(!$)return!1;if(!$.resetsAt)return!0;let _=Date.parse($.resetsAt);return!Number.isFinite(_)||_>C}function u6($,C){return["five_hour","seven_day"].every((_)=>d6($?.[_],C))}function B1($){let C=$.status;if(typeof C==="number"&&Number.isFinite(C)){if(C===429||C>=500)return!0}let _=G0($);if(/Claude quota check failed: (429|5\d\d)\b/.test(_))return!0;if(_.includes("Quota refresh is already in progress"))return!0;if(!($ instanceof Error))return!1;let{message:K,code:G}=$;return K.includes("fetch failed")||G==="ECONNRESET"||G==="ECONNREFUSED"||G==="ETIMEDOUT"||G==="UND_ERR_CONNECT_TIMEOUT"}function i6($,C,_,K){return B1(_)&&E1($.quota,C)&&u6($.quota,K)}function P0($){if(!Number.isFinite($))return 0;if($<0)return 0;if($>100)return 100;return $}function g($){return typeof $==="string"&&$.trim()?$.trim():void 0}function D1($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function c6($,C){if(!Array.isArray($))return[];let _=new Set,K=[];for(let G of $){if(G?.kind!=="weekly_scoped"||G.group!=="weekly")continue;if(typeof G.percent!=="number"||!Number.isFinite(G.percent))continue;let j=g(G.scope?.model?.display_name);if(!j)continue;let J=g(G.scope?.model?.id)??j,Z=D1(J);if(!Z)continue;let z=`claude-weekly-scoped-${Z}`;if(_.has(z))continue;_.add(z);let X=P0(G.percent),Y=g(G.scope?.model?.id);K.push({id:z,title:`${j} only`,...Y&&{modelId:Y},modelName:j,usedPercent:X,remainingPercent:P0(100-X),resetsAt:G.resets_at,checkedAt:C})}return K}function r6($){if($.extra_usage?.is_enabled!==!0)return;let C=$.extra_usage.used_credits,_=$.extra_usage.monthly_limit;if(typeof C!=="number"||!Number.isFinite(C)||typeof _!=="number"||!Number.isFinite(_))return;let K=$.spend?.limit?.currency,G=K==null?"USD":g(K),j=$.spend?.limit?.exponent,J=j==null?2:j;if(!G||!/^[A-Za-z]{3}$/.test(G)||!Number.isInteger(J)||J<0||J>20)return;return{used:{amountMinor:C,currency:G,exponent:J},limit:{amountMinor:_,currency:G,exponent:J},...typeof $.extra_usage.utilization==="number"&&Number.isFinite($.extra_usage.utilization)&&{utilizationPercent:$.extra_usage.utilization},...g($.spend?.severity)&&{severity:g($.spend?.severity)},exhausted:C>=_}}function s6($){if(!Array.isArray($))return;let C=$.find((j)=>j?.is_active===!0);if(!C)return;if(C.kind==="session")return"five_hour";if(C.kind==="weekly_all")return"seven_day";if(C.kind!=="weekly_scoped"||C.group!=="weekly")return;let _=g(C.scope?.model?.display_name);if(!_)return;let K=g(C.scope?.model?.id)??_,G=D1(K);return G?`claude-weekly-scoped-${G}`:void 0}function z1($,C){if(typeof $?.utilization!=="number")return;if(!Number.isFinite($.utilization))return;let _=P0($.utilization);return{usedPercent:_,remainingPercent:P0(100-_),resetsAt:$.resets_at,checkedAt:C}}async function T0($){let _=await($.fetchImpl??fetch)(rC,{method:"GET",headers:{Authorization:`Bearer ${$.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${p}`}});if(!_.ok){let J=await _.text().catch(()=>"");throw Object.assign(Error(`Claude quota check failed: ${_.status} — ${J}`),{status:_.status,retryAfter:j$(_.headers.get("Retry-After"))})}let K=$.now?.()??Date.now(),G=await _.json(),j=s6(G.limits);return{five_hour:z1(G.five_hour,K),seven_day:z1(G.seven_day,K),scoped:c6(G.limits,K),extraUsage:r6(G),...j&&{bindingWindow:j,bindingWindowSource:"poll"},source:"poll",checkedAt:K}}function A($,C){let _=$.accounts.findIndex((K)=>K.id===C.id);if(_>=0)$.accounts[_]=C}function n6($,C){let _=$.accounts.findIndex((K)=>K.id===C.id||C.label&&K.label===C.label);if(_>=0){$.accounts[_]={...$.accounts[_],...C,addedAt:$.accounts[_]?.addedAt??C.addedAt,...C.type==="oauth"&&{quota:C.quota,profile:C.profile,lastRefreshedAt:C.lastRefreshedAt,lastRefreshError:C.lastRefreshError,lastQuotaRefreshError:C.lastQuotaRefreshError}};return}$.accounts.push(C)}function o6($,C){let _=$.accounts.findIndex((K)=>K.id===C);if(_<0)return!1;return $.accounts.splice(_,1),!0}function a6($,C){let _=new Map(C.map((j,J)=>[j,J])),K=$.accounts.filter((j)=>_.has(j.id)),G=$.accounts.filter((j)=>!_.has(j.id));K.sort((j,J)=>(_.get(j.id)??0)-(_.get(J.id)??0)),$.accounts=[...K,...G]}function t6($,C,_){let K=$.accounts.find((G)=>G.id===C);if(!K)return!1;return K.enabled=_,!0}function G0($){return $ instanceof Error?$.message:String($)}function S1($,C,_){$.lastRefreshError=l6({error:C,now:_,refreshToken:$.refresh,previous:$.lastRefreshError})}function X1($,C,_){if(H$(C))return;if($.lastQuotaRefreshError=h0({error:C,now:_,previous:$.lastQuotaRefreshError}),C.isRefreshError)S1($,C,_)}function e6($){return`fallback-oauth-refresh-${Y1("sha256").update($).digest("hex").slice(0,16)}`}class $_{now;fetchImpl;configPath;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;constructor($={}){this.now=$.now??Date.now,this.fetchImpl=$.fetchImpl??fetch,this.configPath=$.configPath??f(),this.quotaManager=$.quotaManager??null,this.onFallbackStorageChanged=$.onFallbackStorageChanged}seedFallbackQuota($,C){if(!this.quotaManager)return;if(!$.quota)return;let _=Math.max($.quota.five_hour?.checkedAt??0,$.quota.seven_day?.checkedAt??0);if(_<=0)return;let K=this.quotaManager.getFallback($.id,$.access);if(K&&K.checkedAt>=_)return;let G=m(C);this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:_+G,checkedAt:_},$.access)}async load(){return S(this.configPath)}async save($,C){await h6($,this.configPath,{accounts:C??!0})}startBackgroundRefresh(){let $=async()=>{await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()};if($().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{$().catch(()=>{})},G6+y6(j6)),"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($,C={}){let _=$!==void 0?$:await this.load();if(!_)return[];let K=[],G=!1;for(let j of _.accounts){if(j.enabled===!1||!k(j))continue;try{let J=j;if(c(J,_,this.now())){let z=J.lastRefreshError;if(z&&O0(z,J.refresh,this.now()))throw Error(J$(z,this.now()));J=await this.refreshAccount(J,_),G=!0}if(this.seedFallbackQuota(J,_),(this.quotaManager?this.quotaManager.isFallbackStale(J.id,J.access,C.modelId):Z$(J,_,this.now(),C.modelId))&&!K0(J.lastQuotaRefreshError,this.now()))J=await this.refreshAccountQuota(J,_),G=!0;if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount(J),_,{modelId:C.modelId}))K.push(J)}catch(J){if(i6(j,_,J,this.now())){if(r("[refresh] fallback quota using cached quota after refresh error",{accountId:j.id,error:G0(J)}),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(j),_,{modelId:C.modelId}))K.push(j)}else if(!A0(_)&&Z1(j.quota,C.modelId))K.push(j)}}if(G)await this.save(_);return K}async markUsed($){let C=await this.load();if(!C)return;let _=C.accounts.find((K)=>K.id===$.id);if(!_)return;_.lastUsed=this.now(),await this.save(C)}accountPassesQuotaPolicy($,C,_={}){return E1($.quota,C)&&Z1($.quota,_.modelId)}quotaPolicyAccount($){if(!this.quotaManager)return $;let C=this.quotaManager.getFallback($.id,$.access)?.quota;return C?{...$,quota:C}:$}async refreshDueAccounts(){let $=await this.load();if(!$||!k6($))return;let C=!1;for(let _ of $.accounts){if(_.enabled===!1||!k(_))continue;if(!c(_,$,this.now()))continue;if(O0(_.lastRefreshError,_.refresh,this.now()))continue;try{r("[refresh] fallback oauth background due",{accountId:_.id,expiresInMs:_.expires?_.expires-this.now():void 0}),await this.refreshAccount(_,$),C=!0}catch(K){P.warn("refresh","fallback oauth background failed",{accountId:_.id,error:K instanceof Error?K.message:String(K)}),S1(_,K,this.now()),A($,_),C=!0}}if(C)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!F0($))return;let C=!1;for(let _ of $.accounts){if(_.enabled===!1||!k(_))continue;let K=_;try{if(c(K,$,this.now())){if(O0(K.lastRefreshError,K.refresh,this.now()))continue;K=await this.refreshAccount(K,$),C=!0}if(K0(K.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(K,$),!(this.quotaManager?this.quotaManager.isFallbackStale(K.id,K.access):Z$(K,$,this.now())))continue;await this.refreshAccountQuota(K,$),C=!0}catch(G){X1(_,G,this.now()),A($,_),C=!0}}if(C)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let C=await this.load(),_=[];if(!C||!F0(C))return{storage:C,errors:_};let K=$.force??!1,G=!1;for(let j of C.accounts){if(j.enabled===!1||!k(j))continue;let J=j;try{if(c(J,C,this.now())){let Z=J.lastRefreshError;if(Z&&O0(Z,J.refresh,this.now()))throw Error(J$(Z,this.now()));J=await this.refreshAccount(J,C),G=!0}if(!K&&!Z$(J,C,this.now())){if(J.lastQuotaRefreshError)J.lastQuotaRefreshError=void 0,A(C,J),G=!0;continue}await this.refreshAccountQuota(J,C),G=!0}catch(Z){X1(j,Z,this.now()),A(C,j),G=!0,_.push({accountId:j.id,message:G0(Z)})}}if(G)await this.save(C);return{storage:C,errors:_}}async refreshAccount($,C,_={}){let K=this.refreshPromises.get($.id);if(K){let J=await K;return A(C,J),J}let G=this.refreshAccountNow($,C,_).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,G);let j=await G;return A(C,j),j}async waitForConcurrentFallbackRefresh($,C,_,K){let G=Date.now()+Z6;while(Date.now()<G){await new Promise((X)=>setTimeout(X,z6));let j=await this.load(),J=j?.accounts.find((X)=>X.id===$.id&&k(X));if(!J)continue;if((J.access!==_.access||J.refresh!==_.refresh||(J.expires??0)>(_.expires??0)+60000)&&(K.force||!c(J,j,this.now())))return A(C,J),r("[refresh] fallback oauth joined concurrent refresh",{accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J;let z=J.lastRefreshError;if(z&&O0(z,J.refresh,this.now()))throw A(C,J),Error(J$(z,this.now()))}return null}async refreshAccountNow($,C,_){let K=await this.load(),G=K?.accounts.find((Z)=>Z.id===$.id&&k(Z));if(G&&!_.force&&!c(G,K,this.now()))return A(C,G),G;let j=G??$,J=await o({name:e6(j.id),ttlMs:J6,path:this.configPath,now:this.now,renew:!0});if(!J){r("[refresh] fallback oauth refresh skipped file lock",{accountId:j.id});let Z=await this.waitForConcurrentFallbackRefresh($,C,j,_);if(Z)return Z;throw Error("Fallback OAuth refresh is already in progress")}try{if(K=await this.load(),G=K?.accounts.find((X)=>X.id===$.id&&k(X)),G&&!_.force&&!c(G,K,this.now()))return A(C,G),G;j=G??j;let Z=j.refresh;r("[refresh] fallback oauth refresh request start",{accountId:j.id,force:_.force===!0,expiresInMs:j.expires?j.expires-this.now():void 0});let z=await a$({refreshToken:Z,fetchImpl:this.fetchImpl,now:this.now});return j.access=z.access,j.refresh=z.refresh,j.expires=z.expires,j.lastRefreshedAt=z.expires-z.expiresIn*1000,j.lastRefreshError=void 0,A(C,j),await this.save(C),r("[refresh] fallback oauth refresh succeeded",{accountId:j.id,expiresInMs:j.expires?j.expires-this.now():void 0}),j}finally{await J.release()}}async refreshAccountQuota($,C){let _=$;if(!_.access)throw Error(`Fallback account ${$.id} has no access token`);let K=(Z)=>this.quotaManager?this.quotaManager.refreshFallback(_.id,Z):T0({accessToken:Z,fetchImpl:this.fetchImpl,now:this.now}),G=this.now();try{_.quota=await K(_.access)}catch(Z){if(!(Z instanceof Error?Z.message:String(Z)).includes("Claude quota check failed: 401"))throw Z;if(_=await this.refreshAccount($,C,{force:!0}),!_.access)throw Z;_.quota=await K(_.access)}let j=await this.load(),J=j?.accounts.find((Z)=>Z.id===_.id&&k(Z));if(j&&J&&J.access!==_.access)return this.seedFallbackQuota(J,j),A(C,J),J;if(j&&J?.access===_.access&&J.quota&&H0(J.quota)>=G&&Q1(J.quota,j,this.now()))return this.seedFallbackQuota(J,j),A(C,J),J;if(_.lastQuotaRefreshError=void 0,A(C,_),this.quotaManager&&_.quota){let Z=this.now();this.quotaManager.setFallback(_.id,{quota:_.quota,refreshAfter:Z+m(C),checkedAt:Z},_.access)}return _}}var v2="claude-cache",R1="## Claude Cache Status",C_="## Claude Cache Enabled",__="## Claude Cache Disabled",K_="## Claude Cache Usage",G_="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",w0=!1,x0=B0;function l2(){return w0}function p2(){return x0}function g2($){w0=$.enabled,x0=$.mode}function j_($){let C=$.trim().split(/\s+/).filter(Boolean);if(C.length===0)return{type:"status"};if(C.length===1&&C[0]==="on")return{type:"enable"};if(C.length===1&&C[0]==="off")return{type:"disable"};if(C.length===2&&C[0]==="mode"&&(C[1]==="explicit"||C[1]==="automatic"||C[1]==="hybrid"))return{type:"mode",mode:C[1]};return{type:"usage"}}function V0($){let C=$?.enabled??w0,_=$?.mode??x0;return[R1,"",`- Enabled: ${C?"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 d2($){let C=j_($.argumentsText),_=$.enabled??w0,K=$.mode??x0;if(C.type==="status")return V0({enabled:_,mode:K});if(C.type==="enable")return[C_,"",V0({enabled:!0,mode:K})].join(`
8
+ `);if(C.type==="disable")return[__,"",V0({enabled:!1,mode:K})].join(`
9
+ `);if(C.type==="mode")return[R1,"",`Mode updated to \`${C.mode}\`.`,"",V0({enabled:_,mode:C.mode})].join(`
10
+ `);return[K_,"",G_,"",V0({enabled:_,mode:K})].join(`
11
+ `)}import{randomBytes as J_,randomUUID as P1}from"node:crypto";var Z_=1000,a=new Map;function M0($,C,_){if(!$.has(C)&&$.size>=Z_){let K=$.keys().next().value;if(K!==void 0)$.delete(K)}$.set(C,_)}function I1($){let C=$||"anonymous",_=a.get(C);if(_)return _;let K={deviceId:J_(32).toString("hex"),sessionId:P1()};return M0(a,C,K),K}var z_=86400000,X_=300000,V$=new Map,q1=new Map;async function Y_($,C){if(!$.startsWith("sk-ant-oat"))return null;let _=new AbortController,K=setTimeout(()=>_.abort(),5000);try{let G=new URL("https://api.anthropic.com/api/claude_cli/bootstrap");if(G.searchParams.set("entrypoint",u$),C)G.searchParams.set("model",C);let j=await fetch(G,{method:"GET",headers:{accept:"application/json, text/plain, */*",authorization:`Bearer ${$}`,"content-type":"application/json","anthropic-beta":"oauth-2025-04-20","user-agent":`claude-code/${p}`},signal:_.signal});if(!j.ok)return null;let Z=(await j.json().catch(()=>null))?.oauth_account?.account_uuid;return typeof Z==="string"&&Z?Z:null}catch{return null}finally{clearTimeout(K)}}async function r2($,C){let _=I1($);if(!$.startsWith("sk-ant-oat"))return _;let K=Date.now(),G=q1.get($);if(G&&G.expiresAt>K){if(!G.accountUuid)return _;let X=`account:${G.accountUuid}`,Y=a.get(X);if(Y)return M0(a,$,Y),Y}let j=V$.get($);if(!j)j=Y_($,C),V$.set($,j);let J=await j.finally(()=>{V$.delete($)});if(M0(q1,$,{accountUuid:J,expiresAt:K+(J?z_:X_)}),!J)return _;let Z=`account:${J}`,z=a.get(Z);if(z)return M0(a,$,z),z;return _.accountUuid=J,M0(a,Z,_),_}function t($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function O_($){if(!$.accountUuid)return null;return JSON.stringify({device_id:$.deviceId,account_uuid:$.accountUuid,session_id:$.sessionId})}function s2($,C){let _=O_(C);if(!_){if(t($.metadata))delete $.metadata.user_id;return!1}if(!t($.metadata))$.metadata={};let K=$.metadata;if(t(K))K.user_id=_;return!0}var N_=["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"],L_=["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"],A1=["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 W_($){return $.output_config?.format?.type==="json_schema"}function H_($){return Array.isArray($.tools)&&$.tools.length>0&&Array.isArray($.system)&&t($.thinking)&&t($.context_management)&&t($.output_config)&&t($.diagnostics)}function F_($,C=[]){let _=$?H_($)?[...N_]:W_($)?[...L_]:[...A1]:[...A1];if($?.speed==="fast")_.push(d$);for(let K of C){let G=K.trim();if(G)_.push(G)}return[...new Set(_)].join(",")}function U_(){switch(process.platform){case"darwin":return"MacOS";case"win32":return"Windows";case"linux":return"Linux";case"freebsd":return"FreeBSD";default:return"Unknown"}}function V_(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";case"ia32":return"x32";default:return process.arch}}function n2($,C,_={}){let K=_.identity??I1(C),j=[...($.get("anthropic-beta")??"").split(",").map((J)=>J.trim()).filter(Boolean),..._.extraBetas??[]];return $.set("accept","application/json"),$.set("authorization",`Bearer ${C}`),$.set("content-type","application/json"),$.set("user-agent",r$),$.set("anthropic-beta",F_(_.body,j)),$.set("anthropic-dangerous-direct-browser-access","true"),$.set("anthropic-version","2023-06-01"),$.set("x-app","cli"),$.set("x-client-request-id",P1()),$.set("x-claude-code-session-id",K.sessionId),$.set("x-stainless-arch",V_()),$.set("x-stainless-lang","js"),$.set("x-stainless-os",U_()),$.set("x-stainless-package-version",i$),$.set("x-stainless-retry-count","0"),$.set("x-stainless-runtime","node"),$.set("x-stainless-runtime-version",c$),$.set("x-stainless-timeout","600"),$.delete("x-api-key"),$}var M_=["model","messages","system","tools","tool_choice","metadata","max_tokens","temperature","thinking","context_management","output_config","diagnostics","stream","speed"];function h1($){let C={};for(let _ of M_)if(Object.hasOwn($,_))C[_]=$[_];for(let[_,K]of Object.entries($))if(!Object.hasOwn(C,_))C[_]=K;return C}import{createHash as b_}from"node:crypto";var f_=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 T1(){return function($){let{exports:{mem:C,xxh32:_,xxh64:K,init32:G,update32:j,digest32:J,init64:Z,update64:z,digest64:X}}=$,Y=new Uint8Array(C.buffer);function O(H,M){if(C.buffer.byteLength<H+M){let q=Math.ceil((H+M-C.buffer.byteLength)/65536);C.grow(q),Y=new Uint8Array(C.buffer)}}function L(H,M,q,i,v$,E0){O(H);let l=new Uint8Array(H);return Y.set(l),q(0,M),l.set(Y.subarray(0,H)),{update(w){let e0;return Y.set(l),typeof w=="string"?(O(3*w.length,H),e0=E.encodeInto(w,Y.subarray(H)).written):(O(w.byteLength,H),Y.set(w,H),e0=w.byteLength),i(0,H,e0),l.set(Y.subarray(0,H)),this},digest:()=>(Y.set(l),E0(v$(0)))}}function W(H){return H>>>0}let F=2n**64n-1n;function V(H){return H&F}let E=new TextEncoder,N=0,x=0n;function u(H,M=N){return O(3*H.length,0),W(_(0,E.encodeInto(H,Y).written,M))}function T(H,M=x){return O(3*H.length,0),V(K(0,E.encodeInto(H,Y).written,M))}return{h32:u,h32ToString:(H,M=N)=>u(H,M).toString(16).padStart(8,"0"),h32Raw:(H,M=N)=>(O(H.byteLength,0),Y.set(H),W(_(0,H.byteLength,M))),create32:(H=N)=>L(48,H,G,j,J,W),h64:T,h64ToString:(H,M=x)=>T(H,M).toString(16).padStart(16,"0"),h64Raw:(H,M=x)=>(O(H.byteLength,0),Y.set(H),V(K(0,H.byteLength,M))),create64:(H=x)=>L(88,H,Z,z,X,V)}}((await WebAssembly.instantiate(f_)).instance)}var E_=0x6e52736ac806831en,Q_="cch=00000;";var f$=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=([0-9a-f]{5});/,B_=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=00000;/,w1=null,M$=null;async function D_(){if(M$)return;w1??=(async()=>{M$=(await T1()).h64Raw})(),await w1}async function S_($){return await D_(),((M$?.($,E_)??0n)&0xfffffn).toString(16).padStart(5,"0")}function R_($){return $.replace(f$,`$1${Q_}`)}function x1($){return f$.exec($)?.[2]??null}async function k1($){if(!f$.test($))return $;let C=R_($),_=await S_(new TextEncoder().encode(C));return C.replace(B_,`$1cch=${_};`)}function q_($=p,C=new Date){if($===p)return K$;return b_("sha256").update($).digest("hex").slice(0,3)}function C4($,C=p,_,K=new Date){let G=q_(C,K);return`x-anthropic-billing-header: cc_version=${C}.${G}; cc_entrypoint=${_}; cch=00000;`}var J4="claude-cachekeep",b$=3600000,k0=300000,A_=60000,Z4="extended-cache-ttl-2025-04-11",P_=32,y1=16777216,I_=2*b$,h_=30000,m1="## Claude Cache Keep Status",v1="## Claude Cache Keep Enabled",T_="## Claude Cache Keep Disabled",w_="## Claude Cache Keep Usage",x_="Usage: `/claude-cachekeep`, `/claude-cachekeep always`, `/claude-cachekeep off`, or `/claude-cachekeep HH-HH`.";function y0($){return String($).padStart(2,"0")}function k_($){let C=$.trim();if(!C)return{type:"status"};if(C==="off")return{type:"disable"};if(C==="always")return{type:"always"};if(C==="subagents on")return{type:"subagents",enabled:!0};if(C==="subagents off")return{type:"subagents",enabled:!1};let _=/^(\d{1,2})-(\d{1,2})$/.exec(C);if(!_)return{type:"usage"};let K=Number(_[1]),G=Number(_[2]);if(!Number.isInteger(K)||!Number.isInteger(G)||K<0||K>23||G<0||G>23||K===G)return{type:"usage"};return{type:"window",startHour:K,endHour:G}}function m0($){let C=Number($?.cacheKeep?.startHour),_=Number($?.cacheKeep?.endHour);if(!Number.isInteger(C)||!Number.isInteger(_)||C<0||C>23||_<0||_>23||C===_)return;return{startHour:C,endHour:_}}function v0($){return $?.cacheKeep?.enabled===!0&&$.cacheKeep.always===!0}function d1($){return $?.cacheKeep?.enabled===!0&&(v0($)||!!m0($))}function y_($){return d1($)&&$?.claudeCache?.enabled===!0&&$.claudeCache.mode==="hybrid"}function m_($,C=new Date){if(!$)return!1;let _=C.getHours();if($.startHour<$.endHour)return _>=$.startHour&&_<$.endHour;return _>=$.startHour||_<$.endHour}function l1($,C=new Date){if($?.cacheKeep?.enabled!==!0)return!1;return v0($)||m_(m0($),C)}function p1($=new Date){return`${$.getFullYear()}-${y0($.getMonth()+1)}-${y0($.getDate())}`}function u1($,C=new Date){if($&&$.startHour>$.endHour&&C.getHours()<$.endHour){let _=new Date(C);return _.setDate(_.getDate()-1),p1(_)}return p1(C)}function g1($,C,_=new Date){return v0($)?"always":u1(C,_)}function J0($){let C=$.always?"always (while this process is running)":$.window?`${y0($.window.startHour)}-${y0($.window.endHour)}`:"not configured",_=[`Cache keep: ${$.enabled?"enabled":"disabled"}`,`Schedule: ${C}`,"Mode requirement: `/claude-cache mode hybrid` must be active."];if(typeof $.hybridActive==="boolean")_.push(`Hybrid active: ${$.hybridActive?"yes":"no"}`);if(typeof $.trackedSessions==="number")_.push(`Tracked sessions: ${$.trackedSessions}`);if($.trackedSessionDetails?.length){_.push("Sessions:");for(let K of $.trackedSessionDetails)_.push(`- ${K.id}`)}if($.nextPrewarmAt)_.push(`Next prewarm: ${new Date($.nextPrewarmAt).toLocaleString()}`);return _.join(`
12
+ `)}function z4($){let C=k_($.argumentsText),_={enabled:$.enabled??!1,always:$.always,window:$.window,trackedSessions:$.trackedSessions,trackedSessionDetails:$.trackedSessionDetails,nextPrewarmAt:$.nextPrewarmAt,hybridActive:$.hybridActive};if(C.type==="status")return[m1,"",J0(_)].join(`
13
+ `);if(C.type==="disable")return[T_,"",J0({..._,enabled:!1})].join(`
14
+ `);if(C.type==="always")return[v1,"",J0({..._,enabled:!0,always:!0,window:void 0})].join(`
15
+ `);if(C.type==="window")return[v1,"",J0({..._,enabled:!0,always:!1,window:{startHour:C.startHour,endHour:C.endHour}})].join(`
16
+ `);if(C.type==="subagents")return[m1,"",J0(_),"",`Subagent tracking: ${C.enabled?"enabled":"disabled"}`].join(`
17
+ `);return[w_,"",x_,"",J0(_)].join(`
18
+ `)}function E$($){if(!$||typeof $!=="object")return!1;if(Array.isArray($))return $.some(E$);let C=$,_=C.cache_control;if(_&&typeof _==="object"&&_.type==="ephemeral")return!0;return Object.values(C).some(E$)}async function v_($){let C;try{C=JSON.parse($)}catch{return{ok:!1,reason:"body is not valid JSON"}}if(!E$(C))return{ok:!1,reason:"body has no explicit cache breakpoints"};let _=structuredClone(C);if(_.max_tokens=0,delete _.stream,_.thinking?.type==="enabled")delete _.thinking;if(_.output_config?.format)delete _.output_config;let j=_.tool_choice;if(j?.type==="tool"||j?.type==="any")delete _.tool_choice;return{ok:!0,bodyText:await k1(JSON.stringify(h1(_)))}}class l_{options;targets=new Map;timer=null;constructor($){this.options=$}start(){if(this.timer)return;if(P.debug("cachekeep","started"),this.timer=setInterval(()=>{this.tick().catch(($)=>{P.warn("cachekeep","tick failed",{error:$ instanceof Error?$.message:String($)})})},A_),"unref"in this.timer)this.timer.unref()}stop(){if(!this.timer)return;P.debug("cachekeep","stopped"),clearInterval(this.timer),this.timer=null}stats($,C=this.options.now?.()??Date.now(),_=!1){let K=_?"always":u1($,new Date(C)),G=[...this.targets.values()].filter((J)=>J.dayKey===K),j=G.length?Math.min(...G.map((J)=>J.cacheExpiresAt-k0)):void 0;return{trackedSessions:G.length,nextPrewarmAt:j}}trackedSessions(){return[...this.targets.values()].map(($)=>({id:$.id,cacheExpiresAt:$.cacheExpiresAt,nextPrewarmAt:$.cacheExpiresAt-k0})).sort(($,C)=>$.id.localeCompare(C.id))}trackedOAuthRoute($){let C=this.targets.get($);return C?{oauthAccountId:C.oauthAccountId}:void 0}trackedCount(){return this.targets.size}publishTrackedSessions(){let $=this.options.onTrackedSessionsChanged;if(!$)return;try{Promise.resolve($(this.trackedSessions())).catch((C)=>{P.warn("cachekeep","failed to publish tracked sessions",{error:C instanceof Error?C.message:String(C)})})}catch(C){P.warn("cachekeep","failed to publish tracked sessions",{error:C instanceof Error?C.message:String(C)})}}totalBodyBytes(){return[...this.targets.values()].reduce(($,C)=>$+C.bodyText.length,0)}evictOldestTarget(){let $=this.targets.keys().next().value;if($!==void 0)this.targets.delete($)}pruneTargets($,C){for(let[_,K]of this.targets){if(C&&K.dayKey!==C){this.targets.delete(_);continue}if($-K.cacheExpiresAt>I_)this.targets.delete(_)}while(this.targets.size>P_)this.evictOldestTarget();while(this.totalBodyBytes()>y1){let _=this.targets.size;if(this.evictOldestTarget(),this.targets.size===_)break}}track($){if(!$.sessionId)return{tracked:!1,reason:"missing session id"};if(!d1($.storage))return{tracked:!1,reason:"cachekeep disabled"};if($.cacheMode!=="hybrid")return{tracked:!1,reason:"cache mode is not hybrid"};if($.bodyText.length>y1)return{tracked:!1,reason:"body exceeds cachekeep memory budget"};let C=this.options.now?.()??Date.now(),_=m0($.storage);if(!l1($.storage,new Date(C)))return{tracked:!1,reason:"outside configured schedule"};let K=g1($.storage,_,new Date(C));if(this.pruneTargets(C,K),this.targets.has($.sessionId))this.targets.delete($.sessionId);let G={};return $.headers.forEach((j,J)=>{G[J]=j}),this.targets.set($.sessionId,{id:$.sessionId,url:$.url,headers:G,bodyText:$.bodyText,cacheExpiresAt:C+b$,dayKey:K,oauthAccountId:$.oauthAccountId}),this.pruneTargets(C,K),this.publishTrackedSessions(),this.start(),{tracked:!0}}async prewarmNow($){let C={};$.headers.forEach((K,G)=>{C[G]=K});let _={id:$.sessionId,url:$.url,headers:C,bodyText:$.bodyText,cacheExpiresAt:this.options.now?.()??Date.now(),dayKey:"",oauthAccountId:$.oauthAccountId};return this.sendPrewarm(_)}async tick(){let $=await this.options.loadStorage(),C=m0($),_=this.options.now?.()??Date.now(),K=g1($,C,new Date(_));if(v0($))for(let j of this.targets.values())j.dayKey="always";if(this.pruneTargets(_,K),!this.targets.size){this.publishTrackedSessions(),this.stop();return}if(!y_($)){this.publishTrackedSessions();return}if(!l1($,new Date(_))){this.publishTrackedSessions();return}P.debug("cachekeep","fired",{targets:this.targets.size});let G=_+k0;for(let j of this.targets.values()){if(j.cacheExpiresAt>G)continue;await this.prewarm(j,_)}this.publishTrackedSessions()}async sendPrewarm($){let C=await v_($.bodyText);if(!C.ok)return C;let _=this.options.fetchImpl??fetch,K={...$,bodyText:C.bodyText},G=this.options.prepareHeaders?await this.options.prepareHeaders(new Headers($.headers),K):new Headers($.headers);G.delete("content-length"),G.delete("transfer-encoding");let j=await _($.url,{method:"POST",headers:G,body:C.bodyText,signal:AbortSignal.timeout(this.options.prewarmTimeoutMs??h_)});if(!j.ok)return{ok:!1,reason:await j.text().catch(()=>"").then((z)=>z||`HTTP ${j.status}`),status:j.status};let Z=(await j.json().catch(()=>null))?.usage;return{ok:!0,...Z&&{usage:Z}}}async prewarm($,C){let _=await this.sendPrewarm($);if(!_.ok){if(_.status==null)P.debug("cachekeep","prewarm skipped",{session:$.id,reason:_.reason}),this.targets.delete($.id);else P.warn("cachekeep","prewarm failed",{session:$.id,status:_.status,reason:_.reason}),$.cacheExpiresAt=C+k0+300000;return}$.cacheExpiresAt=C+b$,P.debug("cachekeep","prewarm succeeded",{session:$.id,..._.usage&&{usage:_.usage}})}}import{randomUUID as i1}from"node:crypto";import{mkdir as p_,readdir as g_,readFile as d_,rename as u_,rm as c1,writeFile as i_}from"node:fs/promises";import{tmpdir as c_}from"node:os";import{join as Q$}from"node:path";var r_=180000;function s_($){if(!$||typeof $!=="object"||Array.isArray($))return;let C=$;if(typeof C.id!=="string"||C.id.length===0||typeof C.cacheExpiresAt!=="number"||!Number.isFinite(C.cacheExpiresAt)||typeof C.nextPrewarmAt!=="number"||!Number.isFinite(C.nextPrewarmAt))return;return{id:C.id,cacheExpiresAt:C.cacheExpiresAt,nextPrewarmAt:C.nextPrewarmAt}}function n_($){if(!$||typeof $!=="object"||Array.isArray($))return;let C=$;if(C.version!==1||typeof C.updatedAt!=="number"||!Number.isFinite(C.updatedAt)||!Array.isArray(C.sessions))return;return{version:1,updatedAt:C.updatedAt,sessions:C.sessions.flatMap((_)=>{let K=s_(_);return K?[K]:[]})}}function W4($){return Q$(c_(),"opencode-anthropic-auth","cachekeep-sessions",$)}class o_{options;filePath;writeChain=Promise.resolve();constructor($){this.options=$;let C=$.instanceId??`${process.pid}-${i1()}`;this.filePath=Q$($.directory,`${C}.json`)}publish($){let C=$.map((_)=>({..._}));return this.writeChain=this.writeChain.catch(()=>{}).then(async()=>{if(C.length===0){await c1(this.filePath,{force:!0});return}await p_(this.options.directory,{recursive:!0,mode:448});let _=`${this.filePath}.${i1()}.tmp`,K={version:1,updatedAt:this.options.now?.()??Date.now(),sessions:C};await i_(_,`${JSON.stringify(K)}
19
+ `,{mode:384}),await u_(_,this.filePath)}),this.writeChain}async list($=[]){await this.writeChain.catch(()=>{});let C=this.options.now?.()??Date.now(),_=this.options.leaseMs??r_,K;try{K=(await g_(this.options.directory)).filter((J)=>J.endsWith(".json"))}catch{K=[]}let G=await Promise.all(K.map(async(J)=>{try{let Z=await d_(Q$(this.options.directory,J),"utf8");return n_(JSON.parse(Z))}catch{return}})),j=new Map;for(let J of G){if(!J||C-J.updatedAt>_||J.updatedAt>C)continue;for(let Z of J.sessions){let z=j.get(Z.id);if(!z||Z.cacheExpiresAt>z.cacheExpiresAt)j.set(Z.id,Z)}}for(let J of $){let Z=j.get(J.id);if(!Z||J.cacheExpiresAt>Z.cacheExpiresAt)j.set(J.id,{...J})}return[...j.values()].sort((J,Z)=>J.id.localeCompare(Z.id))}async dispose(){await this.writeChain.catch(()=>{}),await c1(this.filePath,{force:!0})}}var r1={"5h":"five_hour","7d":"seven_day"};function F4($){return Object.keys(r1).some((C)=>Number.isFinite(B$($,`anthropic-ratelimit-unified-${C}-utilization`)))}function B$($,C){let _=$.get(C);if(_==null||_.trim()==="")return;let K=Number(_);return Number.isFinite(K)?K:void 0}function a_($,C,_){let K=B$($,`anthropic-ratelimit-unified-${C}-utilization`);if(K==null)return;let G=Math.min(100,Math.max(0,Math.round(K*100))),j=B$($,`anthropic-ratelimit-unified-${C}-reset`),J=j==null?void 0:new Date(j*1000),Z=J&&Number.isFinite(J.getTime())?J.toISOString():void 0;return{usedPercent:G,remainingPercent:100-G,...Z&&{resetsAt:Z},checkedAt:_}}function U4($,C=Date.now()){let _={fallbackAdvised:$.get("anthropic-ratelimit-unified-fallback")==="available",source:"headers",checkedAt:C};for(let[G,j]of Object.entries(r1)){let J=a_($,G,C);if(J)_[j]=J}let K=$.get("anthropic-ratelimit-unified-representative-claim");if(K)_.bindingWindow=K,_.bindingWindowSource="headers";return _}function l0($,C){return{...$,...C,scoped:$&&"scoped"in $?$.scoped:void 0,extraUsage:$?.extraUsage,bindingWindow:$?.bindingWindowSource==="poll"?$.bindingWindow:C.bindingWindow??$?.bindingWindow,bindingWindowSource:$?.bindingWindowSource==="poll"?"poll":C.bindingWindowSource??$?.bindingWindowSource,source:"headers"}}var t_=globalThis.setTimeout;function s1($,C){if($?.source!=="headers")return C;let _=Boolean($.five_hour&&$.five_hour.checkedAt>(C.five_hour?.checkedAt??0)),K=Boolean($.seven_day&&$.seven_day.checkedAt>(C.seven_day?.checkedAt??0));if(!_&&!K)return C;return l0(C,{..._&&{five_hour:$.five_hour},...K&&{seven_day:$.seven_day},fallbackAdvised:$.fallbackAdvised,...$.bindingWindowSource==="headers"&&{bindingWindow:$.bindingWindow,bindingWindowSource:$.bindingWindowSource},source:"headers",checkedAt:Math.max(_?$.five_hour?.checkedAt??0:0,K?$.seven_day?.checkedAt??0:0)})}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($){this.storage=$.storage,this.fetchImpl=$.fetchImpl??fetch,this.now=$.now??Date.now,this.onMainQuotaFetched=$.onMainQuotaFetched,this.onApiError=$.onApiError,this.seedMainFromStorage($.storage),this.seedMainBackoffFromStorage($.storage)}getMain($){if($&&this.main&&this.mainTokenFp&&this.mainTokenFp!==D($))this.main=null,this.mainTokenFp=null;return this.main}getFallback($,C){let _=this.fallbacks.get($)??null;if(!C||!_)return _;if(this.fallbackTokenFps.get($)!==D(C))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return _}getAllFallbacks(){return this.fallbacks}setMain($,C){this.mainTokenFp=D($),this.main=C}setFallback($,C,_){if(this.fallbacks.set($,C),_)this.fallbackTokenFps.set($,D(_));else this.fallbackTokenFps.delete($)}pushMainFromHeaders($,C){let _=C.checkedAt??this.now(),K=D($),G=l0(this.mainTokenFp===K?this.main?.quota:void 0,C),j={quota:G,checkedAt:_,refreshAfter:j0(G,this.storage,_)};return this.setMain($,j),j}pushFallbackFromHeaders($,C,_){let K=_.checkedAt??this.now(),G=l0(this.getFallback($,C)?.quota,_),j={quota:G,checkedAt:K,refreshAfter:j0(G,this.storage,K)};return this.setFallback($,j,C),j}async refreshMain($){let C=D($);if(this.mainTokenFp&&this.mainTokenFp!==C)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===C)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=C,this.inflightMain=this._fetchMain($),this.inflightMain}async refreshFallback($,C){let _=d.fallbackInflightKey($,C),K=this.inflightFallbacks.get(_);if(K)return K;if(this.isFallbackBackedOff($,C)){let j=this.getFallback($,C);if(j)return j.quota;throw Error("Quota API rate-limited — try again later")}let G=this._fetchFallback($,C);return this.inflightFallbacks.set(_,G),G}async refreshAllFallbacks($){let C=this.now();for(let _ of $){if(_.enabled===!1)continue;if(!_.access)continue;let K=this.getFallback(_.id,_.access);if(K&&C<K.refreshAfter)continue;try{await this.refreshFallback(_.id,_.access)}catch{}}}refreshMainInBackground($){if(this.inflightMain)return;if(this.isBackedOff())return;this.refreshMain($).catch(()=>{})}scopedWindowIsStale($,C){let _=y($.quota,C);return Boolean(_&&this.now()-_.checkedAt>=m(this.storage))}isMainStale($){if(!this.main)return!0;return this.now()>=this.main.refreshAfter||this.scopedWindowIsStale(this.main,$)}isFallbackStale($,C,_){let K=this.getFallback($,C);if(!K)return!0;return this.now()>=K.refreshAfter||this.scopedWindowIsStale(K,_)}shouldRefreshOnRequestCount($){let C=b1(this.storage);if(C<=0)return!1;return $>0&&$%C===0}needsRefresh($,C){return this.isMainStale(C)||this.shouldRefreshOnRequestCount($)}updateStorage($){this.storage=$,this.seedMainFromStorage($),this.seedMainBackoffFromStorage($)}seedMainFromStorage($,C){let _=f1($);if(!_)return;let K=C?D(C):null;if(K&&_.tokenFingerprint&&_.tokenFingerprint!==K)return;let G={quota:_.quota,refreshAfter:j0(_.quota,$,_.checkedAt),checkedAt:_.checkedAt};if(this.main&&this.main.checkedAt>=G.checkedAt&&(!K||!this.mainTokenFp||this.mainTokenFp===K))return;this.main=G,this.mainTokenFp=_.tokenFingerprint??null}seedMainBackoffFromStorage($){let C=$?.quota?.mainLastQuotaApiError;this.mainLastApiError=C&&K0(C,this.now())?C:void 0}seedFallbacksFromAccounts($){let C=m(this.storage);for(let _ of $){if(_.enabled===!1)continue;if(!_.quota)continue;let K=Math.max(_.quota.five_hour?.checkedAt??0,_.quota.seven_day?.checkedAt??0);if(K<=0)continue;let G=this.getFallback(_.id,_.access);if(G&&G.checkedAt>=K)continue;this.setFallback(_.id,{quota:_.quota,refreshAfter:K+C,checkedAt:K},_.access)}}isBackedOff(){return K0(this.mainLastApiError,this.now())}isFallbackBackedOff($,C){if(C){if(this.fallbackErrorTokenFps.get($)!==D(C))return!1}return K0(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,C){return JSON.stringify([$,D(C)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let C=async()=>{let K=this.now()-this.lastApiCallAt;if(K<d.API_CALL_GAP_MS)await new Promise((G)=>{let j=t_(G,d.API_CALL_GAP_MS-K);if(typeof j==="object"&&"unref"in j)j.unref()});return this.lastApiCallAt=this.now(),$()},_=this.apiGate.then(C,C);return this.apiGate=_.catch(()=>{}),_}async _fetchMain($){let C=D($);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 o({name:"opencode-main-quota-refresh",ttlMs:30000});if(!_){let K=this.main;if(K&&this.now()<K.refreshAfter)return K.quota;throw Error("Quota refresh is already in progress")}try{let K=this.now(),G=await T0({accessToken:$,fetchImpl:this.fetchImpl,now:this.now}),j=this.now(),J=s1(this.mainTokenFp===C?this.main?.quota:void 0,G);return this.mainTokenFp=D($),this.main={quota:J,refreshAfter:j0(J,this.storage,j),checkedAt:J.checkedAt??j},this.mainLastApiError=void 0,this.onMainQuotaFetched?.(J,j,this.mainTokenFp,K),J}catch(K){throw this._handleMainFetchError(K),K}finally{await _.release()}}finally{if(this.inflightMainFp===C)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback($,C){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff($,C)){let K=this.getFallback($,C);if(K)return K.quota;throw Error("Quota API rate-limited — try again later")}let _=await o({name:d.quotaLockName($),ttlMs:30000});if(!_){let K=this.getFallback($,C);if(K&&this.now()<K.refreshAfter)return K.quota;throw Error("Quota refresh is already in progress")}try{let K=await T0({accessToken:C,fetchImpl:this.fetchImpl,now:this.now}),G=this.now(),j=s1(this.getFallback($,C)?.quota,K);return this.setFallback($,{quota:j,refreshAfter:j0(j,this.storage,G),checkedAt:j.checkedAt??G},C),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),j}finally{await _.release()}}catch(_){throw this._handleFallbackFetchError($,C,_),_}finally{this.inflightFallbacks.delete(d.fallbackInflightKey($,C))}})}static isAuthError($){if($.status===401||H$($))return!0;let _=$ instanceof Error?$.message:String($);return/quota check failed: 401\b/.test(_)}_handleMainFetchError($){if(d.isAuthError($))return;this.mainLastApiError=h0({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,C,_){if(d.isAuthError(_))return;let K=D(C),G=this.fallbackErrorTokenFps.get($)===K?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,h0({error:_,now:this.now(),previous:G})),this.fallbackErrorTokenFps.set($,K)}}var e_="https://api.anthropic.com/api/oauth/profile",$K=604800000;async function D4($){let C=await($.fetchImpl??fetch)(e_,{method:"GET",signal:$.signal,headers:{Authorization:`Bearer ${$.accessToken}`,Accept:"application/json","anthropic-beta":"oauth-2025-04-20"}});if(!C.ok)throw Error(`Claude profile check failed: ${C.status}`);let _=await C.json(),K=_.organization?.rate_limit_tier,G=_.organization?.organization_type;if(typeof K!=="string"||K.trim()===""||typeof G!=="string"||G.trim()==="")throw Error("Claude profile response is missing account metadata");return{tier:K,orgType:G,checkedAt:$.now?.()??Date.now(),tokenFingerprint:D($.accessToken)}}function S4($,C){return $?.tokenFingerprint===D(C)}function R4($,C=Date.now()){return Boolean($&&Number.isFinite($.checkedAt)&&C>=$.checkedAt&&C-$.checkedAt<$K)}function Z0($){let C=$?.tier.match(/^default_claude_max_(\d+)x$/);if(!C)return;let _=`Max ${C[1]}x`;return $?.orgType==="claude_team"?`Team · ${_}`:_}var P4="claude-account";function CK($){let C=$.trim().split(/\s+/).filter(Boolean);if(C.length===0)return{type:"status"};let _=C[0],K=C.slice(1).join(" ");if(_==="enable"&&K)return{type:"enable",id:K};if(_==="disable"&&K)return{type:"disable",id:K};if(_==="remove"&&K)return{type:"remove",id:K};if(_==="move-up"&&K)return{type:"move-up",id:K};if(_==="move-down"&&K)return{type:"move-down",id:K};if(_==="add-apikey"&&K){let G=K,j,J,Z=G.match(/--base-url\s+(\S+)/);if(Z)j=Z[1],G=G.replace(Z[0],"").trim();let z=G.match(/--auth-header\s+(authorization-bearer|x-api-key)/);if(z)J=z[1],G=G.replace(z[0],"").trim();let X,Y=G.match(/--label\s+(.+)/);if(Y)X=Y[1]?.trim()||void 0,G=G.replace(Y[0],"").trim();let O=G.indexOf(" ");if(O===-1){if(!G)return{type:"usage"};return{type:"add-apikey",apiKey:G,baseURL:j,authHeader:J,label:X}}let L=G.slice(0,O),W=G.slice(O+1).trim();return{type:"add-apikey",apiKey:L,label:X??(W||void 0),baseURL:j,authHeader:J}}if(_==="add-oauth-start")return{type:"add-oauth-start"};if(_==="add-oauth-finish"&&K){let G=K,j,J=G.match(/--label\s+(.+)/);if(J)j=J[1]?.trim()||void 0,G=G.replace(J[0],"").trim();if(!G)return{type:"usage"};return{type:"add-oauth-finish",code:G,label:j}}return{type:"usage"}}function _K($){let C=[],_=$.quota?.mainQuota?.five_hour;C.push({id:"main",label:$.main?.provider==="anthropic"?"OpenCode anthropic":"Main",role:"main",enabled:!0,quotaPercent:_?.usedPercent??null,tierLabel:Z0($.main?.profile)});for(let K of $.accounts){let G=K.quota?.five_hour;C.push({id:K.id,label:K.label??K.id,role:"fallback",enabled:K.enabled!==!1,quotaPercent:G?.usedPercent??null,tierLabel:K.type==="oauth"?Z0(K.profile):void 0})}return C}var D$=["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(`
20
+ `);function I4($){let C=CK($.argumentsText),_=$.storage.accounts,K="main";if(C.type==="status"){let j=_K($.storage),J=["## Claude Accounts",""];for(let Z of j){let z=Z.quotaPercent!=null?` ${Math.round(Z.quotaPercent)}%`:"",X=!Z.enabled?" (disabled)":"",Y=Z.tierLabel?` · ${Z.tierLabel}`:"";J.push(`- **${Z.label}** [${Z.role}]${Y}${X}${z}`)}return J.push("",D$),{text:J.join(`
21
+ `)}}if(C.type==="usage")return{text:D$};if(C.type==="add-apikey")return{text:"add-apikey"};if(C.type==="add-oauth-start")return{text:"add-oauth-start"};if(C.type==="add-oauth-finish")return{text:"add-oauth-finish"};let G=C.id;if(G==="main")return{text:`Cannot ${C.type} the main account (OpenCode managed).`};if(C.type==="enable"||C.type==="disable"){let j=_.find((J)=>J.id===G);if(!j)return{text:`Account "${G}" not found.`};return{text:`Account "${j.label??G}" ${C.type}d.`,updated:{id:G,action:C.type,enabled:C.type==="enable"}}}if(C.type==="remove"){let j=_.find((J)=>J.id===G);if(!j)return{text:`Account "${G}" not found.`};return{text:`Account "${j.label??G}" removed.`,updated:{id:G,action:"remove"}}}if(C.type==="move-up"){let j=_.findIndex((X)=>X.id===G);if(j<0)return{text:`Account "${G}" not found.`};if(j===0)return{text:`Account "${_[j]?.label??G}" is already first.`};let J=_.map((X)=>X.id),Z=[..._];[Z[j-1],Z[j]]=[Z[j],Z[j-1]];let z=Z.map((X)=>X.id);return{text:`Account "${_[j]?.label??G}" moved up.`,updated:{id:G,action:"reorder",previousOrder:J,newOrder:z}}}if(C.type==="move-down"){let j=_.findIndex((X)=>X.id===G);if(j<0)return{text:`Account "${G}" not found.`};if(j===_.length-1)return{text:`Account "${_[j]?.label??G}" is already last.`};let J=_.map((X)=>X.id),Z=[..._];[Z[j],Z[j+1]]=[Z[j+1],Z[j]];let z=Z.map((X)=>X.id);return{text:`Account "${_[j]?.label??G}" moved down.`,updated:{id:G,action:"reorder",previousOrder:J,newOrder:z}}}return{text:D$}}import{createHash as KK,randomBytes as GK}from"node:crypto";import{lstat as n1,mkdir as jK,readdir as JK,rename as ZK,unlink as $C,writeFile as zK}from"node:fs/promises";import{tmpdir as XK}from"node:os";import{join as A$,resolve as d0}from"node:path";var v4="claude-dump",YK="## Claude Dump Status",OK="## Claude Dump Enabled",NK="## Claude Dump Disabled",LK="## Claude Dump Usage",WK="Usage: `/claude-dump`, `/claude-dump on`, or `/claude-dump off`.",HK="OPENCODE_ANTHROPIC_AUTH_DUMP_DIR",FK="OPENCODE_ANTHROPIC_AUTH_DUMP_MAX_BYTES",UK=A$(XK(),"opencode-anthropic-auth-dumps"),VK=536870912,MK=300000,fK=60000,bK=600000,EK=/\.(body|meta|relay|request)\.json$/,QK=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d{5,}-(.+)$/,R$="[a-zA-Z0-9._-]",BK=new RegExp(`^${R$}{1,80}-direct(?:-${R$}{1,80})?$`),DK=new RegExp(`^${R$}{1,80}-(?:http|websocket)-p[12]-(?:full_sync|patch)$`),f0=!1,o1=0,a1=0,SK=100,z0=new Map;function l4($){f0=$}function i0(){return process.env[HK]||UK}function RK(){let $=Number(process.env[FK]);return Number.isFinite($)&&$>=0?Math.floor($):VK}function qK($){return d0($)===d0(i0())}function q$($){let C=$.replace(EK,"");if(C===$)return!1;let K=QK.exec(C)?.[1];if(!K)return!1;return BK.test(K)||DK.test(K)}function AK($){if(!$.endsWith(".partial"))return!1;let C=$.slice(0,-8);if(q$(C))return!0;let _=C.lastIndexOf(".");if(_<0)return!1;let K=C.slice(_+1);return/^[a-f0-9]{24}$/.test(K)&&q$(C.slice(0,_))}async function p0($,C){for(let _=0;_<2;_+=1){let K=GK(12).toString("hex"),G=`${$}.${K}.partial`,j=!1;try{return await zK(G,C,{encoding:"utf8",flag:"wx"}),j=!0,await ZK(G,$),!0}catch(J){if(J.code==="EEXIST")continue;if(j)await $C(G).catch(()=>{});throw J}}return!1}async function PK($){let C=$.dumpDir??i0(),_=$.maxBytes??RK(),K=$.now??Date.now(),G=$.minAgeMs??fK,j=$.partialStaleMs??bK,J={removed:0,freedBytes:0};if(!qK(C)||_<=0)return J;try{if((await n1(C)).isSymbolicLink())return J;let z=new Set(($.protectedPaths??[]).map((F)=>d0(F))),X=await JK(C,{withFileTypes:!0}),Y=[];await Promise.all(X.map(async(F)=>{if(!F.isFile())return;let V=AK(F.name);if(!V&&!q$(F.name))return;let E=A$(C,F.name);try{let N=await n1(E);if(!N.isFile()||N.isSymbolicLink())return;Y.push({path:E,size:N.size,mtimeMs:N.mtimeMs,partial:V})}catch{}}));let O=Y.reduce((F,V)=>F+V.size,0);Y.sort((F,V)=>F.mtimeMs-V.mtimeMs||F.path.localeCompare(V.path));let L=0,W=0;for(let F of Y){if(z.has(d0(F.path)))continue;let V=K-F.mtimeMs,E=F.partial&&V>=j;if(!E&&O<=_)continue;if(F.partial?!E:V<G)continue;try{await $C(F.path),O-=F.size,W+=F.size,L+=1}catch{}}if(L>0)P.debug("dump","removed old dump files",{removed:L,freedBytes:W});return{removed:L,freedBytes:W}}catch{return J}}function IK($,C){let _=Date.now();if(_-a1<MK)return;a1=_,PK({dumpDir:$,protectedPaths:C}).catch(()=>{})}function hK($){let C=$.trim().split(/\s+/).filter(Boolean);if(C.length===0)return{type:"status"};if(C.length===1&&C[0]==="on")return{type:"enable"};if(C.length===1&&C[0]==="off")return{type:"disable"};return{type:"usage"}}function g0($){let C=$?.enabled??f0;return[YK,"",`- Enabled: ${C?"enabled":"disabled"}`,`- Directory: ${i0()}`,"- 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(`
22
+ `)}function p4($){let C=hK($.argumentsText),_=$.enabled??f0;if(C.type==="status")return g0({enabled:_});if(C.type==="enable")return[OK,"",g0({enabled:!0})].join(`
23
+ `);if(C.type==="disable")return[NK,"",g0({enabled:!1})].join(`
24
+ `);return[LK,"",WK,"",g0({enabled:_})].join(`
25
+ `)}function t1($){return $.length<=16?$:`${$.slice(0,12)}…`}function CC($){let C=$.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!C)return"session-unknown";return C.length<=80?C:C.slice(0,80)}function TK($){if($.transport!=="direct")return`${$.transport}-p${$.protocol}-${$.mode}`;return`direct${$.route?`-${CC($.route)}`:""}`}function wK($){let C=$.affinity?.trim();if(C)return`session:${C}`;return`request:${$.route??"direct"}:${$.url??""}`}function xK($,C){if(!z0.has($))while(z0.size>=SK){let _=z0.keys().next().value;if(_===void 0)break;z0.delete(_)}z0.set($,C)}function kK($){if($==null)return;return Object.fromEntries(new Headers($).entries())}function _C($){return KK("sha256").update($).digest("hex")}function yK($){return x1($)}function mK($,C){if($==null)return null;if($===C)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:$.length,currentBytes:C.length};let _=0;while(_<$.length&&_<C.length&&$[_]===C[_])_+=1;let K=$.length-1,G=C.length-1;while(K>=_&&G>=_&&$[K]===C[G])K-=1,G-=1;return{changed:!0,firstByte:_,lastPreviousByte:K,lastCurrentByte:G,changedPreviousBytes:K-_+1,changedCurrentBytes:G-_+1,previousBytes:$.length,currentBytes:C.length}}function vK($){try{let C=JSON.parse($);return C!=null&&typeof C==="object"&&!Array.isArray(C)?C:null}catch(C){return b(`dump body parse failed: ${C instanceof Error?C.message:String(C)}`),null}}function S$($){return _C(JSON.stringify($))}function lK($){let C=vK($);if(!C)return{parseable:!1};let _=Array.isArray(C.messages)?C.messages:[],K=Array.isArray(C.system)?C.system:[],G=_[0],j=_.slice(1);return{parseable:!0,model:typeof C.model==="string"?C.model:void 0,stream:C.stream,systemCount:K.length,messagesCount:_.length,systemHash:S$(K),message0Hash:G===void 0?null:S$(G),message0Bytes:G===void 0?0:JSON.stringify(G).length,messagesAfter0Hash:S$(j),messagesAfter0Bytes:JSON.stringify(j).length,cch:yK($)}}function u0($){if(Array.isArray($))return $.map(u0);if($==null||typeof $!=="object")return $;let C={};for(let[_,K]of Object.entries($)){let G=_.toLowerCase();if(G==="authorization"||G==="x-api-key"||G==="cookie"||G==="set-cookie"||e1(_)){C[_]="[redacted]";continue}C[_]=u0(K)}return C}async function KC($){if(!f0)return;o1+=1;let C=$.affinity?.trim()||"session-unknown",_=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(o1).padStart(6,"0")}-${CC(C)}-${TK($)}`,K=i0(),G=A$(K,_),j={body:`${G}.body.json`,metadata:`${G}.meta.json`};if($.payload!==void 0)j.relay=`${G}.relay.json`;if($.request!==void 0)j.request=`${G}.request.json`;try{await jK(K,{recursive:!0});let J={id:_,createdAt:new Date().toISOString(),session:t1(C),transport:$.transport,protocol:$.protocol,mode:$.mode,route:$.route,status:$.status,error:$.error,bodyBytes:$.bodyText.length,relayBytes:$.relayBytes,bodyHash:_C($.bodyText),diff:mK($.previousBodyText,$.bodyText),body:lK($.bodyText),files:j},Z=[p0(j.body,$.bodyText),p0(j.metadata,`${JSON.stringify(J,null,2)}
26
+ `)];if($.payload!==void 0&&j.relay)Z.push(p0(j.relay,`${JSON.stringify(u0($.payload),null,2)}
27
+ `));if($.request!==void 0&&j.request)Z.push(p0(j.request,`${JSON.stringify(u0({...$.request,headers:kK($.request.headers)}),null,2)}
28
+ `));await Promise.all(Z),IK(K,Object.values(j)),b(`dumped request id=${_} session=${t1(C)} body=${j.body} meta=${j.metadata}`)}catch(J){b(`dump failed: ${J instanceof Error?J.message:String(J)}`)}}async function g4($){if(!f0)return;let C=wK($),_=z0.get(C);await KC({affinity:$.affinity,transport:"direct",route:$.route,status:$.status,error:$.error,bodyText:$.bodyText,previousBodyText:_,request:{url:$.url,method:$.method,headers:$.headers}}),xK(C,$.bodyText)}async function GC($){await KC({affinity:$.affinity,transport:$.transport,protocol:$.protocol,mode:$.mode,status:$.status,bodyText:$.bodyText,previousBodyText:$.previousBodyText,payload:$.payload,relayBytes:$.relayBytes})}var u4="claude-fast";var r0=!1;function i4(){return r0}function c4($){r0=$}function pK($){let C=$.trim().split(/\s+/).filter(Boolean);if(C.length===0)return{type:"status"};if(C.length===1&&C[0]==="on")return{type:"enable"};if(C.length===1&&C[0]==="off")return{type:"disable"};return{type:"usage"}}function c0($){return["## Claude Fast Mode Status","",`- Enabled: ${$?.enabled??r0?"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, claude-opus-4-8, and claude-opus-5",'- 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(`
29
+ `)}function r4($){let C=pK($.argumentsText),_=$.enabled??r0;if(C.type==="status")return c0({enabled:_});if(C.type==="enable")return["## Claude Fast Mode Enabled","",c0({enabled:!0})].join(`
30
+ `);if(C.type==="disable")return["## Claude Fast Mode Disabled","",c0({enabled:!1})].join(`
31
+ `);return["## Claude Fast Mode Usage","","Usage: `/claude-fast`, `/claude-fast on`, or `/claude-fast off`.","",c0({enabled:_})].join(`
32
+ `)}var X0="claude-killswitch";function gK($){let C=$.trim().split(/\s+/).filter(Boolean);if(C.length===0)return{type:"status"};if(C.length===1&&C[0]==="on")return{type:"on"};if(C.length===1&&C[0]==="off")return{type:"off"};if(C[0]==="set"){let _=[];for(let K=1;K<C.length;K++){let G=C[K]?.match(/^([^:]+):(\d+),(\d+)(?:,(\d+))?$/);if(!G)return{type:"usage"};let[,j,J,Z,z]=G,X=typeof z==="string"&&z.length>0?Number.parseInt(z,10):void 0,Y={account:j,fh:Number.parseInt(J,10),sd:Number.parseInt(Z,10)};if(X!==void 0)Y.scoped=X;_.push(Y)}if(_.length===0)return{type:"usage"};return{type:"set",entries:_}}return{type:"usage"}}function s0($,C){let _=$.enabled===!0,K=["## Killswitch","",`Status: **${_?"ON":"OFF"}**`];if(_){K.push(""),K.push("| Account | 5h threshold | 1w threshold | Scoped |"),K.push("| ------- | ------------ | ------------ | ------ |");let G=U0($.main);K.push(`| main | ≥ ${G.five_hour}% | ≥ ${G.seven_day}% | ≤ ${G.scoped}% |`);for(let j of C){let J=U0($.accounts?.[j]??$.main);K.push(`| ${j} | ≥ ${J.five_hour}% | ≥ ${J.seven_day}% | ≤ ${J.scoped}% |`)}}return K.join(`
33
+ `)}var jC=["## Killswitch Commands","","```",`/${X0} — show status`,`/${X0} on — enable with current or default thresholds`,`/${X0} off — disable`,`/${X0} set all:5,10 — set all accounts to 5h≥5%, 1w≥10%`,`/${X0} set main:3,8,0 — set 5h≥3%, 1w≥8%, scoped≤0%`,`/${X0} set main:3,8 work-alt:5,10 — per-account`,"```"].join(`
34
+ `);function o4($){let C=gK($.argumentsText);if(C.type==="status")return{text:`${s0($.config,$.accountIds)}
35
+
36
+ ${jC}`};if(C.type==="on"){let K={...$.config,enabled:!0,main:$.config.main??{five_hour:s.five_hour,seven_day:s.seven_day}};return{text:`## Killswitch Enabled
37
+
38
+ ${s0(K,$.accountIds)}`,updatedConfig:K}}if(C.type==="off")return{text:"## Killswitch Disabled",updatedConfig:{...$.config,enabled:!1}};if(C.type==="set"){let K={...$.config.accounts??{}},G={...$.config,enabled:!0,accounts:K};for(let J of C.entries){let Z={five_hour:J.fh,seven_day:J.sd};if(J.scoped!==void 0)Z.scoped=J.scoped;if(J.account==="main")G.main=Z;else if(J.account==="all"){G.main=Z;for(let z of $.accountIds)K[z]=Z}else K[J.account]=Z}return{text:`## Killswitch Updated
39
+
40
+ ${s0(G,$.accountIds)}`,updatedConfig:G}}return{text:`${s0($.config,$.accountIds)}
41
+
42
+ ${jC}`}}var t4="claude-logging",dK=["error","warn","info","debug","trace"];function uK($){let C=$.trim().toLowerCase().split(/\s+/).filter(Boolean);if(C.length===0)return{type:"status"};if(C.length===1&&dK.includes(C[0]))return{type:"level",level:C[0]};return{type:"usage"}}function P$($){return["## Claude Log Level","",`Current log level: \`${$?.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(`
43
+ `)}function e4($){let C=uK($.argumentsText),_=$.level??"info";if(C.type==="status")return P$({level:_});if(C.type==="level")return["## Claude Log Level Updated","",`Level set to \`${C.level}\`.`,"",...P$({level:C.level}).split(`
44
+ `).slice(2)].join(`
45
+ `);return["## Claude Log Level Usage","","Usage: `/claude-logging`, `/claude-logging error|warn|info|debug|trace`.","",...P$({level:_}).split(`
46
+ `).slice(2)].join(`
47
+ `)}var Cj="claude-fable-5";var iK=["claude-fable-5","claude-mythos-5"],zC={type:"adaptive",display:"summarized"},_j={input:10,output:50,cacheRead:1,cacheWrite5m:12.5,cacheWrite1h:20},Kj=1e6,Gj=128000,jj="2026-06-09",Jj={["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 XC($){return typeof $==="string"&&iK.some((C)=>$===C||$.startsWith(`${C}-`))}var JC="claude-sonnet-5",Zj=zC;function zj($){return typeof $==="string"&&($===JC||$.startsWith(`${JC}-`))}var ZC="claude-opus-5",Xj=zC;function Yj($){return typeof $==="string"&&($===ZC||$.startsWith(`${ZC}-`))}function Oj($){if(typeof $!=="string")return!1;if($.startsWith("gAAAA"))return!0;if(!$.startsWith("{"))return!1;try{let C=JSON.parse($);return C.type==="reasoning"&&typeof C.id==="string"&&C.id.startsWith("rs_")&&typeof C.encrypted_content==="string"&&C.encrypted_content.startsWith("gAAAA")}catch{return!1}}var Hj="claude-quota",YC={five_hour:"5h",seven_day:"1w"};function n0($){return`${Math.round($*10)/10}%`}function o0($,C){let _=Math.max(0,C-$),K=Math.floor(_/60000);if(K<1)return"just now";if(K===1)return"1m ago";if(K<60)return`${K}m ago`;let G=Math.floor(K/60),j=K%60;if(j===0)return`${G}h ago`;return`${G}h ${j}m ago`}function cK($,C){let _=Date.parse($);if(!Number.isFinite(_))return $;let K=_-C;if(K<=0)return"now";let G=Math.max(1,Math.ceil(K/60000));if(G<60)return`in ${G}m`;let j=Math.floor(G/60),J=G%60;if(J===0)return`in ${j}h`;return`in ${j}h ${J}m`}function LC($,C){if(!$)return"";return`, resets ${cK($,C)}`}function OC($,C,_,K){if(!C)return` - ${YC[$]}: unknown`;let G=[` - ${YC[$]}: ${n0(C.remainingPercent)} remaining`,` (${n0(C.usedPercent)} used`,`${LC(C.resetsAt,_)}, checked ${o0(C.checkedAt,_)})`].join("");return K===$?`${G} •`:G}function NC($){try{return new Intl.NumberFormat("en-US",{style:"currency",currency:$.currency,minimumFractionDigits:$.exponent,maximumFractionDigits:$.exponent}).format($.amountMinor/10**$.exponent)}catch{return`${$.amountMinor} ${$.currency}`}}function rK($,C){return[` - ${$.title}: ${n0($.remainingPercent)} remaining`,` (${n0($.usedPercent)} used`,`${LC($.resetsAt,C)}, checked ${o0($.checkedAt,C)})`].join("")}function sK($){return $.label?.trim()||$.id}function nK($){return $.lastQuotaRefreshError?.message??$.lastRefreshError?.message}function Fj($,C=new Map){if(!$?.accounts.length)return[];return $.accounts.filter(k).map((_)=>{let K=C.get(_.id)??nK(_);return{name:sK(_),role:"fallback",enabled:_.enabled!==!1,quota:_.quota,...Z0(_.profile)&&{tierLabel:Z0(_.profile)},lastRefreshedAt:_.lastRefreshedAt,...K&&{error:K}}})}function Uj($){let C=$.now??Date.now(),_=["## Claude Quotas",""];if($.refreshedAt)_.push(`Refreshed: ${o0($.refreshedAt,C)}`,"");if(!$.accounts.length)return _.push("No Claude OAuth accounts found yet."),_.join(`
48
+ `);for(let K of $.accounts){let G=K.role==="main"?"main":"fallback",j=K.enabled===!1?" disabled":"";if(_.push(`### ${K.name} (${G}${j})`),K.tierLabel)_.push(` - Tier: ${K.tierLabel}`);if(K.lastRefreshedAt)_.push(` - Last token refresh: ${o0(K.lastRefreshedAt,C)}`);if(K.error)_.push(` - Error: ${K.error}`);_.push(OC("five_hour",K.quota?.five_hour,C,K.quota?.bindingWindow)),_.push(OC("seven_day",K.quota?.seven_day,C,K.quota?.bindingWindow));for(let Z of K.quota?.scoped??[]){let z=rK(Z,C);_.push(K.quota?.bindingWindow===Z.id?`${z} •`:z)}let J=K.quota?.extraUsage;if(J){let Z=NC(J.used),z=NC(J.limit);_.push(` - credits ${Z}/${z}${J.exhausted?" · exhausted":""}`)}if(K.quota?.fallbackAdvised===!0)_.push(" - → fallback advised");_.push("")}return _.join(`
49
+ `).trimEnd()}import{Buffer as bC}from"node:buffer";import{createHash as oK,randomBytes as aK}from"node:crypto";class h$ extends Error{}class T$ extends Error{code="ECONNRESET";syscall="websocket";closeCode;closeReason;wasClean;constructor($,C){super($);this.name="RelayWebSocketConnectionResetError",this.closeCode=C?.code,this.closeReason=C?.reason,this.wasClean=C?.wasClean}}var v=new Map,e=new Map,WC=new Set,tK=7200000,eK=1800000,$G=128,CG=32,HC=0;function I$(){return HC+=1,`req_${Date.now().toString(36)}_${HC.toString(36)}`}function a0($){if(WC.has($))return;WC.add($),b($)}function Qj($){let C=$?.relay;if(!C)return a0("disabled: no relay config found"),null;if(C.enabled!==!0)return a0("disabled: relay.enabled is not true"),null;if(!C.url?.trim()||!C.token?.trim())return a0("disabled: missing relay url or token"),null;let _=C.transport==="http"?"http":"websocket";return a0(`configured transport=${_} protocol=${_==="websocket"?2:1} url=${C.url.trim()} fallbackToDirect=${C.fallbackToDirect!==!1}`),{enabled:!0,url:C.url.trim(),token:C.token.trim(),fallbackToDirect:C.fallbackToDirect!==!1,transport:_}}function Bj(){return aK(32).toString("base64url")}function _G($){return`sha256:${oK("sha256").update($).digest("hex")}`}function FC($,C){let _=0,K=Math.min($.length,C.length);while(_<K&&$.charCodeAt(_)===C.charCodeAt(_))_++;let G=$.length,j=C.length;while(G>_&&j>_&&$.charCodeAt(G-1)===C.charCodeAt(j-1))G--,j--;return{start:_,deleteCount:G-_,insert:C.slice(_,j)}}function KG($){return $.deleteCount===0&&$.insert.length===0}function UC($){let C=$.match(/\bcch=([0-9a-f]{5});/),_=C?.[1];if(!_||C.index==null)return null;let K=C.index+4;return{start:K,end:K+_.length,token:_}}function GG($,C,_,K){return`${$.slice(0,C)}${K}${$.slice(_)}`}function EC($,C){let _=UC($),K=UC(C);if(_&&K&&_.start===K.start&&_.end-_.start===K.end-K.start&&_.token!==K.token){let G={start:_.start,deleteCount:_.end-_.start,insert:K.token},j=GG($,_.start,_.end,K.token),J=FC(j,C);return KG(J)?G:[G,J]}return FC($,C)}function jG($,C){if(typeof C!=="string")return!1;try{let _=$ instanceof Request?new URL($.url):new URL($.toString());return _.pathname==="/v1/messages"||_.pathname==="/messages"}catch{return!1}}function JG($){let C={};for(let[_,K]of $.entries()){if(_==="x-session-affinity"||_==="x-opencode-session")continue;C[_]=K}return C}async function VC($,C,_){let K=Q(),G=JSON.stringify(C);return Y0("http_payload_stringify",{session:B(C.affinity),ms:h(Q()-K),relayBytes:G.length,mode:C.mode}),fetch($.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":$.token},body:G,signal:_??void 0})}function B($){return $.length>12?`${$.slice(0,12)}…`:$}function Q(){return performance.now()}function h($){return Math.round($*10)/10}function ZG(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function Y0($,C){if(!ZG())return;b(`[perf] relay ${$} ${JSON.stringify(C)}`)}function zG($){let{input:C,init:_,headers:K,bodyText:G,affinity:j,previous:J,nextHash:Z}=$,z=C instanceof Request?C.url:C.toString(),X={protocol:1,type:"request",affinity:j,upstream:{url:z,method:_?.method||(C instanceof Request?C.method:"POST"),headers:JG(K)},next_hash:Z};return J?{...X,mode:"patch",base_hash:J.hash,revision:J.revision+1,patch:EC(J.body,G)}:{...X,mode:"full_sync",revision:1,body:G}}function w$($,C){return{protocol:$.protocol,type:"request",affinity:$.affinity,upstream:$.upstream,next_hash:$.next_hash,mode:"full_sync",revision:1,body:C}}function QC($,C,_,K){let G=Date.now();v.delete($),v.set($,{body:C,hash:_,revision:K,updatedAt:G}),x$(G)}async function MC($){let{config:C,payload:_,bodyText:K,fallback:G,signal:j}=$,J=_,Z=await VC(C,J,j);if(Z.status===409&&J.mode==="patch")b(`state mismatch from relay session=${B(J.affinity)}; retrying full_sync`),await Z.body?.cancel().catch(()=>{}),J=w$(J,K),Z=await VC(C,J,j);if(!Z.ok&&Z.status>=500&&C.fallbackToDirect)return b(`relay returned ${Z.status}; falling back direct session=${B(J.affinity)}`),await Z.body?.cancel().catch(()=>{}),{response:await G(),payload:J,transport:"http",protocol:J.protocol,usedRelay:!1};return{response:Z,payload:J,transport:"http",protocol:J.protocol,usedRelay:!0}}function XG($,C){let _=new URL($);return _.protocol=_.protocol==="http:"?"ws:":"wss:",_.pathname="/ws",_.searchParams.set("token",C),_.toString()}function YG($){return new Uint8Array(bC.from($,"base64"))}function OG($){if($ instanceof Uint8Array)return $;if($ instanceof ArrayBuffer)return new Uint8Array($);if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);return new Uint8Array(bC.from(String($)))}function NG($){return JSON.parse($)}function fC($){let C=$,_=[`code=${C.code??"unknown"}`,`wasClean=${C.wasClean??"unknown"}`];if(C.reason)_.push(`reason=${JSON.stringify(C.reason)}`);return _.join(" ")}function LG($){let C=$.message||"relay websocket error";return $.status?`relay websocket error ${$.status}: ${C}`:C}class BC{config;affinity;socket;connecting;queue=Promise.resolve();pending;serverState;lastUsedAt=Date.now();constructor($,C){this.config=$,this.affinity=C}touch($=Date.now()){this.lastUsedAt=$}canEvict($=Date.now()){return!this.pending&&!this.connecting&&$-this.lastUsedAt>eK}dispose(){this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0}send($,C,_=!1,K){this.touch();let G=Q(),j=this.queue.catch(()=>{}).then(()=>this.startQueued($,C,G,_,K)),J=j.then(async({response:Z,getPayload:z})=>({response:await Z,payload:z(),transport:"websocket",protocol:2,usedRelay:!0}));return this.queue=j.then(({done:Z})=>Z.catch(()=>{}),()=>{}),J}async startQueued($,C,_,K,G){let j=Q();await this.ensureConnected();let J=Q(),Z=v.get(this.affinity),z=this.serverState?.hash,X={...$,protocol:2,id:I$()};if(X.mode==="patch"&&(!z||z!==X.base_hash))X.mode="full_sync",X.revision=(this.serverState?.revision??0)+1,delete X.base_hash,delete X.patch,X.body=C;if(X.mode==="patch"&&Z)X.patch=EC(Z.body,C);b(`perf websocket send_start session=${B(this.affinity)} request=${X.id} mode=${X.mode} queueMs=${h(J-_)} connectMs=${h(J-j)} bodyBytes=${C.length} relayBytes=${JSON.stringify(X).length}`);let Y=X,O=this.sendPayload(X,C,K,G);O.done.catch(()=>{});let L=O.done,W=O.response.catch((V)=>{if(!(V instanceof h$)||X.mode!=="patch")throw V;let E=w$(X,C);E.protocol=2,E.id=I$(),E.revision=(this.serverState?.revision??0)+1,Y=E;let N=this.sendPayload(E,C,K,G);return N.done.catch(()=>{}),L=N.done,N.response}),F=W.then(()=>L,()=>L.catch(()=>{}));return{response:W,done:F,getPayload:()=>Y}}async ensureConnected(){if(this.socket?.readyState===WebSocket.OPEN&&this.serverState!==void 0)return;if(this.connecting)return await this.connecting;this.connecting=new Promise(($,C)=>{let _=XG(this.config.url,this.config.token),K=new URL(_);K.searchParams.set("affinity",this.affinity);let G=new WebSocket(K.toString());this.socket=G,this.serverState=void 0;let j=setTimeout(()=>{G.close(),C(Error("relay websocket ready timed out"))},15000);G.addEventListener("message",(J)=>{try{if(typeof J.data!=="string"){this.handleBinaryChunk(J.data);return}let Z=NG(J.data);if(Z.type==="ready"){clearTimeout(j),this.serverState=Z.state,$();return}this.handleMessage(Z)}catch(Z){clearTimeout(j),C(Z),this.failPending(Z),G.close()}}),G.addEventListener("error",()=>{clearTimeout(j);let J=new T$("relay websocket error");C(J),this.failPending(J)}),G.addEventListener("close",(J)=>{if(clearTimeout(j),this.socket===G)this.socket=void 0,this.serverState=void 0,this.connecting=void 0;if(this.pending){if(this.pending.retryingBeforeResponse)return;let Z=this.pending.responseStartedAt!=null,z=Z?"closed after response_start before stream bytes":"closed before response";if(this.retryPendingBeforeResponse(this.pending,z,J))return;let X=Z?new T$("relay websocket closed during response stream",J):Error("relay websocket closed before response");b(`websocket ${Z?"closed during response stream":"closed before response without retry"} session=${B(this.affinity)} request=${this.pending.payload.id} chunks=${this.pending.streamChunkCount} bytes=${this.pending.streamByteCount} ${fC(J)}`),this.failPending(X)}})}).finally(()=>{this.connecting=void 0}),await this.connecting}sendPayload($,C,_,K){let G=this.socket;if(!G||G.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");let j=Q(),J,Z,z=new Promise((Y,O)=>{J=Y,Z=O});return{response:new Promise((Y,O)=>{let L={payload:$,bodyText:C,resolve:Y,reject:O,streamDone:!1,accepted:!1,responseStarted:!1,resolveDone:J,rejectDone:Z,sentAt:j,optimisticResponse:_,streamChunkCount:0,streamByteCount:0,retryAttempts:0,retryingBeforeResponse:!1,onResponseHeaders:K,stagedResponseHeaders:void 0,responseHeadersDelivered:!1};if(this.pending=L,this.resetPendingTimeout(L),G.send(JSON.stringify($)),_)this.resolvePendingResponse(L,200,"OK",{"content-type":"text/event-stream","x-cortexkit-relay-optimistic":"true"})}),done:z}}resetPendingTimeout($){clearTimeout($.timeout),$.timeout=setTimeout(()=>{if(this.pending!==$)return;if(this.retryPendingBeforeResponse($,"response timed out"))return;this.failPending(Error("relay websocket response timed out")),this.socket?.close()},45000)}retryPendingBeforeResponse($,C,_){if($.responseStartedAt!=null&&$.streamByteCount>0)return!1;if($.streamDone)return!1;if($.retryAttempts>=1)return!1;$.retryAttempts+=1,$.retryingBeforeResponse=!0,clearTimeout($.timeout);let K=$.retryAttempts,G=$.payload.id;return b(`websocket ${C}; reconnecting and retrying full_sync session=${B(this.affinity)} request=${G} retry=${K} chunks=${$.streamChunkCount} bytes=${$.streamByteCount}${_?` ${fC(_)}`:""}`),this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0,(async()=>{try{if(await this.ensureConnected(),this.pending!==$)return;let j=w$($.payload,$.bodyText);j.protocol=2,j.id=I$(),j.revision=(this.serverState?.revision??0)+1,$.payload=j,$.accepted=!1,$.acceptedAt=void 0,$.responseStartedAt=void 0,$.stagedResponseHeaders=void 0,$.responseHeadersDelivered=!1,$.sentAt=Q(),$.retryingBeforeResponse=!1;let J=this.socket;if(!J||J.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");this.resetPendingTimeout($),b(`perf websocket retry_send session=${B(this.affinity)} request=${j.id} previous=${G} mode=full_sync retry=${K} bodyBytes=${$.bodyText.length} relayBytes=${JSON.stringify(j).length}`),J.send(JSON.stringify(j))}catch(j){if($.retryingBeforeResponse=!1,this.pending===$)this.failPending(j)}})(),!0}enqueueStreamChunk($,C){this.deliverResponseHeaders($),$.streamChunkCount+=1,$.streamByteCount+=C.byteLength,$.streamController?.enqueue(C)}deliverResponseHeaders($){if($.responseHeadersDelivered||$.stagedResponseHeaders==null)return;$.responseHeadersDelivered=!0;try{$.onResponseHeaders?.($.stagedResponseHeaders)}catch{}}handleBinaryChunk($){let C=this.pending;if(!C?.responseStarted)return;this.enqueueStreamChunk(C,OG($))}resolvePendingResponse($,C,_,K){if($.responseStarted)return;$.responseStarted=!0;let G=new ReadableStream({start:(j)=>{$.streamController=j},cancel:()=>{this.socket?.close()}});$.resolve(new Response(G,{status:C,statusText:_,headers:K}))}handleMessage($){if($.type==="keepalive"){if(this.pending)this.resetPendingTimeout(this.pending);return}let C=this.pending;if(!C)return;if("id"in $&&$.id&&$.id!==C.payload.id)return;if($.type==="accepted"){let _=Q();C.accepted=!0,C.acceptedAt=_,b(`perf websocket accepted session=${B(this.affinity)} request=${C.payload.id} sentMs=${h(_-C.sentAt)} mode=${C.payload.mode}`),this.serverState={hash:$.hash,revision:$.revision},QC(this.affinity,C.bodyText,$.hash,$.revision),this.resetPendingTimeout(C);return}if($.type==="response_start"){if(C.responseStartedAt!=null)return;let _=Q();if(C.responseStartedAt=_,b(`perf websocket response_start session=${B(this.affinity)} request=${C.payload.id} sentMs=${h(_-C.sentAt)} upstreamMs=${C.acceptedAt==null?"unknown":h(_-C.acceptedAt)} status=${$.status}`),clearTimeout(C.timeout),$.headers)C.stagedResponseHeaders=new Headers($.headers);if(this.resolvePendingResponse(C,$.status,$.statusText,$.headers),C.optimisticResponse&&$.status>=400)this.deliverResponseHeaders(C),C.streamController?.enqueue(new TextEncoder().encode(`event: error
50
+ data: ${JSON.stringify({type:"error",error:{type:"relay_upstream_error",message:`Relay upstream returned HTTP ${$.status}`}})}
51
+
52
+ `)),this.finishPending();return}if($.type==="chunk"){this.enqueueStreamChunk(C,YG($.base64));return}if($.type==="done"){this.finishPending($);return}if($.type==="error"){if(C.optimisticResponse&&C.responseStartedAt!=null){b(`websocket relay error during optimistic response session=${B(this.affinity)} request=${C.payload.id} status=${$.status} message=${$.message||"unknown"} chunks=${C.streamChunkCount} bytes=${C.streamByteCount}`),this.deliverResponseHeaders(C),C.streamController?.enqueue(new TextEncoder().encode(`event: error
53
+ data: ${JSON.stringify({type:"error",error:{type:"relay_error",message:$.message||"relay error"}})}
54
+
55
+ `)),this.finishPending(),this.socket?.close();return}if($.status===409&&this.retryPendingBeforeResponse(C,$.message||"state mismatch"))return;let _=$.status===409?new h$($.message||"state mismatch"):Error(LG($));this.failPending(_)}}finishPending($){let C=this.pending;if(!C)return;let _=Q(),K=$&&"frames"in $?` upstreamChunks=${$.upstreamChunks??"unknown"} upstreamBytes=${$.upstreamBytes??"unknown"} frames=${$.frames} frameBytes=${$.frameBytes??"unknown"}`:"";if(b(`perf websocket done session=${B(this.affinity)} request=${C.payload.id} sentMs=${h(_-C.sentAt)} streamMs=${C.responseStartedAt==null?"unknown":h(_-C.responseStartedAt)} chunks=${C.streamChunkCount} bytes=${C.streamByteCount}${K}`),clearTimeout(C.timeout),!C.streamDone)this.deliverResponseHeaders(C),C.streamDone=!0,C.streamController?.close();C.resolveDone(),this.pending=void 0}failPending($){let C=this.pending;if(!C)return;if(clearTimeout(C.timeout),this.pending=void 0,C.responseStarted)C.streamController?.error($);else C.reject($);C.rejectDone($)}}function x$($=Date.now()){for(let[C,_]of v)if($-_.updatedAt>tK)v.delete(C);while(v.size>$G){let C=v.keys().next().value;if(C===void 0)break;v.delete(C)}for(let[C,_]of e)if(_.canEvict($))_.dispose(),e.delete(C);while(e.size>CG){let C=!1;for(let[_,K]of e){if(!K.canEvict($))continue;K.dispose(),e.delete(_),C=!0;break}if(!C)break}}function WG($,C){x$();let _=e.get(C);if(_)return _.touch(),_;let K=new BC($,C);return e.set(C,K),x$(),K}async function Dj($){let{config:C,input:_,init:K,headers:G,body:j,fallback:J,affinity:Z,optimisticResponse:z,onResponseHeaders:X}=$;if(!C||!jG(_,j))return J();let Y=Z||G.get("x-session-affinity")||G.get("x-opencode-session");if(!Y)return b("skipping relay: missing x-session-affinity header"),J();let O=j,L=Q(),W=_G(O);Y0("hash_body",{session:B(Y),ms:h(Q()-L),bodyBytes:O.length});let F=v.get(Y),V=Q(),E=zG({input:_,init:K,headers:G,bodyText:O,affinity:Y,previous:F,nextHash:W});Y0("create_payload",{session:B(Y),ms:h(Q()-V),mode:E.mode,bodyBytes:O.length,previousBytes:F?.body.length});try{let N,x=Q();if(C.transport==="websocket")try{N=await WG(C,Y).send(E,O,z===!0,X)}catch(M){b(`websocket relay failed session=${B(Y)}; trying http relay: ${M instanceof Error?M.message:String(M)}`),N=await MC({config:C,payload:E,bodyText:O,fallback:J,signal:K?.signal})}else N=await MC({config:C,payload:E,bodyText:O,fallback:J,signal:K?.signal});if(Y0("send",{session:B(Y),ms:h(Q()-x),transport:N.transport,protocol:N.protocol,mode:N.payload.mode,status:N.response.status,usedRelay:N.usedRelay}),!N.usedRelay)return N.response;if(N.transport==="http")try{X?.(N.response.headers)}catch{}if(N.transport==="http")QC(Y,O,N.payload.next_hash,N.payload.revision);let u=Q(),T=JSON.stringify(N.payload).length;Y0("payload_stringify",{session:B(Y),ms:h(Q()-u),relayBytes:T}),b(`used relay transport=${N.transport} protocol=${N.protocol} mode=${N.payload.mode} status=${N.response.status} session=${B(Y)} bodyBytes=${O.length} relayBytes=${T}`);let H=Q();return await GC({affinity:Y,transport:N.transport,protocol:N.protocol,mode:N.payload.mode,status:N.response.status,bodyText:O,previousBodyText:F?.body,payload:N.payload,relayBytes:T}),Y0("dump",{session:B(Y),ms:h(Q()-H),enabled:!0}),N.response}catch(N){if(!C.fallbackToDirect)throw b(`relay failed session=${B(Y)} and fallbackToDirect=false: ${N instanceof Error?N.message:String(N)}`),N;return b(`relay failed; falling back direct session=${B(Y)}: ${N instanceof Error?N.message:String(N)}`),J()}}var Sj=`
56
+ async function hashBody(body) {
57
+ const bytes = new TextEncoder().encode(body)
58
+ const digest = await crypto.subtle.digest('SHA-256', bytes)
59
+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
60
+ return 'sha256:' + hex
61
+ }
62
+
63
+ function applyPatch(base, patch) {
64
+ return base.slice(0, patch.start) + patch.insert + base.slice(patch.start + patch.deleteCount)
65
+ }
66
+
67
+ function applyPatchSet(base, patch) {
68
+ if (!Array.isArray(patch)) return applyPatch(base, patch)
69
+ if (patch.length === 0) return base
70
+
71
+ let result = ''
72
+ let cursor = 0
73
+ for (const item of patch) {
74
+ if (item.start < cursor) return { error: 'overlapping patch', status: 400 }
75
+ result += base.slice(cursor, item.start)
76
+ result += item.insert
77
+ cursor = item.start + item.deleteCount
78
+ }
79
+ return result + base.slice(cursor)
80
+ }
81
+
82
+ async function readState(env, affinity) {
83
+ const raw = await env.RELAY_STATE.get('session:' + affinity)
84
+ return raw ? JSON.parse(raw) : null
85
+ }
86
+
87
+ async function writeState(env, affinity, state) {
88
+ await env.RELAY_STATE.put('session:' + affinity, JSON.stringify(state), { expirationTtl: 86400 })
89
+ }
90
+
91
+ async function resolveBody(env, payload) {
92
+ if (payload.mode === 'full_sync') return payload.body
93
+ if (payload.mode === 'patch') {
94
+ const state = await readState(env, payload.affinity)
95
+ if (!state || state.hash !== payload.base_hash) {
96
+ return { error: 'state mismatch', status: 409 }
97
+ }
98
+ return applyPatchSet(state.body, payload.patch)
99
+ }
100
+ return { error: 'unknown mode', status: 400 }
101
+ }
102
+
103
+ async function prepareUpstream(env, payload) {
104
+ if ((payload.protocol !== 1 && payload.protocol !== 2) || payload.type !== 'request' || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
105
+ return { error: 'invalid payload', status: 400 }
106
+ }
107
+
108
+ const body = await resolveBody(env, payload)
109
+ if (body && typeof body === 'object' && 'error' in body) return body
110
+
111
+ if (typeof body !== 'string' || (await hashBody(body)) !== payload.next_hash) {
112
+ return { error: 'hash mismatch', status: 409 }
113
+ }
114
+
115
+ const stateWrite = writeState(env, payload.affinity, { body, hash: payload.next_hash, revision: payload.revision }).catch(() => {})
116
+ console.log(JSON.stringify({
117
+ relay: 'opencode-anthropic-auth',
118
+ transport: 'relay',
119
+ mode: payload.mode,
120
+ revision: payload.revision,
121
+ affinity: String(payload.affinity).slice(0, 12),
122
+ bodyBytes: body.length,
123
+ }))
124
+
125
+ return { body, stateWrite }
126
+ }
127
+
128
+ function resolveBodyFromState(state, payload) {
129
+ if (payload.mode === 'full_sync') return payload.body
130
+ if (payload.mode === 'patch') {
131
+ if (!state || state.hash !== payload.base_hash) {
132
+ return { error: 'state mismatch', status: 409 }
133
+ }
134
+ return applyPatchSet(state.body, payload.patch)
135
+ }
136
+ return { error: 'unknown mode', status: 400 }
137
+ }
138
+
139
+ function deferWorkerTask(task) {
140
+ return new Promise((resolve) => setTimeout(resolve, 0)).then(task)
141
+ }
142
+
143
+ const WEBSOCKET_STREAM_FLUSH_BYTES = 1024
144
+ const WEBSOCKET_STREAM_FLUSH_MS = 20
145
+
146
+ function createWebSocketStreamCoalescer(socket, options = {}) {
147
+ const flushBytes = options.flushBytes || WEBSOCKET_STREAM_FLUSH_BYTES
148
+ const flushMs = options.flushMs ?? WEBSOCKET_STREAM_FLUSH_MS
149
+ let chunks = []
150
+ let byteLength = 0
151
+ let flushTimer = null
152
+ const stats = {
153
+ upstreamChunks: 0,
154
+ upstreamBytes: 0,
155
+ frames: 0,
156
+ frameBytes: 0,
157
+ }
158
+
159
+ const clearFlushTimer = () => {
160
+ if (flushTimer === null) return
161
+ clearTimeout(flushTimer)
162
+ flushTimer = null
163
+ }
164
+
165
+ const mergeChunks = () => {
166
+ if (chunks.length === 1) return chunks[0]
167
+ const frame = new Uint8Array(byteLength)
168
+ let offset = 0
169
+ for (const chunk of chunks) {
170
+ frame.set(chunk, offset)
171
+ offset += chunk.byteLength
172
+ }
173
+ return frame
174
+ }
175
+
176
+ const flush = () => {
177
+ clearFlushTimer()
178
+ if (byteLength === 0) return
179
+ const frame = mergeChunks()
180
+ chunks = []
181
+ byteLength = 0
182
+ socket.send(frame)
183
+ stats.frames += 1
184
+ stats.frameBytes += frame.byteLength
185
+ }
186
+
187
+ const scheduleFlush = () => {
188
+ if (flushTimer !== null) return
189
+ flushTimer = setTimeout(flush, flushMs)
190
+ }
191
+
192
+ return {
193
+ push(value) {
194
+ const chunk = value instanceof Uint8Array ? value : new Uint8Array(value)
195
+ if (chunk.byteLength === 0) return
196
+ stats.upstreamChunks += 1
197
+ stats.upstreamBytes += chunk.byteLength
198
+ chunks.push(chunk)
199
+ byteLength += chunk.byteLength
200
+ if (byteLength >= flushBytes) flush()
201
+ else scheduleFlush()
202
+ },
203
+ flush,
204
+ stats() {
205
+ return { ...stats, pendingBytes: byteLength }
206
+ },
207
+ }
208
+ }
209
+
210
+ function checkpointWebSocketState(env, payload, body, nextState) {
211
+ return deferWorkerTask(async () => {
212
+ try {
213
+ if ((await hashBody(body)) !== payload.next_hash) {
214
+ throw new Error('hash mismatch')
215
+ }
216
+ await writeState(env, payload.affinity, nextState)
217
+ } catch (error) {
218
+ console.log(JSON.stringify({
219
+ relay: 'opencode-anthropic-auth',
220
+ transport: 'websocket',
221
+ event: 'checkpoint_write_failed',
222
+ affinity: String(payload.affinity).slice(0, 12),
223
+ message: error instanceof Error ? error.message : String(error),
224
+ }))
225
+ }
226
+ })
227
+ }
228
+
229
+ async function prepareWebSocketUpstream(env, state, payload) {
230
+ if (payload.protocol !== 2 || payload.type !== 'request' || !payload.id || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
231
+ return { error: 'invalid payload', status: 400 }
232
+ }
233
+
234
+ const body = resolveBodyFromState(state, payload)
235
+ if (body && typeof body === 'object' && 'error' in body) return body
236
+ if (typeof body !== 'string') return { error: 'invalid body', status: 400 }
237
+ if ((await hashBody(body)) !== payload.next_hash) {
238
+ return { error: 'hash mismatch', status: 409 }
239
+ }
240
+
241
+ const nextState = { body, hash: payload.next_hash, revision: payload.revision }
242
+ const checkpoint = checkpointWebSocketState(env, payload, body, nextState)
243
+ const logAccepted = () => console.log(JSON.stringify({
244
+ relay: 'opencode-anthropic-auth',
245
+ transport: 'websocket',
246
+ mode: payload.mode,
247
+ revision: payload.revision,
248
+ affinity: String(payload.affinity).slice(0, 12),
249
+ bodyBytes: body.length,
250
+ }))
251
+
252
+ return { body, state: nextState, checkpoint, logAccepted }
253
+ }
254
+
255
+ function headersToObject(headers) {
256
+ const result = {}
257
+ for (const [key, value] of headers.entries()) result[key] = value
258
+ return result
259
+ }
260
+
261
+ async function handleRelayPayload(env, payload) {
262
+ const prepared = await prepareUpstream(env, payload)
263
+ if (prepared.error) return prepared
264
+ const upstream = await fetch(payload.upstream.url, {
265
+ method: payload.upstream.method || 'POST',
266
+ headers: payload.upstream.headers,
267
+ body: prepared.body,
268
+ })
269
+ return { upstream, stateWrite: prepared.stateWrite }
270
+ }
271
+
272
+ async function handleWebSocket(socket, env, ctx, payload, getState, setState) {
273
+ const heartbeat = setInterval(() => {
274
+ try {
275
+ socket.send(JSON.stringify({ protocol: 2, type: 'keepalive' }))
276
+ } catch {
277
+ clearInterval(heartbeat)
278
+ }
279
+ }, 15000)
280
+ let streamCoalescer = null
281
+ try {
282
+ const result = await prepareWebSocketUpstream(env, getState(), payload)
283
+ if (result.error) {
284
+ socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: result.status, message: result.error }))
285
+ return
286
+ }
287
+
288
+ setState(result.state)
289
+ socket.send(JSON.stringify({ protocol: 2, type: 'accepted', id: payload.id, hash: result.state.hash, revision: result.state.revision }))
290
+ ctx?.waitUntil?.(deferWorkerTask(result.logAccepted))
291
+
292
+ const upstreamPromise = fetch(payload.upstream.url, {
293
+ method: payload.upstream.method || 'POST',
294
+ headers: payload.upstream.headers,
295
+ body: result.body,
296
+ })
297
+ ctx?.waitUntil?.(result.checkpoint)
298
+ const upstream = await upstreamPromise
299
+ socket.send(JSON.stringify({
300
+ protocol: 2,
301
+ type: 'response_start',
302
+ id: payload.id,
303
+ status: upstream.status,
304
+ statusText: upstream.statusText,
305
+ headers: headersToObject(upstream.headers),
306
+ }))
307
+
308
+ const reader = upstream.body?.getReader()
309
+ if (reader) {
310
+ streamCoalescer = createWebSocketStreamCoalescer(socket)
311
+ while (true) {
312
+ const { done, value } = await reader.read()
313
+ if (done) break
314
+ streamCoalescer.push(value)
315
+ }
316
+ streamCoalescer.flush()
317
+ }
318
+ const stats = streamCoalescer?.stats?.() || {}
319
+ socket.send(JSON.stringify({ protocol: 2, type: 'done', id: payload.id, ...stats }))
320
+ } catch (error) {
321
+ try {
322
+ streamCoalescer?.flush?.()
323
+ } catch {}
324
+ socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: 500, message: error instanceof Error ? error.message : String(error) }))
325
+ } finally {
326
+ clearInterval(heartbeat)
327
+ }
328
+ }
329
+
330
+ export default {
331
+ async fetch(request, env, ctx) {
332
+ if (request.headers.get('Upgrade') === 'websocket') {
333
+ const url = new URL(request.url)
334
+ const token = url.searchParams.get('token')
335
+ const affinity = url.searchParams.get('affinity')
336
+ if (token !== env.RELAY_TOKEN) return new Response('unauthorized', { status: 401 })
337
+ if (!affinity) return new Response('missing affinity', { status: 400 })
338
+ const pair = new WebSocketPair()
339
+ const client = pair[0]
340
+ const server = pair[1]
341
+ server.binaryType = 'arraybuffer'
342
+ let state = null
343
+ let ready = false
344
+ server.accept()
345
+ const loadState = readState(env, affinity).then((loadedState) => {
346
+ state = loadedState
347
+ ready = true
348
+ server.send(JSON.stringify({
349
+ protocol: 2,
350
+ type: 'ready',
351
+ state: state ? { hash: state.hash, revision: state.revision } : null,
352
+ }))
353
+ }).catch((error) => {
354
+ server.send(JSON.stringify({ protocol: 2, type: 'error', status: 500, message: error instanceof Error ? error.message : String(error) }))
355
+ server.close(1011, 'state load failed')
356
+ })
357
+ ctx?.waitUntil?.(loadState)
358
+ if (!ctx?.waitUntil) void loadState
359
+ let busy = false
360
+ server.addEventListener('message', (event) => {
361
+ if (!ready) {
362
+ server.send(JSON.stringify({ protocol: 2, type: 'error', status: 425, message: 'relay state is not ready' }))
363
+ return
364
+ }
365
+ if (busy) {
366
+ server.send(JSON.stringify({ protocol: 2, type: 'error', status: 429, message: 'request already in flight' }))
367
+ return
368
+ }
369
+ let payload
370
+ try {
371
+ payload = JSON.parse(event.data)
372
+ } catch {
373
+ server.send(JSON.stringify({ protocol: 2, type: 'error', status: 400, message: 'invalid JSON payload' }))
374
+ return
375
+ }
376
+ payload.affinity = affinity
377
+ busy = true
378
+ const run = handleWebSocket(server, env, ctx, payload, () => state, (nextState) => { state = nextState }).finally(() => { busy = false })
379
+ ctx?.waitUntil?.(run)
380
+ if (!ctx?.waitUntil) void run
381
+ })
382
+ return new Response(null, { status: 101, webSocket: client })
383
+ }
384
+
385
+ if (request.method === 'GET') {
386
+ return Response.json({ status: 'ok', transports: ['http', 'websocket'] })
387
+ }
388
+ if (request.method !== 'POST') return new Response('method not allowed', { status: 405 })
389
+ if (request.headers.get('x-relay-token') !== env.RELAY_TOKEN) {
390
+ return new Response('unauthorized', { status: 401 })
391
+ }
392
+
393
+ try {
394
+ const payload = await request.json()
395
+ const result = await handleRelayPayload(env, payload)
396
+ if (result.error) return Response.json({ error: result.error }, { status: result.status })
397
+
398
+ if (result.stateWrite) ctx.waitUntil(result.stateWrite)
399
+
400
+ const upstream = result.upstream
401
+ return new Response(upstream.body, {
402
+ status: upstream.status,
403
+ statusText: upstream.statusText,
404
+ headers: upstream.headers,
405
+ })
406
+ } catch (error) {
407
+ return Response.json(
408
+ { error: error instanceof Error ? error.message : 'internal relay error' },
409
+ { status: 502 },
410
+ )
411
+ }
412
+ },
413
+ }
414
+ `;var Aj="claude-routing",k$=["main-first","fallback-first","sticky-balanced"],y$="main-first",DC="Usage: `/claude-routing`, `/claude-routing main-first`, `/claude-routing fallback-first`, `/claude-routing sticky-balanced`, or `/claude-routing reset`.";function HG($){return typeof $==="string"&&k$.includes($)?$:y$}function Pj($){return HG($?.routing?.mode)}async function Ij($,C=f()){let _=await S(C)??I();return _.routing={..._.routing??{},mode:$},await R(_,C),_}function FG($){let C=$.trim().toLowerCase().split(/\s+/).filter(Boolean);if(C.length===0)return{type:"status"};if(C.length===1&&C[0]==="reset")return{type:"reset"};if(C.length===1&&k$.includes(C[0]))return{type:"mode",mode:C[0]};if(C.length===2&&C[0]==="mode"&&k$.includes(C[1]))return{type:"mode",mode:C[1]};return{type:"usage"}}function UG($){if($==="fallback-first")return"Try usable fallback accounts before the main account. If no fallback succeeds, try the main account.";if($==="sticky-balanced")return"Assign each session to a quota-weighted OAuth account, keep it sticky across transient failures, and migrate only for confirmed long-lived exhaustion or permanent account failure.";return"Try the main account first. Use fallback accounts only when quota policy or fallback errors require it."}function t0($){let C=$?.mode??y$;return["## Claude Routing Status","",`- Mode: \`${C}\``,`- Behavior: ${UG(C)}`,"",DC].join(`
415
+ `)}function hj($){let C=FG($.argumentsText),_=$.mode??y$;if(C.type==="status")return t0({mode:_});if(C.type==="mode")return["## Claude Routing Updated","",`Mode updated to \`${C.mode}\`.`,"",...t0({mode:C.mode}).split(`
416
+ `).slice(2)].join(`
417
+ `);if(C.type==="reset")return["## Claude Routing Assignment Reset","","The current session will be assigned again on its next request.","",...t0({mode:_}).split(`
418
+ `).slice(2)].join(`
419
+ `);return["## Claude Routing Usage","",DC,"",...t0({mode:_}).split(`
420
+ `).slice(2)].join(`
421
+ `)}import{createHash as wC,randomUUID as VG}from"node:crypto";import{mkdir as MG,readFile as fG,rename as bG,rm as EG,stat as QG,writeFile as BG}from"node:fs/promises";import{basename as DG,dirname as xC,join as SG}from"node:path";var RG="main",qG=900000,SC=604800000,AG=3600000,PG=1e4,IG=5000,hG=10,RC=4096,TG=0.000001;function m$($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function b0($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function wG($){if(!m$($))return;if(typeof $.accountId!=="string"||!["fable","opus","general"].includes(String($.family)))return;let C=b0($.assignedAt),_=b0($.lastSeenAt),K=b0($.initialInputBytes),G=b0($.quotaCheckedAt);if(C===void 0||_===void 0||K===void 0||G===void 0)return;return{accountId:$.accountId,family:$.family,assignedAt:C,lastSeenAt:_,initialInputBytes:Math.max(0,K),quotaCheckedAt:G}}function xG($){if(!m$($)||$.version!==1||!m$($.assignments))return;let C={};for(let[_,K]of Object.entries($.assignments)){let G=wG(K);if(G)C[_]=G}return{version:1,updatedAt:b0($.updatedAt)??0,assignments:C}}function qC($){return{version:1,updatedAt:$,assignments:{}}}function AC($){return wC("sha256").update($).digest("hex")}function kC($,C,_=Date.now(),K){let G=m(C);if(!["five_hour","seven_day"].every((Z)=>{let z=$?.[Z];return Boolean(z&&_-z.checkedAt<G)}))return!1;let J=y($,K);return!J||_-J.checkedAt<G}function PC($){return Math.max($.checkedAt??0,$.five_hour?.checkedAt??0,$.seven_day?.checkedAt??0,...($.scoped??[]).map((C)=>C.checkedAt??0))}function IC($,C,_){let K=I0($),G=_==="five_hour"?K.five_hour:_==="seven_day"?K.seven_day:0;if(!F$($))return G;let j=U$($,C===RG?void 0:C);return Math.max(G,j[_])}function hC($,C,_,K){let G=Math.max(0,$-C);if(G<=0)return 0;if(!_)return G;let j=Date.parse(_);if(!Number.isFinite(j)||j<=K)return G;let J=Math.max((j-K)/3600000,0.016666666666666666);return G/J}function vj($){if(XC($))return"fable";return typeof $==="string"&&$.toLowerCase().includes("opus")?"opus":"general"}function TC($){let C=$.now??Date.now(),{candidate:_,storage:K}=$;if(!kC(_.quota,K,C,$.modelId))return 0;let G=[];for(let j of["five_hour","seven_day"]){let J=_.quota[j];if(!J||!Number.isFinite(J.remainingPercent))return 0;G.push(hC(J.remainingPercent,IC(K,_.accountId,j),J.resetsAt,C))}if($.family==="fable"){let j=y(_.quota,$.modelId);if(j&&Number.isFinite(j.remainingPercent))G.push(hC(j.remainingPercent,IC(K,_.accountId,"scoped"),j.resetsAt,C))}return Math.min(...G)}function kG($,C,_=Date.now()){let K=y($.quota,"claude-fable-5");return Boolean(K&&kC($.quota,C,_,"claude-fable-5")&&Number.isFinite(K.remainingPercent)&&K.remainingPercent<=0)}function lj($){let C=$.now??Date.now();if(!$.quota)return{action:"retain",reason:"unknown"};let _=y($.quota,$.modelId);if(_&&Number.isFinite(_.remainingPercent)&&_.remainingPercent<=0)return{action:"migrate",reason:"model-scoped"};let K=$.quota.seven_day;if(K&&Number.isFinite(K.remainingPercent)&&K.remainingPercent<=0)return{action:"migrate",reason:"seven-day"};let G=$.quota.five_hour;if(G&&Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0){let j=G.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(j)&&j>C&&j-C<=qG)return{action:"hold",reason:"five-hour-short-reset",retryAfterSeconds:Math.max(1,Math.ceil((j-C)/1000))};return{action:"migrate",reason:"five-hour"}}return{action:"retain",reason:"not-exhausted"}}function pj($){let C=DG($),_=C.endsWith(".json")?C.slice(0,-5):C;return SG(xC($),`${_}-routing-state.json`)}function gj($,C){let _=wC("sha256").update($).digest().readUInt32BE(0);return Math.max(1,Math.ceil(C))+_%21}class yG{options;loaded=!1;state;stateMtimeNs;touchChain=Promise.resolve();constructor($){this.options=$,this.state=qC(this.now())}now(){return this.options.now?.()??Date.now()}async readState(){try{let $=await fG(this.options.path,"utf8"),C=xG(JSON.parse($));if(!C)throw Error(`Invalid sticky routing state at ${this.options.path}`);return C}catch($){if($.code==="ENOENT")return qC(this.now());throw $}}async readStateMtimeNs(){try{return(await QG(this.options.path,{bigint:!0})).mtimeNs}catch($){if($.code==="ENOENT")return 0n;throw $}}async refreshStateIfChanged(){for(let $=0;$<3;$++){let C=await this.readStateMtimeNs();if(this.loaded&&C===this.stateMtimeNs)return;let _=await this.readState(),K=await this.readStateMtimeNs();if(C!==K)continue;this.state=_,this.stateMtimeNs=K,this.loaded=!0;return}this.state=await this.readState(),this.stateMtimeNs=await this.readStateMtimeNs(),this.loaded=!0}async acquireLock(){await MG(xC(this.options.path),{recursive:!0,mode:448});let $=this.now()+IG;while(!0){let C=await o({name:"write",path:this.options.path,ttlMs:PG,renew:!0});if(C)return C;if(this.now()>=$)throw Error("Timed out acquiring sticky routing state lock");await new Promise((_)=>setTimeout(_,hG))}}assignmentIsActive($){return $.lastSeenAt>=this.now()-(this.options.assignmentTtlMs??SC)}prune($){let C=this.now()-(this.options.assignmentTtlMs??SC);for(let[K,G]of Object.entries($.assignments))if(G.lastSeenAt<C)delete $.assignments[K];let _=Object.entries($.assignments);if(_.length<=RC)return;_.sort((K,G)=>G[1].lastSeenAt-K[1].lastSeenAt).slice(RC).forEach(([K])=>{delete $.assignments[K]})}async writeState($){this.prune($),$.updatedAt=this.now();let C=`${this.options.path}.${VG()}.tmp`;try{await BG(C,`${JSON.stringify($)}
422
+ `,{mode:384}),await bG(C,this.options.path)}finally{await EG(C,{force:!0}).catch(()=>{})}this.state=$,this.stateMtimeNs=await this.readStateMtimeNs(),this.loaded=!0}scheduleTouch($){this.touchChain=this.touchChain.catch(()=>{}).then(async()=>{let C=await this.acquireLock();try{let _=await this.readState(),K=_.assignments[$];if(!K)return;K.lastSeenAt=this.now(),await this.writeState(_)}finally{await C.release()}}).catch(()=>{})}selectCandidate($){let C=[...$.candidates];if($.family==="opus"){let G=C.filter((j)=>kG(j,$.storage,this.now()));if(G.length>0)C=G}let _=C.flatMap((G)=>{let j=TC({candidate:G,family:$.family,modelId:$.modelId,storage:$.storage,now:this.now()});return j>0?[{candidate:G,weight:j}]:[]});if(_.length===0)return;let K=new Map;for(let G of Object.values($.state.assignments)){let j=_.find((J)=>J.candidate.accountId===G.accountId)?.candidate;if(!j)continue;if(G.quotaCheckedAt!==PC(j.quota))continue;K.set(G.accountId,(K.get(G.accountId)??0)+G.initialInputBytes)}return _.map(({candidate:G,weight:j})=>({candidate:G,score:((K.get(G.accountId)??0)+$.inputBytes)/Math.max(j,TG)})).sort((G,j)=>G.score-j.score||G.candidate.order-j.candidate.order||G.candidate.accountId.localeCompare(j.candidate.accountId))[0]?.candidate}async resolve($){if(!$.sessionId)return null;await this.refreshStateIfChanged();let C=AC($.sessionId),_=this.state.assignments[C];if(_&&this.assignmentIsActive(_)&&$.retainAccountIds.has(_.accountId)&&!$.excludeAccountIds?.has(_.accountId)){if(this.now()-_.lastSeenAt>=AG)_.lastSeenAt=this.now(),this.scheduleTouch(C);return{accountId:_.accountId,assignment:{..._},created:!1,migrated:!1}}let K=await this.acquireLock();try{let G=await this.readState();this.prune(G);let j=G.assignments[C];if(j&&$.retainAccountIds.has(j.accountId)&&!$.excludeAccountIds?.has(j.accountId))return j.lastSeenAt=this.now(),await this.writeState(G),{accountId:j.accountId,assignment:{...j},created:!1,migrated:!1};let J=$.candidates.filter((O)=>!$.excludeAccountIds?.has(O.accountId)),z=($.preferredAccountId?J.find((O)=>O.accountId===$.preferredAccountId&&TC({candidate:O,family:$.family,modelId:$.modelId,storage:$.storage,now:this.now()})>0):void 0)??this.selectCandidate({...$,candidates:J,state:G});if(!z){if(j)delete G.assignments[C],await this.writeState(G);return null}let X=this.now(),Y={accountId:z.accountId,family:$.family,assignedAt:X,lastSeenAt:X,initialInputBytes:Math.max(1,$.inputBytes),quotaCheckedAt:PC(z.quota)};return G.assignments[C]=Y,await this.writeState(G),{accountId:z.accountId,assignment:{...Y},created:!j,migrated:Boolean(j&&j.accountId!==z.accountId)}}finally{await K.release()}}async clear($){if(!$)return;let C=AC($),_=await this.acquireLock();try{let K=await this.readState();if(!(C in K.assignments))return;delete K.assignments[C],await this.writeState(K)}finally{await _.release()}}}export{mG as s,d$ as t,vG as u,lG as v,pG as w,gG as x,dG as y,u$ as z,uG as A,iG as B,a$ as C,oG as D,aG as E,D as F,k as G,X2 as H,sC as I,Y2 as J,f as K,I as L,S as M,R as N,h6 as O,O2 as P,o as Q,N2 as R,w6 as S,L2 as T,W2 as U,H2 as V,F2 as W,U2 as X,V2 as Y,M2 as Z,f2 as _,b2 as $,E2 as aa,Q2 as ba,B2 as ca,M1 as da,l6 as ea,D2 as fa,O0 as ga,J$ as ha,S2 as ia,R2 as ja,q2 as ka,f1 as la,y as ma,g6 as na,Z1 as oa,E1 as pa,F$ as qa,U$ as ra,A2 as sa,P2 as ta,I2 as ua,h2 as va,T2 as wa,w2 as xa,x2 as ya,k2 as za,j0 as Aa,$_ as Ba,v2 as Ca,l2 as Da,p2 as Ea,g2 as Fa,j_ as Ga,d2 as Ha,k1 as Ia,C4 as Ja,r2 as Ka,s2 as La,n2 as Ma,h1 as Na,J4 as Oa,Z4 as Pa,k_ as Qa,m0 as Ra,v0 as Sa,d1 as Ta,y_ as Ua,z4 as Va,l_ as Wa,W4 as Xa,o_ as Ya,F4 as Za,U4 as _a,d as $a,D4 as ab,S4 as bb,R4 as cb,Z0 as db,P4 as eb,CK as fb,_K as gb,I4 as hb,v4 as ib,l4 as jb,hK as kb,p4 as lb,g4 as mb,u4 as nb,i4 as ob,c4 as pb,pK as qb,r4 as rb,X0 as sb,o4 as tb,t4 as ub,uK as vb,e4 as wb,Cj as xb,zC as yb,_j as zb,Kj as Ab,Gj as Bb,jj as Cb,Jj as Db,XC as Eb,Zj as Fb,zj as Gb,Xj as Hb,Yj as Ib,Oj as Jb,Hj as Kb,Fj as Lb,Uj as Mb,Qj as Nb,Bj as Ob,Dj as Pb,Sj as Qb,Aj as Rb,Pj as Sb,Ij as Tb,FG as Ub,hj as Vb,RG as Wb,kC as Xb,vj as Yb,lj as Zb,pj as _b,gj as $b,yG as ac};