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