@cortexkit/opencode-anthropic-auth 1.19.1 → 1.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -2
- package/dist/cache-diagnostics.d.ts +79 -0
- package/dist/cli.js +2 -2
- package/dist/index-1db17bc2.js +2 -0
- package/dist/{index-dex8fs0m.js → index-4nz423bt.js} +1 -1
- package/dist/{index-dzs7w297.js → index-4x20896x.js} +1 -1
- package/dist/{index-2k47hc8b.js → index-w9d41yy9.js} +1 -1
- package/dist/index-wezdyxst.js +2 -0
- package/dist/{index-075t8qec.js → index-y0khnbt6.js} +1 -1
- package/dist/index-yskwj5e6.js +428 -0
- package/dist/index.d.ts +0 -37
- package/dist/index.js +23 -19
- package/dist/lane-start.d.ts +17 -0
- package/dist/{logger-n49md99d.js → logger-ftk4bg3p.js} +1 -1
- package/dist/prime-manager-registry.d.ts +7 -0
- package/dist/request-policy.d.ts +25 -0
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +2 -1
- package/dist/rpc/protocol.js +1 -0
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/server-fallback.d.ts +2 -0
- package/dist/sidebar-state.d.ts +26 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/transform.d.ts +13 -0
- package/dist/tui/command-dialogs.d.ts +16 -1
- package/dist/tui-preferences.js +1 -1
- package/package.json +4 -4
- package/src/rpc/protocol.ts +15 -10
- package/src/sidebar-state.ts +154 -17
- package/src/tui/command-dialogs.tsx +112 -0
- package/src/tui-compiled/rpc/protocol.ts +15 -10
- package/src/tui-compiled/sidebar-state.ts +154 -17
- package/src/tui-compiled/tui/command-dialogs.tsx +134 -18
- package/src/tui-compiled/tui.tsx +43 -1
- package/src/tui.tsx +28 -0
- package/dist/index-a13w4gm9.js +0 -2
- package/dist/index-vwgzgh5x.js +0 -422
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
import{Lc as LC,Pc as N,Qc as a,Rc as B}from"./index-4nz423bt.js";import{Zc as l6}from"./index-4x20896x.js";var y0="9d1c250a-e61b-44d9-88ed-5944d1962f5e",O$={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.com/cai/oauth/authorize"},M1="https://platform.claude.com/oauth/code/callback",Q1="https://platform.claude.com/v1/oauth/token",S1="axios/1.15.2",f$=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],L$="user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload",N8="mcp_";var N$="fast-mode-2026-02-01";function E8($,C){let j=($??"").split(",").map((_)=>_.trim()).filter(Boolean);return[...new Set([...j,...C])].join(",")}function F8($){return typeof $==="string"&&($.startsWith("claude-opus-4-6")||$.startsWith("claude-opus-4-7")||$.startsWith("claude-opus-4-8")||$.startsWith("claude-opus-5"))}var M8="You are OpenCode",Q8="You are Claude Code, Anthropic's official CLI for Claude.",S8=["<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 u="2.1.177",U1="3bf",E$="cli",F$="0.94.0",M$="v24.3.0",Q$="claude-cli/2.1.177 (external, cli)",S$=["explicit","automatic","hybrid"],l0="explicit",U8=["github.com/anomalyco/opencode","opencode.ai/docs"],B8=[{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 U$($){let C="";for(let j of $)C+=String.fromCharCode(j);return btoa(C).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function B$(){let $=new Uint8Array(64);crypto.getRandomValues($);let C=U$($),j=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(C));return{verifier:C,challenge:U$(new Uint8Array(j)),method:"S256"}}function b1($){if(!$)return;let C=Number($);if(Number.isFinite(C)&&C>0)return Math.ceil(C);let j=Date.parse($);if(Number.isFinite(j)){let _=Math.ceil((j-Date.now())/1000);return _>0?_:void 0}return}class B1 extends Error{status;body;retryAfter;isRefreshError=!0;constructor($,C,j){super(`Claude OAuth refresh failed: ${$} — ${C}`);this.status=$,this.body=C,this.name="ClaudeOAuthRefreshError",this.retryAfter=b1(j??void 0)}}function I6($){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 b$($){let C=$.fetchImpl??fetch,j=$.maxRetries??2,_=$.baseDelayMs??500,J=$.setTimeoutImpl??globalThis.setTimeout;for(let G=0;G<=j;G++)try{if(G>0){let z=_*2**(G-1);await new Promise((X)=>J(X,z))}let K=await C(Q1,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":S1},body:JSON.stringify({grant_type:"refresh_token",refresh_token:$.refreshToken,client_id:y0,scope:L$})});if(!K.ok){if(K.status>=500&&G<j){await K.body?.cancel().catch(()=>{});continue}let z=await K.text().catch(()=>"");throw new B1(K.status,z,K.headers.get("retry-after"))}let V=await K.json(),Z=$.now?.()??Date.now();return{access:V.access_token,refresh:V.refresh_token??$.refreshToken,expires:Z+V.expires_in*1000,expiresIn:V.expires_in,authLineageId:$.authLineageId}}catch(K){if(K instanceof B1)throw K;if(G<j&&I6(K))continue;throw K}throw Error("Token refresh exhausted all retries")}function v6(){return crypto.randomUUID().replace(/-/g,"")}function m6($){let C=$.trim();try{let K=new URL(C),V=K.searchParams.get("code"),Z=K.searchParams.get("state");if(V&&Z)return{code:V,state:Z}}catch{}let j=C.split("#");if(j.length===2&&j[0]&&j[1])return{code:j[0],state:j[1]};let _=new URLSearchParams(C),J=_.get("code"),G=_.get("state");if(J&&G)return{code:J,state:G};return null}async function y6($,C,j){let _=await fetch(Q1,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":S1},body:JSON.stringify({code:$.code,state:$.state,grant_type:"authorization_code",client_id:y0,redirect_uri:j,code_verifier:C})});if(!_.ok)return{type:"failed"};let J=await _.json();return{type:"success",refresh:J.refresh_token,access:J.access_token,expires:Date.now()+J.expires_in*1000}}async function q8($){let C=await B$(),j=v6(),_=new URL(O$[$],import.meta.url);return _.searchParams.set("code","true"),_.searchParams.set("client_id",y0),_.searchParams.set("response_type","code"),_.searchParams.set("redirect_uri",M1),_.searchParams.set("scope",f$.join(" ")),_.searchParams.set("code_challenge",C.challenge),_.searchParams.set("code_challenge_method","S256"),_.searchParams.set("state",j),{url:_.toString(),redirectUri:M1,state:j,verifier:C.verifier}}async function x8($,C,j,_){let J=m6($);if(!J)return{type:"failed"};if(_&&J.state!==_)return{type:"failed"};return y6(J,C,j)}import{createHash as v$,randomUUID as d}from"node:crypto";import{mkdir as q1,readFile as g0,rename as m$,rm as G0,stat as D$,writeFile as p0}from"node:fs/promises";import{homedir as g6}from"node:os";import{dirname as x1,join as K0}from"node:path";var p6=globalThis.setTimeout.bind(globalThis),s6=globalThis.clearTimeout.bind(globalThis),y$="anthropic-auth.json",u6="anthropic-auth-state.json",d6="https://api.anthropic.com/api/oauth/usage";function P($){return $.type==="oauth"}function y8($){return $.type==="api"}function c6($){let C=$?.trim();if(!C)return!1;try{let j=new URL(C);return(j.protocol==="http:"||j.protocol==="https:")&&!j.username&&!j.password}catch{return!1}}function l8($){return $.costZeroing?.enabled!==!1}var i6=[401,403,429],l$=240,r6=l$;var o6=300000,n6=3600000,g$=86400000,a6=60000,t6=900000,e6=300000,$2=5,T$={five_hour:0,seven_day:0},C2=!0,j2=60000,_2=60000,J2=600000,G2=1e4,K2=100;function V2(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return K0(process.env.XDG_CONFIG_HOME||K0(g6(),".config"),"opencode")}function Q(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||K0(V2(),y$)}function P1($=Q()){let C=process.env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim();if(C)return C;return $.endsWith(y$)?K0(x1($),u6):`${$}.state.json`}function F($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function R$($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():d(),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 Z2($){if(!F($))return null;if($.type==="api"){let C=typeof $.baseURL==="string"?$.baseURL.trim():"",j=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!c6(C))return null;let _=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...R$($),type:"api",apiKey:j||void 0,baseURL:C,authHeader:_}}if($.type!=="oauth")return null;if(typeof $.refresh!=="string"||!$.refresh.trim())return null;return{...R$($),type:"oauth",authLineageId:typeof $.authLineageId==="string"&&$.authLineageId.trim()?$.authLineageId:void 0,access:typeof $.access==="string"?$.access:void 0,refresh:$.refresh,expires:typeof $.expires==="number"?$.expires:void 0,lastRefreshedAt:typeof $.lastRefreshedAt==="number"?$.lastRefreshedAt:void 0,lastRefreshError:q$($.lastRefreshError),lastQuotaRefreshError:q$($.lastQuotaRefreshError),quota:z2($.quota),profile:B0($.profile),prime:A1($.prime)}}function B0($){if(!F($))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 $.accountIdentity==="string"&&$.accountIdentity.trim()&&{accountIdentity:$.accountIdentity.trim()},...typeof $.tokenFingerprint==="string"&&$.tokenFingerprint.trim()&&{tokenFingerprint:$.tokenFingerprint.trim()}}}function q$($){if(!F($))return;if(typeof $.message!=="string")return;let C=Number($.checkedAt);if(!Number.isFinite(C))return;let j=Number($.nextRetryAt),_=Number($.retryCount),J=Number($.status);return{message:$.message,checkedAt:C,nextRetryAt:Number.isFinite(j)?j:void 0,retryCount:Number.isFinite(_)?_:void 0,accountIdentity:typeof $.accountIdentity==="string"&&$.accountIdentity.trim()?$.accountIdentity.trim():void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0,status:Number.isFinite(J)?J:void 0,permanent:typeof $.permanent==="boolean"?$.permanent:void 0}}function x$($){if(!F($))return;let C=Number($.usedPercent),j=Number($.remainingPercent),_=Number($.checkedAt);if(!Number.isFinite(C)||!Number.isFinite(j)||!Number.isFinite(_))return;return{usedPercent:C,remainingPercent:j,checkedAt:_,resetsAt:typeof $.resetsAt==="string"?$.resetsAt:void 0}}function A1($){if(!F($))return;let C=Number($.count),j=Number($.inputTokens),_=Number($.outputTokens),J=Number($.since);if(![C,j,_,J].every(Number.isFinite)||C<0||j<0||_<0||J<0)return;return{count:Math.floor(C),inputTokens:Math.floor(j),outputTokens:Math.floor(_),since:Math.floor(J)}}function z2($){if(!F($))return;let C={};for(let j of["five_hour","seven_day"]){let _=x$($[j]);if(_)C[j]=_}if(typeof $.checkedAt==="number"&&Number.isFinite($.checkedAt))C.checkedAt=$.checkedAt;if(typeof $.accountIdentity==="string"&&$.accountIdentity.trim())C.accountIdentity=$.accountIdentity.trim();if(Array.isArray($.scoped)){let j=$.scoped.map((_)=>{if(!F(_))return;let J=x$(_);if(!J)return;if(typeof _.id!=="string"||!_.id.trim())return;if(typeof _.title!=="string"||!_.title.trim())return;if(typeof _.modelName!=="string"||!_.modelName.trim())return;let G=typeof _.modelId==="string"&&_.modelId.trim()?_.modelId.trim():void 0;return{...J,id:_.id.trim(),title:_.title.trim(),...G&&{modelId:G},modelName:_.modelName.trim()}}).filter((_)=>_!=null);C.scoped=j}if(F($.extraUsage)){let j=P$($.extraUsage.used),_=P$($.extraUsage.limit);if(j&&_&&typeof $.extraUsage.exhausted==="boolean")C.extraUsage={used:j,limit:_,...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 P$($){if(!F($))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 A(){return{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]}}function X2($){if(!F($)||!Array.isArray($.accounts))return null;return{version:1,mainAccountId:typeof $.mainAccountId==="string"&&$.mainAccountId.trim()?$.mainAccountId.trim():void 0,main:{type:"opencode",provider:"anthropic",profile:B0(F($.main)?$.main.profile:void 0)},routing:F($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((C)=>Number.isInteger(C)):void 0,refresh:F($.refresh)?$.refresh:void 0,quota:F($.quota)?$.quota:void 0,quotaHeaderFeed:F($.quotaHeaderFeed)?$.quotaHeaderFeed:void 0,claudeCache:F($.claudeCache)?$.claudeCache:void 0,dump:F($.dump)?$.dump:void 0,claudeFast:F($.claudeFast)?$.claudeFast:void 0,costZeroing:F($.costZeroing)?$.costZeroing:void 0,cacheKeep:F($.cacheKeep)?$.cacheKeep:void 0,relay:F($.relay)?$.relay:void 0,logging:F($.logging)?$.logging:void 0,killswitch:F($.killswitch)?$.killswitch:void 0,prime:(()=>{if(!F($.prime))return;let C=typeof $.prime.enabled==="boolean"?$.prime.enabled:void 0,j=A1($.prime.main),_=typeof $.prime.mainAuthLineageId==="string"&&$.prime.mainAuthLineageId.trim()?$.prime.mainAuthLineageId:void 0,J=typeof $.prime.mainAuthLineageRefreshTokenFingerprint==="string"&&$.prime.mainAuthLineageRefreshTokenFingerprint.trim()?$.prime.mainAuthLineageRefreshTokenFingerprint:void 0;if(C===void 0&&!j&&!_&&!J)return;return{...C!==void 0&&{enabled:C},...j&&{main:j},..._&&{mainAuthLineageId:_},...J&&{mainAuthLineageRefreshTokenFingerprint:J}}})(),accounts:$.accounts.map(Z2).filter((C)=>C!=null)}}async function b0($){try{return{exists:!0,value:JSON.parse(await g0($,"utf8"))}}catch(C){if(C.code==="ENOENT")return{exists:!1,value:null};let j=C instanceof Error?C.message:String(C);throw Error(`account store at ${$} is corrupt or unreadable (${j}) — fix or remove it`)}}function e($){return Object.fromEntries(Object.entries($).filter(([,C])=>C!==void 0))}function s0($){return typeof $==="number"&&Number.isFinite($)?$:0}function H0($,C){if(C===void 0||!Number.isFinite(C))return $;if($===void 0||!Number.isFinite($))return C;return Math.max($,C)}function R1($){return Math.max(s0($.lastRefreshedAt),s0($.lastUsed),s0($.addedAt))}function Y2($,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 R1($)>R1(C)}function H2($,C){if(Y2($,C)){let j={...C,...$},_=R1($);if(_>s0(j.lastRefreshedAt))j.lastRefreshedAt=_;return delete j.quota,delete j.lastRefreshError,delete j.lastQuotaRefreshError,j}return{...$,...C}}function W2($,C){if(!F($))return $;let j=F(C)?C:{},_=F(j.main)?j.main:void 0,J=F(j.accounts)?j.accounts:{},G=F($.quota)?$.quota:{},K=F($.refresh)?$.refresh:{},V=_??G,Z=_??K,z=typeof _?.quotaErrorClearedAt==="number"&&Number.isFinite(_.quotaErrorClearedAt)&&_.quotaErrorClearedAt>=0?_.quotaErrorClearedAt:void 0,X=G.mainLastQuotaApiError,O=_?.lastQuotaApiError??(z!==void 0&&F(X)&&typeof X.checkedAt==="number"&&X.checkedAt<=z?void 0:X),W=Array.isArray($.accounts)?$.accounts.map((Y)=>{if(!F(Y))return Y;let L=typeof Y.id==="string"&&F(J[Y.id])?J[Y.id]:{};return H2(Y,L)}):[];return{...$,main:{type:"opencode",provider:"anthropic",profile:B0(_?.profile)},refresh:e({...K,mainLastRefreshError:Z.lastRefreshError,mainRefreshLeaseId:Z.refreshLeaseId,mainRefreshLeaseUntil:Z.refreshLeaseUntil,mainRefreshLeaseTokenHash:Z.refreshLeaseTokenHash}),quota:e({...G,mainQuota:V.quota,mainQuotaCheckedAt:V.quotaCheckedAt,mainQuotaToken:V.quotaToken,mainLastQuotaApiError:O,mainQuotaErrorGeneration:V.quotaErrorGeneration,mainQuotaErrorClearedAt:V.quotaErrorClearedAt}),prime:(()=>{let Y=F($.prime)?$.prime:void 0,L=A1(_?.prime),E=typeof _?.primeAuthLineageId==="string"&&_.primeAuthLineageId.trim()?_.primeAuthLineageId:void 0,S=typeof _?.primeAuthLineageRefreshTokenFingerprint==="string"&&_.primeAuthLineageRefreshTokenFingerprint.trim()?_.primeAuthLineageRefreshTokenFingerprint:void 0;if(!Y&&!L&&!E&&!S)return;return{...Y&&typeof Y.enabled==="boolean"&&{enabled:Y.enabled},...L&&{main:L},...E&&{mainAuthLineageId:E},...S&&{mainAuthLineageRefreshTokenFingerprint:S}}})(),accounts:W}}async function U($=Q()){let C=await b0($),j=await b0(P1($));if(!C.exists&&!j.exists)return null;let _=C.exists?C.value:A();return X2(W2(_,j.value))}async function k1($){let C=await b0($);return F(C.value)?C.value:{}}function O2($){return Object.fromEntries(Object.entries($).filter(([,C])=>C!==void 0))}function f2($){return e({id:$.id,label:$.label,type:$.type,enabled:$.enabled,addedAt:$.addedAt,baseURL:$.type==="api"?$.baseURL:void 0,authHeader:$.type==="api"?$.authHeader:void 0})}function L2($){if($.type==="api")return e({apiKey:$.apiKey,lastUsed:$.lastUsed});return e({authLineageId:$.authLineageId,access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota,profile:$.profile,prime:$.prime})}function i($){return Math.max($?.five_hour?.checkedAt??0,$?.seven_day?.checkedAt??0,...$?.scoped?.map((C)=>C.checkedAt)??[],$?.checkedAt??0)}function V0($){if($?.source==="poll")return 2;if($?.source==="headers")return 1;return 0}function N2($,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 j=new Map(C.scoped.map((_)=>[_.id,_]));for(let _ of $.scoped){let J=j.get(_.id);if(!J||_.checkedAt>=J.checkedAt)j.set(_.id,_)}return[...j.values()]}function A$($,C,j){let _=$[j],J=C[j];if(!J)return _;if(!_)return J;if(J.checkedAt>_.checkedAt)return J;if(J.checkedAt<_.checkedAt)return _;return V0($)>V0(C)?_:J}function p$($,C){if(!$||C.source!=="headers")return C;let j=$.bindingWindowSource==="poll";return{...$,...C,five_hour:A$($,C,"five_hour"),seven_day:A$($,C,"seven_day"),scoped:N2($,C),extraUsage:$.extraUsage??C.extraUsage,bindingWindow:j?$.bindingWindow:C.bindingWindow??$.bindingWindow,bindingWindowSource:j?"poll":C.bindingWindowSource??$.bindingWindowSource}}function E2($,C){if(!F($))return C;let j=$,_=Boolean(j.access&&C.access&&j.access!==C.access||j.refresh&&C.refresh&&j.refresh!==C.refresh),J=Boolean(!_&&C.quota?.source==="headers"),G=J&&C.quota?{...C,quota:p$(j.quota,C.quota)}:C,K=i(j.quota),V=i(G.quota),Z=Boolean(K===V&&V0(j.quota)>V0(G.quota));if(!J&&(K>V||Z)){let X=j.lastRefreshedAt??0,O=G.lastRefreshedAt??0;if(_&&O<=X){let Y={...j};if(typeof G.lastUsed==="number"&&(typeof j.lastUsed!=="number"||G.lastUsed>j.lastUsed))Y.lastUsed=G.lastUsed;return Y}let W={...j,...G};if(_){if(!("profile"in G))delete W.profile;if(G.quota?.source)W.quota=G.quota;else delete W.quota;if(!("lastQuotaRefreshError"in G))delete W.lastQuotaRefreshError;if(!("lastRefreshError"in G))delete W.lastRefreshError;return W}return{...W,quota:j.quota,lastQuotaRefreshError:j.lastQuotaRefreshError}}let z={...j,...G};if(_){if(!("profile"in G))delete z.profile;if(!G.quota?.source)delete z.quota}if(!("lastQuotaRefreshError"in G))delete z.lastQuotaRefreshError;if(!("lastRefreshError"in G))delete z.lastRefreshError;return z}function h1($){let C=$.refresh?e({enabled:$.refresh.enabled,intervalMinutes:$.refresh.intervalMinutes,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,j=$.quota?e({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota,showToasts:$.quota.showToasts}):void 0;return O2({version:1,mainAccountId:$.mainAccountId,main:{type:"opencode",provider:"anthropic"},routing:$.routing,fallbackOn:$.fallbackOn,refresh:C,quota:j,quotaHeaderFeed:$.quotaHeaderFeed,claudeCache:$.claudeCache,dump:$.dump,logging:$.logging,claudeFast:$.claudeFast,costZeroing:$.costZeroing,cacheKeep:$.cacheKeep,relay:$.relay,killswitch:$.killswitch,prime:(()=>{if(typeof $.prime?.enabled!=="boolean")return;return{enabled:$.prime.enabled}})(),accounts:$.accounts.map(f2)})}var k$=Promise.resolve();function W0($){return new Promise((C,j)=>{k$=k$.then(()=>$().then(C,j),()=>$().then(C,j))})}async function Z0($,C){await q1(x1($),{recursive:!0});let j=`${$}.${d()}.tmp`;await p0(j,`${JSON.stringify(C,null,2)}
|
|
3
|
+
`,{encoding:"utf8",mode:384});try{await m$(j,$)}catch(_){throw await G0(j,{force:!0}).catch(()=>{}),_}}function h$($,C){return $.id===C.id||Boolean($.label&&C.label&&$.label===C.label)}function F2($,C,j){let _=new Set(j.removedAccountIds??[]),J=$.filter((z)=>!_.has(z.id)),G=C.filter((z)=>!_.has(z.id)),K=J.filter((z)=>!G.some((X)=>h$(X,z)));if(!K.length)return[...G];if(j.preserveExistingAccountOrder===!1)return[...G,...K];let V=new Set,Z=J.map((z)=>{let X=G.findIndex((W,Y)=>!V.has(Y)&&h$(W,z)),O=G[X];if(!O)return z;return V.add(X),O});for(let z=0;z<G.length;z++){let X=G[z];if(!V.has(z)&&X)Z.push(X)}return Z}var M2=1e4,Q2=12000,S2=1e4,U2=12000;async function s$($){let{path:C,name:j,ttlMs:_,waitMs:J,description:G}=$;await q1(x1(C),{recursive:!0});let K=Date.now()+J;while(!0){let V=await $0({name:j,ttlMs:_,path:C,renew:!0});if(V)return V;if(Date.now()>=K)throw Error(`Timed out waiting for the account ${G} lock`);await new Promise((Z)=>setTimeout(Z,25))}}function q0($){return s$({path:$,name:"config-write",ttlMs:M2,waitMs:Q2,description:"configuration write"})}function x0($){return s$({path:$,name:"state-write",ttlMs:S2,waitMs:U2,description:"state write"})}function h($,C=Q(),j={}){let _=C;return W0(()=>B2($,_,j))}async function g8($=Q(),C=d){return W0(async()=>{let j=await q0($);try{let _=await U($)??A();if(_.mainAccountId)return _.mainAccountId;let J=C(),G={..._,mainAccountId:J},K=await k1($);return await Z0($,{...K,...h1(G)}),J}finally{await j.release()}})}async function B2($,C,j){let _=await q0(C);try{let J=await U(C),G={...$,accounts:F2(J?.accounts??[],$.accounts,j)},V={...await k1(C),...h1(G)};await Z0(C,V);let Z=await x0(C);try{await z0(G,C,{mainQuota:!0,mainRefresh:!0,accounts:!0})}finally{await Z.release()}}finally{await _.release()}}function b2($,C){$.main=$.main??{},$.main.profile=C.main?.profile}function D2($,C){$.main=$.main??{};let j=C.quota?.mainLastQuotaApiError,_=typeof C.quota?.mainQuotaErrorGeneration==="number"&&Number.isSafeInteger(C.quota.mainQuotaErrorGeneration)&&C.quota.mainQuotaErrorGeneration>=0?C.quota.mainQuotaErrorGeneration:void 0,J=typeof C.quota?.mainQuotaErrorClearedAt==="number"&&Number.isFinite(C.quota.mainQuotaErrorClearedAt)&&C.quota.mainQuotaErrorClearedAt>=0?C.quota.mainQuotaErrorClearedAt:void 0,G=typeof $.main.quotaErrorGeneration==="number"&&Number.isSafeInteger($.main.quotaErrorGeneration)&&$.main.quotaErrorGeneration>=0?$.main.quotaErrorGeneration:0,K=typeof $.main.lastQuotaApiError?.checkedAt==="number"&&Number.isFinite($.main.lastQuotaApiError.checkedAt)&&$.main.lastQuotaApiError.checkedAt>=0?$.main.lastQuotaApiError.checkedAt:void 0,V=typeof $.main.quotaErrorClearedAt==="number"&&Number.isFinite($.main.quotaErrorClearedAt)&&$.main.quotaErrorClearedAt>=0?$.main.quotaErrorClearedAt:void 0,Z=Math.max(K??0,V??0),z=typeof j?.checkedAt==="number"&&Number.isFinite(j.checkedAt)&&j.checkedAt>=0?j.checkedAt:void 0;if(j===void 0&&J!==void 0&&J>=Z){if($.main.lastQuotaApiError=void 0,$.main.quotaErrorClearedAt=H0(V,J),_!==void 0&&_>=G)$.main.quotaErrorGeneration=_}else if(j){let S=z!==void 0&&z>Z,q=z!==void 0&&z===Z&&K!==void 0&&V===void 0&&_!==void 0&&_>=G,f=z===void 0&&J===void 0&&_!==void 0&&_>=G&&V===void 0;if(S||q||f){if($.main.lastQuotaApiError=j,_!==void 0)$.main.quotaErrorGeneration=Math.max(G,_)}}let X=C.quota?.mainQuota,O=Boolean($.main.quotaToken&&C.quota?.mainQuotaToken&&$.main.quotaToken===C.quota.mainQuotaToken),W=O&&X?.source==="headers"?p$($.main.quota,X):X,Y=Boolean(O&&X?.source==="headers"),L=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:i($.main.quota),E=typeof C.quota?.mainQuotaCheckedAt==="number"?C.quota.mainQuotaCheckedAt:i(W);if(!Y&&(L>E||L===E&&V0($.main.quota)>V0(W)))return;$.main.quota=W,$.main.quotaCheckedAt=Y?Math.max(L,E):C.quota?.mainQuotaCheckedAt,$.main.quotaToken=C.quota?.mainQuotaToken}function T2($,C){$.main=$.main??{},$.main.lastRefreshError=C.refresh?.mainLastRefreshError,$.main.refreshLeaseId=C.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=C.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=C.refresh?.mainRefreshLeaseTokenHash}function R2($,C){let j=C.prime?.main,_=C.prime?.mainAuthLineageId,J=C.prime?.mainAuthLineageRefreshTokenFingerprint;if(!j&&!_&&!J)return;if($.main=$.main??{},j)$.main.prime=j;if(_)$.main.primeAuthLineageId=_;if(J)$.main.primeAuthLineageRefreshTokenFingerprint=J}function D0($){if(Array.isArray($))return $.map(D0);if(!F($))return $;return Object.fromEntries(Object.entries($).filter(([,C])=>C!==void 0).map(([C,j])=>[C,D0(j)]))}function q2($,C=Q(),j={mainProfile:!0,mainQuota:!0,mainRefresh:!0,accounts:!0}){let _=C;return W0(async()=>{let J=await x0(_);try{await z0($,_,j)}finally{await J.release()}})}function p8($,C=Q()){let j=C;return W0(async()=>{let _=await q0(j);try{let J=await x0(j);try{let G=await U(j),K=P1(j),V=(await b0(K)).value,Z=F(V)?{...V,version:1}:{version:1},{accountId:z,accountIdentity:X,profile:O}=$;if(z==="main"){Z.main={...Z.main??{}};let W=B0(Z.main.profile);if(!O){if(W&&(X===void 0||W.accountIdentity===void 0||W.accountIdentity===X))return!1;return Z.main.profile=void 0,await Z0(K,D0(Z)).then(()=>!0)}if(O.accountIdentity!==void 0&&O.accountIdentity!==X)return!1;let Y=X===void 0||O.accountIdentity===X?O:{...O,accountIdentity:X};if(W&&(X===void 0||W.accountIdentity===void 0||W.accountIdentity===X)&&W.checkedAt>Y.checkedAt)return!1;Z.main.profile=Y}else{if(!G?.accounts.find((E)=>E.id===z&&P(E)))return!1;Z.accounts={...F(Z.accounts)?Z.accounts:{}};let Y=F(Z.accounts[z])?{...Z.accounts[z]}:{},L=B0(Y.profile);if(!O){if(L&&(X===void 0||L.accountIdentity===void 0||L.accountIdentity===X))return!1;Y.profile=void 0}else{if(O.accountIdentity!==void 0&&O.accountIdentity!==X)return!1;let E=X===void 0||O.accountIdentity===X?O:{...O,accountIdentity:X};if(L&&(X===void 0||L.accountIdentity===void 0||L.accountIdentity===X)&&L.checkedAt>E.checkedAt)return!1;Y.profile=E}Z.accounts[z]=Y}return await Z0(K,D0(Z)),!0}finally{await J.release()}}finally{await _.release()}})}async function z0($,C,j){let _=P1(C),J=(await b0(_)).value,G=F(J)?{...J,version:1}:{version:1};if(j.mainProfile)b2(G,$);if(j.mainQuota)D2(G,$);if(j.mainRefresh)T2(G,$);if(j.mainPrime)R2(G,$);if(j.accounts){let K=j.accounts===!0?null:new Set(j.accounts);G.accounts={...F(G.accounts)?G.accounts:{}};for(let V of $.accounts){if(K&&!K.has(V.id))continue;G.accounts[V.id]=E2(G.accounts[V.id],L2(V))}if(K){for(let V of K)if(!$.accounts.some((Z)=>Z.id===V))delete G.accounts[V]}else{let V=new Set($.accounts.map((Z)=>Z.id));for(let Z of Object.keys(G.accounts))if(!V.has(Z))delete G.accounts[Z]}}await Z0(_,D0(G))}async function $0($){let j=`${$.path??Q()}.${$.name}.lock`,_=K0(j,"owner.json"),J=d(),G=$.now??Date.now,K=null,V=!1;async function Z(){try{return JSON.parse(await g0(j,"utf8"))}catch(Y){if(Y.code!=="EISDIR")throw Y;return JSON.parse(await g0(_,"utf8"))}}async function z(){await p0(j,`${JSON.stringify({ownerId:J,expiresAt:G()+$.ttlMs})}
|
|
4
|
+
`,{encoding:"utf8",mode:384})}async function X(){try{return await p0(j,`${JSON.stringify({ownerId:J,expiresAt:G()+$.ttlMs})}
|
|
5
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(Y){let L=Y.code;if(L==="EEXIST"||L==="EISDIR")return!1;throw Y}}function O(){if(!$.renew||V)return;let Y=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(K=p6(()=>{(async()=>{try{let L=await Z(),E=G();if(V||L?.ownerId!==J||Number(L?.expiresAt)<=E)return;await z(),O()}catch{}})()},Y),"unref"in K)K.unref()}let W=await X();if(!W){let Y=`${j}.evicting`,L=K0(Y,"owner.json"),E=d(),S=5000,q=8;async function f(){await new Promise((k)=>setTimeout(k,Math.floor(Math.random()*4)))}async function M(){try{let k=await Z();return Number(k?.expiresAt)>G()}catch{try{return(await D$(j)).mtimeMs+$.ttlMs>G()}catch{return!1}}}async function x(){try{return JSON.parse(await g0(L,"utf8"))?.ownerId===E}catch{return!1}}async function H(){await q1(Y);try{await p0(L,`${JSON.stringify({ownerId:E,createdAt:G()})}
|
|
6
|
+
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(k){let l=k.code;if(l==="ENOENT"||l==="EINVAL")return!1;throw await b(),k}return await $.onStep?.("eviction-marker-acquired"),!0}async function b(){if(await x())await G0(Y,{recursive:!0,force:!0}).catch(()=>{})}for(let k=0;k<8;k++){if(W=await X(),W)break;if(await M())return null;try{if(!await H()){await f();continue}}catch(l){if(l.code!=="EEXIST")throw l;let o;try{o=await D$(Y)}catch(m){if(m.code==="ENOENT"){await f();continue}throw m}if(o.mtimeMs+5000>G())return null;await $.onStep?.("stale-marker-stat");let I=`${Y}.${d()}`;try{await m$(Y,I)}catch(m){if(m.code==="ENOENT"){await f();continue}throw m}await $.onStep?.("stale-marker-claimed"),await G0(I,{recursive:!0,force:!0}).catch(()=>{}),await f();continue}try{if(await M())return null;if(!await x())return null;if(await $.onStep?.("stale-lock-confirmed"),!await x())return null;if(await G0(j,{recursive:!0,force:!0}).catch(()=>{}),!await x())return null;if(W=await X(),!W)return null;if(!await x())return await G0(j,{recursive:!0,force:!0}).catch(()=>{}),W=!1,null;break}finally{await b()}}}if(!W)return null;return O(),{release:async()=>{if(V=!0,K)s6(K),K=null;try{if((await Z())?.ownerId!==J)return}catch{return}await G0(j,{recursive:!0,force:!0}).catch(()=>{})}}}function s8($){return $?.claudeCache?.enabled===!0}function x2($){return typeof $==="string"&&S$.includes($)?$:l0}function P2($){return x2($?.claudeCache?.mode)}async function u8($,C,j=Q()){let _=await U(j)??A();return _.claudeCache={..._.claudeCache??{},enabled:$,mode:C??P2(_)},await h(_,j),_}async function d8($,C=Q()){let j=await U(C)??A();return j.claudeCache={...j.claudeCache??{},enabled:j.claudeCache?.enabled===!0,mode:$},await h(j,C),j}function c8($){return $?.dump?.enabled===!0}async function i8($,C=Q()){let j=await U(C)??A();return j.dump={...j.dump??{},enabled:$},await h(j,C),j}function r8($){return $?.claudeFast?.enabled===!0}async function o8($,C=Q()){let j=await U(C)??A();return j.claudeFast={...j.claudeFast??{},enabled:$},await h(j,C),j}async function n8($,C,j=Q()){let _=await U(j)??A();return _.cacheKeep={..._.cacheKeep??{},enabled:!0,always:!1,startHour:$,endHour:C},await h(_,j),_}async function a8($=Q()){let C=await U($)??A();return C.cacheKeep={...C.cacheKeep??{},enabled:!0,always:!0},delete C.cacheKeep.startHour,delete C.cacheKeep.endHour,await h(C,$),C}async function t8($,C=Q()){let j=await U(C)??A();return j.cacheKeep={...j.cacheKeep??{},enabled:$},await h(j,C),j}function e8($){return $?.cacheKeep?.subagents===!0}async function $_($,C=Q()){let j=await U(C)??A();return j.cacheKeep={...j.cacheKeep??{},subagents:$},await h(j,C),j}function C_($){return $?.prime?.enabled===!0}async function j_($,C=Q()){let j=await U(C)??A();return j.prime={...j.prime??{},enabled:$},await h(j,C),j}async function __($,C=Q()){return W0(async()=>{let j=await q0(C);try{let _=await x0(C);try{let J=await U(C)??A();if($==="main"){let V=J.prime?.mainAuthLineageId;if(V)return V;let Z=J.mainAccountId??d();if(!J.mainAccountId){let z=await k1(C);await Z0(C,{...z,...h1({...J,mainAccountId:Z})}),J.mainAccountId=Z}return J.prime={...J.prime??{},mainAuthLineageId:Z},await z0(J,C,{mainPrime:!0}),Z}let G=J.accounts.find((V)=>V.id===$&&P(V));if(!G)throw Error(`getOrCreatePrimeAuthLineageId: OAuth account "${$}" not found`);if(G.authLineageId)return G.authLineageId;let K=d();return G.authLineageId=K,await z0(J,C,{accounts:[$]}),K}finally{await _.release()}}finally{await j.release()}})}async function J_($,C,j=Q(),_=Date.now()){let J=Number.isFinite(C?.inputTokens)?Math.max(0,Math.floor(C.inputTokens)):0,G=Number.isFinite(C?.outputTokens)?Math.max(0,Math.floor(C.outputTokens)):0;return W0(async()=>{let K=await q0(j);try{let V=await x0(j);try{let Z=await U(j)??A();if($==="main"){let Y=Z.prime?.main,L={count:(Y?.count??0)+1,inputTokens:(Y?.inputTokens??0)+J,outputTokens:(Y?.outputTokens??0)+G,since:Y?.since??Math.floor(_)};return Z.prime={...Z.prime??{},main:L},await z0(Z,j,{mainPrime:!0}),L}let z=Z.accounts.findIndex((Y)=>Y.id===$);if(z<0)throw Error(`incrementPrimeUsagePersistent: account "${$}" not found`);let X=Z.accounts[z],O=X.prime,W={count:(O?.count??0)+1,inputTokens:(O?.inputTokens??0)+J,outputTokens:(O?.outputTokens??0)+G,since:O?.since??Math.floor(_)};return Z.accounts[z]={...X,prime:W},await z0(Z,j,{accounts:[$]}),W}finally{await V.release()}}finally{await K.release()}})}function A2($){return $?.fallbackOn?.length?$.fallbackOn:i6}function G_($,C){return A2(C).includes($)}function i0($){let C=$?.quota?.minimumRemaining||{};return{five_hour:C.five_hour??C["5h"]??T$.five_hour,seven_day:C.seven_day??C["1w"]??T$.seven_day}}function T0($){return $?.quota?.enabled!==!1}function k2($){return $?.refresh?.enabled!==!1}function h2($){return Math.floor(Math.random()*Math.max(0,$))}function w2($){let C=$?.refresh?.refreshBeforeExpiryMinutes??r6;return Math.max(l$,C)*60000}function K_($){return v$("sha256").update($).digest("hex")}function I2($){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 v2($){let j=($.previous?.accountIdentity===$.accountIdentity?$.previous?.retryCount??0:0)+1,_=$.error.retryAfter,J;if(typeof _==="number"&&_>0)J=_*1000;else if(I2($.error))J=Math.min(n6,o6*2**Math.min(j-1,6));else J=g$;let G=$.error.status,K=typeof G==="number"&&Number.isFinite(G)?G:void 0,V=Y0($.error),z=(typeof $.error.body==="string"?$.error.body:"").includes("invalid_grant")||V.includes("invalid_grant");return{message:V,checkedAt:$.now,nextRetryAt:$.now+J,retryCount:j,accountIdentity:$.accountIdentity,status:K,permanent:K===400&&z}}function O0($){if(!$)return!1;if(typeof $.permanent==="boolean")return $.permanent;if(typeof $.status==="number")return $.status===400;if(typeof $.nextRetryAt==="number")return $.nextRetryAt-$.checkedAt>=g$;return!1}function J0($,C,j){if(!$?.nextRetryAt||$.nextRetryAt<=j)return!1;if(!$.accountIdentity)return!0;if(!C)return!0;return $.accountIdentity===C}function m2($,C){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??C)-C)/1000))}s after: ${$.message}`}function D1($,C){return Object.assign(Error(m2($,C)),{refreshBackoffError:$})}function u$($){if(!$||typeof $!=="object")return;let C=$.refreshBackoffError;return C&&typeof C.message==="string"?C:void 0}function V_($){if(!$)return[];return $.accounts.filter((C)=>C.enabled!==!1&&P(C)&&O0(C.lastRefreshError)).map((C)=>C.label?.trim()||C.id)}function w1($){if($.status===403)return!0;return/Claude quota check failed: 403\b/.test(Y0($))}function r0($){let j=($.previous?.accountIdentity===$.accountIdentity?$.previous?.retryCount??0:0)+1,_=t$($.error)?Math.min(t6,a6*2**Math.min(j-1,6)):e6;return{message:Y0($.error),checkedAt:$.now,nextRetryAt:$.now+_,retryCount:j,...$.accountIdentity!==void 0&&{accountIdentity:$.accountIdentity}}}function X0($,C){if(!$?.nextRetryAt||$.nextRetryAt<=C)return!1;return!0}function Z_($,C){return`Quota API backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??C)-C)/1000))}s after: ${$.message}`}function p($){let C=$?.quota?.checkIntervalMinutes??$2;return Math.max(1,C)*60000}function z_($){return $?.logging?.level}async function X_($,C=Q()){let{setLogLevel:j}=await import("./logger-ftk4bg3p.js"),_=await U(C)??A();_.logging={..._.logging??{},level:$},await h(_,C),j($)}function d$($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken,accountIdentity:$.quota.mainQuota.accountIdentity}}function c$($){let C=$?.quota?.refreshEveryNRequests;return typeof C==="number"&&Number.isFinite(C)&&C>0?Math.floor(C):0}function u0($){return $?.quota?.failClosedOnUnknownQuota??C2}function i$($){return $.toLowerCase().replace(/[^a-z0-9]/g,"")}function y2($){if(typeof $!=="string")return null;let C=i$($);if(C.includes("fable"))return"fable";if(C.includes("mythos"))return"mythos";return C}function y($,C){let j=y2(C);if(!j)return;return $?.scoped?.find((_)=>{return[_.modelId,_.modelName,_.title].filter((G)=>typeof G==="string").map(i$).join(" ").includes(j)})}function l2($,C){let j=y($,C);return Boolean(j&&Number.isFinite(j.remainingPercent)&&j.remainingPercent<=0)}function d0($,C){return!l2($,C)}function r$($,C){if(!T0(C))return!0;let j=i0(C);for(let _ of["five_hour","seven_day"]){let J=$?.[_];if(!J)return!u0(C);if(!Number.isFinite(J.remainingPercent))return!u0(C);if(J.remainingPercent<j[_])return!1}return!0}function Y_($){return Boolean($?.five_hour&&$.seven_day)}var t={five_hour:5,seven_day:10,scoped:0};function R0($){let C=$?.five_hour??$?.["5h"],j=$?.seven_day??$?.["1w"],_=$?.scoped;return{five_hour:typeof C==="number"&&Number.isFinite(C)?C:t.five_hour,seven_day:typeof j==="number"&&Number.isFinite(j)?j:t.seven_day,scoped:typeof _==="number"&&Number.isFinite(_)?_:t.scoped}}function I1($){return $?.killswitch?.enabled===!0}function v1($,C){if(!$?.killswitch)return t;if(C&&$.killswitch.accounts?.[C])return R0($.killswitch.accounts[C]);return R0($.killswitch.main)}function o$($,C,j,_){if(!I1(C))return!0;let J=v1(C,j),G=!1;for(let K of["five_hour","seven_day"]){let V=$?.[K];if(!V){G=!0;continue}if(!Number.isFinite(V.remainingPercent)){G=!0;continue}if(V.remainingPercent<J[K])return!1}if(_){let K=y($,_);if(K&&Number.isFinite(K.remainingPercent)&&K.remainingPercent<=J.scoped)return!1}if(G)return!u0(C);return!0}function n$($,C,j,_){let J=[],G=[$,...C.map((K)=>K.quota)];for(let K of G)if(_){let Z=y(K,_)?.resetsAt;if(!Z)continue;let z=Date.parse(Z);if(Number.isFinite(z)&&z>j)J.push(z)}else for(let V of["five_hour","seven_day"]){let Z=K?.[V]?.resetsAt;if(!Z)continue;let z=Date.parse(Z);if(Number.isFinite(z)&&z>j)J.push(z)}if(!J.length)return 300;return Math.max(1,Math.ceil((Math.min(...J)-j)/1000))+60}function H_($){return $?.killswitch??{enabled:!1}}async function W_($,C=Q()){let j=await U(C)??A();return j.killswitch=$,await h(j,C),j}async function O_($,C=Q()){let j=await U(C);if(!j)return!1;let _=r2(j,$);if(_)await h(j,C,{removedAccountIds:[$]});return _}async function f_($,C=Q()){let j=await U(C);if(!j)return;o2(j,$),await h(j,C,{preserveExistingAccountOrder:!1})}async function L_($,C,j=Q()){let _=await U(j);if(!_)return!1;let J=n2(_,$,C);if(J)await h(_,j);return J}async function N_($,C=Q()){let j=await U(C)??A();i2(j,$),await h(j,C)}function C0($,C,j){let _=p(C);if(!T0(C))return j+_;let J=Math.min(...[...["five_hour","seven_day"].map((Z)=>$?.[Z]?.checkedAt),...($?.scoped??[]).map((Z)=>Z.checkedAt)].filter((Z)=>Number.isFinite(Z)).map((Z)=>Z+_)),G=(Z)=>Number.isFinite(J)?Math.min(Z,J):Z,K=i0(C),V=[];for(let Z of["five_hour","seven_day"]){let z=$?.[Z];if(!z)return G(j+_);if(z.remainingPercent>=K[Z])continue;let X=z.resetsAt?Date.parse(z.resetsAt):Number.NaN;if(!Number.isFinite(X)||X<=j)return G(j+_);V.push(X)}if(!V.length)return G(j+_);return G(Math.min(...V)+60000)}function n($,C,j){return!$.access||!$.expires||$.expires-j<=w2(C)}function a$($,C,j){if(!T0(C))return!0;let _=p(C);return["five_hour","seven_day"].every((J)=>{let G=$?.[J];return Boolean(G&&j-G.checkedAt<_)})}function T1($,C,j,_){if(!a$($.quota,C,j))return!0;let J=y($.quota,_);return Boolean(J&&j-J.checkedAt>=p(C))}function g2($,C){if(!$)return!1;if(!$.resetsAt)return!0;let j=Date.parse($.resetsAt);return!Number.isFinite(j)||j>C}function p2($,C){return["five_hour","seven_day"].every((j)=>g2($?.[j],C))}function t$($){let C=$.status;if(typeof C==="number"&&Number.isFinite(C)){if(C===429||C>=500)return!0}let j=Y0($);if(/Claude quota check failed: (429|5\d\d)\b/.test(j))return!0;if(j.includes("Quota refresh is already in progress"))return!0;if(!($ instanceof Error))return!1;let{message:_,code:J}=$;return _.includes("fetch failed")||J==="ECONNRESET"||J==="ECONNREFUSED"||J==="ETIMEDOUT"||J==="UND_ERR_CONNECT_TIMEOUT"}function s2($,C,j,_){return t$(j)&&r$($.quota,C)&&p2($.quota,_)}function c0($){if(!Number.isFinite($))return 0;if($<0)return 0;if($>100)return 100;return $}function c($){return typeof $==="string"&&$.trim()?$.trim():void 0}function e$($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function u2($,C){if(!Array.isArray($))return[];let j=new Set,_=[];for(let J of $){if(J?.kind!=="weekly_scoped"||J.group!=="weekly")continue;if(typeof J.percent!=="number"||!Number.isFinite(J.percent))continue;let G=c(J.scope?.model?.display_name);if(!G)continue;let K=c(J.scope?.model?.id)??G,V=e$(K);if(!V)continue;let Z=`claude-weekly-scoped-${V}`;if(j.has(Z))continue;j.add(Z);let z=c0(J.percent),X=c(J.scope?.model?.id);_.push({id:Z,title:`${G} only`,...X&&{modelId:X},modelName:G,usedPercent:z,remainingPercent:c0(100-z),resetsAt:J.resets_at,checkedAt:C})}return _}function d2($){if($.extra_usage?.is_enabled!==!0)return;let C=$.extra_usage.used_credits,j=$.extra_usage.monthly_limit;if(typeof C!=="number"||!Number.isFinite(C)||typeof j!=="number"||!Number.isFinite(j))return;let _=$.spend?.limit?.currency,J=_==null?"USD":c(_),G=$.spend?.limit?.exponent,K=G==null?2:G;if(!J||!/^[A-Za-z]{3}$/.test(J)||!Number.isInteger(K)||K<0||K>20)return;return{used:{amountMinor:C,currency:J,exponent:K},limit:{amountMinor:j,currency:J,exponent:K},...typeof $.extra_usage.utilization==="number"&&Number.isFinite($.extra_usage.utilization)&&{utilizationPercent:$.extra_usage.utilization},...c($.spend?.severity)&&{severity:c($.spend?.severity)},exhausted:C>=j}}function c2($){if(!Array.isArray($))return;let C=$.find((G)=>G?.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 j=c(C.scope?.model?.display_name);if(!j)return;let _=c(C.scope?.model?.id)??j,J=e$(_);return J?`claude-weekly-scoped-${J}`:void 0}function w$($,C){if(typeof $?.utilization!=="number")return;if(!Number.isFinite($.utilization))return;let j=c0($.utilization);return{usedPercent:j,remainingPercent:c0(100-j),resetsAt:$.resets_at,checkedAt:C}}async function o0($){let j=await($.fetchImpl??fetch)(d6,{method:"GET",headers:{Authorization:`Bearer ${$.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${u}`}});if(!j.ok){let K=await j.text().catch(()=>"");throw Object.assign(Error(`Claude quota check failed: ${j.status} — ${K}`),{status:j.status,retryAfter:b1(j.headers.get("Retry-After"))})}let _=$.now?.()??Date.now(),J=await j.json(),G=c2(J.limits);return{five_hour:w$(J.five_hour,_),seven_day:w$(J.seven_day,_),scoped:u2(J.limits,_),extraUsage:d2(J),...G&&{bindingWindow:G,bindingWindowSource:"poll"},source:"poll",checkedAt:_}}function w($,C){let j=$.accounts.findIndex((_)=>_.id===C.id);if(j>=0)$.accounts[j]=C}function i2($,C){let j=$.accounts.findIndex((_)=>_.id===C.id||C.label&&_.label===C.label);if(j>=0){$.accounts[j]={...$.accounts[j],...C,addedAt:$.accounts[j]?.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 r2($,C){let j=$.accounts.findIndex((_)=>_.id===C);if(j<0)return!1;return $.accounts.splice(j,1),!0}function o2($,C){let j=new Map(C.map((G,K)=>[G,K])),_=$.accounts.filter((G)=>j.has(G.id)),J=$.accounts.filter((G)=>!j.has(G.id));_.sort((G,K)=>(j.get(G.id)??0)-(j.get(K.id)??0)),$.accounts=[..._,...J]}function n2($,C,j){let _=$.accounts.find((J)=>J.id===C);if(!_)return!1;return _.enabled=j,!0}function Y0($){return $ instanceof Error?$.message:String($)}function $C($,C,j){let _=u$(C);if(_){$.lastRefreshError=_;return}$.lastRefreshError=v2({error:C,now:j,accountIdentity:$.id,previous:$.lastRefreshError})}function I$($,C,j){if(w1(C)||u$(C))return;if($.lastQuotaRefreshError=r0({error:C,now:j,previous:$.lastQuotaRefreshError}),C.isRefreshError)$C($,C,j)}function a2($){return`fallback-oauth-refresh-${v$("sha256").update($).digest("hex").slice(0,16)}`}class t2{now;fetchImpl;configPath;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;setIntervalImpl;clearIntervalImpl;constructor($={}){this.now=$.now??Date.now,this.fetchImpl=$.fetchImpl??fetch,this.configPath=$.configPath??Q(),this.quotaManager=$.quotaManager??null,this.onFallbackStorageChanged=$.onFallbackStorageChanged,this.setIntervalImpl=$.setIntervalImpl??globalThis.setInterval,this.clearIntervalImpl=$.clearIntervalImpl??globalThis.clearInterval}seedFallbackQuota($,C){if(!this.quotaManager)return;if(!$.quota)return;let j=i($.quota);if(j<=0)return;let _=this.quotaManager.getFallback($.id,$);if(_&&_.checkedAt>=j)return;let J=p(C);this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:j+J,checkedAt:j},$)}async load(){return U(this.configPath)}async save($,C){await q2($,this.configPath,{accounts:C??!0})}startBackgroundRefresh(){let $=async()=>{await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()};if($().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=this.setIntervalImpl(()=>{$().catch(()=>{})},j2+h2(_2)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)this.clearIntervalImpl(this.refreshTimer);if(this.quotaTimer)this.clearIntervalImpl(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts($,C={}){let j=$!==void 0?$:await this.load();if(!j)return[];let _=[],J=!1;for(let G of j.accounts){if(G.enabled===!1||!P(G))continue;let K=G;try{if(n(K,j,this.now())){let Z=K.lastRefreshError;if(Z&&J0(Z,K.id,this.now()))throw D1(Z,this.now());K=await this.refreshAccount(K,j),J=!0}if(this.seedFallbackQuota(K,j),(this.quotaManager?this.quotaManager.isFallbackStale(K.id,K.access,C.modelId,K):T1(K,j,this.now(),C.modelId))&&!X0(K.lastQuotaRefreshError,this.now()))K=(await this.refreshAccountQuota(K,j)).account,J=!0;if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount(K),j,{modelId:C.modelId}))_.push(K)}catch(V){if(s2(K,j,V,this.now())){if(a("[refresh] fallback quota using cached quota after refresh error",{accountId:K.id,error:Y0(V)}),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(K),j,{modelId:C.modelId}))_.push(K)}else if(!u0(j)&&!J0(K.lastRefreshError,K.id,this.now())&&d0(K.quota,C.modelId))_.push(K)}}if(J)await this.save(j);return _}async markUsed($){let C=await this.load();if(!C)return;let j=C.accounts.find((_)=>_.id===$.id);if(!j)return;j.lastUsed=this.now(),await this.save(C)}accountPassesQuotaPolicy($,C,j={}){return r$($.quota,C)&&d0($.quota,j.modelId)}quotaPolicyAccount($){if(!this.quotaManager)return $;let C=this.quotaManager.getFallback($.id,$)?.quota;return C?{...$,quota:C}:$}async refreshDueAccounts(){let $=await this.load();if(!$||!k2($))return;let C=!1;for(let j of $.accounts){if(j.enabled===!1||!P(j))continue;if(!n(j,$,this.now()))continue;if(J0(j.lastRefreshError,j.id,this.now()))continue;try{a("[refresh] fallback oauth background due",{accountId:j.id,expiresInMs:j.expires?j.expires-this.now():void 0}),await this.refreshAccount(j,$),C=!0}catch(_){N.warn("refresh","fallback oauth background failed",{accountId:j.id,error:_ instanceof Error?_.message:String(_)}),$C(j,_,this.now()),w($,j),C=!0}}if(C)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!T0($))return;let C=!1;for(let j of $.accounts){if(j.enabled===!1||!P(j))continue;let _=j;try{if(n(_,$,this.now())){if(J0(_.lastRefreshError,_.id,this.now()))continue;_=await this.refreshAccount(_,$),C=!0}if(X0(_.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(_,$),!(this.quotaManager?this.quotaManager.isFallbackStale(_.id,_.access):T1(_,$,this.now())))continue;await this.refreshAccountQuota(_,$),C=!0}catch(J){I$(j,J,this.now()),w($,j),C=!0}}if(C)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let C=await this.load(),j=[];if(!C||!T0(C))return{storage:C,errors:j};let _=$.force??!1,J=!1;for(let G of C.accounts){if(G.enabled===!1||!P(G))continue;let K=G;try{if(n(K,C,this.now())){let V=K.lastRefreshError;if(V&&J0(V,K.id,this.now()))throw D1(V,this.now());K=await this.refreshAccount(K,C),J=!0}if(!_&&!T1(K,C,this.now())){if(K.lastQuotaRefreshError)K.lastQuotaRefreshError=void 0,w(C,K),J=!0;continue}await this.refreshAccountQuota(K,C),J=!0}catch(V){I$(G,V,this.now()),w(C,G),J=!0,j.push({accountId:G.id,message:Y0(V)})}}if(J)await this.save(C);return{storage:C,errors:j}}async refreshAccount($,C,j={}){let _=this.refreshPromises.get($.id);if(_){let K=await _;return w(C,K),K}let J=this.refreshAccountNow($,C,j).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,J);let G=await J;return w(C,G),G}async waitForConcurrentFallbackRefresh($,C,j,_){let J=Date.now()+G2;while(Date.now()<J){await new Promise((z)=>setTimeout(z,K2));let G=await this.load(),K=G?.accounts.find((z)=>z.id===$.id&&P(z));if(!K)continue;if((K.access!==j.access||K.refresh!==j.refresh||(K.expires??0)>(j.expires??0)+60000)&&(_.force||!n(K,G,this.now())))return w(C,K),a("[refresh] fallback oauth joined concurrent refresh",{accountId:K.id,expiresInMs:K.expires?K.expires-this.now():void 0}),K;let Z=K.lastRefreshError;if(Z&&J0(Z,K.id,this.now()))throw w(C,K),D1(Z,this.now())}return null}async refreshAccountNow($,C,j){let _=await this.load(),J=_?.accounts.find((V)=>V.id===$.id&&P(V));if(J&&!j.force&&!n(J,_,this.now()))return w(C,J),J;let G=J??$,K=await $0({name:a2(G.id),ttlMs:J2,path:this.configPath,now:this.now,renew:!0});if(!K){a("[refresh] fallback oauth refresh skipped file lock",{accountId:G.id});let V=await this.waitForConcurrentFallbackRefresh($,C,G,j);if(V)return V;throw Error("Fallback OAuth refresh is already in progress")}try{if(_=await this.load(),J=_?.accounts.find((z)=>z.id===$.id&&P(z)),J&&!j.force&&!n(J,_,this.now()))return w(C,J),J;G=J??G;let V=G.refresh;a("[refresh] fallback oauth refresh request start",{accountId:G.id,force:j.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let Z=await b$({refreshToken:V,authLineageId:G.authLineageId,fetchImpl:this.fetchImpl,now:this.now});return G.access=Z.access,G.refresh=Z.refresh,G.authLineageId=Z.authLineageId??G.authLineageId,G.expires=Z.expires,G.lastRefreshedAt=Z.expires-Z.expiresIn*1000,G.lastRefreshError=void 0,w(C,G),await this.save(C),a("[refresh] fallback oauth refresh succeeded",{accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await K.release()}}async refreshAccountQuota($,C){let j=$;if(!j.access)throw Error(`Fallback account ${$.id} has no access token`);let _=(Z)=>this.quotaManager?this.quotaManager.refreshFallbackWithMetadata(j.id,Z,j):o0({accessToken:Z,fetchImpl:this.fetchImpl,now:this.now}).then((z)=>({quota:z,fetched:!0})),J=this.now(),G=!1;try{let Z=await _(j.access);j.quota=Z.quota,G=Z.fetched}catch(Z){if(!(Z instanceof Error?Z.message:String(Z)).includes("Claude quota check failed: 401"))throw Z;if(j=await this.refreshAccount($,C,{force:!0}),!j.access)throw Z;let X=await _(j.access);j.quota=X.quota,G=X.fetched}let K=await this.load(),V=K?.accounts.find((Z)=>Z.id===j.id&&P(Z));if(K&&V&&V.access!==j.access)return this.seedFallbackQuota(V,K),w(C,V),{account:V,fetched:!1};if(K&&V?.access===j.access&&V.quota&&i(V.quota)>=J&&a$(V.quota,K,this.now()))return this.seedFallbackQuota(V,K),w(C,V),{account:V,fetched:G};if(j.lastQuotaRefreshError=void 0,w(C,j),this.quotaManager&&j.quota){let Z=this.now();this.quotaManager.setFallback(j.id,{quota:j.quota,refreshAfter:Z+p(C),checkedAt:Z},j)}return{account:j,fetched:G}}}var M_="claude-cache",CC="## Claude Cache Status",e2="## Claude Cache Enabled",$4="## Claude Cache Disabled",C4="## Claude Cache Usage",j4="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",n0=!1,a0=l0;function Q_(){return n0}function S_(){return a0}function U_($){n0=$.enabled,a0=$.mode}function _4($){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 P0($){let C=$?.enabled??n0,j=$?.mode??a0;return[CC,"",`- Enabled: ${C?"enabled":"disabled"}`,`- Mode: ${j}`,"- 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 B_($){let C=_4($.argumentsText),j=$.enabled??n0,_=$.mode??a0;if(C.type==="status")return P0({enabled:j,mode:_});if(C.type==="enable")return[e2,"",P0({enabled:!0,mode:_})].join(`
|
|
8
|
+
`);if(C.type==="disable")return[$4,"",P0({enabled:!1,mode:_})].join(`
|
|
9
|
+
`);if(C.type==="mode")return[CC,"",`Mode updated to \`${C.mode}\`.`,"",P0({enabled:j,mode:C.mode})].join(`
|
|
10
|
+
`);return[C4,"",j4,"",P0({enabled:j,mode:_})].join(`
|
|
11
|
+
`)}import{createHash as G4}from"node:crypto";var J4=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 jC(){return function($){let{exports:{mem:C,xxh32:j,xxh64:_,init32:J,update32:G,digest32:K,init64:V,update64:Z,digest64:z}}=$,X=new Uint8Array(C.buffer);function O(H,b){if(C.buffer.byteLength<H+b){let k=Math.ceil((H+b-C.buffer.byteLength)/65536);C.grow(k),X=new Uint8Array(C.buffer)}}function W(H,b,k,l,m0,o){O(H);let I=new Uint8Array(H);return X.set(I),k(0,b),I.set(X.subarray(0,H)),{update(m){let F1;return X.set(I),typeof m=="string"?(O(3*m.length,H),F1=S.encodeInto(m,X.subarray(H)).written):(O(m.byteLength,H),X.set(m,H),F1=m.byteLength),l(0,H,F1),I.set(X.subarray(0,H)),this},digest:()=>(X.set(I),o(m0(0)))}}function Y(H){return H>>>0}let L=2n**64n-1n;function E(H){return H&L}let S=new TextEncoder,q=0,f=0n;function M(H,b=q){return O(3*H.length,0),Y(j(0,S.encodeInto(H,X).written,b))}function x(H,b=f){return O(3*H.length,0),E(_(0,S.encodeInto(H,X).written,b))}return{h32:M,h32ToString:(H,b=q)=>M(H,b).toString(16).padStart(8,"0"),h32Raw:(H,b=q)=>(O(H.byteLength,0),X.set(H),Y(j(0,H.byteLength,b))),create32:(H=q)=>W(48,H,J,G,K,Y),h64:x,h64ToString:(H,b=f)=>x(H,b).toString(16).padStart(16,"0"),h64Raw:(H,b=f)=>(O(H.byteLength,0),X.set(H),E(_(0,H.byteLength,b))),create64:(H=f)=>W(88,H,V,Z,z,E)}}((await WebAssembly.instantiate(J4)).instance)}var K4=0x6e52736ac806831en,V4="cch=00000;";var m1=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=([0-9a-f]{5});/,Z4=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=00000;/,_C=null,t0=null;async function JC(){if(t0)return;_C??=(async()=>{t0=(await jC()).h64Raw})(),await _C}async function z4($){return await JC(),((t0?.($,K4)??0n)&0xfffffn).toString(16).padStart(5,"0")}async function x_($){return await JC(),(t0?.(new TextEncoder().encode($),0n)??0n).toString(16).padStart(16,"0").slice(0,16)}function X4($){return $.replace(m1,`$1${V4}`)}function GC($){return m1.exec($)?.[2]??null}async function KC($){if(!m1.test($))return $;let C=X4($),j=await z4(new TextEncoder().encode(C));return C.replace(Z4,`$1cch=${j};`)}function Y4($=u,C=new Date){if($===u)return U1;return G4("sha256").update($).digest("hex").slice(0,3)}function P_($,C=u,j,_=new Date){let J=Y4(C,_);return`x-anthropic-billing-header: cc_version=${C}.${J}; cc_entrypoint=${j}; cch=00000;`}import{randomBytes as H4,randomUUID as XC}from"node:crypto";var W4=1000,R=new Map;function g($,C,j,_=W4){if(!$.has(C)&&$.size>=_){let J=$.keys().next().value;if(J!==void 0)$.delete(J)}$.set(C,j)}function VC($,C){if(!C.accountUuid)return C;if(R.get($)!==C)return{...C,accountUuid:void 0};let j={...C,accountUuid:void 0};return g(R,$,j),j}function y1($){let C=$||"anonymous",j=R.get(C);if(j)return j;let _={deviceId:H4(32).toString("hex"),sessionId:XC()};return g(R,C,_),_}var O4=86400000,f4=300000,e0=new Map,ZC=new Map;function L4($){return`compat:${$||"anonymous"}`}function YC($){return`identity:${$}`}function l1($,C){return`account:${$}:${C}`}function $1($,C,j){if(!$)return;if($.accountIdentity!==void 0&&$.accountIdentity!==C)return;if(j!==void 0&&$.accountUuid!==void 0&&$.accountUuid!==j)return;if($.accountIdentity===C&&(j===void 0||$.accountUuid===j))return $;return{...$,accountIdentity:C,...j!==void 0&&{accountUuid:j}}}function C1($,C,j){g(R,YC(C),$),g(R,l1(j,C),$)}async function N4($,C){if(!$.startsWith("sk-ant-oat"))return null;let j=new AbortController,_=setTimeout(()=>j.abort(),5000);try{let J=new URL("https://api.anthropic.com/api/claude_cli/bootstrap");if(J.searchParams.set("entrypoint",E$),C)J.searchParams.set("model",C);let G=await fetch(J,{method:"GET",headers:{accept:"application/json, text/plain, */*",authorization:`Bearer ${$}`,"content-type":"application/json","anthropic-beta":"oauth-2025-04-20","user-agent":`claude-code/${u}`},signal:j.signal});if(!G.ok)return null;let V=(await G.json().catch(()=>null))?.oauth_account?.account_uuid;return typeof V==="string"&&V?V:null}catch{return null}finally{clearTimeout(_)}}async function w_($,C,j){let _=j?.trim()||void 0,J=_?YC(_):L4($),G;if(_)G=$1(R.get(J)??R.get($),_)??y1(J),G=$1(G,_)??G,g(R,J,G);else G=R.get(J)??R.get($)??y1(J),g(R,J,G),g(R,$,G);if(!$.startsWith("sk-ant-oat"))return G;let K=Date.now(),V=`${J}:${$}`,Z=ZC.get(V);if(Z&&Z.expiresAt>K){if(!Z.accountUuid)return G=VC(J,G),G;if(!_){if(G.accountUuid===Z.accountUuid)return G;return G={...G,accountUuid:Z.accountUuid},g(R,V,G),G}let W=$1(R.get(l1(Z.accountUuid,_))??R.get(`account:${Z.accountUuid}`),_,Z.accountUuid);if(W)return G=W,C1(G,_,Z.accountUuid),G;if(G.accountUuid===Z.accountUuid)return G;return G={...G,accountIdentity:_,accountUuid:Z.accountUuid},C1(G,_,Z.accountUuid),G}let z=e0.get(V);if(!z)z=N4($,C),g(e0,V,z);let X=await z.finally(()=>{if(e0.get(V)===z)e0.delete(V)});if(g(ZC,V,{accountUuid:X,expiresAt:K+(X?O4:f4)}),!X)return G=VC(J,G),G;if(!_)return G={...G,accountUuid:X},g(R,V,G),G;let O=$1(R.get(l1(X,_))??R.get(`account:${X}`),_,X);if(O)return G=O,C1(G,_,X),G;return G={...G,accountIdentity:_,accountUuid:X},C1(G,_,X),G}function j0($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function E4($){if(!$.accountUuid)return null;return JSON.stringify({device_id:$.deviceId,account_uuid:$.accountUuid,session_id:$.sessionId})}function I_($,C){let j=E4(C);if(!j){if(j0($.metadata))delete $.metadata.user_id;return!1}if(!j0($.metadata))$.metadata={};let _=$.metadata;if(j0(_))_.user_id=j;return!0}var F4=["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"],M4=["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"],zC=["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 Q4($){return $.output_config?.format?.type==="json_schema"}function S4($){return Array.isArray($.tools)&&$.tools.length>0&&Array.isArray($.system)&&j0($.thinking)&&j0($.context_management)&&j0($.output_config)&&j0($.diagnostics)}function U4($,C=[]){let j=$?S4($)?[...F4]:Q4($)?[...M4]:[...zC]:[...zC];if($?.speed==="fast")j.push(N$);for(let _ of C){let J=_.trim();if(J)j.push(J)}return[...new Set(j)].join(",")}function B4(){switch(process.platform){case"darwin":return"MacOS";case"win32":return"Windows";case"linux":return"Linux";case"freebsd":return"FreeBSD";default:return"Unknown"}}function b4(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";case"ia32":return"x32";default:return process.arch}}function v_($,C,j={}){let _=j.identity??y1(C),G=[...($.get("anthropic-beta")??"").split(",").map((K)=>K.trim()).filter(Boolean),...j.extraBetas??[]];return $.set("accept","application/json"),$.set("authorization",`Bearer ${C}`),$.set("content-type","application/json"),$.set("user-agent",Q$),$.set("anthropic-beta",U4(j.body,G)),$.set("anthropic-dangerous-direct-browser-access","true"),$.set("anthropic-version","2023-06-01"),$.set("x-app","cli"),$.set("x-client-request-id",XC()),$.set("x-claude-code-session-id",_.sessionId),$.set("x-stainless-arch",b4()),$.set("x-stainless-lang","js"),$.set("x-stainless-os",B4()),$.set("x-stainless-package-version",F$),$.set("x-stainless-retry-count","0"),$.set("x-stainless-runtime","node"),$.set("x-stainless-runtime-version",M$),$.set("x-stainless-timeout","600"),$.delete("x-api-key"),$}var D4=["model","messages","system","tools","tool_choice","metadata","max_tokens","temperature","thinking","context_management","output_config","diagnostics","stream","speed"];function HC($){let C={};for(let j of D4)if(Object.hasOwn($,j))C[j]=$[j];for(let[j,_]of Object.entries($))if(!Object.hasOwn(C,j))C[j]=_;return C}import{createHash as T4,randomBytes as R4}from"node:crypto";import{lstat as p1,mkdir as q4,readdir as NC,readFile as WC,rename as x4,unlink as EC,writeFile as P4}from"node:fs/promises";import{tmpdir as A4}from"node:os";import{join as K1,resolve as k0}from"node:path";var d_="claude-dump",k4="## Claude Dump Status",h4="## Claude Dump Enabled",w4="## Claude Dump Disabled",I4="## Claude Dump Usage",v4="Usage: `/claude-dump`, `/claude-dump on`, or `/claude-dump off`.",m4="OPENCODE_ANTHROPIC_AUTH_DUMP_DIR",y4="OPENCODE_ANTHROPIC_AUTH_DUMP_MAX_BYTES",l4=K1(A4(),"opencode-anthropic-auth-dumps"),g4=536870912,p4=300000,s4=60000,u4=600000,d1=/\.(body|meta|relay|request|response)\.json$/,FC=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d{5,}-(.+)$/,_1="[a-zA-Z0-9._-]",MC=new RegExp(`^${_1}{1,80}-direct(?:-${_1}{1,80})?$`),QC=new RegExp(`^${_1}{1,80}-(?:http|websocket)-p[12]-(?:full_sync|patch)$`),d4=new RegExp(`^-direct(?:-${_1}{1,80})?$`),c4=/^-(?:http|websocket)-p[12]-(?:full_sync|patch)$/,h0=!1,OC=0,fC=0,i4=100,f0=new Map;function c_($){h0=$}function w0(){return process.env[m4]||l4}function r4(){let $=Number(process.env[y4]);return Number.isFinite($)&&$>=0?Math.floor($):g4}function o4($){return k0($)===k0(w0())}function s1($){let C=$.replace(d1,"");if(C===$)return!1;let _=FC.exec(C)?.[1];if(!_)return!1;return MC.test(_)||QC.test(_)}function n4($){if(!$.endsWith(".partial"))return!1;let C=$.slice(0,-8);if(s1(C))return!0;let j=C.lastIndexOf(".");if(j<0)return!1;let _=C.slice(j+1);return/^[a-f0-9]{24}$/.test(_)&&s1(C.slice(0,j))}async function A0($,C){for(let j=0;j<2;j+=1){let _=R4(12).toString("hex"),J=`${$}.${_}.partial`,G=!1;try{return await P4(J,C,{encoding:"utf8",flag:"wx"}),G=!0,await x4(J,$),!0}catch(K){if(K.code==="EEXIST")continue;if(G)await EC(J).catch(()=>{});throw K}}return!1}async function a4($){let C=$.dumpDir??w0(),j=$.maxBytes??r4(),_=$.now??Date.now(),J=$.minAgeMs??s4,G=$.partialStaleMs??u4,K={removed:0,freedBytes:0};if(!o4(C)||j<=0)return K;try{if((await p1(C)).isSymbolicLink())return K;let Z=new Set(($.protectedPaths??[]).map((f)=>k0(f))),z=await NC(C,{withFileTypes:!0}),X=[];await Promise.all(z.map(async(f)=>{if(!f.isFile())return;let M=n4(f.name);if(!M&&!s1(f.name))return;let x=K1(C,f.name);try{let H=await p1(x);if(!H.isFile()||H.isSymbolicLink())return;X.push({path:x,size:H.size,mtimeMs:H.mtimeMs,partial:M,...!M&&{artifactGroup:f.name.replace(d1,"")}})}catch{}}));let O=X.reduce((f,M)=>f+M.size,0),W=0,Y=0,L=async(f)=>{try{await EC(f.path),O-=f.size,Y+=f.size,W+=1}catch{}},E=X.filter((f)=>f.partial).sort((f,M)=>f.mtimeMs-M.mtimeMs||f.path.localeCompare(M.path));for(let f of E){if(Z.has(k0(f.path)))continue;if(_-f.mtimeMs<G)continue;await L(f)}let S=new Map;for(let f of X){if(f.partial||!f.artifactGroup)continue;let M=S.get(f.artifactGroup)??{files:[],newestMtimeMs:0};M.files.push(f),M.newestMtimeMs=Math.max(M.newestMtimeMs,f.mtimeMs),S.set(f.artifactGroup,M)}let q=[...S.entries()].sort(([f,M],[x,H])=>M.newestMtimeMs-H.newestMtimeMs||f.localeCompare(x));for(let[,f]of q){if(O<=j)break;if(_-f.newestMtimeMs<J)continue;if(f.files.some((M)=>Z.has(k0(M.path))))continue;for(let M of f.files)await L(M)}if(W>0)N.debug("dump","removed old dump files",{removed:W,freedBytes:Y});return{removed:W,freedBytes:Y}}catch{return K}}function t4($,C){let j=Date.now();if(j-fC<p4)return;fC=j,a4({dumpDir:$,protectedPaths:C}).catch(()=>{})}function e4($){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 j1($){let C=$?.enabled??h0;return[k4,"",`- Enabled: ${C?"enabled":"disabled"}`,`- Directory: ${w0()}`,"- 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(`
|
|
12
|
+
`)}function i_($){let C=e4($.argumentsText),j=$.enabled??h0;if(C.type==="status")return j1({enabled:j});if(C.type==="enable")return[h4,"",j1({enabled:!0})].join(`
|
|
13
|
+
`);if(C.type==="disable")return[w4,"",j1({enabled:!1})].join(`
|
|
14
|
+
`);return[I4,"",v4,"",j1({enabled:j})].join(`
|
|
15
|
+
`)}function u1($){return $.length<=16?$:`${$.slice(0,12)}…`}function J1($,C=80){let j=$.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!j)return"session-unknown";return j.length<=C?j:j.slice(0,C)}function $3($){if($.transport!=="direct")return`${$.transport}-p${$.protocol}-${$.mode}`;return`direct${$.route?`-${J1($.route)}`:""}`}function SC($){if($==="cachekeep")return"-prewarm-cachekeep";if($==="start")return"-start";return""}function C3($){let C=$.affinity?.trim();if(C)return`session:${C}`;return`request:${$.route??"direct"}:${$.url??""}`}function j3($,C){if(!$.endsWith(".body.json"))return;let j=$.replace(d1,""),_=FC.exec(j)?.[1];if(!_||!MC.test(_)&&!QC.test(_))return;let J=SC("cachekeep"),G=[{prefix:J1(C),tag:null},{prefix:`${J1(C,80-J.length)}${J}`,tag:"cachekeep"}];for(let K of G){if(!_.startsWith(`${K.prefix}-`))continue;let V=_.slice(K.prefix.length);if(d4.test(V)||c4.test(V))return K.tag}return}async function _3($){let C=$.affinity?.trim();if(!C)return;let j=w0(),_;try{_=await NC(j)}catch{return}let J=_.map((G)=>({name:G,tag:j3(G,C)})).filter((G)=>G.tag!==void 0).sort((G,K)=>K.name.localeCompare(G.name));for(let G of J)try{let K=K1(j,G.name),V=K.replace(/\.body\.json$/,".meta.json");if(!(await p1(K)).isFile())continue;let Z=JSON.parse(await WC(V,"utf8"));if(Z.session!==u1(C)||(G.tag===null?Z.tag!=null:Z.tag!==G.tag))continue;return await WC(K,"utf8")}catch{}return}function J3($,C){if(!f0.has($))while(f0.size>=i4){let j=f0.keys().next().value;if(j===void 0)break;f0.delete(j)}f0.set($,C)}function G3($){if($==null)return;return Object.fromEntries(new Headers($).entries())}function UC($){return T4("sha256").update($).digest("hex")}function K3($){return GC($)}function V3($,C){if($==null)return null;if($===C)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:$.length,currentBytes:C.length};let j=0;while(j<$.length&&j<C.length&&$[j]===C[j])j+=1;let _=$.length-1,J=C.length-1;while(_>=j&&J>=j&&$[_]===C[J])_-=1,J-=1;return{changed:!0,firstByte:j,lastPreviousByte:_,lastCurrentByte:J,changedPreviousBytes:_-j+1,changedCurrentBytes:J-j+1,previousBytes:$.length,currentBytes:C.length}}function Z3($){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 g1($){return UC(JSON.stringify($))}function z3($){let C=Z3($);if(!C)return{parseable:!1};let j=Array.isArray(C.messages)?C.messages:[],_=Array.isArray(C.system)?C.system:[],J=j[0],G=j.slice(1);return{parseable:!0,model:typeof C.model==="string"?C.model:void 0,stream:C.stream,systemCount:_.length,messagesCount:j.length,systemHash:g1(_),message0Hash:J===void 0?null:g1(J),message0Bytes:J===void 0?0:JSON.stringify(J).length,messagesAfter0Hash:g1(G),messagesAfter0Bytes:JSON.stringify(G).length,cch:K3($)}}function G1($){if(Array.isArray($))return $.map(G1);if($==null||typeof $!=="object")return $;let C={};for(let[j,_]of Object.entries($)){let J=j.toLowerCase();if(J==="authorization"||J==="x-api-key"||J==="cookie"||J==="set-cookie"||LC(j)){C[j]="[redacted]";continue}C[j]=G1(_)}return C}async function BC($){if(!h0)return null;OC+=1;let C=$.affinity?.trim()||"session-unknown",j=SC($.tag),_=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(OC).padStart(6,"0")}-${J1(C,80-j.length)}${j}-${$3($)}`,J=w0(),G=K1(J,_),K={body:`${G}.body.json`,metadata:`${G}.meta.json`,response:`${G}.response.json`};if($.payload!==void 0)K.relay=`${G}.relay.json`;if($.request!==void 0)K.request=`${G}.request.json`;try{await q4(J,{recursive:!0});let V=$.previousBodyText??await _3($),Z={id:_,createdAt:new Date().toISOString(),session:u1(C),transport:$.transport,protocol:$.protocol,mode:$.mode,route:$.route,status:$.status,error:$.error,tag:$.tag,bodyBytes:$.bodyText.length,relayBytes:$.relayBytes,bodyHash:UC($.bodyText),diff:V3(V,$.bodyText),body:z3($.bodyText),files:K},z=[A0(K.body,$.bodyText),A0(K.metadata,`${JSON.stringify(Z,null,2)}
|
|
16
|
+
`)];if($.payload!==void 0&&K.relay)z.push(A0(K.relay,`${JSON.stringify(G1($.payload),null,2)}
|
|
17
|
+
`));if($.request!==void 0&&K.request)z.push(A0(K.request,`${JSON.stringify(G1({...$.request,headers:G3($.request.headers)}),null,2)}
|
|
18
|
+
`));await Promise.all(z),t4(J,Object.values(K)),B(`dumped request id=${_} session=${u1(C)} body=${K.body} meta=${K.metadata}`)}catch(V){return B(`dump failed: ${V instanceof Error?V.message:String(V)}`),null}return{responsePath:K.response,...$.tag?{tag:$.tag}:{}}}async function bC($){if(!h0)return null;let C=C3($),j=f0.get(C),_=await BC({affinity:$.affinity,transport:"direct",route:$.route,status:$.status,error:$.error,bodyText:$.bodyText,previousBodyText:j,request:{url:$.url,method:$.method,headers:$.headers},tag:$.tag});return J3(C,$.bodyText),_}async function DC($){return BC({affinity:$.affinity,transport:$.transport,protocol:$.protocol,mode:$.mode,status:$.status,bodyText:$.bodyText,previousBodyText:$.previousBodyText,payload:$.payload,relayBytes:$.relayBytes,tag:$.tag})}async function TC($,C){if(!$)return;let j=C.message!=null&&typeof C.message==="object"&&!Array.isArray(C.message)?C.message:{},_={status:C.status,stream_complete:C.complete??!0};if(typeof j.id==="string"&&j.id.length>0)_.message_id=j.id;if(typeof j.model==="string"&&j.model.length>0)_.model=j.model;if(Object.hasOwn(j,"usage"))_.usage=j.usage;if(Object.hasOwn(j,"diagnostics"))_.diagnostics=j.diagnostics;if(typeof j.stop_reason==="string"&&j.stop_reason.length>0)_.stop_reason=j.stop_reason;try{await A0($.responsePath,`${JSON.stringify(_,null,2)}
|
|
19
|
+
`)}catch(J){B(`dump response failed: ${J instanceof Error?J.message:String(J)}`)}}var e_="claude-cachekeep",c1=3600000,RC=300000,X3=60000,$J="extended-cache-ttl-2025-04-11",Y3=32,qC=16777216,H3=30000,W3=60000,O3=900000,f3=30000,xC="## Claude Cache Keep Status",PC="## Claude Cache Keep Enabled",L3="## Claude Cache Keep Disabled",N3="## Claude Cache Keep Usage",E3="Usage: `/claude-cachekeep`, `/claude-cachekeep always`, `/claude-cachekeep off`, or `/claude-cachekeep HH-HH`.";function V1($){return String($).padStart(2,"0")}function F3($){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 j=/^(\d{1,2})-(\d{1,2})$/.exec(C);if(!j)return{type:"usage"};let _=Number(j[1]),J=Number(j[2]);if(!Number.isInteger(_)||!Number.isInteger(J)||_<0||_>23||J<0||J>23||_===J)return{type:"usage"};return{type:"window",startHour:_,endHour:J}}function Z1($){let C=Number($?.cacheKeep?.startHour),j=Number($?.cacheKeep?.endHour);if(!Number.isInteger(C)||!Number.isInteger(j)||C<0||C>23||j<0||j>23||C===j)return;return{startHour:C,endHour:j}}function z1($){return $?.cacheKeep?.enabled===!0&&$.cacheKeep.always===!0}function IC($){return $?.cacheKeep?.enabled===!0&&(z1($)||!!Z1($))}function M3($){return IC($)&&$?.claudeCache?.enabled===!0&&$.claudeCache.mode==="hybrid"}function Q3($,C=new Date){if(!$)return!1;let j=C.getHours();if($.startHour<$.endHour)return j>=$.startHour&&j<$.endHour;return j>=$.startHour||j<$.endHour}function AC($,C=new Date){if($?.cacheKeep?.enabled!==!0)return!1;return z1($)||Q3(Z1($),C)}function kC($=new Date){return`${$.getFullYear()}-${V1($.getMonth()+1)}-${V1($.getDate())}`}function vC($,C=new Date){if($&&$.startHour>$.endHour&&C.getHours()<$.endHour){let j=new Date(C);return j.setDate(j.getDate()-1),kC(j)}return kC(C)}function hC($,C,j=new Date){return z1($)?"always":vC(C,j)}function L0($){let C=$.always?"always (while this process is running)":$.window?`${V1($.window.startHour)}-${V1($.window.endHour)}`:"not configured",j=[`Cache keep: ${$.enabled?"enabled":"disabled"}`,`Schedule: ${C}`,"Mode requirement: `/claude-cache mode hybrid` must be active."];if(typeof $.hybridActive==="boolean")j.push(`Hybrid active: ${$.hybridActive?"yes":"no"}`);if(typeof $.trackedSessions==="number")j.push(`Tracked sessions: ${$.trackedSessions}`);if($.trackedSessionDetails?.length){j.push("Sessions:");for(let _ of $.trackedSessionDetails)j.push(`- ${_.id}`)}if($.nextPrewarmAt)j.push(`Next prewarm: ${new Date($.nextPrewarmAt).toLocaleString()}`);return j.join(`
|
|
20
|
+
`)}function CJ($){let C=F3($.argumentsText),j={enabled:$.enabled??!1,always:$.always,window:$.window,trackedSessions:$.trackedSessions,trackedSessionDetails:$.trackedSessionDetails,nextPrewarmAt:$.nextPrewarmAt,hybridActive:$.hybridActive};if(C.type==="status")return[xC,"",L0(j)].join(`
|
|
21
|
+
`);if(C.type==="disable")return[L3,"",L0({...j,enabled:!1})].join(`
|
|
22
|
+
`);if(C.type==="always")return[PC,"",L0({...j,enabled:!0,always:!0,window:void 0})].join(`
|
|
23
|
+
`);if(C.type==="window")return[PC,"",L0({...j,enabled:!0,always:!1,window:{startHour:C.startHour,endHour:C.endHour}})].join(`
|
|
24
|
+
`);if(C.type==="subagents")return[xC,"",L0(j),"",`Subagent tracking: ${C.enabled?"enabled":"disabled"}`].join(`
|
|
25
|
+
`);return[N3,"",E3,"",L0(j)].join(`
|
|
26
|
+
`)}function i1($){if(!$||typeof $!=="object")return!1;if(Array.isArray($))return $.some(i1);let C=$,j=C.cache_control;if(j&&typeof j==="object"&&j.type==="ephemeral")return!0;return Object.values(C).some(i1)}async function S3($){let C;try{C=JSON.parse($)}catch{return{ok:!1,reason:"body is not valid JSON"}}if(!i1(C))return{ok:!1,reason:"body has no explicit cache breakpoints"};let j=structuredClone(C);if(j.max_tokens=0,delete j.stream,j.thinking?.type==="enabled")delete j.thinking;if(j.output_config?.format)delete j.output_config;let G=j.tool_choice;if(G?.type==="tool"||G?.type==="any")delete j.tool_choice;return{ok:!0,bodyText:await KC(JSON.stringify(HC(j)))}}function wC($,C){let j=Math.min(O3,W3*2**Math.min(Math.max(C-1,0),8)),_=2166136261;for(let G of`${$}:${C}`)_^=G.charCodeAt(0),_=Math.imul(_,16777619);let J=(_>>>0)%(Math.min(f3,j/4)+1);return j+J}class U3{options;targets=new Map;timer=null;tickPromise=null;constructor($){this.options=$}start(){if(this.timer)return;if(N.debug("cachekeep","started"),this.timer=(this.options.setIntervalImpl??globalThis.setInterval)(()=>{this.tick().catch(($)=>{N.warn("cachekeep","tick failed",{error:$ instanceof Error?$.message:String($)})})},X3),"unref"in this.timer)this.timer.unref()}stop(){if(!this.timer)return;N.debug("cachekeep","stopped"),(this.options.clearIntervalImpl??globalThis.clearInterval)(this.timer),this.timer=null}stats($,C=this.options.now?.()??Date.now(),j=!1){let _=j?"always":vC($,new Date(C)),J=[...this.targets.values()].filter((K)=>K.dayKey===_),G=J.length?Math.min(...J.map((K)=>K.nextPrewarmAt)):void 0;return{trackedSessions:J.length,nextPrewarmAt:G}}trackedSessions(){return[...this.targets.values()].map(($)=>({id:$.id,cacheExpiresAt:$.cacheExpiresAt,nextPrewarmAt:$.nextPrewarmAt})).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)=>{N.warn("cachekeep","failed to publish tracked sessions",{error:C instanceof Error?C.message:String(C)})})}catch(C){N.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[j,_]of this.targets){if(C&&_.dayKey!==C){this.targets.delete(j);continue}if($>=_.cacheExpiresAt)this.targets.delete(j)}while(this.targets.size>Y3)this.evictOldestTarget();while(this.totalBodyBytes()>qC){let j=this.targets.size;if(this.evictOldestTarget(),this.targets.size===j)break}}track($){if(!$.sessionId)return{tracked:!1,reason:"missing session id"};if(!IC($.storage))return{tracked:!1,reason:"cachekeep disabled"};if($.cacheMode!=="hybrid")return{tracked:!1,reason:"cache mode is not hybrid"};if($.bodyText.length>qC)return{tracked:!1,reason:"body exceeds cachekeep memory budget"};let C=this.options.now?.()??Date.now(),j=Z1($.storage);if(!AC($.storage,new Date(C)))return{tracked:!1,reason:"outside configured schedule"};let _=hC($.storage,j,new Date(C));if(this.pruneTargets(C,_),this.targets.has($.sessionId))this.targets.delete($.sessionId);let J={};return $.headers.forEach((G,K)=>{J[K]=G}),this.targets.set($.sessionId,{id:$.sessionId,url:$.url,headers:J,bodyText:$.bodyText,cacheExpiresAt:C+c1,nextPrewarmAt:C+c1-RC,consecutiveFailures:0,dayKey:_,oauthAccountId:$.oauthAccountId,isSubagent:$.isSubagent??!1}),this.pruneTargets(C,_),this.publishTrackedSessions(),this.start(),{tracked:!0}}async prewarmNow($){let C={};$.headers.forEach((_,J)=>{C[J]=_});let j={id:$.sessionId,url:$.url,headers:C,bodyText:$.bodyText,cacheExpiresAt:this.options.now?.()??Date.now(),nextPrewarmAt:this.options.now?.()??Date.now(),consecutiveFailures:0,dayKey:"",oauthAccountId:$.oauthAccountId,isSubagent:$.isSubagent??!1};return this.sendPrewarm(j)}tick(){if(this.tickPromise)return this.tickPromise;let $;return $=this.runTick().finally(()=>{if(this.tickPromise===$)this.tickPromise=null}),this.tickPromise=$,$}async runTick(){let $=await this.options.loadStorage(),C=Z1($),j=this.options.now?.()??Date.now(),_=hC($,C,new Date(j));if(z1($))for(let J of this.targets.values())J.dayKey="always";if(this.pruneTargets(j,_),!this.targets.size){this.publishTrackedSessions(),this.stop();return}if(!M3($)){this.publishTrackedSessions();return}if(!AC($,new Date(j))){this.publishTrackedSessions();return}N.debug("cachekeep","fired",{targets:this.targets.size});for(let J of this.targets.values()){if(J.nextPrewarmAt>j)continue;try{await this.prewarm(J,j)}catch(G){N.warn("cachekeep","prewarm failed",{session:J.id,reason:G instanceof Error?G.message:String(G)}),J.consecutiveFailures+=1,J.nextPrewarmAt=j+wC(J.id,J.consecutiveFailures)}}this.publishTrackedSessions()}async sendPrewarm($){let C=$.bodyText;if(this.options.prepareBody)try{C=await this.options.prepareBody(C,$)}catch(Y){N.warn("cachekeep","prepare body failed",{session:$.id,error:Y instanceof Error?Y.message:String(Y)})}let j={...$,bodyText:C},_=await S3(C);if(!_.ok)return _;let J=this.options.fetchImpl??fetch,G={...j,bodyText:_.bodyText},K=this.options.prepareHeaders?await this.options.prepareHeaders(new Headers($.headers),G):new Headers($.headers);K.delete("content-length"),K.delete("transfer-encoding");let V;try{V=await J($.url,{method:"POST",headers:K,body:_.bodyText,signal:AbortSignal.timeout(this.options.prewarmTimeoutMs??H3)})}catch(Y){return{ok:!1,reason:Y instanceof Error?Y.message:String(Y),transient:!0}}let Z=this.options.now?.()??Date.now(),z=await V.text().catch(()=>""),X=null;try{X=z?JSON.parse(z):null}catch{}try{await this.options.onResponse?.({target:$,bodyText:_.bodyText,status:V.status,data:X,receivedAt:Z})}catch{}try{let Y=await bC({affinity:$.id,route:"cachekeep",status:V.status,bodyText:_.bodyText,url:$.url,method:"POST",headers:K,tag:"cachekeep"});await TC(Y,{status:V.status,message:X})}catch(Y){N.debug("cachekeep","dump failed",{session:$.id,error:Y instanceof Error?Y.message:String(Y)})}if(!V.ok)return{ok:!1,reason:z||`HTTP ${V.status}`,status:V.status};let W=(X&&typeof X==="object"&&!Array.isArray(X)?X:null)?.usage;return{ok:!0,...W&&{usage:W}}}async prewarm($,C){let j=await this.sendPrewarm($);if(!j.ok){if(j.status==null&&!j.transient)N.debug("cachekeep","prewarm skipped",{session:$.id,reason:j.reason}),this.targets.delete($.id);else N.warn("cachekeep","prewarm failed",{session:$.id,status:j.status,reason:j.reason}),$.consecutiveFailures+=1,$.nextPrewarmAt=C+wC($.id,$.consecutiveFailures);return}$.cacheExpiresAt=C+c1,$.nextPrewarmAt=$.cacheExpiresAt-RC,$.consecutiveFailures=0,N.debug("cachekeep","prewarm succeeded",{session:$.id,...j.usage&&{usage:j.usage}})}}import{randomUUID as mC}from"node:crypto";import{mkdir as B3,readdir as b3,readFile as D3,rename as T3,rm as yC,writeFile as R3}from"node:fs/promises";import{tmpdir as q3}from"node:os";import{join as r1}from"node:path";var x3=180000;function P3($){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 A3($){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((j)=>{let _=P3(j);return _?[_]:[]})}}function VJ($){return r1(q3(),"opencode-anthropic-auth","cachekeep-sessions",$)}class k3{options;filePath;writeChain=Promise.resolve();constructor($){this.options=$;let C=$.instanceId??`${process.pid}-${mC()}`;this.filePath=r1($.directory,`${C}.json`)}publish($){let C=$.map((j)=>({...j}));return this.writeChain=this.writeChain.catch(()=>{}).then(async()=>{if(C.length===0){await yC(this.filePath,{force:!0});return}await B3(this.options.directory,{recursive:!0,mode:448});let j=`${this.filePath}.${mC()}.tmp`,_={version:1,updatedAt:this.options.now?.()??Date.now(),sessions:C};await R3(j,`${JSON.stringify(_)}
|
|
27
|
+
`,{mode:384}),await T3(j,this.filePath)}),this.writeChain}async list($=[]){await this.writeChain.catch(()=>{});let C=this.options.now?.()??Date.now(),j=this.options.leaseMs??x3,_;try{_=(await b3(this.options.directory)).filter((K)=>K.endsWith(".json"))}catch{_=[]}let J=await Promise.all(_.map(async(K)=>{try{let V=await D3(r1(this.options.directory,K),"utf8");return A3(JSON.parse(V))}catch{return}})),G=new Map;for(let K of J){if(!K||C-K.updatedAt>j||K.updatedAt>C)continue;for(let V of K.sessions){let Z=G.get(V.id);if(!Z||V.cacheExpiresAt>Z.cacheExpiresAt)G.set(V.id,V)}}for(let K of $){let V=G.get(K.id);if(!V||K.cacheExpiresAt>V.cacheExpiresAt)G.set(K.id,{...K})}return[...G.values()].sort((K,V)=>K.id.localeCompare(V.id))}async dispose(){await this.writeChain.catch(()=>{}),await yC(this.filePath,{force:!0})}}async function zJ($){let C=await($.fetchImpl??fetch)("https://api.anthropic.com/api/oauth/profile",{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 j=await C.json(),_=j.organization?.rate_limit_tier,J=j.organization?.organization_type;if(typeof _!=="string"||_.trim()===""||typeof J!=="string"||J.trim()==="")throw Error("Claude profile response is missing account metadata");return{tier:_,orgType:J,checkedAt:$.now?.()??Date.now(),...$.accountIdentity!==void 0&&{accountIdentity:$.accountIdentity}}}function XJ($,C){if(!$)return!1;if(C===void 0)return!0;return $.accountIdentity===void 0||$.accountIdentity===C}function YJ($,C=Date.now()){return Boolean($&&Number.isFinite($.checkedAt)&&C>=$.checkedAt&&C-$.checkedAt<604800000)}function N0($){let C=$?.tier.match(/^default_claude_max_(\d+)x$/);if(!C)return;let j=`Max ${C[1]}x`;return $?.orgType==="claude_team"?`Team · ${j}`:j}var OJ="claude-account";function h3($){let C=$.trim().split(/\s+/).filter(Boolean);if(C.length===0)return{type:"status"};let j=C[0],_=C.slice(1).join(" ");if(j==="enable"&&_)return{type:"enable",id:_};if(j==="disable"&&_)return{type:"disable",id:_};if(j==="remove"&&_)return{type:"remove",id:_};if(j==="move-up"&&_)return{type:"move-up",id:_};if(j==="move-down"&&_)return{type:"move-down",id:_};if(j==="add-apikey"&&_){let J=_,G,K,V=J.match(/--base-url\s+(\S+)/);if(V)G=V[1],J=J.replace(V[0],"").trim();let Z=J.match(/--auth-header\s+(authorization-bearer|x-api-key)/);if(Z)K=Z[1],J=J.replace(Z[0],"").trim();let z,X=J.match(/--label\s+(.+)/);if(X)z=X[1]?.trim()||void 0,J=J.replace(X[0],"").trim();let O=J.indexOf(" ");if(O===-1){if(!J)return{type:"usage"};return{type:"add-apikey",apiKey:J,baseURL:G,authHeader:K,label:z}}let W=J.slice(0,O),Y=J.slice(O+1).trim();return{type:"add-apikey",apiKey:W,label:z??(Y||void 0),baseURL:G,authHeader:K}}if(j==="add-oauth-start")return{type:"add-oauth-start"};if(j==="add-oauth-finish"&&_){let J=_,G,K=J.match(/--label\s+(.+)/);if(K)G=K[1]?.trim()||void 0,J=J.replace(K[0],"").trim();if(!J)return{type:"usage"};return{type:"add-oauth-finish",code:J,label:G}}return{type:"usage"}}function w3($){let C=[],j=$.quota?.mainQuota?.five_hour;C.push({id:"main",label:$.main?.provider==="anthropic"?"OpenCode anthropic":"Main",role:"main",enabled:!0,quotaPercent:j?.usedPercent??null,tierLabel:N0($.main?.profile)});for(let _ of $.accounts){let J=_.quota?.five_hour;C.push({id:_.id,label:_.label??_.id,role:"fallback",enabled:_.enabled!==!1,quotaPercent:J?.usedPercent??null,tierLabel:_.type==="oauth"?N0(_.profile):void 0})}return C}var o1=["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(`
|
|
28
|
+
`);function fJ($){let C=h3($.argumentsText),j=$.storage.accounts,_="main";if(C.type==="status"){let G=w3($.storage),K=["## Claude Accounts",""];for(let V of G){let Z=V.quotaPercent!=null?` ${Math.round(V.quotaPercent)}%`:"",z=!V.enabled?" (disabled)":"",X=V.tierLabel?` · ${V.tierLabel}`:"";K.push(`- **${V.label}** [${V.role}]${X}${z}${Z}`)}return K.push("",o1),{text:K.join(`
|
|
29
|
+
`)}}if(C.type==="usage")return{text:o1};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 J=C.id;if(J==="main")return{text:`Cannot ${C.type} the main account (OpenCode managed).`};if(C.type==="enable"||C.type==="disable"){let G=j.find((K)=>K.id===J);if(!G)return{text:`Account "${J}" not found.`};return{text:`Account "${G.label??J}" ${C.type}d.`,updated:{id:J,action:C.type,enabled:C.type==="enable"}}}if(C.type==="remove"){let G=j.find((K)=>K.id===J);if(!G)return{text:`Account "${J}" not found.`};return{text:`Account "${G.label??J}" removed.`,updated:{id:J,action:"remove"}}}if(C.type==="move-up"){let G=j.findIndex((z)=>z.id===J);if(G<0)return{text:`Account "${J}" not found.`};if(G===0)return{text:`Account "${j[G]?.label??J}" is already first.`};let K=j.map((z)=>z.id),V=[...j];[V[G-1],V[G]]=[V[G],V[G-1]];let Z=V.map((z)=>z.id);return{text:`Account "${j[G]?.label??J}" moved up.`,updated:{id:J,action:"reorder",previousOrder:K,newOrder:Z}}}if(C.type==="move-down"){let G=j.findIndex((z)=>z.id===J);if(G<0)return{text:`Account "${J}" not found.`};if(G===j.length-1)return{text:`Account "${j[G]?.label??J}" is already last.`};let K=j.map((z)=>z.id),V=[...j];[V[G],V[G+1]]=[V[G+1],V[G]];let Z=V.map((z)=>z.id);return{text:`Account "${j[G]?.label??J}" moved down.`,updated:{id:J,action:"reorder",previousOrder:K,newOrder:Z}}}return{text:o1}}var NJ="claude-fast";var Y1=!1;function EJ(){return Y1}function FJ($){Y1=$}function I3($){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 X1($){return["## Claude Fast Mode Status","",`- Enabled: ${$?.enabled??Y1?"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(`
|
|
30
|
+
`)}function MJ($){let C=I3($.argumentsText),j=$.enabled??Y1;if(C.type==="status")return X1({enabled:j});if(C.type==="enable")return["## Claude Fast Mode Enabled","",X1({enabled:!0})].join(`
|
|
31
|
+
`);if(C.type==="disable")return["## Claude Fast Mode Disabled","",X1({enabled:!1})].join(`
|
|
32
|
+
`);return["## Claude Fast Mode Usage","","Usage: `/claude-fast`, `/claude-fast on`, or `/claude-fast off`.","",X1({enabled:j})].join(`
|
|
33
|
+
`)}var E0="claude-killswitch";function v3($){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 j=[];for(let _=1;_<C.length;_++){let J=C[_]?.match(/^([^:]+):(\d+),(\d+)(?:,(\d+))?$/);if(!J)return{type:"usage"};let[,G,K,V,Z]=J,z=typeof Z==="string"&&Z.length>0?Number.parseInt(Z,10):void 0,X={account:G,fh:Number.parseInt(K,10),sd:Number.parseInt(V,10)};if(z!==void 0)X.scoped=z;j.push(X)}if(j.length===0)return{type:"usage"};return{type:"set",entries:j}}return{type:"usage"}}function H1($,C){let j=$.enabled===!0,_=["## Killswitch","",`Status: **${j?"ON":"OFF"}**`];if(j){_.push(""),_.push("| Account | 5h threshold | 1w threshold | Scoped |"),_.push("| ------- | ------------ | ------------ | ------ |");let J=R0($.main);_.push(`| main | ≥ ${J.five_hour}% | ≥ ${J.seven_day}% | ≤ ${J.scoped}% |`);for(let G of C){let K=R0($.accounts?.[G]??$.main);_.push(`| ${G} | ≥ ${K.five_hour}% | ≥ ${K.seven_day}% | ≤ ${K.scoped}% |`)}}return _.join(`
|
|
34
|
+
`)}var lC=["## Killswitch Commands","","```",`/${E0} — show status`,`/${E0} on — enable with current or default thresholds`,`/${E0} off — disable`,`/${E0} set all:5,10 — set all accounts to 5h≥5%, 1w≥10%`,`/${E0} set main:3,8,0 — set 5h≥3%, 1w≥8%, scoped≤0%`,`/${E0} set main:3,8 work-alt:5,10 — per-account`,"```"].join(`
|
|
35
|
+
`);function UJ($){let C=v3($.argumentsText);if(C.type==="status")return{text:`${H1($.config,$.accountIds)}
|
|
36
|
+
|
|
37
|
+
${lC}`};if(C.type==="on"){let _={...$.config,enabled:!0,main:$.config.main??{five_hour:t.five_hour,seven_day:t.seven_day}};return{text:`## Killswitch Enabled
|
|
38
|
+
|
|
39
|
+
${H1(_,$.accountIds)}`,updatedConfig:_}}if(C.type==="off")return{text:"## Killswitch Disabled",updatedConfig:{...$.config,enabled:!1}};if(C.type==="set"){let _={...$.config.accounts??{}},J={...$.config,enabled:!0,accounts:_};for(let K of C.entries){let V={five_hour:K.fh,seven_day:K.sd};if(K.scoped!==void 0)V.scoped=K.scoped;if(K.account==="main")J.main=V;else if(K.account==="all"){J.main=V;for(let Z of $.accountIds)_[Z]=V}else _[K.account]=V}return{text:`## Killswitch Updated
|
|
40
|
+
|
|
41
|
+
${H1(J,$.accountIds)}`,updatedConfig:J}}return{text:`${H1($.config,$.accountIds)}
|
|
42
|
+
|
|
43
|
+
${lC}`}}var bJ="claude-logging",m3=["error","warn","info","debug","trace"];function y3($){let C=$.trim().toLowerCase().split(/\s+/).filter(Boolean);if(C.length===0)return{type:"status"};if(C.length===1&&m3.includes(C[0]))return{type:"level",level:C[0]};return{type:"usage"}}function n1($){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(`
|
|
44
|
+
`)}function DJ($){let C=y3($.argumentsText),j=$.level??"info";if(C.type==="status")return n1({level:j});if(C.type==="level")return["## Claude Log Level Updated","",`Level set to \`${C.level}\`.`,"",...n1({level:C.level}).split(`
|
|
45
|
+
`).slice(2)].join(`
|
|
46
|
+
`);return["## Claude Log Level Usage","","Usage: `/claude-logging`, `/claude-logging error|warn|info|debug|trace`.","",...n1({level:j}).split(`
|
|
47
|
+
`).slice(2)].join(`
|
|
48
|
+
`)}var RJ="claude-fable-5";var a1="claude-haiku-4-5",t1={input:1,output:5},l3=["claude-fable-5","claude-mythos-5"],sC={type:"adaptive",display:"summarized"},qJ={input:10,output:50,cacheRead:1,cacheWrite5m:12.5,cacheWrite1h:20},xJ=1e6,PJ=128000,AJ="2026-06-09",kJ={["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 uC($){return typeof $==="string"&&l3.some((C)=>$===C||$.startsWith(`${C}-`))}var gC="claude-sonnet-5",hJ=sC;function wJ($){return typeof $==="string"&&($===gC||$.startsWith(`${gC}-`))}var pC="claude-opus-5",IJ=sC;function vJ($){return typeof $==="string"&&($===pC||$.startsWith(`${pC}-`))}function mJ($){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}}import{createHash as g3}from"node:crypto";import{realpathSync as p3}from"node:fs";import{mkdir as s3,readdir as dC,rm as W1,stat as cC,writeFile as u3}from"node:fs/promises";import{tmpdir as d3}from"node:os";import{join as F0,resolve as c3}from"node:path";var rJ="claude-prime",i3=60000,eC=60000,r3=21600000,o3=90000,n3=300000;function a3($){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 $$($){if(!$)return 0;return($.inputTokens*t1.input+$.outputTokens*t1.output)/1e6}function t3($,C,j){if(j?.label?.trim())return j.label;if($==="main")return"main";let _=C?.accounts?.find((J)=>J.id===$);if(_?.label?.trim())return _.label;return $}function e3($,C){let j=C?.transient,_=$?.quota?.mainQuota,J=$?.prime?.main,G={id:"main",label:"main",nextDueAt:iC(_?.five_hour),lastPrimedAt:j?.get("main")?.lastPrimedAt??null,lastResult:j?.get("main")?.lastResult,usage:J,estimatedCostUsd:$$(J)},K=($?.accounts??[]).filter(P).filter((V)=>V.id!=="main").filter((V)=>V.enabled!==!1).map((V)=>({id:V.id,label:t3(V.id,$,V),nextDueAt:iC(V.quota?.five_hour),lastPrimedAt:j?.get(V.id)?.lastPrimedAt??null,lastResult:j?.get(V.id)?.lastResult,usage:V.prime,estimatedCostUsd:$$(V.prime)}));return[G,...K]}function iC($){if(!$?.resetsAt)return;let C=Date.parse($.resetsAt);if(!Number.isFinite(C))return;return C+eC}function O1($){let j=[$.enabled?"## Claude Prime Status":"## Claude Prime Disabled",""];j.push(`Status: ${$.enabled?"enabled":"disabled"}`),j.push(""),j.push("Accounts:");for(let _ of $.accounts){let G=_.usage?.count??0,K=$j(_.nextDueAt),V=Cj(_.lastPrimedAt,_.lastResult),Z=[`${_.label}`];if(K)Z.push(`next prime ${K}`);if(V)Z.push(V);if(G>0)Z.push(`${G} ${G===1?"prime":"primes"} ≈ $${jj(_.estimatedCostUsd??0)}`);j.push(`- ${Z.join(" · ")}`)}return j.push(""),j.push("Usage: `/claude-prime on`, `/claude-prime off`, or status."),j.join(`
|
|
49
|
+
`)}function $j($){if(typeof $!=="number")return"";return new Date($).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Cj($,C){if(typeof $!=="number")return"";let j=new Date($).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(C==="error")return`primed ${j} err`;return`primed ${j} ✓`}function jj($){if($===0)return"0";if($<0.0001)return $.toExponential(2);return $.toFixed(Math.min(6,Math.max(0,4)))}function oJ($){let C=a3($.argumentsText);if(C.type==="status")return{text:O1({enabled:$.enabled,accounts:$.accounts})};if(C.type==="enable")return{text:O1({enabled:!0,accounts:$.accounts}),updated:{enabled:!0}};if(C.type==="disable")return{text:O1({enabled:!1,accounts:$.accounts}),updated:{enabled:!1}};return{text:["## Claude Prime Usage","","Usage: `/claude-prime`, `/claude-prime on`, or `/claude-prime off`.","",O1({enabled:$.enabled,accounts:$.accounts})].join(`
|
|
50
|
+
`)}}var _j={"not-oauth":"API-key account",disabled:"disabled","needs-reauth":"needs re-login",killswitch:"killswitch"};function Jj($){if(!$.isOAuth)return{eligible:!1,reason:"not-oauth"};if(!$.isEnabled)return{eligible:!1,reason:"disabled"};if($.hasPermanentRefreshError)return{eligible:!1,reason:"needs-reauth"};return{eligible:!0}}function rC($){return _j[$]}var Gj={model:a1,max_tokens:1,system:"Reply with 1 when you receive 0.",messages:[{role:"user",content:"0"}]};function nJ(){return JSON.parse(JSON.stringify(Gj))}function oC(){return F0(d3(),"opencode-anthropic-auth","prime")}function Kj($){let C=c3($),j;try{j=p3(C)}catch(_){if(_.code!=="ENOENT")throw _;j=C}return g3("sha256").update(j).digest("hex").slice(0,12)}function $6($,C){return F0($,Kj(C))}function Vj($,C,j){if(!/^[a-f0-9]{12,}$/i.test(j))throw Error("Prime account fingerprint must be a hexadecimal digest");return F0($6($,C),j.toLowerCase().slice(0,12))}function nC($,C,j){return F0($,`${encodeURIComponent(C)}-${j}`)}function aC($,C){return F0($,`${encodeURIComponent(C)}-bootstrap`)}function e1($,C){if($==="main")return"main";if(C&&"label"in C&&C.label?.trim())return C.label;return $}function Zj($){let C=[],j=$.refresh?.mainLastRefreshError;C.push({id:"main",label:"main",isOAuth:!0,isEnabled:!0,hasPermanentRefreshError:O0(j),storedQuota:$.quota?.mainQuota,storedFiveHour:$.quota?.mainQuota?.five_hour});for(let _ of $.accounts??[]){if(_.id==="main"){N.debug("prime","ineligible",{account:e1(_.id,_),reason:"reserved-id"});continue}if(!P(_)){C.push({id:_.id,label:e1(_.id,_),isOAuth:!1,isEnabled:_.enabled!==!1,hasPermanentRefreshError:!1});continue}C.push({id:_.id,label:e1(_.id,_),isOAuth:!0,isEnabled:_.enabled!==!1,hasPermanentRefreshError:O0(_.lastRefreshError),storedQuota:_.quota,storedFiveHour:_.quota?.five_hour})}return C}function tC($){if(!$?.resetsAt)return;let C=Date.parse($.resetsAt);return Number.isFinite(C)?C:void 0}class zj{timer=null;postFireRefreshTimers=new Set;lastForcedCheck=new Map;stopped=!1;options;transient=new Map;counters=new Map;windowActive=new Map;constructor($){this.options=$}updateOptions($){this.options=$}start(){if(this.timer)return;if(this.stopped=!1,N.trace("prime","manager started"),this.timer=setInterval(()=>{this.tick().catch(($)=>{N.warn("prime","tick failed",{error:$ instanceof Error?$.message:String($)})})},i3),typeof this.timer==="object"&&"unref"in this.timer)this.timer.unref?.()}stop(){let $=this.timer!==null,C=this.postFireRefreshTimers.size>0;if(this.stopped=!0,this.timer)clearInterval(this.timer),this.timer=null;for(let j of this.postFireRefreshTimers)clearTimeout(j);if(this.postFireRefreshTimers.clear(),this.lastForcedCheck.clear(),!$&&!C)return;N.trace("prime","manager stopped")}isStopped(){return this.stopped}async tick(){let $=this.options.now?.()??Date.now();if(N.trace("prime","tick start",{now:$}),await this.sweepMarkers($),this.stopped){N.trace("prime","tick: stopped, aborting");return}let C=await this.options.loadStorage();if(!C){N.trace("prime","tick: no storage, skipping");return}if(C.prime?.enabled!==!0){N.trace("prime","tick: feature disabled, skipping");return}let j=Zj(C);await Promise.all(j.map((_)=>this.runForAccount(_,C,$))),N.trace("prime","tick end")}stats($,C){let j=e3($??null,{now:C,transient:this.transient});if(this.counters.size===0)return j;return j.map((_)=>{let J=this.counters.get(_.id);if(!J)return _;return{..._,usage:J,estimatedCostUsd:$$(J)}})}isWindowActive($){return this.windowActive.has($)}async runForAccount($,C,j){try{if(this.stopped)return;let _=Jj({storage:C,accountId:$.id,isOAuth:$.isOAuth,isEnabled:$.isEnabled,hasPermanentRefreshError:$.hasPermanentRefreshError,quota:$.storedQuota});if(!_.eligible){N.debug("prime","ineligible",{account:$.label,reason:rC(_.reason)});return}let J=tC($.storedFiveHour);if(J!==void 0&&j<J+eC){N.trace("prime","not due",{account:$.label});return}let G=await this.options.getAccountFingerprint($.id);if(!G){N.debug("prime","credential identity unavailable",{account:$.label});return}let K=`${$.id}:${G.toLowerCase().slice(0,12)}`,V=this.markerDir(G),Z=aC(V,$.id),z=J===void 0?Z:nC(V,$.id,J);try{await cC(z);return}catch(f){if(f.code!=="ENOENT")throw f}if(J===void 0&&await this.hasAnyClaimMarker($.id,G))return;if(this.stopped)return;let X=this.lastForcedCheck.get(K);if(X!==void 0&&X.resetEpoch===J&&j<X.at+n3)return;this.lastForcedCheck.set(K,{at:j,resetEpoch:J});let O;try{O=await this.options.refreshQuota($.id)}catch(f){N.warn("prime","refresh failed",{account:$.label,error:f instanceof Error?f.message:String(f)});return}if(this.stopped)return;let W=await this.options.loadStorage();if(W?.prime?.enabled!==!0)return;let Y=O.quota;if(!O.fresh){N.debug("prime","stale fresh-check",{account:$.label});return}if(!o$(Y,W,$.id,a1)){N.debug("prime","ineligible",{account:$.label,reason:rC("killswitch")});return}let L=tC(Y?.five_hour);if(L!==void 0&&L>j){N.debug("prime","window active",{account:$.label,resetsAt:Y.five_hour?.resetsAt}),this.windowActive.set($.id,j);return}this.windowActive.delete($.id);let E=L??J,S=E===void 0?await this.tryClaimBootstrap($.id,G):await this.tryClaim($.id,G,E);if(!S){N.debug("prime","claim lost",{account:$.label,marker:`${$.id}-${E??"bootstrap"}`});return}let q=await this.options.loadStorage();if(this.stopped||q?.prime?.enabled!==!0){await W1(S,{force:!0});return}if(E!==void 0){if(await W1(Z,{force:!0}),this.stopped){await W1(S,{force:!0});return}}await this.fire($,j,q)}catch(_){N.warn("prime","account evaluation failed",{account:$.label,error:_ instanceof Error?_.message:String(_)})}}async tryClaim($,C,j){let _=this.markerDir(C),J=nC(_,$,j);return this.tryClaimPath(_,J)}async tryClaimBootstrap($,C){let j=this.markerDir(C),_=aC(j,$);return this.tryClaimPath(j,_)}async tryClaimPath($,C){try{await s3($,{recursive:!0})}catch{}try{return await u3(C,"",{encoding:"utf8",flag:"wx"}),C}catch(j){if(j.code==="EEXIST")return null;throw j}}async hasAnyClaimMarker($,C){let j=this.markerDir(C),_=`${encodeURIComponent($)}-`;try{return(await dC(j)).some((J)=>J.startsWith(_))}catch(J){if(J.code==="ENOENT")return!1;throw J}}async fire($,C,j){let _;try{_=await this.options.sendPrime($.id)}catch(G){let K=G instanceof Error?G.message:String(G);N.warn("prime","prime fire threw",{account:$.label,error:K}),this.transient.set($.id,{lastPrimedAt:C,lastResult:"error"});return}if(this.stopped)return;if(!_.ok){if(_.reason==="token-refresh")N.warn("prime","prime token refresh failed",{account:$.label,error:_.error});else N.warn("prime","prime fire failed",{account:$.label,status:_.status,error:_.error});this.transient.set($.id,{lastPrimedAt:C,lastResult:"error"});return}let J={inputTokens:_.usage?.inputTokens,outputTokens:_.usage?.outputTokens};try{let G=await this.options.recordSuccess($.id,J);if(this.stopped){this.transient.delete($.id),this.counters.delete($.id);return}this.counters.set($.id,G),this.transient.set($.id,{lastPrimedAt:C,lastResult:"ok"}),N.info("prime","prime fired",{account:$.label,status:_.status,ms:_.ms,usage:{inputTokens:G.inputTokens,outputTokens:G.outputTokens}}),this.schedulePostFireRefresh($)}catch(G){N.warn("prime","recordSuccess failed",{account:$.label,error:G instanceof Error?G.message:String(G)}),this.transient.set($.id,{lastPrimedAt:C,lastResult:"error"})}}schedulePostFireRefresh($){let C=setTimeout(()=>{if(this.postFireRefreshTimers.delete(C),this.stopped)return;(async()=>{let j=await this.options.loadStorage();if(this.stopped||j?.prime?.enabled!==!0)return;await this.options.refreshQuota($.id)})().catch((j)=>{N.debug("prime","post-fire refresh failed",{account:$.label,error:j instanceof Error?j.message:String(j)})})},o3);if(this.postFireRefreshTimers.add(C),typeof C==="object"&&"unref"in C)C.unref?.()}async sweepMarkers($){let C=this.storageMarkerDir(),j=await this.sweepMarkerDirectory(C,$);if(j>0)N.trace("prime","swept stale markers",{swept:j})}async sweepMarkerDirectory($,C){let j;try{j=await dC($)}catch{return 0}let _=0;for(let J of j)try{let G=F0($,J),K=await cC(G);if(K.isDirectory()){_+=await this.sweepMarkerDirectory(G,C);continue}if(C-K.mtimeMs>r3)await W1(G,{force:!0}),_+=1}catch{}return _}storageMarkerDir(){return $6(this.options.markerDir??oC(),this.options.storagePath)}markerDir($){return Vj(this.options.markerDir??oC(),this.options.storagePath,$)}}import{randomUUID as C6}from"node:crypto";import{chmod as j6,mkdir as Xj,readdir as Yj,readFile as _6,rename as Hj,rm as J6,writeFile as Wj}from"node:fs/promises";import{tmpdir as Oj}from"node:os";import{join as j$}from"node:path";var M0=2,fj=180000;function C$(){return process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR??j$(Oj(),"opencode-anthropic-auth","quota-header-feed")}function _5($){return($.storage?.accounts.filter(P).length??0)+($.mainOAuthConfigured?1:0)}function K6($){if($.schema_version!==M0||$.provider!=="anthropic")return!1;if(!Number.isFinite($.configured_account_count)||!Number.isFinite($.observed_at_ms))return!1;if(!$.quota||typeof $.quota!=="object")return!1;if($.identity_source==="none")return!("credential_id"in $)&&!("account_ref"in $);if($.identity_source==="credential_id")return typeof $.credential_id==="string"&&$.credential_id.length>0&&$.credential_id!=="main"&&!("account_ref"in $);if($.identity_source==="account_ref")return typeof $.account_ref==="string"&&$.account_ref.length>0&&$.account_ref!=="main"&&!("credential_id"in $);return!1}function Lj($){if($.schema_version!==M0||$.provider!=="anthropic"||!K6($))throw Error("Invalid quota header feed entry")}function Q0($){return typeof $==="number"&&Number.isFinite($)}function _$($){if(!$||typeof $!=="object")return;let C=$;if(!Q0(C.usedPercent)||!Q0(C.remainingPercent)||!Q0(C.checkedAt))return;return{usedPercent:C.usedPercent,remainingPercent:C.remainingPercent,...typeof C.resetsAt==="string"&&{resetsAt:C.resetsAt},checkedAt:C.checkedAt}}function Nj($){if(!$||typeof $!=="object")return;let C=$,j=_$(C);if(!j||typeof C.id!=="string"||!C.id.trim()||typeof C.title!=="string"||!C.title.trim()||typeof C.modelName!=="string"||!C.modelName.trim())return;return{...j,id:C.id,title:C.title,...typeof C.modelId==="string"&&C.modelId.trim()&&{modelId:C.modelId},modelName:C.modelName}}function G6($){if(!$||typeof $!=="object")return;let C=$;if(!Q0(C.amountMinor)||typeof C.currency!=="string"||!C.currency.trim()||!Q0(C.exponent))return;return{amountMinor:C.amountMinor,currency:C.currency,exponent:C.exponent}}function Ej($){if(!$||typeof $!=="object")return;let C=$,j=G6(C.used),_=G6(C.limit);if(!j||!_||typeof C.exhausted!=="boolean")return;return{used:j,limit:_,...Q0(C.utilizationPercent)&&{utilizationPercent:C.utilizationPercent},...typeof C.severity==="string"&&{severity:C.severity},exhausted:C.exhausted}}function Fj($){let C=_$($.five_hour),j=_$($.seven_day),_=Array.isArray($.scoped)?$.scoped.map(Nj).filter((G)=>G!=null):void 0,J=Ej($.extraUsage);return{...C&&{five_hour:C},...j&&{seven_day:j},...typeof $.bindingWindow==="string"&&{bindingWindow:$.bindingWindow},...typeof $.fallbackAdvised==="boolean"&&{fallbackAdvised:$.fallbackAdvised},..._&&{scoped:_},...J&&{extraUsage:J}}}class Mj{options;filePath;writeChain=Promise.resolve();constructor($={}){this.options=$;let C=$.instanceId??`${process.pid}-${C6()}`;this.filePath=j$($.directory??C$(),`${C}.json`)}publish($){let{accountKey:C,quota:j,..._}=$,J={..._,quota:Fj(j)};try{Lj(J)}catch(G){return Promise.reject(G)}if(!C)return Promise.reject(Error("Invalid quota header feed account key"));return this.writeChain=this.writeChain.catch(()=>{}).then(async()=>{let G=this.options.directory??C$();await Xj(G,{recursive:!0,mode:448}),await j6(G,448);let K={};try{let Z=JSON.parse(await _6(this.filePath,"utf8"));if(Z.version===M0&&Z.entries&&typeof Z.entries==="object")K=Z.entries}catch{}K[C]=J;let V=`${this.filePath}.${C6()}.tmp`;try{await Wj(V,`${JSON.stringify({version:M0,entries:K})}
|
|
51
|
+
`,{mode:384}),await j6(V,384),await Hj(V,this.filePath)}finally{await J6(V,{force:!0})}}),this.writeChain}async list(){await this.writeChain.catch(()=>{});let $=this.options.directory??C$(),C=this.options.now?.()??Date.now(),j=this.options.leaseMs??fj,_;try{_=(await Yj($)).filter((G)=>G.endsWith(".json"))}catch{return[]}let J=new Map;return await Promise.all(_.map(async(G)=>{try{let K=JSON.parse(await _6(j$($,G),"utf8"));if(K.version!==M0||!K.entries||typeof K.entries!=="object")return;for(let[V,Z]of Object.entries(K.entries)){if(!Z||typeof Z!=="object"||Z.schema_version!==M0||Z.provider!=="anthropic"||!K6(Z))continue;let z=Z.observed_at_ms;if(z>C||C-z>=j)continue;let X=J.get(V);if(!X||z>X.observed_at_ms)J.set(V,Z)}}catch{}})),[...J.values()].sort((G,K)=>G.observed_at_ms-K.observed_at_ms)}async dispose(){await this.writeChain.catch(()=>{}),await J6(this.filePath,{force:!0})}}var V6={"5h":"five_hour","7d":"seven_day"};function G5($){return Object.keys(V6).some((C)=>Number.isFinite(J$($,`anthropic-ratelimit-unified-${C}-utilization`)))}function J$($,C){let j=$.get(C);if(j==null||j.trim()==="")return;let _=Number(j);return Number.isFinite(_)?_:void 0}function Qj($,C,j){let _=J$($,`anthropic-ratelimit-unified-${C}-utilization`);if(_==null)return;let J=Math.min(100,Math.max(0,Math.round(_*100))),G=J$($,`anthropic-ratelimit-unified-${C}-reset`),K=G==null?void 0:new Date(G*1000),V=K&&Number.isFinite(K.getTime())?K.toISOString():void 0;return{usedPercent:J,remainingPercent:100-J,...V&&{resetsAt:V},checkedAt:j}}function K5($,C=Date.now()){let j={fallbackAdvised:$.get("anthropic-ratelimit-unified-fallback")==="available",source:"headers",checkedAt:C};for(let[J,G]of Object.entries(V6)){let K=Qj($,J,C);if(K)j[G]=K}let _=$.get("anthropic-ratelimit-unified-representative-claim");if(_)j.bindingWindow=_,j.bindingWindowSource="headers";return j}function I0($,C){let{scoped:j,extraUsage:_,...J}=$??{},{scoped:G,extraUsage:K,...V}=C;return{...J,...V,...Array.isArray(j)&&{scoped:j},..._!=null&&{extraUsage:_},bindingWindow:$?.bindingWindowSource==="poll"?$.bindingWindow:C.bindingWindow??$?.bindingWindow,bindingWindowSource:$?.bindingWindowSource==="poll"?"poll":C.bindingWindowSource??$?.bindingWindowSource,source:"headers"}}import{createHash as Sj}from"node:crypto";function G$($){return Sj("sha256").update($).digest("hex").slice(0,16)}var Uj=globalThis.setTimeout;function Z6($,C){if($?.source!=="headers")return C;let j=Boolean($.five_hour&&$.five_hour.checkedAt>(C.five_hour?.checkedAt??0)),_=Boolean($.seven_day&&$.seven_day.checkedAt>(C.seven_day?.checkedAt??0));if(!j&&!_)return C;return I0(C,{...j&&{five_hour:$.five_hour},..._&&{seven_day:$.seven_day},fallbackAdvised:$.fallbackAdvised,...$.bindingWindowSource==="headers"&&{bindingWindow:$.bindingWindow,bindingWindowSource:$.bindingWindowSource},source:"headers",checkedAt:Math.max(j?$.five_hour?.checkedAt??0:0,_?$.seven_day?.checkedAt??0:0)})}class r{main=null;mainAccountId;mainQuotaIdentityKnown=!1;mainQuotaIdentityStrict=!1;mainGeneration=0;mainQuotaErrorGeneration=0;mainQuotaErrorClearedAt;fallbacks=new Map;fallbackAuthLineages=new Map;fallbackGenerations=new Map;inflightMain=null;inflightMainAccountId;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=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,$.storage?.mainAccountId),this.seedMainBackoffFromStorage($.storage)}getMain($){if(this.mainAccountId!==$)return null;if(this.mainQuotaIdentityKnown&&this.mainQuotaIdentityStrict&&($===void 0||this.main?.quota.accountIdentity!==$))return null;return this.main}getFallback($,C){return this.bindFallbackLineage($,C),this.fallbacks.get($)??null}getAllFallbacks(){return this.fallbacks}setMain($,C){this.mainAccountId=$,this.main=C}setMainQuotaAccountIdentity($,C=!0){let j=this.mainQuotaIdentityKnown,_=this.mainAccountId,J=!j||this.mainAccountId!==$||this.mainQuotaIdentityStrict!==C;if(this.mainQuotaIdentityKnown=!0,this.mainQuotaIdentityStrict=C,!J)return;if(this.mainGeneration+=1,this.mainAccountId=$,$!==void 0&&this.main?.quota.accountIdentity!==$)this.main=null;if($!==void 0&&this.mainLastApiError&&(this.mainLastApiError.accountIdentity!==void 0?this.mainLastApiError.accountIdentity!==$:j&&_!==void 0&&_!==$))return this.mainLastApiError=void 0,this.mainQuotaErrorGeneration+=1,this.mainQuotaErrorClearedAt=H0(this.mainQuotaErrorClearedAt,this.now()),this.mainQuotaErrorGeneration;return}setFallback($,C,j){this.bindFallbackLineage($,j),this.fallbacks.set($,C)}clearFallback($){this.fallbackGenerations.set($,(this.fallbackGenerations.get($)??0)+1),this.fallbacks.delete($),this.fallbackApiErrors.delete($),this.inflightFallbacks.delete(r.fallbackInflightKey($))}pushMainFromHeaders($,C){let j=C.checkedAt??this.now(),_=I0(this.mainAccountId===$&&(!this.mainQuotaIdentityKnown||!this.mainQuotaIdentityStrict||this.main?.quota.accountIdentity===$)?this.main?.quota:void 0,{...C,...$!==void 0&&{accountIdentity:$}}),J={quota:_,checkedAt:j,refreshAfter:C0(_,this.storage,j)};return this.setMain($,J),J}pushFallbackFromHeaders($,C,j){if(!this.acceptFallbackQuotaObservation($,j))return null;let _=C.checkedAt??this.now(),J=I0(this.fallbacks.get($)?.quota,{...C,accountIdentity:$}),G={quota:J,checkedAt:_,refreshAfter:C0(J,this.storage,_)};return this.fallbacks.set($,G),G}async refreshMain($,C,j){let _=$,J=C??$;if(!J)throw Error("Main OAuth access token is unavailable");return(await this.refreshMainWithMetadata(_,J,j)).quota}async refreshMainWithMetadata($,C,j){let _=$,J=C??$;if(!J)throw Error("Main OAuth access token is unavailable");if(j!==void 0&&(this.mainGeneration!==j||this.mainAccountId!==_))throw Error("Main quota identity changed before refresh");if(this.mainAccountId!==_){if(this.main=null,this.mainAccountId=_,this.mainQuotaIdentityKnown)this.mainGeneration+=1}if(this.inflightMain&&this.inflightMainAccountId===_)return this.inflightMain;if(this.isBackedOff()){if(this.main&&this.mainAccountId===_)return{quota:this.main.quota,fetched:!1};throw Error("Quota API rate-limited — try again later")}this.inflightMainAccountId=_;let G=this.mainGeneration;return this.inflightMain=this._fetchMain(_,J,G),this.inflightMain}async refreshFallback($,C,j){return(await this.refreshFallbackWithMetadata($,C,j)).quota}async refreshFallbackWithMetadata($,C,j){this.bindFallbackLineage($,j);let _=r.fallbackInflightKey($),J=this.inflightFallbacks.get(_);if(J)return J;if(this.isFallbackBackedOff($)){let V=this.getFallback($);if(V)return{quota:V.quota,fetched:!1};throw Error("Quota API rate-limited — try again later")}let G=this.fallbackGenerations.get($)??0,K=this._fetchFallback($,C,G,j);return this.inflightFallbacks.set(_,K),K.then(()=>{if(this.inflightFallbacks.get(_)===K)this.inflightFallbacks.delete(_)},()=>{if(this.inflightFallbacks.get(_)===K)this.inflightFallbacks.delete(_)}),K}async refreshAllFallbacks($){let C=this.now();for(let j of $){if(j.enabled===!1)continue;if(!j.access)continue;this.bindFallbackLineage(j.id,j);let _=this.getFallback(j.id);if(_&&C<_.refreshAfter)continue;try{await this.refreshFallback(j.id,j.access,j)}catch{}}}refreshMainInBackground($){if(this.inflightMain)return;if(this.isBackedOff())return;this.refreshMain(this.mainAccountId,$).catch(()=>{})}scopedWindowIsStale($,C){let j=y($.quota,C);return Boolean(j&&this.now()-j.checkedAt>=p(this.storage))}isMainStale($){if(!this.main)return!0;if(this.mainQuotaIdentityKnown&&this.mainQuotaIdentityStrict&&(this.mainAccountId===void 0||this.main.quota.accountIdentity!==this.mainAccountId))return!0;return this.now()>=this.main.refreshAfter||this.scopedWindowIsStale(this.main,$)}isFallbackStale($,C,j,_){let J=this.getFallback($,_);if(!J)return!0;return this.now()>=J.refreshAfter||this.scopedWindowIsStale(J,j)}shouldRefreshOnRequestCount($){let C=c$(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.mainQuotaIdentityKnown?this.mainAccountId:$?.mainAccountId),this.seedMainBackoffFromStorage($)}seedMainFromStorage($,C){let j=d$($);if(!j)return;let _={quota:{...j.quota,...(!this.mainQuotaIdentityKnown||!this.mainQuotaIdentityStrict)&&C!==void 0&&j.accountIdentity===void 0&&{accountIdentity:C}},refreshAfter:C0(j.quota,$,j.checkedAt),checkedAt:j.checkedAt},J=this.main&&this.mainAccountId===C&&(!this.mainQuotaIdentityKnown||!this.mainQuotaIdentityStrict||this.main.quota.accountIdentity===C)?this.main:void 0;if(J&&J.checkedAt>=_.checkedAt&&J.quota.source==="headers"&&_.quota.source==="poll"){let G=I0(_.quota,J.quota);this.main={quota:G,refreshAfter:C0(G,$,J.checkedAt),checkedAt:J.checkedAt};return}if(this.main&&this.mainAccountId===C&&this.main.checkedAt>=_.checkedAt)return;if(this.main=_,C!==void 0)this.mainAccountId=C}seedMainBackoffFromStorage($){let C=$?.quota?.mainLastQuotaApiError,j=C?.accountIdentity,_=typeof $?.quota?.mainQuotaErrorGeneration==="number"&&Number.isSafeInteger($.quota.mainQuotaErrorGeneration)&&$.quota.mainQuotaErrorGeneration>=0?$.quota.mainQuotaErrorGeneration:void 0,J=typeof $?.quota?.mainQuotaErrorClearedAt==="number"&&Number.isFinite($.quota.mainQuotaErrorClearedAt)&&$.quota.mainQuotaErrorClearedAt>=0?$.quota.mainQuotaErrorClearedAt:void 0;if(J!==void 0&&(this.mainQuotaErrorClearedAt===void 0||J>this.mainQuotaErrorClearedAt)){if(this.mainQuotaErrorClearedAt=H0(this.mainQuotaErrorClearedAt,J),(!C||typeof C.checkedAt==="number"&&C.checkedAt<=J)&&(this.mainLastApiError?.checkedAt===void 0||this.mainLastApiError.checkedAt<=J))this.mainLastApiError=void 0}if(_!==void 0&&_>this.mainQuotaErrorGeneration){if(this.mainQuotaErrorGeneration=_,!C&&(this.mainLastApiError?.checkedAt===void 0||this.mainQuotaErrorClearedAt===void 0||this.mainLastApiError.checkedAt<=this.mainQuotaErrorClearedAt))this.mainLastApiError=void 0}if(C&&(!this.mainQuotaIdentityKnown||j===void 0||j===this.mainAccountId)&&(this.mainQuotaErrorClearedAt===void 0||typeof C.checkedAt!=="number"||C.checkedAt>this.mainQuotaErrorClearedAt)&&(this.mainLastApiError?.checkedAt===void 0||C.checkedAt>=this.mainLastApiError.checkedAt)&&X0(C,this.now())){if(this.mainLastApiError=C,_!==void 0)this.mainQuotaErrorGeneration=_;return}if(this.mainAccountId!==void 0&&this.mainLastApiError?.accountIdentity!==void 0&&this.mainLastApiError.accountIdentity!==this.mainAccountId)this.mainLastApiError=void 0}seedFallbacksFromAccounts($){let C=p(this.storage),j=new Set($.map((_)=>_.id));for(let _ of this.fallbackAuthLineages.keys())if(!j.has(_))this.clearFallback(_),this.fallbackAuthLineages.delete(_);for(let _ of $){if(this.bindFallbackLineage(_.id,_))continue;if(_.enabled===!1)continue;if(!_.quota)continue;let G=i(_.quota);if(G<=0)continue;let K=this.getFallback(_.id);if(K&&K.checkedAt>=G)continue;this.setFallback(_.id,{quota:{..._.quota,accountIdentity:_.id},refreshAfter:G+C,checkedAt:G},_)}}isBackedOff(){return X0(this.mainLastApiError,this.now())}isFallbackBackedOff($){return X0(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}getMainQuotaErrorGeneration(){return this.mainQuotaErrorGeneration}getMainQuotaIdentityGeneration(){return this.mainGeneration}getMainQuotaErrorClearedAt(){return this.mainQuotaErrorClearedAt}clearMainBackoff(){if(!this.mainLastApiError)return;return this.mainLastApiError=void 0,this.mainQuotaErrorGeneration+=1,this.mainQuotaErrorClearedAt=H0(this.mainQuotaErrorClearedAt,this.now()),this.mainQuotaErrorGeneration}static API_CALL_GAP_MS=1000;static fallbackInflightKey($){return $}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}bindFallbackLineage($,C){if(!C)return!1;let j=this.fallbackAuthLineages.has($),_=this.fallbackAuthLineages.get($),J=j&&C.authLineageId!==void 0&&_!==C.authLineageId;if(J)this.clearFallback($);return this.fallbackAuthLineages.set($,C.authLineageId),J}acceptFallbackQuotaObservation($,C){let j=this.fallbackAuthLineages.has($),_=this.fallbackAuthLineages.get($),J=C?.authLineageId;if(j&&_!==J)return N.trace("quota","skipped stale fallback quota observation after lineage change",{accountId:$,storedLineage:_,servedLineage:J}),!1;if(!j)this.fallbackAuthLineages.set($,J);return!0}_enqueueApiFetch($){let C=async()=>{let _=this.now()-this.lastApiCallAt;if(_<r.API_CALL_GAP_MS)await new Promise((J)=>{let G=Uj(J,r.API_CALL_GAP_MS-_);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),$()},j=this.apiGate.then(C,C);return this.apiGate=j.catch(()=>{}),j}async _fetchMain($,C,j){return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main&&this.mainAccountId===$)return{quota:this.main.quota,fetched:!1};throw Error("Quota API rate-limited — try again later")}if(this.mainQuotaIdentityKnown&&this.mainQuotaIdentityStrict&&this.mainGeneration!==j)return{quota:{accountIdentity:$},fetched:!1};let _=await $0({name:"opencode-main-quota-refresh",ttlMs:30000});if(!_){let J=this.main;if(J&&this.mainAccountId===$&&this.now()<J.refreshAfter)return{quota:J.quota,fetched:!1};throw Error("Quota refresh is already in progress")}try{let J=this.now(),G=await o0({accessToken:C,fetchImpl:this.fetchImpl,now:this.now}),K=this.now();if(this.mainQuotaIdentityKnown&&this.mainQuotaIdentityStrict&&this.mainGeneration!==j)return{quota:{...G,...$!==void 0&&{accountIdentity:$}},fetched:!0};let V=Z6(this.mainAccountId===$&&(!this.mainQuotaIdentityKnown||!this.mainQuotaIdentityStrict||this.main?.quota.accountIdentity===$)?this.main?.quota:void 0,{...G,...$!==void 0&&{accountIdentity:$}});if(this.mainAccountId=$,this.main={quota:V,refreshAfter:C0(V,this.storage,K),checkedAt:V.checkedAt??K},this.mainLastApiError)this.mainLastApiError=void 0,this.mainQuotaErrorGeneration+=1,this.mainQuotaErrorClearedAt=H0(this.mainQuotaErrorClearedAt,K);return this.onMainQuotaFetched?.(V,K,G$(C),J,this.mainQuotaErrorGeneration,this.mainQuotaErrorClearedAt),{quota:V,fetched:!0}}catch(J){throw this._handleMainFetchError(J,j),J}finally{await _.release()}}finally{if(this.inflightMainAccountId===$)this.inflightMain=null,this.inflightMainAccountId=void 0}})}async _fetchFallback($,C,j,_){return this._enqueueApiFetch(async()=>{try{if((this.fallbackGenerations.get($)??0)!==j)return{quota:{accountIdentity:$},fetched:!1};if(this.isFallbackBackedOff($)){let G=this.getFallback($,_);if(G)return{quota:G.quota,fetched:!1};throw Error("Quota API rate-limited — try again later")}let J=await $0({name:r.quotaLockName($),ttlMs:30000});if(!J){let G=this.getFallback($,_);if(G&&this.now()<G.refreshAfter)return{quota:G.quota,fetched:!1};throw Error("Quota refresh is already in progress")}try{let G=await o0({accessToken:C,fetchImpl:this.fetchImpl,now:this.now}),K=this.now();if((this.fallbackGenerations.get($)??0)!==j)return{quota:{...G,accountIdentity:$},fetched:!0};let V=Z6(this.getFallback($,_)?.quota,{...G,accountIdentity:$});return this.setFallback($,{quota:V,refreshAfter:C0(V,this.storage,K),checkedAt:V.checkedAt??K},_),this.fallbackApiErrors.delete($),{quota:V,fetched:!0}}finally{await J.release()}}catch(J){throw this._handleFallbackFetchError($,J,j),J}})}static isAuthError($){if($.status===401||w1($))return!0;let j=$ instanceof Error?$.message:String($);return/quota check failed: 401\b/.test(j)}_handleMainFetchError($,C){if(this.mainGeneration!==C)return;if(this.mainQuotaIdentityKnown&&this.mainQuotaIdentityStrict&&this.mainAccountId===void 0)return;if(r.isAuthError($))return;this.mainLastApiError=r0({error:$,now:this.now(),accountIdentity:this.mainAccountId,previous:this.mainLastApiError}),this.mainQuotaErrorGeneration+=1,this.onApiError?.(this.mainLastApiError,this.mainQuotaErrorGeneration)}_handleFallbackFetchError($,C,j){if((this.fallbackGenerations.get($)??0)!==j)return;if(r.isAuthError(C))return;let _=this.fallbackApiErrors.get($);this.fallbackApiErrors.set($,r0({error:C,now:this.now(),previous:_,accountIdentity:$}))}}var E5="claude-quota",z6={five_hour:"5h",seven_day:"1w"};function f1($){return`${Math.round($*10)/10}%`}function L1($,C){let j=Math.max(0,C-$),_=Math.floor(j/60000);if(_<1)return"just now";if(_===1)return"1m ago";if(_<60)return`${_}m ago`;let J=Math.floor(_/60),G=_%60;if(G===0)return`${J}h ago`;return`${J}h ${G}m ago`}function Bj($,C){let j=Date.parse($);if(!Number.isFinite(j))return $;let _=j-C;if(_<=0)return"now";let J=Math.max(1,Math.ceil(_/60000));if(J<60)return`in ${J}m`;let G=Math.floor(J/60),K=J%60;if(K===0)return`in ${G}h`;return`in ${G}h ${K}m`}function H6($,C){if(!$)return"";return`, resets ${Bj($,C)}`}function X6($,C,j,_){if(!C)return` - ${z6[$]}: unknown`;let J=[` - ${z6[$]}: ${f1(C.remainingPercent)} remaining`,` (${f1(C.usedPercent)} used`,`${H6(C.resetsAt,j)}, checked ${L1(C.checkedAt,j)})`].join("");return _===$?`${J} •`:J}function Y6($){try{return new Intl.NumberFormat("en-US",{style:"currency",currency:$.currency,minimumFractionDigits:$.exponent,maximumFractionDigits:$.exponent}).format($.amountMinor/10**$.exponent)}catch{return`${$.amountMinor} ${$.currency}`}}function bj($,C){return[` - ${$.title}: ${f1($.remainingPercent)} remaining`,` (${f1($.usedPercent)} used`,`${H6($.resetsAt,C)}, checked ${L1($.checkedAt,C)})`].join("")}function Dj($){return $.label?.trim()||$.id}function Tj($){return $.lastQuotaRefreshError?.message??$.lastRefreshError?.message}function F5($,C=new Map){if(!$?.accounts.length)return[];return $.accounts.filter(P).map((j)=>{let _=C.get(j.id)??Tj(j);return{name:Dj(j),role:"fallback",enabled:j.enabled!==!1,quota:j.quota,...N0(j.profile)&&{tierLabel:N0(j.profile)},lastRefreshedAt:j.lastRefreshedAt,..._&&{error:_}}})}function M5($){let C=$.now??Date.now(),j=["## Claude Quotas",""];if($.refreshedAt)j.push(`Refreshed: ${L1($.refreshedAt,C)}`,"");if(!$.accounts.length)return j.push("No Claude OAuth accounts found yet."),j.join(`
|
|
52
|
+
`);for(let _ of $.accounts){let J=_.role==="main"?"main":"fallback",G=_.enabled===!1?" disabled":"";if(j.push(`### ${_.name} (${J}${G})`),_.tierLabel)j.push(` - Tier: ${_.tierLabel}`);if(_.lastRefreshedAt)j.push(` - Last token refresh: ${L1(_.lastRefreshedAt,C)}`);if(_.error)j.push(` - Error: ${_.error}`);j.push(X6("five_hour",_.quota?.five_hour,C,_.quota?.bindingWindow)),j.push(X6("seven_day",_.quota?.seven_day,C,_.quota?.bindingWindow));for(let V of _.quota?.scoped??[]){let Z=bj(V,C);j.push(_.quota?.bindingWindow===V.id?`${Z} •`:Z)}let K=_.quota?.extraUsage;if(K){let V=Y6(K.used),Z=Y6(K.limit);j.push(` - credits ${V}/${Z}${K.exhausted?" · exhausted":""}`)}if(_.quota?.fallbackAdvised===!0)j.push(" - → fallback advised");j.push("")}return j.join(`
|
|
53
|
+
`).trimEnd()}import{Buffer as M6}from"node:buffer";import{createHash as Rj,randomBytes as qj}from"node:crypto";class V$ extends Error{}class Z$ 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 s=new Map,_0=new Map,W6=new Set,xj=7200000,Pj=1800000,Aj=128,kj=32,O6=0;function K$(){return O6+=1,`req_${Date.now().toString(36)}_${O6.toString(36)}`}function N1($){if(W6.has($))return;W6.add($),B($)}function D5($){let C=$?.relay;if(!C)return N1("disabled: no relay config found"),null;if(C.enabled!==!0)return N1("disabled: relay.enabled is not true"),null;if(!C.url?.trim()||!C.token?.trim())return N1("disabled: missing relay url or token"),null;let j=C.transport==="http"?"http":"websocket";return N1(`configured transport=${j} protocol=${j==="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:j}}function T5(){return qj(32).toString("base64url")}function hj($){return`sha256:${Rj("sha256").update($).digest("hex")}`}function f6($,C){let j=0,_=Math.min($.length,C.length);while(j<_&&$.charCodeAt(j)===C.charCodeAt(j))j++;let J=$.length,G=C.length;while(J>j&&G>j&&$.charCodeAt(J-1)===C.charCodeAt(G-1))J--,G--;return{start:j,deleteCount:J-j,insert:C.slice(j,G)}}function wj($){return $.deleteCount===0&&$.insert.length===0}function L6($){let C=$.match(/\bcch=([0-9a-f]{5});/),j=C?.[1];if(!j||C.index==null)return null;let _=C.index+4;return{start:_,end:_+j.length,token:j}}function Ij($,C,j,_){return`${$.slice(0,C)}${_}${$.slice(j)}`}function Q6($,C){let j=L6($),_=L6(C);if(j&&_&&j.start===_.start&&j.end-j.start===_.end-_.start&&j.token!==_.token){let J={start:j.start,deleteCount:j.end-j.start,insert:_.token},G=Ij($,j.start,j.end,_.token),K=f6(G,C);return wj(K)?J:[J,K]}return f6($,C)}function vj($,C){if(typeof C!=="string")return!1;try{let j=$ instanceof Request?new URL($.url):new URL($.toString());return j.pathname==="/v1/messages"||j.pathname==="/messages"}catch{return!1}}function mj($){let C={};for(let[j,_]of $.entries()){if(j==="x-session-affinity"||j==="x-opencode-session")continue;C[j]=_}return C}async function N6($,C,j){let _=D(),J=JSON.stringify(C);return S0("http_payload_stringify",{session:T(C.affinity),ms:v(D()-_),relayBytes:J.length,mode:C.mode}),fetch($.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":$.token},body:J,signal:j??void 0})}function T($){return $.length>12?`${$.slice(0,12)}…`:$}function D(){return performance.now()}function v($){return Math.round($*10)/10}function yj(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function S0($,C){if(!yj())return;B(`[perf] relay ${$} ${JSON.stringify(C)}`)}function lj($){let{input:C,init:j,headers:_,bodyText:J,affinity:G,previous:K,nextHash:V}=$,Z=C instanceof Request?C.url:C.toString(),z={protocol:1,type:"request",affinity:G,upstream:{url:Z,method:j?.method||(C instanceof Request?C.method:"POST"),headers:mj(_)},next_hash:V};return K?{...z,mode:"patch",base_hash:K.hash,revision:K.revision+1,patch:Q6(K.body,J)}:{...z,mode:"full_sync",revision:1,body:J}}function z$($,C){return{protocol:$.protocol,type:"request",affinity:$.affinity,upstream:$.upstream,next_hash:$.next_hash,mode:"full_sync",revision:1,body:C}}function S6($,C,j,_){let J=Date.now();s.delete($),s.set($,{body:C,hash:j,revision:_,updatedAt:J}),X$(J)}async function E6($){let{config:C,payload:j,bodyText:_,fallback:J,signal:G}=$,K=j,V=await N6(C,K,G);if(V.status===409&&K.mode==="patch")B(`state mismatch from relay session=${T(K.affinity)}; retrying full_sync`),await V.body?.cancel().catch(()=>{}),K=z$(K,_),V=await N6(C,K,G);if(!V.ok&&V.status>=500&&C.fallbackToDirect)return B(`relay returned ${V.status}; falling back direct session=${T(K.affinity)}`),await V.body?.cancel().catch(()=>{}),{response:await J(),payload:K,transport:"http",protocol:K.protocol,usedRelay:!1};return{response:V,payload:K,transport:"http",protocol:K.protocol,usedRelay:!0}}function gj($,C){let j=new URL($);return j.protocol=j.protocol==="http:"?"ws:":"wss:",j.pathname="/ws",j.searchParams.set("token",C),j.toString()}function pj($){return new Uint8Array(M6.from($,"base64"))}function sj($){if($ instanceof Uint8Array)return $;if($ instanceof ArrayBuffer)return new Uint8Array($);if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);return new Uint8Array(M6.from(String($)))}function uj($){return JSON.parse($)}function F6($){let C=$,j=[`code=${C.code??"unknown"}`,`wasClean=${C.wasClean??"unknown"}`];if(C.reason)j.push(`reason=${JSON.stringify(C.reason)}`);return j.join(" ")}function dj($){let C=$.message||"relay websocket error";return $.status?`relay websocket error ${$.status}: ${C}`:C}class U6{config;affinity;timers;socket;connecting;queue=Promise.resolve();pending;serverState;lastUsedAt=Date.now();constructor($,C,j){this.config=$,this.affinity=C,this.timers=j}touch($=Date.now()){this.lastUsedAt=$}canEvict($=Date.now()){return!this.pending&&!this.connecting&&$-this.lastUsedAt>Pj}dispose(){this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0}send($,C,j=!1,_){this.touch();let J=D(),G=this.queue.catch(()=>{}).then(()=>this.startQueued($,C,J,j,_)),K=G.then(async({response:V,getPayload:Z})=>({response:await V,payload:Z(),transport:"websocket",protocol:2,usedRelay:!0}));return this.queue=G.then(({done:V})=>V.catch(()=>{}),()=>{}),K}async startQueued($,C,j,_,J){let G=D();await this.ensureConnected();let K=D(),V=s.get(this.affinity),Z=this.serverState?.hash,z={...$,protocol:2,id:K$()};if(z.mode==="patch"&&(!Z||Z!==z.base_hash))z.mode="full_sync",z.revision=(this.serverState?.revision??0)+1,delete z.base_hash,delete z.patch,z.body=C;if(z.mode==="patch"&&V)z.patch=Q6(V.body,C);B(`perf websocket send_start session=${T(this.affinity)} request=${z.id} mode=${z.mode} queueMs=${v(K-j)} connectMs=${v(K-G)} bodyBytes=${C.length} relayBytes=${JSON.stringify(z).length}`);let X=z,O=this.sendPayload(z,C,_,J);O.done.catch(()=>{});let W=O.done,Y=O.response.catch((E)=>{if(!(E instanceof V$)||z.mode!=="patch")throw E;let S=z$(z,C);S.protocol=2,S.id=K$(),S.revision=(this.serverState?.revision??0)+1,X=S;let q=this.sendPayload(S,C,_,J);return q.done.catch(()=>{}),W=q.done,q.response}),L=Y.then(()=>W,()=>W.catch(()=>{}));return{response:Y,done:L,getPayload:()=>X}}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 j=gj(this.config.url,this.config.token),_=new URL(j);_.searchParams.set("affinity",this.affinity);let J=new WebSocket(_.toString());this.socket=J,this.serverState=void 0;let G=this.timers.setTimeout(()=>{J.close(),C(Error("relay websocket ready timed out"))},15000);J.addEventListener("message",(K)=>{try{if(typeof K.data!=="string"){this.handleBinaryChunk(K.data);return}let V=uj(K.data);if(V.type==="ready"){this.timers.clearTimeout(G),this.serverState=V.state,$();return}this.handleMessage(V)}catch(V){this.timers.clearTimeout(G),C(V),this.failPending(V),J.close()}}),J.addEventListener("error",()=>{this.timers.clearTimeout(G);let K=new Z$("relay websocket error");C(K),this.failPending(K)}),J.addEventListener("close",(K)=>{if(this.timers.clearTimeout(G),this.socket===J)this.socket=void 0,this.serverState=void 0,this.connecting=void 0;if(this.pending){if(this.pending.retryingBeforeResponse)return;let V=this.pending.responseStartedAt!=null,Z=V?"closed after response_start before stream bytes":"closed before response";if(this.retryPendingBeforeResponse(this.pending,Z,K))return;let z=V?new Z$("relay websocket closed during response stream",K):Error("relay websocket closed before response");B(`websocket ${V?"closed during response stream":"closed before response without retry"} session=${T(this.affinity)} request=${this.pending.payload.id} chunks=${this.pending.streamChunkCount} bytes=${this.pending.streamByteCount} ${F6(K)}`),this.failPending(z)}})}).finally(()=>{this.connecting=void 0}),await this.connecting}sendPayload($,C,j,_){let J=this.socket;if(!J||J.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");let G=D(),K,V,Z=new Promise((X,O)=>{K=X,V=O});return{response:new Promise((X,O)=>{let W={payload:$,bodyText:C,resolve:X,reject:O,streamDone:!1,accepted:!1,responseStarted:!1,resolveDone:K,rejectDone:V,sentAt:G,optimisticResponse:j,streamChunkCount:0,streamByteCount:0,retryAttempts:0,retryingBeforeResponse:!1,onResponseHeaders:_,stagedResponseHeaders:void 0,responseHeadersDelivered:!1};if(this.pending=W,this.resetPendingTimeout(W),J.send(JSON.stringify($)),j)this.resolvePendingResponse(W,200,"OK",{"content-type":"text/event-stream","x-cortexkit-relay-optimistic":"true"})}),done:Z}}resetPendingTimeout($){this.timers.clearTimeout($.timeout),$.timeout=this.timers.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,j){if($.responseStartedAt!=null&&$.streamByteCount>0)return!1;if($.streamDone)return!1;if($.retryAttempts>=1)return!1;$.retryAttempts+=1,$.retryingBeforeResponse=!0,this.timers.clearTimeout($.timeout);let _=$.retryAttempts,J=$.payload.id;return B(`websocket ${C}; reconnecting and retrying full_sync session=${T(this.affinity)} request=${J} retry=${_} chunks=${$.streamChunkCount} bytes=${$.streamByteCount}${j?` ${F6(j)}`:""}`),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 G=z$($.payload,$.bodyText);G.protocol=2,G.id=K$(),G.revision=(this.serverState?.revision??0)+1,$.payload=G,$.accepted=!1,$.acceptedAt=void 0,$.responseStartedAt=void 0,$.stagedResponseHeaders=void 0,$.responseHeadersDelivered=!1,$.sentAt=D(),$.retryingBeforeResponse=!1;let K=this.socket;if(!K||K.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");this.resetPendingTimeout($),B(`perf websocket retry_send session=${T(this.affinity)} request=${G.id} previous=${J} mode=full_sync retry=${_} bodyBytes=${$.bodyText.length} relayBytes=${JSON.stringify(G).length}`),K.send(JSON.stringify(G))}catch(G){if($.retryingBeforeResponse=!1,this.pending===$)this.failPending(G)}})(),!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,sj($))}resolvePendingResponse($,C,j,_){if($.responseStarted)return;$.responseStarted=!0;let J=new ReadableStream({start:(G)=>{$.streamController=G},cancel:()=>{this.socket?.close()}});$.resolve(new Response(J,{status:C,statusText:j,headers:_}))}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 j=D();C.accepted=!0,C.acceptedAt=j,B(`perf websocket accepted session=${T(this.affinity)} request=${C.payload.id} sentMs=${v(j-C.sentAt)} mode=${C.payload.mode}`),this.serverState={hash:$.hash,revision:$.revision},S6(this.affinity,C.bodyText,$.hash,$.revision),this.resetPendingTimeout(C);return}if($.type==="response_start"){if(C.responseStartedAt!=null)return;let j=D();if(C.responseStartedAt=j,B(`perf websocket response_start session=${T(this.affinity)} request=${C.payload.id} sentMs=${v(j-C.sentAt)} upstreamMs=${C.acceptedAt==null?"unknown":v(j-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
|
|
54
|
+
data: ${JSON.stringify({type:"error",error:{type:"relay_upstream_error",message:`Relay upstream returned HTTP ${$.status}`}})}
|
|
55
|
+
|
|
56
|
+
`)),this.finishPending();return}if($.type==="chunk"){this.enqueueStreamChunk(C,pj($.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=${T(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
|
|
57
|
+
data: ${JSON.stringify({type:"error",error:{type:"relay_error",message:$.message||"relay error"}})}
|
|
58
|
+
|
|
59
|
+
`)),this.finishPending(),this.socket?.close();return}if($.status===409&&this.retryPendingBeforeResponse(C,$.message||"state mismatch"))return;let j=$.status===409?new V$($.message||"state mismatch"):Error(dj($));this.failPending(j)}}finishPending($){let C=this.pending;if(!C)return;let j=D(),_=$&&"frames"in $?` upstreamChunks=${$.upstreamChunks??"unknown"} upstreamBytes=${$.upstreamBytes??"unknown"} frames=${$.frames} frameBytes=${$.frameBytes??"unknown"}`:"";if(B(`perf websocket done session=${T(this.affinity)} request=${C.payload.id} sentMs=${v(j-C.sentAt)} streamMs=${C.responseStartedAt==null?"unknown":v(j-C.responseStartedAt)} chunks=${C.streamChunkCount} bytes=${C.streamByteCount}${_}`),this.timers.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(this.timers.clearTimeout(C.timeout),this.pending=void 0,C.responseStarted)C.streamController?.error($);else C.reject($);C.rejectDone($)}}function X$($=Date.now()){for(let[C,j]of s)if($-j.updatedAt>xj)s.delete(C);while(s.size>Aj){let C=s.keys().next().value;if(C===void 0)break;s.delete(C)}for(let[C,j]of _0)if(j.canEvict($))j.dispose(),_0.delete(C);while(_0.size>kj){let C=!1;for(let[j,_]of _0){if(!_.canEvict($))continue;_.dispose(),_0.delete(j),C=!0;break}if(!C)break}}function cj($,C,j){X$();let _=_0.get(C);if(_)return _.touch(),_;let J=new U6($,C,j);return _0.set(C,J),X$(),J}async function R5($){let{config:C,input:j,init:_,headers:J,body:G,fallback:K,affinity:V,optimisticResponse:Z,onResponseHeaders:z,dumpTag:X,onDumpCreated:O,setTimeoutImpl:W=globalThis.setTimeout,clearTimeoutImpl:Y=globalThis.clearTimeout}=$;if(!C||!vj(j,G))return K();let L=V||J.get("x-session-affinity")||J.get("x-opencode-session");if(!L)return B("skipping relay: missing x-session-affinity header"),K();let E=G,S=D(),q=hj(E);S0("hash_body",{session:T(L),ms:v(D()-S),bodyBytes:E.length});let f=s.get(L),M=D(),x=lj({input:j,init:_,headers:J,bodyText:E,affinity:L,previous:f,nextHash:q});S0("create_payload",{session:T(L),ms:v(D()-M),mode:x.mode,bodyBytes:E.length,previousBytes:f?.body.length});try{let H,b=D();if(C.transport==="websocket")try{H=await cj(C,L,{setTimeout:W,clearTimeout:Y}).send(x,E,Z===!0,z)}catch(I){B(`websocket relay failed session=${T(L)}; trying http relay: ${I instanceof Error?I.message:String(I)}`),H=await E6({config:C,payload:x,bodyText:E,fallback:K,signal:_?.signal})}else H=await E6({config:C,payload:x,bodyText:E,fallback:K,signal:_?.signal});if(S0("send",{session:T(L),ms:v(D()-b),transport:H.transport,protocol:H.protocol,mode:H.payload.mode,status:H.response.status,usedRelay:H.usedRelay}),!H.usedRelay)return H.response;if(H.transport==="http")try{z?.(H.response.headers)}catch{}if(H.transport==="http")S6(L,E,H.payload.next_hash,H.payload.revision);let k=D(),l=JSON.stringify(H.payload).length;S0("payload_stringify",{session:T(L),ms:v(D()-k),relayBytes:l}),B(`used relay transport=${H.transport} protocol=${H.protocol} mode=${H.payload.mode} status=${H.response.status} session=${T(L)} bodyBytes=${E.length} relayBytes=${l}`);let m0=D(),o=await DC({affinity:L,transport:H.transport,protocol:H.protocol,mode:H.payload.mode,status:H.response.status,bodyText:E,previousBodyText:f?.body,payload:H.payload,relayBytes:l,tag:X});try{if(o)O?.(o)}catch{}return S0("dump",{session:T(L),ms:v(D()-m0),enabled:!0}),H.response}catch(H){if(!C.fallbackToDirect)throw B(`relay failed session=${T(L)} and fallbackToDirect=false: ${H instanceof Error?H.message:String(H)}`),H;return B(`relay failed; falling back direct session=${T(L)}: ${H instanceof Error?H.message:String(H)}`),K()}}var q5=`
|
|
60
|
+
async function hashBody(body) {
|
|
61
|
+
const bytes = new TextEncoder().encode(body)
|
|
62
|
+
const digest = await crypto.subtle.digest('SHA-256', bytes)
|
|
63
|
+
const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
64
|
+
return 'sha256:' + hex
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function applyPatch(base, patch) {
|
|
68
|
+
return base.slice(0, patch.start) + patch.insert + base.slice(patch.start + patch.deleteCount)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function applyPatchSet(base, patch) {
|
|
72
|
+
if (!Array.isArray(patch)) return applyPatch(base, patch)
|
|
73
|
+
if (patch.length === 0) return base
|
|
74
|
+
|
|
75
|
+
let result = ''
|
|
76
|
+
let cursor = 0
|
|
77
|
+
for (const item of patch) {
|
|
78
|
+
if (item.start < cursor) return { error: 'overlapping patch', status: 400 }
|
|
79
|
+
result += base.slice(cursor, item.start)
|
|
80
|
+
result += item.insert
|
|
81
|
+
cursor = item.start + item.deleteCount
|
|
82
|
+
}
|
|
83
|
+
return result + base.slice(cursor)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function readState(env, affinity) {
|
|
87
|
+
const raw = await env.RELAY_STATE.get('session:' + affinity)
|
|
88
|
+
return raw ? JSON.parse(raw) : null
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function writeState(env, affinity, state) {
|
|
92
|
+
await env.RELAY_STATE.put('session:' + affinity, JSON.stringify(state), { expirationTtl: 86400 })
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function resolveBody(env, payload) {
|
|
96
|
+
if (payload.mode === 'full_sync') return payload.body
|
|
97
|
+
if (payload.mode === 'patch') {
|
|
98
|
+
const state = await readState(env, payload.affinity)
|
|
99
|
+
if (!state || state.hash !== payload.base_hash) {
|
|
100
|
+
return { error: 'state mismatch', status: 409 }
|
|
101
|
+
}
|
|
102
|
+
return applyPatchSet(state.body, payload.patch)
|
|
103
|
+
}
|
|
104
|
+
return { error: 'unknown mode', status: 400 }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function prepareUpstream(env, payload) {
|
|
108
|
+
if ((payload.protocol !== 1 && payload.protocol !== 2) || payload.type !== 'request' || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
|
|
109
|
+
return { error: 'invalid payload', status: 400 }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const body = await resolveBody(env, payload)
|
|
113
|
+
if (body && typeof body === 'object' && 'error' in body) return body
|
|
114
|
+
|
|
115
|
+
if (typeof body !== 'string' || (await hashBody(body)) !== payload.next_hash) {
|
|
116
|
+
return { error: 'hash mismatch', status: 409 }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const stateWrite = writeState(env, payload.affinity, { body, hash: payload.next_hash, revision: payload.revision }).catch(() => {})
|
|
120
|
+
console.log(JSON.stringify({
|
|
121
|
+
relay: 'opencode-anthropic-auth',
|
|
122
|
+
transport: 'relay',
|
|
123
|
+
mode: payload.mode,
|
|
124
|
+
revision: payload.revision,
|
|
125
|
+
affinity: String(payload.affinity).slice(0, 12),
|
|
126
|
+
bodyBytes: body.length,
|
|
127
|
+
}))
|
|
128
|
+
|
|
129
|
+
return { body, stateWrite }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function resolveBodyFromState(state, payload) {
|
|
133
|
+
if (payload.mode === 'full_sync') return payload.body
|
|
134
|
+
if (payload.mode === 'patch') {
|
|
135
|
+
if (!state || state.hash !== payload.base_hash) {
|
|
136
|
+
return { error: 'state mismatch', status: 409 }
|
|
137
|
+
}
|
|
138
|
+
return applyPatchSet(state.body, payload.patch)
|
|
139
|
+
}
|
|
140
|
+
return { error: 'unknown mode', status: 400 }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function deferWorkerTask(task) {
|
|
144
|
+
return new Promise((resolve) => setTimeout(resolve, 0)).then(task)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const WEBSOCKET_STREAM_FLUSH_BYTES = 1024
|
|
148
|
+
const WEBSOCKET_STREAM_FLUSH_MS = 20
|
|
149
|
+
|
|
150
|
+
function createWebSocketStreamCoalescer(socket, options = {}) {
|
|
151
|
+
const flushBytes = options.flushBytes || WEBSOCKET_STREAM_FLUSH_BYTES
|
|
152
|
+
const flushMs = options.flushMs ?? WEBSOCKET_STREAM_FLUSH_MS
|
|
153
|
+
let chunks = []
|
|
154
|
+
let byteLength = 0
|
|
155
|
+
let flushTimer = null
|
|
156
|
+
const stats = {
|
|
157
|
+
upstreamChunks: 0,
|
|
158
|
+
upstreamBytes: 0,
|
|
159
|
+
frames: 0,
|
|
160
|
+
frameBytes: 0,
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const clearFlushTimer = () => {
|
|
164
|
+
if (flushTimer === null) return
|
|
165
|
+
clearTimeout(flushTimer)
|
|
166
|
+
flushTimer = null
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const mergeChunks = () => {
|
|
170
|
+
if (chunks.length === 1) return chunks[0]
|
|
171
|
+
const frame = new Uint8Array(byteLength)
|
|
172
|
+
let offset = 0
|
|
173
|
+
for (const chunk of chunks) {
|
|
174
|
+
frame.set(chunk, offset)
|
|
175
|
+
offset += chunk.byteLength
|
|
176
|
+
}
|
|
177
|
+
return frame
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const flush = () => {
|
|
181
|
+
clearFlushTimer()
|
|
182
|
+
if (byteLength === 0) return
|
|
183
|
+
const frame = mergeChunks()
|
|
184
|
+
chunks = []
|
|
185
|
+
byteLength = 0
|
|
186
|
+
socket.send(frame)
|
|
187
|
+
stats.frames += 1
|
|
188
|
+
stats.frameBytes += frame.byteLength
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const scheduleFlush = () => {
|
|
192
|
+
if (flushTimer !== null) return
|
|
193
|
+
flushTimer = setTimeout(flush, flushMs)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return {
|
|
197
|
+
push(value) {
|
|
198
|
+
const chunk = value instanceof Uint8Array ? value : new Uint8Array(value)
|
|
199
|
+
if (chunk.byteLength === 0) return
|
|
200
|
+
stats.upstreamChunks += 1
|
|
201
|
+
stats.upstreamBytes += chunk.byteLength
|
|
202
|
+
chunks.push(chunk)
|
|
203
|
+
byteLength += chunk.byteLength
|
|
204
|
+
if (byteLength >= flushBytes) flush()
|
|
205
|
+
else scheduleFlush()
|
|
206
|
+
},
|
|
207
|
+
flush,
|
|
208
|
+
stats() {
|
|
209
|
+
return { ...stats, pendingBytes: byteLength }
|
|
210
|
+
},
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function checkpointWebSocketState(env, payload, body, nextState) {
|
|
215
|
+
return deferWorkerTask(async () => {
|
|
216
|
+
try {
|
|
217
|
+
if ((await hashBody(body)) !== payload.next_hash) {
|
|
218
|
+
throw new Error('hash mismatch')
|
|
219
|
+
}
|
|
220
|
+
await writeState(env, payload.affinity, nextState)
|
|
221
|
+
} catch (error) {
|
|
222
|
+
console.log(JSON.stringify({
|
|
223
|
+
relay: 'opencode-anthropic-auth',
|
|
224
|
+
transport: 'websocket',
|
|
225
|
+
event: 'checkpoint_write_failed',
|
|
226
|
+
affinity: String(payload.affinity).slice(0, 12),
|
|
227
|
+
message: error instanceof Error ? error.message : String(error),
|
|
228
|
+
}))
|
|
229
|
+
}
|
|
230
|
+
})
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function prepareWebSocketUpstream(env, state, payload) {
|
|
234
|
+
if (payload.protocol !== 2 || payload.type !== 'request' || !payload.id || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
|
|
235
|
+
return { error: 'invalid payload', status: 400 }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const body = resolveBodyFromState(state, payload)
|
|
239
|
+
if (body && typeof body === 'object' && 'error' in body) return body
|
|
240
|
+
if (typeof body !== 'string') return { error: 'invalid body', status: 400 }
|
|
241
|
+
if ((await hashBody(body)) !== payload.next_hash) {
|
|
242
|
+
return { error: 'hash mismatch', status: 409 }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const nextState = { body, hash: payload.next_hash, revision: payload.revision }
|
|
246
|
+
const checkpoint = checkpointWebSocketState(env, payload, body, nextState)
|
|
247
|
+
const logAccepted = () => console.log(JSON.stringify({
|
|
248
|
+
relay: 'opencode-anthropic-auth',
|
|
249
|
+
transport: 'websocket',
|
|
250
|
+
mode: payload.mode,
|
|
251
|
+
revision: payload.revision,
|
|
252
|
+
affinity: String(payload.affinity).slice(0, 12),
|
|
253
|
+
bodyBytes: body.length,
|
|
254
|
+
}))
|
|
255
|
+
|
|
256
|
+
return { body, state: nextState, checkpoint, logAccepted }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function headersToObject(headers) {
|
|
260
|
+
const result = {}
|
|
261
|
+
for (const [key, value] of headers.entries()) result[key] = value
|
|
262
|
+
return result
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function handleRelayPayload(env, payload) {
|
|
266
|
+
const prepared = await prepareUpstream(env, payload)
|
|
267
|
+
if (prepared.error) return prepared
|
|
268
|
+
const upstream = await fetch(payload.upstream.url, {
|
|
269
|
+
method: payload.upstream.method || 'POST',
|
|
270
|
+
headers: payload.upstream.headers,
|
|
271
|
+
body: prepared.body,
|
|
272
|
+
})
|
|
273
|
+
return { upstream, stateWrite: prepared.stateWrite }
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async function handleWebSocket(socket, env, ctx, payload, getState, setState) {
|
|
277
|
+
const heartbeat = setInterval(() => {
|
|
278
|
+
try {
|
|
279
|
+
socket.send(JSON.stringify({ protocol: 2, type: 'keepalive' }))
|
|
280
|
+
} catch {
|
|
281
|
+
clearInterval(heartbeat)
|
|
282
|
+
}
|
|
283
|
+
}, 15000)
|
|
284
|
+
let streamCoalescer = null
|
|
285
|
+
try {
|
|
286
|
+
const result = await prepareWebSocketUpstream(env, getState(), payload)
|
|
287
|
+
if (result.error) {
|
|
288
|
+
socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: result.status, message: result.error }))
|
|
289
|
+
return
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
setState(result.state)
|
|
293
|
+
socket.send(JSON.stringify({ protocol: 2, type: 'accepted', id: payload.id, hash: result.state.hash, revision: result.state.revision }))
|
|
294
|
+
ctx?.waitUntil?.(deferWorkerTask(result.logAccepted))
|
|
295
|
+
|
|
296
|
+
const upstreamPromise = fetch(payload.upstream.url, {
|
|
297
|
+
method: payload.upstream.method || 'POST',
|
|
298
|
+
headers: payload.upstream.headers,
|
|
299
|
+
body: result.body,
|
|
300
|
+
})
|
|
301
|
+
ctx?.waitUntil?.(result.checkpoint)
|
|
302
|
+
const upstream = await upstreamPromise
|
|
303
|
+
socket.send(JSON.stringify({
|
|
304
|
+
protocol: 2,
|
|
305
|
+
type: 'response_start',
|
|
306
|
+
id: payload.id,
|
|
307
|
+
status: upstream.status,
|
|
308
|
+
statusText: upstream.statusText,
|
|
309
|
+
headers: headersToObject(upstream.headers),
|
|
310
|
+
}))
|
|
311
|
+
|
|
312
|
+
const reader = upstream.body?.getReader()
|
|
313
|
+
if (reader) {
|
|
314
|
+
streamCoalescer = createWebSocketStreamCoalescer(socket)
|
|
315
|
+
while (true) {
|
|
316
|
+
const { done, value } = await reader.read()
|
|
317
|
+
if (done) break
|
|
318
|
+
streamCoalescer.push(value)
|
|
319
|
+
}
|
|
320
|
+
streamCoalescer.flush()
|
|
321
|
+
}
|
|
322
|
+
const stats = streamCoalescer?.stats?.() || {}
|
|
323
|
+
socket.send(JSON.stringify({ protocol: 2, type: 'done', id: payload.id, ...stats }))
|
|
324
|
+
} catch (error) {
|
|
325
|
+
try {
|
|
326
|
+
streamCoalescer?.flush?.()
|
|
327
|
+
} catch {}
|
|
328
|
+
socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: 500, message: error instanceof Error ? error.message : String(error) }))
|
|
329
|
+
} finally {
|
|
330
|
+
clearInterval(heartbeat)
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export default {
|
|
335
|
+
async fetch(request, env, ctx) {
|
|
336
|
+
if (request.headers.get('Upgrade') === 'websocket') {
|
|
337
|
+
const url = new URL(request.url)
|
|
338
|
+
const token = url.searchParams.get('token')
|
|
339
|
+
const affinity = url.searchParams.get('affinity')
|
|
340
|
+
if (token !== env.RELAY_TOKEN) return new Response('unauthorized', { status: 401 })
|
|
341
|
+
if (!affinity) return new Response('missing affinity', { status: 400 })
|
|
342
|
+
const pair = new WebSocketPair()
|
|
343
|
+
const client = pair[0]
|
|
344
|
+
const server = pair[1]
|
|
345
|
+
server.binaryType = 'arraybuffer'
|
|
346
|
+
let state = null
|
|
347
|
+
let ready = false
|
|
348
|
+
server.accept()
|
|
349
|
+
const loadState = readState(env, affinity).then((loadedState) => {
|
|
350
|
+
state = loadedState
|
|
351
|
+
ready = true
|
|
352
|
+
server.send(JSON.stringify({
|
|
353
|
+
protocol: 2,
|
|
354
|
+
type: 'ready',
|
|
355
|
+
state: state ? { hash: state.hash, revision: state.revision } : null,
|
|
356
|
+
}))
|
|
357
|
+
}).catch((error) => {
|
|
358
|
+
server.send(JSON.stringify({ protocol: 2, type: 'error', status: 500, message: error instanceof Error ? error.message : String(error) }))
|
|
359
|
+
server.close(1011, 'state load failed')
|
|
360
|
+
})
|
|
361
|
+
ctx?.waitUntil?.(loadState)
|
|
362
|
+
if (!ctx?.waitUntil) void loadState
|
|
363
|
+
let busy = false
|
|
364
|
+
server.addEventListener('message', (event) => {
|
|
365
|
+
if (!ready) {
|
|
366
|
+
server.send(JSON.stringify({ protocol: 2, type: 'error', status: 425, message: 'relay state is not ready' }))
|
|
367
|
+
return
|
|
368
|
+
}
|
|
369
|
+
if (busy) {
|
|
370
|
+
server.send(JSON.stringify({ protocol: 2, type: 'error', status: 429, message: 'request already in flight' }))
|
|
371
|
+
return
|
|
372
|
+
}
|
|
373
|
+
let payload
|
|
374
|
+
try {
|
|
375
|
+
payload = JSON.parse(event.data)
|
|
376
|
+
} catch {
|
|
377
|
+
server.send(JSON.stringify({ protocol: 2, type: 'error', status: 400, message: 'invalid JSON payload' }))
|
|
378
|
+
return
|
|
379
|
+
}
|
|
380
|
+
payload.affinity = affinity
|
|
381
|
+
busy = true
|
|
382
|
+
const run = handleWebSocket(server, env, ctx, payload, () => state, (nextState) => { state = nextState }).finally(() => { busy = false })
|
|
383
|
+
ctx?.waitUntil?.(run)
|
|
384
|
+
if (!ctx?.waitUntil) void run
|
|
385
|
+
})
|
|
386
|
+
return new Response(null, { status: 101, webSocket: client })
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
if (request.method === 'GET') {
|
|
390
|
+
return Response.json({ status: 'ok', transports: ['http', 'websocket'] })
|
|
391
|
+
}
|
|
392
|
+
if (request.method !== 'POST') return new Response('method not allowed', { status: 405 })
|
|
393
|
+
if (request.headers.get('x-relay-token') !== env.RELAY_TOKEN) {
|
|
394
|
+
return new Response('unauthorized', { status: 401 })
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
try {
|
|
398
|
+
const payload = await request.json()
|
|
399
|
+
const result = await handleRelayPayload(env, payload)
|
|
400
|
+
if (result.error) return Response.json({ error: result.error }, { status: result.status })
|
|
401
|
+
|
|
402
|
+
if (result.stateWrite) ctx.waitUntil(result.stateWrite)
|
|
403
|
+
|
|
404
|
+
const upstream = result.upstream
|
|
405
|
+
return new Response(upstream.body, {
|
|
406
|
+
status: upstream.status,
|
|
407
|
+
statusText: upstream.statusText,
|
|
408
|
+
headers: upstream.headers,
|
|
409
|
+
})
|
|
410
|
+
} catch (error) {
|
|
411
|
+
return Response.json(
|
|
412
|
+
{ error: error instanceof Error ? error.message : 'internal relay error' },
|
|
413
|
+
{ status: 502 },
|
|
414
|
+
)
|
|
415
|
+
}
|
|
416
|
+
},
|
|
417
|
+
}
|
|
418
|
+
`;var A5="claude-routing",Y$=["main-first","fallback-first","sticky-balanced"],H$="main-first",B6="Usage: `/claude-routing`, `/claude-routing main-first`, `/claude-routing fallback-first`, `/claude-routing sticky-balanced`, or `/claude-routing reset`.";function ij($){return typeof $==="string"&&Y$.includes($)?$:H$}function k5($){return ij($?.routing?.mode)}async function h5($,C=Q()){let j=await U(C)??A();return j.routing={...j.routing??{},mode:$},await h(j,C),j}function rj($){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&&Y$.includes(C[0]))return{type:"mode",mode:C[0]};if(C.length===2&&C[0]==="mode"&&Y$.includes(C[1]))return{type:"mode",mode:C[1]};return{type:"usage"}}function oj($){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 E1($){let C=$?.mode??H$;return["## Claude Routing Status","",`- Mode: \`${C}\``,`- Behavior: ${oj(C)}`,"",B6].join(`
|
|
419
|
+
`)}function w5($){let C=rj($.argumentsText),j=$.mode??H$;if(C.type==="status")return E1({mode:j});if(C.type==="mode")return["## Claude Routing Updated","",`Mode updated to \`${C.mode}\`.`,"",...E1({mode:C.mode}).split(`
|
|
420
|
+
`).slice(2)].join(`
|
|
421
|
+
`);if(C.type==="reset")return["## Claude Routing Assignment Reset","","The current session will be assigned again on its next request.","",...E1({mode:j}).split(`
|
|
422
|
+
`).slice(2)].join(`
|
|
423
|
+
`);return["## Claude Routing Usage","",B6,"",...E1({mode:j}).split(`
|
|
424
|
+
`).slice(2)].join(`
|
|
425
|
+
`)}var v5="claude-start";function nj($){if($.trim().split(/\s+/).filter(Boolean).length===0)return{type:"fire"};return{type:"usage"}}function m5($){let C=nj($.argumentsText);if(C.type==="fire")return{action:C,text:["## Claude Lane Start Queued","","- Queued an explicit lane-start request.","- This is a billed request: the one-token limit does not remove prompt-cache read or write charges."].join(`
|
|
426
|
+
`)};return{action:C,text:["## Claude Lane Start Usage","","Usage: `/claude-start`.","","## Claude Lane Start Status"].join(`
|
|
427
|
+
`)}}import{createHash as k6,randomUUID as aj}from"node:crypto";import{mkdir as tj,readFile as ej,rename as $8,rm as C8,stat as j8,writeFile as _8}from"node:fs/promises";import{basename as J8,dirname as h6,join as G8}from"node:path";var K8="main",V8=900000,b6=604800000,Z8=3600000,z8=1e4,X8=5000,Y8=10,D6=4096,H8=0.000001;function d5($){let C=$.modelId,j=C?$.routeQuotas.map((W)=>y(W,C)).find(Boolean)?.modelName:void 0,_;if(O0($.mainRefreshError))_=j?`Main Claude OAuth account requires re-login, and no fallback OAuth account is currently routable for ${j}.`:"Main Claude OAuth account requires re-login, and no fallback OAuth account is currently routable.";else if($.fallbackReauthLabels?.length)_=`No OAuth account is currently routable${j?` for ${j}`:""}. Fallback Claude OAuth accounts require re-login: ${$.fallbackReauthLabels.join(", ")}.`;if(_)return new Response(JSON.stringify({type:"error",error:{type:"authentication_error",message:_}}),{status:401,headers:{"content-type":"application/json"}});let J=Boolean(C&&$.routeQuotas.length>0&&$.routeQuotas.every((W)=>!d0(W,C))),[G,...K]=$.routeQuotas,V=n$(G,K.map((W)=>({quota:W})),$.now??Date.now(),J?C:void 0),Z=Math.floor(V/60),z=V%60,O=`${J&&j?`${j} weekly limit reached, no routable OAuth accounts.`:"No OAuth account currently satisfies sticky-balanced quota policy."} Retry in ${Z}m ${z}s.`;return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:O}}),{status:429,headers:{"content-type":"application/json","retry-after":String(V)}})}function W$($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function v0($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function W8($){if(!W$($))return;if(typeof $.accountId!=="string"||!["fable","opus","general"].includes(String($.family)))return;let C=v0($.assignedAt),j=v0($.lastSeenAt),_=v0($.initialInputBytes),J=v0($.quotaCheckedAt);if(C===void 0||j===void 0||_===void 0||J===void 0)return;return{accountId:$.accountId,family:$.family,assignedAt:C,lastSeenAt:j,initialInputBytes:Math.max(0,_),quotaCheckedAt:J}}function O8($){if(!W$($)||$.version!==1||!W$($.assignments))return;let C={};for(let[j,_]of Object.entries($.assignments)){let J=W8(_);if(J)C[j]=J}return{version:1,updatedAt:v0($.updatedAt)??0,assignments:C}}function T6($){return{version:1,updatedAt:$,assignments:{}}}function R6($){return k6("sha256").update($).digest("hex")}function w6($,C,j=Date.now(),_){let J=p(C);if(!["five_hour","seven_day"].every((V)=>{let Z=$?.[V];return Boolean(Z&&j-Z.checkedAt<J)}))return!1;let K=y($,_);return!K||j-K.checkedAt<J}function q6($){return Math.max($.checkedAt??0,$.five_hour?.checkedAt??0,$.seven_day?.checkedAt??0,...($.scoped??[]).map((C)=>C.checkedAt??0))}function U0($){if(!$)return;if("kind"in $)return $.kind==="known"?$.quota:void 0;return $}function x6($,C,j){let _=i0($),J=j==="five_hour"?_.five_hour:j==="seven_day"?_.seven_day:0;if(!I1($))return J;let G=v1($,C===K8?void 0:C);return Math.max(J,G[j])}function P6($,C,j,_){let J=Math.max(0,$-C);if(J<=0)return 0;if(!j)return J;let G=Date.parse(j);if(!Number.isFinite(G)||G<=_)return J;let K=Math.max((G-_)/3600000,0.016666666666666666);return J/K}function c5($){if(uC($))return"fable";return typeof $==="string"&&$.toLowerCase().includes("opus")?"opus":"general"}function A6($){let C=$.now??Date.now(),{candidate:j,storage:_}=$,J=U0(j.quota);if(!J)return 0;if(!w6(J,_,C,$.modelId))return 0;let G=[];for(let K of["five_hour","seven_day"]){let V=J[K];if(!V||!Number.isFinite(V.remainingPercent))return 0;G.push(P6(V.remainingPercent,x6(_,j.accountId,K),V.resetsAt,C))}if($.family==="fable"){let K=y(J,$.modelId);if(K&&Number.isFinite(K.remainingPercent))G.push(P6(K.remainingPercent,x6(_,j.accountId,"scoped"),K.resetsAt,C))}return Math.min(...G)}function f8($,C,j=Date.now()){let _=U0($.quota),J=y(_,"claude-fable-5");return Boolean(J&&w6(_,C,j,"claude-fable-5")&&Number.isFinite(J.remainingPercent)&&J.remainingPercent<=0)}function i5($){let C=$.now??Date.now(),j=U0($.quota);if(!j)return{action:"retain",reason:"unknown"};let _=y(j,$.modelId);if(_&&Number.isFinite(_.remainingPercent)&&_.remainingPercent<=0)return{action:"migrate",reason:"model-scoped"};let J=j.seven_day;if(J&&Number.isFinite(J.remainingPercent)&&J.remainingPercent<=0)return{action:"migrate",reason:"seven-day"};let G=j.five_hour;if(G&&Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0){let K=G.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(K)&&K>C&&K-C<=V8)return{action:"hold",reason:"five-hour-short-reset",retryAfterSeconds:Math.max(1,Math.ceil((K-C)/1000))};return{action:"migrate",reason:"five-hour"}}return{action:"retain",reason:"not-exhausted"}}function r5($){let C=J8($),j=C.endsWith(".json")?C.slice(0,-5):C;return G8(h6($),`${j}-routing-state.json`)}function o5($,C){let j=k6("sha256").update($).digest().readUInt32BE(0);return Math.max(1,Math.ceil(C))+j%21}class L8{options;loaded=!1;state;stateMtimeNs;touchChain=Promise.resolve();constructor($){this.options=$,this.state=T6(this.now())}now(){return this.options.now?.()??Date.now()}async readState(){try{let $=await ej(this.options.path,"utf8"),C=O8(JSON.parse($));if(!C)throw Error(`Invalid sticky routing state at ${this.options.path}`);return C}catch($){if($.code==="ENOENT")return T6(this.now());throw $}}async readStateMtimeNs(){try{return(await j8(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 j=await this.readState(),_=await this.readStateMtimeNs();if(C!==_)continue;this.state=j,this.stateMtimeNs=_,this.loaded=!0;return}this.state=await this.readState(),this.stateMtimeNs=await this.readStateMtimeNs(),this.loaded=!0}async acquireLock(){await tj(h6(this.options.path),{recursive:!0,mode:448});let $=this.now()+X8;while(!0){let C=await $0({name:"write",path:this.options.path,ttlMs:z8,renew:!0});if(C)return C;if(this.now()>=$)throw Error("Timed out acquiring sticky routing state lock");await new Promise((j)=>setTimeout(j,Y8))}}assignmentIsActive($){return $.lastSeenAt>=this.now()-(this.options.assignmentTtlMs??b6)}prune($){let C=this.now()-(this.options.assignmentTtlMs??b6);for(let[_,J]of Object.entries($.assignments))if(J.lastSeenAt<C)delete $.assignments[_];let j=Object.entries($.assignments);if(j.length<=D6)return;j.sort((_,J)=>J[1].lastSeenAt-_[1].lastSeenAt).slice(D6).forEach(([_])=>{delete $.assignments[_]})}async writeState($){this.prune($),$.updatedAt=this.now();let C=`${this.options.path}.${aj()}.tmp`;try{await _8(C,`${JSON.stringify($)}
|
|
428
|
+
`,{mode:384}),await $8(C,this.options.path)}finally{await C8(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 j=await this.readState(),_=j.assignments[$];if(!_)return;_.lastSeenAt=this.now(),await this.writeState(j)}finally{await C.release()}}).catch(()=>{})}selectCandidate($){let C=[...$.candidates];if($.family==="opus"){let J=C.filter((G)=>f8(G,$.storage,this.now()));if(J.length>0)C=J}let j=C.flatMap((J)=>{let G=A6({candidate:J,family:$.family,modelId:$.modelId,storage:$.storage,now:this.now()});return G>0?[{candidate:J,weight:G}]:[]});if(j.length===0&&C.every((J)=>!U0(J.quota)))return[...C].sort((J,G)=>J.order-G.order||J.accountId.localeCompare(G.accountId))[0];let _=new Map;for(let J of Object.values($.state.assignments)){let G=j.find((V)=>V.candidate.accountId===J.accountId)?.candidate;if(!G)continue;let K=U0(G.quota);if(K&&J.quotaCheckedAt!==q6(K))continue;_.set(J.accountId,(_.get(J.accountId)??0)+J.initialInputBytes)}return j.map(({candidate:J,weight:G})=>({candidate:J,score:((_.get(J.accountId)??0)+$.inputBytes)/Math.max(G,H8)})).sort((J,G)=>J.score-G.score||J.candidate.order-G.candidate.order||J.candidate.accountId.localeCompare(G.candidate.accountId))[0]?.candidate}async resolve($){if(!$.sessionId)return null;await this.refreshStateIfChanged();let C=R6($.sessionId),j=this.state.assignments[C];if(j&&this.assignmentIsActive(j)&&$.retainAccountIds.has(j.accountId)&&!$.excludeAccountIds?.has(j.accountId)){if(this.now()-j.lastSeenAt>=Z8)j.lastSeenAt=this.now(),this.scheduleTouch(C);return{accountId:j.accountId,assignment:{...j},created:!1,migrated:!1}}let _=await this.acquireLock();try{let J=await this.readState();this.prune(J);let G=J.assignments[C];if(G&&$.retainAccountIds.has(G.accountId)&&!$.excludeAccountIds?.has(G.accountId))return G.lastSeenAt=this.now(),await this.writeState(J),{accountId:G.accountId,assignment:{...G},created:!1,migrated:!1};let K=$.candidates.filter((W)=>!$.excludeAccountIds?.has(W.accountId)),Z=($.preferredAccountId?K.find((W)=>W.accountId===$.preferredAccountId&&A6({candidate:W,family:$.family,modelId:$.modelId,storage:$.storage,now:this.now()})>0):void 0)??this.selectCandidate({...$,candidates:K,state:J});if(!Z){if(G)delete J.assignments[C],await this.writeState(J);return null}let z=this.now(),X=U0(Z.quota),O={accountId:Z.accountId,family:$.family,assignedAt:z,lastSeenAt:z,initialInputBytes:Math.max(1,$.inputBytes),quotaCheckedAt:X?q6(X):0};return J.assignments[C]=O,await this.writeState(J),{accountId:Z.accountId,assignment:{...O},created:!G,migrated:Boolean(G&&G.accountId!==Z.accountId)}}finally{await _.release()}}async clear($){if(!$)return;let C=R6($),j=await this.acquireLock();try{let _=await this.readState();if(!(C in _.assignments))return;delete _.assignments[C],await this.writeState(_)}finally{await j.release()}}}export{N8 as v,N$ as w,E8 as x,F8 as y,M8 as z,Q8 as A,S8 as B,E$ as C,U8 as D,B8 as E,b$ as F,q8 as G,x8 as H,P as I,y8 as J,c6 as K,l8 as L,Q as M,A as N,H0 as O,U as P,p$ as Q,h as R,g8 as S,q2 as T,p8 as U,$0 as V,s8 as W,P2 as X,u8 as Y,d8 as Z,c8 as _,i8 as $,r8 as aa,o8 as ba,n8 as ca,a8 as da,t8 as ea,e8 as fa,$_ as ga,C_ as ha,j_ as ia,__ as ja,J_ as ka,G_ as la,K_ as ma,v2 as na,O0 as oa,J0 as pa,m2 as qa,V_ as ra,Z_ as sa,z_ as ta,X_ as ua,d$ as va,y as wa,l2 as xa,d0 as ya,r$ as za,Y_ as Aa,I1 as Ba,v1 as Ca,o$ as Da,n$ as Ea,H_ as Fa,W_ as Ga,O_ as Ha,f_ as Ia,L_ as Ja,N_ as Ka,C0 as La,t2 as Ma,M_ as Na,Q_ as Oa,S_ as Pa,U_ as Qa,_4 as Ra,B_ as Sa,x_ as Ta,KC as Ua,P_ as Va,g as Wa,w_ as Xa,I_ as Ya,U4 as Za,v_ as _a,HC as $a,d_ as ab,c_ as bb,e4 as cb,i_ as db,bC as eb,TC as fb,e_ as gb,$J as hb,F3 as ib,Z1 as jb,z1 as kb,IC as lb,M3 as mb,CJ as nb,U3 as ob,VJ as pb,k3 as qb,zJ as rb,XJ as sb,YJ as tb,N0 as ub,OJ as vb,h3 as wb,w3 as xb,fJ as yb,NJ as zb,EJ as Ab,FJ as Bb,I3 as Cb,MJ as Db,E0 as Eb,UJ as Fb,bJ as Gb,y3 as Hb,DJ as Ib,RJ as Jb,a1 as Kb,sC as Lb,qJ as Mb,xJ as Nb,PJ as Ob,AJ as Pb,kJ as Qb,uC as Rb,hJ as Sb,wJ as Tb,IJ as Ub,vJ as Vb,mJ as Wb,rJ as Xb,a3 as Yb,oJ as Zb,nJ as _b,Kj as $b,zj as ac,M0 as bc,_5 as cc,Mj as dc,G5 as ec,K5 as fc,G$ as gc,r as hc,E5 as ic,F5 as jc,M5 as kc,D5 as lc,T5 as mc,R5 as nc,q5 as oc,A5 as pc,k5 as qc,h5 as rc,rj as sc,w5 as tc,v5 as uc,nj as vc,m5 as wc,K8 as xc,d5 as yc,w6 as zc,c5 as Ac,i5 as Bc,r5 as Cc,o5 as Dc,L8 as Ec};
|