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