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