@cortexkit/opencode-anthropic-auth 1.9.0 → 1.9.1
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
CHANGED
|
@@ -31,6 +31,7 @@ This repo is a Bun workspace monorepo with two user-facing integrations and one
|
|
|
31
31
|
- **Persistent Claude cache controls**: manage Anthropic 1-hour prompt caching from `/claude-cache` with explicit, automatic, or hybrid modes.
|
|
32
32
|
- **Cache keepalive**: use `/claude-cachekeep HH-HH` to pre-warm hybrid cache anchors for active sessions before the 1-hour TTL expires.
|
|
33
33
|
- **Fast mode toggle**: use `/claude-fast on|off` to request Anthropic fast mode for supported Opus models.
|
|
34
|
+
- **Fable/Mythos reasoning visibility**: request summarized adaptive thinking for Claude Fable 5 and Mythos 5 so agents can display reasoning summaries instead of blank signed-thinking blocks.
|
|
34
35
|
- **Live quota visibility**: use `/claude-quota` to see main and fallback quota state, reset times, and refresh errors.
|
|
35
36
|
- **Killswitch**: per-account hard-block thresholds that stop requests before hitting Anthropic's rate limits, with synthetic 429 retry-after when all accounts are exhausted.
|
|
36
37
|
- **User-owned Cloudflare relay**: optionally provision your own Worker relay to reduce repeated client upload bytes for large OpenCode or Pi requests.
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{Ka as I,Ma as $,m as w,n as k,p as A,r as R,t as d,u as l,v as p}from"./index-hjkkewsy.js";import{stdin as E,stdout as U}from"node:process";import{createInterface as _}from"node:readline/promises";function g(){return{version:1,main:{type:"opencode",provider:"anthropic"},fallbackOn:[401,403,429],refresh:{enabled:!0,intervalMinutes:10,refreshBeforeExpiryMinutes:240},quota:{enabled:!0,checkIntervalMinutes:5,minimumRemaining:{five_hour:10,seven_day:20},failClosedOnUnknownQuota:!0},accounts:[]}}function y(){console.log(`Usage:
|
|
3
3
|
opencode-anthropic-auth login [label]
|
|
4
4
|
opencode-anthropic-auth api add [label]
|
|
5
5
|
opencode-anthropic-auth list
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{mkdir as O,readFile as Q,writeFile as W}from"node:fs/promises";import{tmpdir as X}from"node:os";import{dirname as Y,join as K}from"node:path";var Z="OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE",$=K(X(),"opencode-anthropic-auth"),x=K($,"sidebar-state.json");function M(){return process.env[Z]||x}var B={main:{quota:null},fallbacks:[],activeId:void 0,route:"main",relay:null,fastMode:!1,lastUpdated:0};async function h(){try{let G=await Q(M(),"utf8");return JSON.parse(G)}catch{return B}}async function j(G){try{let z=M();await O(Y(z),{recursive:!0}),await W(z,JSON.stringify(G),"utf8")}catch{}}function w(G){let z=G.activeId;if(z&&z!=="main"){let C=G.fallbacks.find((J)=>J.enabled&&J.id===z);if(C)return{id:C.id,name:C.label??C.id,quota:C.quota}}return{id:"main",name:"main",quota:G.main.quota}}function R(G){let z=G?.five_hour?.usedPercent??null,C=G?.seven_day?.usedPercent??null;if(z==null&&C==null)return{fiveHourUsedPercent:z,sevenDayUsedPercent:C,text:null};return{fiveHourUsedPercent:z,sevenDayUsedPercent:C,text:`5h: ${z==null?"—":`${Math.round(z)}%`} 7d: ${C==null?"—":`${Math.round(C)}%`}`}}
|
|
2
|
-
export{M as
|
|
2
|
+
export{M as Sa,B as Ta,h as Ua,j as Va,w as Wa,R as Xa};
|
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
var $f="9d1c250a-e61b-44d9-88ed-5944d1962f5e",m_={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.ai/oauth/authorize"},Yf="https://platform.claude.com/oauth/code/callback",Wf="https://platform.claude.com/v1/oauth/token",$_=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],
|
|
2
|
-
`);var
|
|
1
|
+
var $f="9d1c250a-e61b-44d9-88ed-5944d1962f5e",m_={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.ai/oauth/authorize"},Yf="https://platform.claude.com/oauth/code/callback",Wf="https://platform.claude.com/v1/oauth/token",$_=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],Om="mcp_";var C_="fast-mode-2026-02-01";function Sm(f,_){let E=(f??"").split(",").map((D)=>D.trim()).filter(Boolean);return[...new Set([...E,..._])].join(",")}function Hm(f){return typeof f==="string"&&(f.startsWith("claude-opus-4-6")||f.startsWith("claude-opus-4-7")||f.startsWith("claude-opus-4-8"))}var Nm="You are OpenCode",Fm="You are a Claude agent, built on Anthropic's Claude Agent SDK.",bm=["<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 T="2.1.141",Xf="67b",M_="sdk-cli",L_="0.94.0",A_="v24.3.0",U_="claude-cli/2.1.141 (external, sdk-cli)",O_=["explicit","automatic","hybrid"],Cf="explicit",Bm=["github.com/anomalyco/opencode","opencode.ai/docs"],Km=[{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 S_(f){let _="";for(let E of f)_+=String.fromCharCode(E);return btoa(_).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function H_(){let f=new Uint8Array(64);crypto.getRandomValues(f);let _=S_(f),E=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(_));return{verifier:_,challenge:S_(new Uint8Array(E)),method:"S256"}}function W0(f){if(!f)return;let _=Number(f);if(Number.isFinite(_)&&_>0)return Math.ceil(_);let E=Date.parse(f);if(Number.isFinite(E)){let D=Math.ceil((E-Date.now())/1000);return D>0?D:void 0}return}class i extends Error{status;body;retryAfter;constructor(f,_,E){super(`Claude OAuth refresh failed: ${f} — ${_}`);this.status=f,this.body=_,this.name="ClaudeOAuthRefreshError",this.retryAfter=W0(E??void 0)}}function X0(f){if(!(f instanceof Error))return!1;let _=f.code;return f.message.includes("fetch failed")||_==="ECONNRESET"||_==="ECONNREFUSED"||_==="ETIMEDOUT"||_==="UND_ERR_CONNECT_TIMEOUT"}async function N_(f){let _=f.fetchImpl??fetch,E=f.maxRetries??2,D=f.baseDelayMs??500;for(let m=0;m<=E;m++)try{if(m>0){let L=D*2**(m-1);await new Promise((A)=>setTimeout(A,L))}let $=await _(Wf,{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:$f})});if(!$.ok){if($.status>=500&&m<E){await $.body?.cancel().catch(()=>{});continue}let L=await $.text().catch(()=>"");throw new i($.status,L,$.headers.get("retry-after"))}let C=await $.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($){if($ instanceof i)throw $;if(m<E&&X0($))continue;throw $}throw Error("Token refresh exhausted all retries")}function Z0(){return crypto.randomUUID().replace(/-/g,"")}function h0(f){let _=f.trim();try{let C=new URL(_),M=C.searchParams.get("code"),L=C.searchParams.get("state");if(M&&L)return{code:M,state:L}}catch{}let E=_.split("#");if(E.length===2&&E[0]&&E[1])return{code:E[0],state:E[1]};let D=new URLSearchParams(_),m=D.get("code"),$=D.get("state");if(m&&$)return{code:m,state:$};return null}async function V0(f,_,E){let D=await fetch(Wf,{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:$f,redirect_uri:E,code_verifier:_})});if(!D.ok)return{type:"failed"};let m=await D.json();return{type:"success",refresh:m.refresh_token,access:m.access_token,expires:Date.now()+m.expires_in*1000}}async function Ym(f){let _=await H_(),E=Z0(),D=new URL(m_[f],import.meta.url);return D.searchParams.set("code","true"),D.searchParams.set("client_id",$f),D.searchParams.set("response_type","code"),D.searchParams.set("redirect_uri",Yf),D.searchParams.set("scope",$_.join(" ")),D.searchParams.set("code_challenge",_.challenge),D.searchParams.set("code_challenge_method","S256"),D.searchParams.set("state",E),{url:D.toString(),redirectUri:Yf,state:E,verifier:_.verifier}}async function Wm(f,_,E,D){let m=h0(f);if(!m)return{type:"failed"};if(D&&m.state!==D)return{type:"failed"};return V0(m,_,E)}import*as F_ from"node:fs";import*as b_ from"node:os";import*as B_ from"node:path";var x0=B_.join(b_.tmpdir(),"opencode-anthropic-auth.log"),K_=!1,Q0=500,I0=50,t=[],n=null;function Zf(){if(n)clearTimeout(n),n=null;if(t.length===0)return;let f=t.join("");t=[];try{F_.appendFileSync(x0,f)}catch{}}function P0(){if(n)return;n=setTimeout(()=>{n=null,Zf()},Q0)}function R0(f){if(f===void 0)return"";if(f instanceof Error)return` ${f.message}${f.stack?`
|
|
3
3
|
${f.stack}`:""}`;return` ${JSON.stringify(f)}`}function V(f,_){if(K_)return;try{if(t.push(`[${new Date().toISOString()}] ${f}${R0(_)}
|
|
4
|
-
`),t.length>=I0)Zf();else P0()}catch{}}function
|
|
5
|
-
`,{encoding:"utf8",mode:384}),await
|
|
4
|
+
`),t.length>=I0)Zf();else P0()}catch{}}function F(f,_){V(`[relay] ${f}`,_)}if(!K_)process.on("exit",Zf);import{createHash as h_,randomUUID as Rf}from"node:crypto";import{mkdir as T0,readFile as xf,rename as q0,rm as j_,stat as w0,writeFile as Qf}from"node:fs/promises";import{homedir as i0}from"node:os";import{dirname as V_,join as a}from"node:path";var y0=globalThis.setTimeout.bind(globalThis),l0=globalThis.clearTimeout.bind(globalThis),x_="anthropic-auth.json",k0="anthropic-auth-state.json",p0="https://api.anthropic.com/api/oauth/usage";function x(f){return f.type==="oauth"}function Tm(f){return f.type==="api"}function v0(f){let _=f?.trim();if(!_)return!1;try{let E=new URL(_);return(E.protocol==="http:"||E.protocol==="https:")&&!E.username&&!E.password}catch{return!1}}function qm(f){return f.costZeroing?.enabled!==!1}var d0=[401,403,429],Q_=240,u0=Q_;var g0=300000,n0=3600000,r0=86400000,s0=60000,c0=900000,t0=300000,o0=5,G_={five_hour:0,seven_day:0},a0=!0,e0=60000,fE=60000,_E=600000,EE=1e4,DE=100;function mE(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return a(process.env.XDG_CONFIG_HOME||a(i0(),".config"),"opencode")}function z(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||a(mE(),x_)}function Tf(f=z()){let _=process.env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim();if(_)return _;return f.endsWith(x_)?a(V_(f),k0):`${f}.state.json`}function H(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function z_(f){return{id:typeof f.id==="string"&&f.id.trim()?f.id.trim():Rf(),label:typeof f.label==="string"?f.label:void 0,enabled:typeof f.enabled==="boolean"?f.enabled:void 0,addedAt:typeof f.addedAt==="number"?f.addedAt:void 0,lastUsed:typeof f.lastUsed==="number"?f.lastUsed:void 0}}function $E(f){if(!H(f))return null;if(f.type==="api"){let _=typeof f.baseURL==="string"?f.baseURL.trim():"",E=typeof f.apiKey==="string"?f.apiKey.trim():"";if(!v0(_))return null;let D=f.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...z_(f),type:"api",apiKey:E||void 0,baseURL:_,authHeader:D}}if(f.type!=="oauth")return null;if(typeof f.refresh!=="string"||!f.refresh.trim())return null;return{...z_(f),type:"oauth",access:typeof f.access==="string"?f.access:void 0,refresh:f.refresh,expires:typeof f.expires==="number"?f.expires:void 0,lastRefreshedAt:typeof f.lastRefreshedAt==="number"?f.lastRefreshedAt:void 0,lastRefreshError:J_(f.lastRefreshError),lastQuotaRefreshError:J_(f.lastQuotaRefreshError),quota:CE(f.quota)}}function J_(f){if(!H(f))return;if(typeof f.message!=="string")return;let _=Number(f.checkedAt);if(!Number.isFinite(_))return;let E=Number(f.nextRetryAt),D=Number(f.retryCount);return{message:f.message,checkedAt:_,nextRetryAt:Number.isFinite(E)?E:void 0,retryCount:Number.isFinite(D)?D:void 0,tokenHash:typeof f.tokenHash==="string"?f.tokenHash:void 0}}function CE(f){if(!H(f))return;let _={};for(let E of["five_hour","seven_day"]){let D=f[E];if(!H(D))continue;let m=Number(D.usedPercent),$=Number(D.remainingPercent),C=Number(D.checkedAt);if(!Number.isFinite(m)||!Number.isFinite($)||!Number.isFinite(C))continue;_[E]={usedPercent:m,remainingPercent:$,checkedAt:C,resetsAt:typeof D.resetsAt==="string"?D.resetsAt:void 0}}return Object.keys(_).length?_:void 0}function ME(f){if(!H(f)||!Array.isArray(f.accounts))return null;return{version:1,main:{type:"opencode",provider:"anthropic"},routing:H(f.routing)?f.routing:void 0,fallbackOn:Array.isArray(f.fallbackOn)?f.fallbackOn.filter((_)=>Number.isInteger(_)):void 0,refresh:H(f.refresh)?f.refresh:void 0,quota:H(f.quota)?f.quota:void 0,claudeCache:H(f.claudeCache)?f.claudeCache:void 0,dump:H(f.dump)?f.dump:void 0,claudeFast:H(f.claudeFast)?f.claudeFast:void 0,costZeroing:H(f.costZeroing)?f.costZeroing:void 0,cacheKeep:H(f.cacheKeep)?f.cacheKeep:void 0,relay:H(f.relay)?f.relay:void 0,killswitch:H(f.killswitch)?f.killswitch:void 0,accounts:f.accounts.map($E).filter((_)=>_!=null)}}async function Mf(f){try{return{exists:!0,value:JSON.parse(await xf(f,"utf8"))}}catch(_){if(_.code==="ENOENT")return{exists:!1,value:null};return{exists:!1,value:null}}}function q(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function LE(f,_){if(!H(f))return f;let E=H(_)?_:{},D=H(E.main)?E.main:void 0,m=H(E.accounts)?E.accounts:{},$=H(f.quota)?f.quota:{},C=H(f.refresh)?f.refresh:{},M=D??$,L=D??C,A=Array.isArray(f.accounts)?f.accounts.map((U)=>{if(!H(U))return U;let N=typeof U.id==="string"&&H(m[U.id])?m[U.id]:{};return{...U,...N}}):[];return{...f,refresh:q({...C,mainLastRefreshError:L.lastRefreshError,mainRefreshLeaseId:L.refreshLeaseId,mainRefreshLeaseUntil:L.refreshLeaseUntil,mainRefreshLeaseTokenHash:L.refreshLeaseTokenHash}),quota:q({...$,mainQuota:M.quota,mainQuotaCheckedAt:M.quotaCheckedAt,mainQuotaToken:M.quotaToken,mainLastQuotaApiError:M.lastQuotaApiError}),accounts:A}}async function h(f=z()){let _=await Mf(f);if(!_.exists)return null;let E=await Mf(Tf(f));return ME(LE(_.value,E.value))}async function AE(f){let _=await Mf(f);return H(_.value)?_.value:{}}function UE(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function OE(f){return q({id:f.id,label:f.label,type:f.type,enabled:f.enabled,addedAt:f.addedAt,baseURL:f.type==="api"?f.baseURL:void 0,authHeader:f.type==="api"?f.authHeader:void 0})}function I_(f){if(f.type==="api")return q({apiKey:f.apiKey,lastUsed:f.lastUsed});return q({access:f.access,refresh:f.refresh,expires:f.expires,lastUsed:f.lastUsed,lastRefreshedAt:f.lastRefreshedAt,lastRefreshError:f.lastRefreshError,lastQuotaRefreshError:f.lastQuotaRefreshError,quota:f.quota})}function SE(f){let _=f.refresh?q({enabled:f.refresh.enabled,intervalMinutes:f.refresh.intervalMinutes,refreshBeforeExpiryMinutes:f.refresh.refreshBeforeExpiryMinutes}):void 0,E=f.quota?q({enabled:f.quota.enabled,checkIntervalMinutes:f.quota.checkIntervalMinutes,refreshEveryNRequests:f.quota.refreshEveryNRequests,minimumRemaining:f.quota.minimumRemaining,failClosedOnUnknownQuota:f.quota.failClosedOnUnknownQuota,showToasts:f.quota.showToasts}):void 0;return UE({version:1,main:f.main,routing:f.routing,fallbackOn:f.fallbackOn,refresh:_,quota:E,claudeCache:f.claudeCache,dump:f.dump,claudeFast:f.claudeFast,costZeroing:f.costZeroing,cacheKeep:f.cacheKeep,relay:f.relay,killswitch:f.killswitch,accounts:f.accounts.map(OE)})}function HE(f){let _=Object.fromEntries(f.accounts.map((E)=>[E.id,I_(E)]));return{version:1,main:q({quota:f.quota?.mainQuota,quotaCheckedAt:f.quota?.mainQuotaCheckedAt,quotaToken:f.quota?.mainQuotaToken,lastQuotaApiError:f.quota?.mainLastQuotaApiError,lastRefreshError:f.refresh?.mainLastRefreshError,refreshLeaseId:f.refresh?.mainRefreshLeaseId,refreshLeaseUntil:f.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:f.refresh?.mainRefreshLeaseTokenHash}),accounts:_}}async function If(f,_){await T0(V_(f),{recursive:!0});let E=`${f}.${Rf()}.tmp`;await Qf(E,`${JSON.stringify(_,null,2)}
|
|
5
|
+
`,{encoding:"utf8",mode:384}),await q0(E,f)}async function Q(f,_=z()){let D={...await AE(_),...SE(f)};await If(_,D),await If(Tf(_),HE(f))}function NE(f,_){f.main=f.main??{},f.main.quota=_.quota?.mainQuota,f.main.quotaCheckedAt=_.quota?.mainQuotaCheckedAt,f.main.quotaToken=_.quota?.mainQuotaToken,f.main.lastQuotaApiError=_.quota?.mainLastQuotaApiError}function FE(f,_){f.main=f.main??{},f.main.lastRefreshError=_.refresh?.mainLastRefreshError,f.main.refreshLeaseId=_.refresh?.mainRefreshLeaseId,f.main.refreshLeaseUntil=_.refresh?.mainRefreshLeaseUntil,f.main.refreshLeaseTokenHash=_.refresh?.mainRefreshLeaseTokenHash}function Pf(f){if(Array.isArray(f))return f.map(Pf);if(!H(f))return f;return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0).map(([_,E])=>[_,Pf(E)]))}async function bE(f,_=z(),E={mainQuota:!0,mainRefresh:!0,accounts:!0}){let D=Tf(_),m=(await Mf(D)).value,$=H(m)?{...m,version:1}:{version:1};if(E.mainQuota)NE($,f);if(E.mainRefresh)FE($,f);if(E.accounts){let C=E.accounts===!0?null:new Set(E.accounts);$.accounts={...H($.accounts)?$.accounts:{}};for(let M of f.accounts){if(C&&!C.has(M.id))continue;$.accounts[M.id]=I_(M)}if(C){for(let M of C)if(!f.accounts.some((L)=>L.id===M))delete $.accounts[M]}}await If(D,Pf($))}async function Lf(f){let E=`${f.path??z()}.${f.name}.lock`,D=a(E,"owner.json"),m=Rf(),$=f.now??Date.now,C=null,M=!1;async function L(){try{return JSON.parse(await xf(E,"utf8"))}catch(K){if(K.code!=="EISDIR")throw K;return JSON.parse(await xf(D,"utf8"))}}async function A(){await Qf(E,`${JSON.stringify({ownerId:m,expiresAt:$()+f.ttlMs})}
|
|
6
6
|
`,{encoding:"utf8",mode:384})}async function U(){try{return await Qf(E,`${JSON.stringify({ownerId:m,expiresAt:$()+f.ttlMs})}
|
|
7
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(K){let j=K.code;if(j==="EEXIST"||j==="EISDIR")return!1;throw K}}function N(){if(!f.renew||M)return;let K=f.renewIntervalMs??Math.max(1000,Math.floor(f.ttlMs/3));if(C=l0(()=>{(async()=>{try{let j=await L(),R=$();if(M||j?.ownerId!==m||Number(j?.expiresAt)<=R)return;await A(),N()}catch{}})()},K),"unref"in C)C.unref()}if(!await U()){try{let K=await L();if(Number(K?.expiresAt)>$())return null}catch{try{if((await w0(E)).mtimeMs+f.ttlMs>Date.now())return null}catch{return null}}if(await j_(E,{recursive:!0,force:!0}).catch(()=>{}),!await U())return null}return N(),{release:async()=>{if(M=!0,C)y0(C),C=null;try{if((await L())?.ownerId!==m)return}catch{return}await j_(E,{recursive:!0,force:!0}).catch(()=>{})}}}function w1(f){return f?.claudeCache?.enabled===!0}function BE(f){return typeof f==="string"&&O_.includes(f)?f:Cf}function KE(f){return BE(f?.claudeCache?.mode)}async function i1(f,_,E=z()){let D=await h(E)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.claudeCache={...D.claudeCache??{},enabled:f,mode:_??KE(D)},await Q(D,E),D}async function l1(f,_=z()){let E=await h(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.claudeCache={...E.claudeCache??{},enabled:E.claudeCache?.enabled===!0,mode:f},await Q(E,_),E}function y1(f){return f?.dump?.enabled===!0}async function k1(f,_=z()){let E=await h(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.dump={...E.dump??{},enabled:f},await Q(E,_),E}function p1(f){return f?.claudeFast?.enabled===!0}async function v1(f,_=z()){let E=await h(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.claudeFast={...E.claudeFast??{},enabled:f},await Q(E,_),E}async function d1(f,_,E=z()){let D=await h(E)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.cacheKeep={enabled:!0,startHour:f,endHour:_},await Q(D,E),D}async function u1(f,_=z()){let E=await h(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.cacheKeep={...E.cacheKeep??{},enabled:f},await Q(E,_),E}function jE(f){return f?.fallbackOn?.length?f.fallbackOn:d0}function g1(f,_){return jE(_).includes(f)}function P_(f){let _=f?.quota?.minimumRemaining||{};return{five_hour:_.five_hour??_["5h"]??G_.five_hour,seven_day:_.seven_day??_["1w"]??G_.seven_day}}function e(f){return f?.quota?.enabled!==!1}function GE(f){return f?.refresh?.enabled!==!1}function zE(f){return Math.floor(Math.random()*Math.max(0,f))}function JE(f){let _=f?.refresh?.refreshBeforeExpiryMinutes??u0;return Math.max(Q_,_)*60000}function R_(f){return h_("sha256").update(f).digest("hex")}function YE(f){if(f instanceof i)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 WE(f){let _=R_(f.refreshToken),D=(f.previous?.tokenHash===_?f.previous.retryCount??0:0)+1,m;if(f.error instanceof i&&f.error.retryAfter)m=f.error.retryAfter*1000;else if(YE(f.error))m=Math.min(n0,g0*2**Math.min(D-1,6));else m=r0;return{message:ff(f.error),checkedAt:f.now,nextRetryAt:f.now+m,retryCount:D,tokenHash:_}}function o(f,_,E){if(!f?.nextRetryAt||f.nextRetryAt<=E)return!1;if(!_)return!0;return f.tokenHash===R_(_)}function hf(f,_){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function Af(f){let E=(f.previous?.retryCount??0)+1,D=i_(f.error)?Math.min(c0,s0*2**Math.min(E-1,6)):t0;return{message:ff(f.error),checkedAt:f.now,nextRetryAt:f.now+D,retryCount:E}}function r(f,_){if(!f?.nextRetryAt||f.nextRetryAt<=_)return!1;return!0}function n1(f,_){return`Quota API backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function X(f){let _=f?.quota?.checkIntervalMinutes??o0;return Math.max(1,_)*60000}function q_(f){if(!f?.quota?.mainQuota||!f.quota.mainQuotaCheckedAt)return null;return{quota:f.quota.mainQuota,checkedAt:f.quota.mainQuotaCheckedAt,tokenFingerprint:f.quota.mainQuotaToken}}function T_(f){let _=f?.quota?.refreshEveryNRequests;return typeof _==="number"&&Number.isFinite(_)&&_>0?Math.floor(_):0}function Tf(f){return f?.quota?.failClosedOnUnknownQuota??a0}function w_(f,_){if(!e(_))return!0;let E=P_(_);for(let D of["five_hour","seven_day"]){let m=f?.[D];if(!m)return!Tf(_);if(m.remainingPercent<E[D])return!1}return!0}var Z={five_hour:5,seven_day:10};function Y_(f){return{five_hour:f?.five_hour??f?.["5h"]??Z.five_hour,seven_day:f?.seven_day??f?.["1w"]??Z.seven_day}}function XE(f){return f?.killswitch?.enabled===!0}function ZE(f,_){if(!f?.killswitch)return Z;if(_&&f.killswitch.accounts?.[_])return Y_(f.killswitch.accounts[_]);return Y_(f.killswitch.main)}function r1(f,_,E){if(!XE(_))return!0;let D=ZE(_,E),m=!1;for(let $ of["five_hour","seven_day"]){let C=f?.[$];if(!C){m=!0;continue}if(C.remainingPercent<D[$])return!1}if(m)return!Tf(_);return!0}function s1(f,_,E){let D=[],m=[f,..._.map(($)=>$.quota)];for(let $ of m)for(let C of["five_hour","seven_day"]){let M=$?.[C]?.resetsAt;if(!M)continue;let L=Date.parse(M);if(Number.isFinite(L)&&L>E)D.push(L)}if(!D.length)return 300;return Math.max(1,Math.ceil((Math.min(...D)-E)/1000))+60}function c1(f){return f?.killswitch??{enabled:!1}}async function t1(f,_=z()){let E=await h(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.killswitch=f,await Q(E,_),E}function wf(f,_,E){if(!e(_))return E+X(_);let D=P_(_),m=[];for(let $ of["five_hour","seven_day"]){let C=f?.[$];if(!C)return E+X(_);if(C.remainingPercent>=D[$])continue;let M=C.resetsAt?Date.parse(C.resetsAt):Number.NaN;if(!Number.isFinite(M)||M<=E)return E+X(_);m.push(M)}if(!m.length)return E+X(_);return Math.min(...m)+60000}function l(f,_,E){return!f.access||!f.expires||f.expires-E<=JE(_)}function Vf(f,_,E){if(!e(_))return!1;let D=X(_);return["five_hour","seven_day"].some((m)=>{let $=f.quota?.[m];return!$||E-$.checkedAt>=D})}function hE(f,_){if(!f)return!1;if(!f.resetsAt)return!0;let E=Date.parse(f.resetsAt);return!Number.isFinite(E)||E>_}function VE(f,_){return["five_hour","seven_day"].every((E)=>hE(f?.[E],_))}function i_(f){let _=ff(f);if(/Claude quota check failed: (429|5\d\d)\b/.test(_))return!0;if(!(f instanceof Error))return!1;let E=f.code;return _.includes("fetch failed")||E==="ECONNRESET"||E==="ECONNREFUSED"||E==="ETIMEDOUT"||E==="UND_ERR_CONNECT_TIMEOUT"}function xE(f,_,E,D){return i_(E)&&w_(f.quota,_)&&VE(f.quota,D)}function W_(f){if(!Number.isFinite(f))return 0;if(f<0)return 0;if(f>100)return 100;return f}function X_(f,_){if(typeof f?.utilization!=="number")return;let E=W_(f.utilization);return{usedPercent:E,remainingPercent:W_(100-E),resetsAt:f.resets_at,checkedAt:_}}async function Uf(f){let E=await(f.fetchImpl??fetch)(p0,{method:"GET",headers:{Authorization:`Bearer ${f.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${q}`}});if(!E.ok){let $=await E.text().catch(()=>"");throw Error(`Claude quota check failed: ${E.status} — ${$}`)}let D=f.now?.()??Date.now(),m=await E.json();return{five_hour:X_(m.five_hour,D),seven_day:X_(m.seven_day,D)}}function W(f,_){let E=f.accounts.findIndex((D)=>D.id===_.id);if(E>=0)f.accounts[E]=_}function ff(f){return f instanceof Error?f.message:String(f)}function l_(f,_,E){f.lastRefreshError=WE({error:_,now:E,refreshToken:f.refresh,previous:f.lastRefreshError})}function Z_(f,_,E){if(f.lastQuotaRefreshError=Af({error:_,now:E,previous:f.lastQuotaRefreshError}),_ instanceof i)l_(f,_,E)}function QE(f){return`fallback-oauth-refresh-${h_("sha256").update(f).digest("hex").slice(0,16)}`}class IE{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,_){if(!this.quotaManager)return;if(this.quotaManager.getFallback(f.id,f.access))return;if(!f.quota)return;let E=Math.max(f.quota.five_hour?.checkedAt??0,f.quota.seven_day?.checkedAt??0);if(E<=0)return;let D=X(_);this.quotaManager.setFallback(f.id,{quota:f.quota,refreshAfter:E+D,checkedAt:E},f.access)}async load(){return h(this.configPath)}async save(f,_){await FE(f,this.configPath,{accounts:_??!0})}startBackgroundRefresh(){let f=async()=>{await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()};if(f().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{f().catch(()=>{})},e0+zE(fE)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts(f){let _=f!==void 0?f:await this.load();if(!_)return[];let E=[],D=!1;for(let m of _.accounts){if(m.enabled===!1||!x(m))continue;try{let $=m;if(l($,_,this.now())){let M=$.lastRefreshError;if(M&&o(M,$.refresh,this.now()))throw Error(hf(M,this.now()));$=await this.refreshAccount($,_),D=!0}if(this.seedFallbackQuota($,_),(this.quotaManager?this.quotaManager.isFallbackStale($.id,$.access):Vf($,_,this.now()))&&!r($.lastQuotaRefreshError,this.now()))$=await this.refreshAccountQuota($,_),D=!0;if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount($),_))E.push($)}catch($){if(xE(m,_,$,this.now()))V("[refresh] fallback quota using cached quota after refresh error",{accountId:m.id,error:ff($)}),E.push(m);else if(!Tf(_))E.push(m)}}if(D)await this.save(_);return E}async markUsed(f){let _=await this.load();if(!_)return;let E=_.accounts.find((D)=>D.id===f.id);if(!E)return;E.lastUsed=this.now(),await this.save(_)}accountPassesQuotaPolicy(f,_){return w_(f.quota,_)}quotaPolicyAccount(f){if(!this.quotaManager)return f;let _=this.quotaManager.getFallback(f.id,f.access)?.quota;return _?{...f,quota:_}:f}async refreshDueAccounts(){let f=await this.load();if(!f||!GE(f))return;let _=!1;for(let E of f.accounts){if(E.enabled===!1||!x(E))continue;if(!l(E,f,this.now()))continue;if(o(E.lastRefreshError,E.refresh,this.now()))continue;try{V("[refresh] fallback oauth background due",{accountId:E.id,expiresInMs:E.expires?E.expires-this.now():void 0}),await this.refreshAccount(E,f),_=!0}catch(D){V("[refresh] fallback oauth background failed",{accountId:E.id,error:D instanceof Error?D.message:String(D)}),l_(E,D,this.now()),W(f,E),_=!0}}if(_)await this.save(f)}async refreshQuotaForDueAccounts(){let f=await this.load();if(!f||!e(f))return;let _=!1;for(let E of f.accounts){if(E.enabled===!1||!x(E))continue;let D=E;try{if(l(D,f,this.now())){if(o(D.lastRefreshError,D.refresh,this.now()))continue;D=await this.refreshAccount(D,f),_=!0}if(r(D.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(D,f),!(this.quotaManager?this.quotaManager.isFallbackStale(D.id,D.access):Vf(D,f,this.now())))continue;await this.refreshAccountQuota(D,f),_=!0}catch(m){Z_(E,m,this.now()),W(f,E),_=!0}}if(_)await this.save(f),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(f={}){let _=await this.load(),E=[];if(!_||!e(_))return{storage:_,errors:E};let D=f.force??!1,m=!1;for(let $ of _.accounts){if($.enabled===!1||!x($))continue;let C=$;try{if(l(C,_,this.now())){let M=C.lastRefreshError;if(M&&o(M,C.refresh,this.now()))throw Error(hf(M,this.now()));C=await this.refreshAccount(C,_),m=!0}if(!D&&!Vf(C,_,this.now())){if(C.lastQuotaRefreshError)C.lastQuotaRefreshError=void 0,W(_,C),m=!0;continue}await this.refreshAccountQuota(C,_),m=!0}catch(M){Z_($,M,this.now()),W(_,$),m=!0,E.push({accountId:$.id,message:ff(M)})}}if(m)await this.save(_);return{storage:_,errors:E}}async refreshAccount(f,_,E={}){let D=this.refreshPromises.get(f.id);if(D){let C=await D;return W(_,C),C}let m=this.refreshAccountNow(f,_,E).finally(()=>{this.refreshPromises.delete(f.id)});this.refreshPromises.set(f.id,m);let $=await m;return W(_,$),$}async waitForConcurrentFallbackRefresh(f,_,E,D){let m=Date.now()+EE;while(Date.now()<m){await new Promise((A)=>setTimeout(A,DE));let $=await this.load(),C=$?.accounts.find((A)=>A.id===f.id&&x(A));if(!C)continue;if((C.access!==E.access||C.refresh!==E.refresh||(C.expires??0)>(E.expires??0)+60000)&&(D.force||!l(C,$,this.now())))return W(_,C),V("[refresh] fallback oauth joined concurrent refresh",{accountId:C.id,expiresInMs:C.expires?C.expires-this.now():void 0}),C;let L=C.lastRefreshError;if(L&&o(L,C.refresh,this.now()))throw W(_,C),Error(hf(L,this.now()))}return null}async refreshAccountNow(f,_,E){let D=await this.load(),m=D?.accounts.find((M)=>M.id===f.id&&x(M));if(m&&!E.force&&!l(m,D,this.now()))return W(_,m),m;let $=m??f,C=await Lf({name:QE($.id),ttlMs:_E,path:this.configPath,now:this.now,renew:!0});if(!C){V("[refresh] fallback oauth refresh skipped file lock",{accountId:$.id});let M=await this.waitForConcurrentFallbackRefresh(f,_,$,E);if(M)return M;throw Error("Fallback OAuth refresh is already in progress")}try{if(D=await this.load(),m=D?.accounts.find((A)=>A.id===f.id&&x(A)),m&&!E.force&&!l(m,D,this.now()))return W(_,m),m;$=m??$;let M=$.refresh;V("[refresh] fallback oauth refresh request start",{accountId:$.id,force:E.force===!0,expiresInMs:$.expires?$.expires-this.now():void 0});let L=await N_({refreshToken:M,fetchImpl:this.fetchImpl,now:this.now});return $.access=L.access,$.refresh=L.refresh,$.expires=L.expires,$.lastRefreshedAt=L.expires-L.expiresIn*1000,$.lastRefreshError=void 0,W(_,$),await this.save(_),V("[refresh] fallback oauth refresh succeeded",{accountId:$.id,expiresInMs:$.expires?$.expires-this.now():void 0}),$}finally{await C.release()}}async refreshAccountQuota(f,_){let E=f;if(!E.access)throw Error(`Fallback account ${f.id} has no access token`);let D=(m)=>this.quotaManager?this.quotaManager.refreshFallback(E.id,m):Uf({accessToken:m,fetchImpl:this.fetchImpl,now:this.now});try{E.quota=await D(E.access)}catch(m){if(!(m instanceof Error?m.message:String(m)).includes("Claude quota check failed: 401"))throw m;if(E=await this.refreshAccount(f,_,{force:!0}),!E.access)throw m;E.quota=await D(E.access)}if(E.lastQuotaRefreshError=void 0,W(_,E),this.quotaManager&&E.quota){let m=this.now();this.quotaManager.setFallback(E.id,{quota:E.quota,refreshAfter:m+X(_),checkedAt:m},E.access)}return E}}var e1="claude-cache",y_="## Claude Cache Status",PE="## Claude Cache Enabled",RE="## Claude Cache Disabled",qE="## Claude Cache Usage",TE="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",Of=!1,Sf=Cf;function fm(){return Of}function _m(){return Sf}function Em(f){Of=f.enabled,Sf=f.mode}function wE(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&_[0]==="on")return{type:"enable"};if(_.length===1&&_[0]==="off")return{type:"disable"};if(_.length===2&&_[0]==="mode"&&(_[1]==="explicit"||_[1]==="automatic"||_[1]==="hybrid"))return{type:"mode",mode:_[1]};return{type:"usage"}}function _f(f){let _=f?.enabled??Of,E=f?.mode??Sf;return[y_,"",`- Enabled: ${_?"enabled":"disabled"}`,`- Mode: ${E}`,"- 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
|
|
7
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(K){let j=K.code;if(j==="EEXIST"||j==="EISDIR")return!1;throw K}}function N(){if(!f.renew||M)return;let K=f.renewIntervalMs??Math.max(1000,Math.floor(f.ttlMs/3));if(C=y0(()=>{(async()=>{try{let j=await L(),R=$();if(M||j?.ownerId!==m||Number(j?.expiresAt)<=R)return;await A(),N()}catch{}})()},K),"unref"in C)C.unref()}if(!await U()){try{let K=await L();if(Number(K?.expiresAt)>$())return null}catch{try{if((await w0(E)).mtimeMs+f.ttlMs>Date.now())return null}catch{return null}}if(await j_(E,{recursive:!0,force:!0}).catch(()=>{}),!await U())return null}return N(),{release:async()=>{if(M=!0,C)l0(C),C=null;try{if((await L())?.ownerId!==m)return}catch{return}await j_(E,{recursive:!0,force:!0}).catch(()=>{})}}}function wm(f){return f?.claudeCache?.enabled===!0}function BE(f){return typeof f==="string"&&O_.includes(f)?f:Cf}function KE(f){return BE(f?.claudeCache?.mode)}async function im(f,_,E=z()){let D=await h(E)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.claudeCache={...D.claudeCache??{},enabled:f,mode:_??KE(D)},await Q(D,E),D}async function ym(f,_=z()){let E=await h(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.claudeCache={...E.claudeCache??{},enabled:E.claudeCache?.enabled===!0,mode:f},await Q(E,_),E}function lm(f){return f?.dump?.enabled===!0}async function km(f,_=z()){let E=await h(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.dump={...E.dump??{},enabled:f},await Q(E,_),E}function pm(f){return f?.claudeFast?.enabled===!0}async function vm(f,_=z()){let E=await h(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.claudeFast={...E.claudeFast??{},enabled:f},await Q(E,_),E}async function dm(f,_,E=z()){let D=await h(E)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.cacheKeep={enabled:!0,startHour:f,endHour:_},await Q(D,E),D}async function um(f,_=z()){let E=await h(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.cacheKeep={...E.cacheKeep??{},enabled:f},await Q(E,_),E}function jE(f){return f?.fallbackOn?.length?f.fallbackOn:d0}function gm(f,_){return jE(_).includes(f)}function P_(f){let _=f?.quota?.minimumRemaining||{};return{five_hour:_.five_hour??_["5h"]??G_.five_hour,seven_day:_.seven_day??_["1w"]??G_.seven_day}}function e(f){return f?.quota?.enabled!==!1}function GE(f){return f?.refresh?.enabled!==!1}function zE(f){return Math.floor(Math.random()*Math.max(0,f))}function JE(f){let _=f?.refresh?.refreshBeforeExpiryMinutes??u0;return Math.max(Q_,_)*60000}function R_(f){return h_("sha256").update(f).digest("hex")}function YE(f){if(f instanceof i)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 WE(f){let _=R_(f.refreshToken),D=(f.previous?.tokenHash===_?f.previous.retryCount??0:0)+1,m;if(f.error instanceof i&&f.error.retryAfter)m=f.error.retryAfter*1000;else if(YE(f.error))m=Math.min(n0,g0*2**Math.min(D-1,6));else m=r0;return{message:ff(f.error),checkedAt:f.now,nextRetryAt:f.now+m,retryCount:D,tokenHash:_}}function o(f,_,E){if(!f?.nextRetryAt||f.nextRetryAt<=E)return!1;if(!_)return!0;return f.tokenHash===R_(_)}function hf(f,_){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function Af(f){let E=(f.previous?.retryCount??0)+1,D=i_(f.error)?Math.min(c0,s0*2**Math.min(E-1,6)):t0;return{message:ff(f.error),checkedAt:f.now,nextRetryAt:f.now+D,retryCount:E}}function r(f,_){if(!f?.nextRetryAt||f.nextRetryAt<=_)return!1;return!0}function nm(f,_){return`Quota API backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function X(f){let _=f?.quota?.checkIntervalMinutes??o0;return Math.max(1,_)*60000}function T_(f){if(!f?.quota?.mainQuota||!f.quota.mainQuotaCheckedAt)return null;return{quota:f.quota.mainQuota,checkedAt:f.quota.mainQuotaCheckedAt,tokenFingerprint:f.quota.mainQuotaToken}}function q_(f){let _=f?.quota?.refreshEveryNRequests;return typeof _==="number"&&Number.isFinite(_)&&_>0?Math.floor(_):0}function qf(f){return f?.quota?.failClosedOnUnknownQuota??a0}function w_(f,_){if(!e(_))return!0;let E=P_(_);for(let D of["five_hour","seven_day"]){let m=f?.[D];if(!m)return!qf(_);if(m.remainingPercent<E[D])return!1}return!0}var Z={five_hour:5,seven_day:10};function Y_(f){return{five_hour:f?.five_hour??f?.["5h"]??Z.five_hour,seven_day:f?.seven_day??f?.["1w"]??Z.seven_day}}function XE(f){return f?.killswitch?.enabled===!0}function ZE(f,_){if(!f?.killswitch)return Z;if(_&&f.killswitch.accounts?.[_])return Y_(f.killswitch.accounts[_]);return Y_(f.killswitch.main)}function rm(f,_,E){if(!XE(_))return!0;let D=ZE(_,E),m=!1;for(let $ of["five_hour","seven_day"]){let C=f?.[$];if(!C){m=!0;continue}if(C.remainingPercent<D[$])return!1}if(m)return!qf(_);return!0}function sm(f,_,E){let D=[],m=[f,..._.map(($)=>$.quota)];for(let $ of m)for(let C of["five_hour","seven_day"]){let M=$?.[C]?.resetsAt;if(!M)continue;let L=Date.parse(M);if(Number.isFinite(L)&&L>E)D.push(L)}if(!D.length)return 300;return Math.max(1,Math.ceil((Math.min(...D)-E)/1000))+60}function cm(f){return f?.killswitch??{enabled:!1}}async function tm(f,_=z()){let E=await h(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.killswitch=f,await Q(E,_),E}function wf(f,_,E){if(!e(_))return E+X(_);let D=P_(_),m=[];for(let $ of["five_hour","seven_day"]){let C=f?.[$];if(!C)return E+X(_);if(C.remainingPercent>=D[$])continue;let M=C.resetsAt?Date.parse(C.resetsAt):Number.NaN;if(!Number.isFinite(M)||M<=E)return E+X(_);m.push(M)}if(!m.length)return E+X(_);return Math.min(...m)+60000}function y(f,_,E){return!f.access||!f.expires||f.expires-E<=JE(_)}function Vf(f,_,E){if(!e(_))return!1;let D=X(_);return["five_hour","seven_day"].some((m)=>{let $=f.quota?.[m];return!$||E-$.checkedAt>=D})}function hE(f,_){if(!f)return!1;if(!f.resetsAt)return!0;let E=Date.parse(f.resetsAt);return!Number.isFinite(E)||E>_}function VE(f,_){return["five_hour","seven_day"].every((E)=>hE(f?.[E],_))}function i_(f){let _=ff(f);if(/Claude quota check failed: (429|5\d\d)\b/.test(_))return!0;if(!(f instanceof Error))return!1;let E=f.code;return _.includes("fetch failed")||E==="ECONNRESET"||E==="ECONNREFUSED"||E==="ETIMEDOUT"||E==="UND_ERR_CONNECT_TIMEOUT"}function xE(f,_,E,D){return i_(E)&&w_(f.quota,_)&&VE(f.quota,D)}function W_(f){if(!Number.isFinite(f))return 0;if(f<0)return 0;if(f>100)return 100;return f}function X_(f,_){if(typeof f?.utilization!=="number")return;let E=W_(f.utilization);return{usedPercent:E,remainingPercent:W_(100-E),resetsAt:f.resets_at,checkedAt:_}}async function Uf(f){let E=await(f.fetchImpl??fetch)(p0,{method:"GET",headers:{Authorization:`Bearer ${f.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${T}`}});if(!E.ok){let $=await E.text().catch(()=>"");throw Error(`Claude quota check failed: ${E.status} — ${$}`)}let D=f.now?.()??Date.now(),m=await E.json();return{five_hour:X_(m.five_hour,D),seven_day:X_(m.seven_day,D)}}function W(f,_){let E=f.accounts.findIndex((D)=>D.id===_.id);if(E>=0)f.accounts[E]=_}function ff(f){return f instanceof Error?f.message:String(f)}function y_(f,_,E){f.lastRefreshError=WE({error:_,now:E,refreshToken:f.refresh,previous:f.lastRefreshError})}function Z_(f,_,E){if(f.lastQuotaRefreshError=Af({error:_,now:E,previous:f.lastQuotaRefreshError}),_ instanceof i)y_(f,_,E)}function QE(f){return`fallback-oauth-refresh-${h_("sha256").update(f).digest("hex").slice(0,16)}`}class IE{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,_){if(!this.quotaManager)return;if(this.quotaManager.getFallback(f.id,f.access))return;if(!f.quota)return;let E=Math.max(f.quota.five_hour?.checkedAt??0,f.quota.seven_day?.checkedAt??0);if(E<=0)return;let D=X(_);this.quotaManager.setFallback(f.id,{quota:f.quota,refreshAfter:E+D,checkedAt:E},f.access)}async load(){return h(this.configPath)}async save(f,_){await bE(f,this.configPath,{accounts:_??!0})}startBackgroundRefresh(){let f=async()=>{await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()};if(f().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{f().catch(()=>{})},e0+zE(fE)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts(f){let _=f!==void 0?f:await this.load();if(!_)return[];let E=[],D=!1;for(let m of _.accounts){if(m.enabled===!1||!x(m))continue;try{let $=m;if(y($,_,this.now())){let M=$.lastRefreshError;if(M&&o(M,$.refresh,this.now()))throw Error(hf(M,this.now()));$=await this.refreshAccount($,_),D=!0}if(this.seedFallbackQuota($,_),(this.quotaManager?this.quotaManager.isFallbackStale($.id,$.access):Vf($,_,this.now()))&&!r($.lastQuotaRefreshError,this.now()))$=await this.refreshAccountQuota($,_),D=!0;if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount($),_))E.push($)}catch($){if(xE(m,_,$,this.now()))V("[refresh] fallback quota using cached quota after refresh error",{accountId:m.id,error:ff($)}),E.push(m);else if(!qf(_))E.push(m)}}if(D)await this.save(_);return E}async markUsed(f){let _=await this.load();if(!_)return;let E=_.accounts.find((D)=>D.id===f.id);if(!E)return;E.lastUsed=this.now(),await this.save(_)}accountPassesQuotaPolicy(f,_){return w_(f.quota,_)}quotaPolicyAccount(f){if(!this.quotaManager)return f;let _=this.quotaManager.getFallback(f.id,f.access)?.quota;return _?{...f,quota:_}:f}async refreshDueAccounts(){let f=await this.load();if(!f||!GE(f))return;let _=!1;for(let E of f.accounts){if(E.enabled===!1||!x(E))continue;if(!y(E,f,this.now()))continue;if(o(E.lastRefreshError,E.refresh,this.now()))continue;try{V("[refresh] fallback oauth background due",{accountId:E.id,expiresInMs:E.expires?E.expires-this.now():void 0}),await this.refreshAccount(E,f),_=!0}catch(D){V("[refresh] fallback oauth background failed",{accountId:E.id,error:D instanceof Error?D.message:String(D)}),y_(E,D,this.now()),W(f,E),_=!0}}if(_)await this.save(f)}async refreshQuotaForDueAccounts(){let f=await this.load();if(!f||!e(f))return;let _=!1;for(let E of f.accounts){if(E.enabled===!1||!x(E))continue;let D=E;try{if(y(D,f,this.now())){if(o(D.lastRefreshError,D.refresh,this.now()))continue;D=await this.refreshAccount(D,f),_=!0}if(r(D.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(D,f),!(this.quotaManager?this.quotaManager.isFallbackStale(D.id,D.access):Vf(D,f,this.now())))continue;await this.refreshAccountQuota(D,f),_=!0}catch(m){Z_(E,m,this.now()),W(f,E),_=!0}}if(_)await this.save(f),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(f={}){let _=await this.load(),E=[];if(!_||!e(_))return{storage:_,errors:E};let D=f.force??!1,m=!1;for(let $ of _.accounts){if($.enabled===!1||!x($))continue;let C=$;try{if(y(C,_,this.now())){let M=C.lastRefreshError;if(M&&o(M,C.refresh,this.now()))throw Error(hf(M,this.now()));C=await this.refreshAccount(C,_),m=!0}if(!D&&!Vf(C,_,this.now())){if(C.lastQuotaRefreshError)C.lastQuotaRefreshError=void 0,W(_,C),m=!0;continue}await this.refreshAccountQuota(C,_),m=!0}catch(M){Z_($,M,this.now()),W(_,$),m=!0,E.push({accountId:$.id,message:ff(M)})}}if(m)await this.save(_);return{storage:_,errors:E}}async refreshAccount(f,_,E={}){let D=this.refreshPromises.get(f.id);if(D){let C=await D;return W(_,C),C}let m=this.refreshAccountNow(f,_,E).finally(()=>{this.refreshPromises.delete(f.id)});this.refreshPromises.set(f.id,m);let $=await m;return W(_,$),$}async waitForConcurrentFallbackRefresh(f,_,E,D){let m=Date.now()+EE;while(Date.now()<m){await new Promise((A)=>setTimeout(A,DE));let $=await this.load(),C=$?.accounts.find((A)=>A.id===f.id&&x(A));if(!C)continue;if((C.access!==E.access||C.refresh!==E.refresh||(C.expires??0)>(E.expires??0)+60000)&&(D.force||!y(C,$,this.now())))return W(_,C),V("[refresh] fallback oauth joined concurrent refresh",{accountId:C.id,expiresInMs:C.expires?C.expires-this.now():void 0}),C;let L=C.lastRefreshError;if(L&&o(L,C.refresh,this.now()))throw W(_,C),Error(hf(L,this.now()))}return null}async refreshAccountNow(f,_,E){let D=await this.load(),m=D?.accounts.find((M)=>M.id===f.id&&x(M));if(m&&!E.force&&!y(m,D,this.now()))return W(_,m),m;let $=m??f,C=await Lf({name:QE($.id),ttlMs:_E,path:this.configPath,now:this.now,renew:!0});if(!C){V("[refresh] fallback oauth refresh skipped file lock",{accountId:$.id});let M=await this.waitForConcurrentFallbackRefresh(f,_,$,E);if(M)return M;throw Error("Fallback OAuth refresh is already in progress")}try{if(D=await this.load(),m=D?.accounts.find((A)=>A.id===f.id&&x(A)),m&&!E.force&&!y(m,D,this.now()))return W(_,m),m;$=m??$;let M=$.refresh;V("[refresh] fallback oauth refresh request start",{accountId:$.id,force:E.force===!0,expiresInMs:$.expires?$.expires-this.now():void 0});let L=await N_({refreshToken:M,fetchImpl:this.fetchImpl,now:this.now});return $.access=L.access,$.refresh=L.refresh,$.expires=L.expires,$.lastRefreshedAt=L.expires-L.expiresIn*1000,$.lastRefreshError=void 0,W(_,$),await this.save(_),V("[refresh] fallback oauth refresh succeeded",{accountId:$.id,expiresInMs:$.expires?$.expires-this.now():void 0}),$}finally{await C.release()}}async refreshAccountQuota(f,_){let E=f;if(!E.access)throw Error(`Fallback account ${f.id} has no access token`);let D=(m)=>this.quotaManager?this.quotaManager.refreshFallback(E.id,m):Uf({accessToken:m,fetchImpl:this.fetchImpl,now:this.now});try{E.quota=await D(E.access)}catch(m){if(!(m instanceof Error?m.message:String(m)).includes("Claude quota check failed: 401"))throw m;if(E=await this.refreshAccount(f,_,{force:!0}),!E.access)throw m;E.quota=await D(E.access)}if(E.lastQuotaRefreshError=void 0,W(_,E),this.quotaManager&&E.quota){let m=this.now();this.quotaManager.setFallback(E.id,{quota:E.quota,refreshAfter:m+X(_),checkedAt:m},E.access)}return E}}var em="claude-cache",l_="## Claude Cache Status",PE="## Claude Cache Enabled",RE="## Claude Cache Disabled",TE="## Claude Cache Usage",qE="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",Of=!1,Sf=Cf;function f1(){return Of}function _1(){return Sf}function E1(f){Of=f.enabled,Sf=f.mode}function wE(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&_[0]==="on")return{type:"enable"};if(_.length===1&&_[0]==="off")return{type:"disable"};if(_.length===2&&_[0]==="mode"&&(_[1]==="explicit"||_[1]==="automatic"||_[1]==="hybrid"))return{type:"mode",mode:_[1]};return{type:"usage"}}function _f(f){let _=f?.enabled??Of,E=f?.mode??Sf;return[l_,"",`- Enabled: ${_?"enabled":"disabled"}`,`- Mode: ${E}`,"- 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 D1(f){let _=wE(f.argumentsText),E=f.enabled??Of,D=f.mode??Sf;if(_.type==="status")return _f({enabled:E,mode:D});if(_.type==="enable")return[PE,"",_f({enabled:!0,mode:D})].join(`
|
|
9
9
|
`);if(_.type==="disable")return[RE,"",_f({enabled:!1,mode:D})].join(`
|
|
10
|
-
`);if(_.type==="mode")return[
|
|
11
|
-
`);return[
|
|
12
|
-
`)}import{randomBytes as iE,randomUUID as v_}from"node:crypto";var lE=1000,y=new Map;function Ef(f,_,E){if(!f.has(_)&&f.size>=lE){let D=f.keys().next().value;if(D!==void 0)f.delete(D)}f.set(_,E)}function d_(f){let _=f||"anonymous",E=y.get(_);if(E)return E;let D={deviceId:iE(32).toString("hex"),sessionId:v_()};return Ef(y,_,D),D}var yE=86400000,kE=300000,lf=new Map,k_=new Map;async function pE(f,_){if(!f.startsWith("sk-ant-oat"))return null;let E=new AbortController,D=setTimeout(()=>E.abort(),5000);try{let m=new URL("https://api.anthropic.com/api/claude_cli/bootstrap");if(m.searchParams.set("entrypoint",M_),_)m.searchParams.set("model",_);let $=await fetch(m,{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/${q}`},signal:E.signal});if(!$.ok)return null;let M=(await $.json().catch(()=>null))?.oauth_account?.account_uuid;return typeof M==="string"&&M?M:null}catch{return null}finally{clearTimeout(D)}}async function Mm(f,_){let E=d_(f);if(!f.startsWith("sk-ant-oat"))return E;let D=Date.now(),m=k_.get(f);if(m&&m.expiresAt>D){if(!m.accountUuid)return E;let A=`account:${m.accountUuid}`,U=y.get(A);if(U)return Ef(y,f,U),U}let $=lf.get(f);if(!$)$=pE(f,_),lf.set(f,$);let C=await $.finally(()=>{lf.delete(f)});if(Ef(k_,f,{accountUuid:C,expiresAt:D+(C?yE:kE)}),!C)return E;let M=`account:${C}`,L=y.get(M);if(L)return Ef(y,f,L),L;return E.accountUuid=C,Ef(y,M,E),E}function k(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function vE(f){if(!f.accountUuid)return null;return JSON.stringify({device_id:f.deviceId,account_uuid:f.accountUuid,session_id:f.sessionId})}function Lm(f,_){let E=vE(_);if(!E){if(k(f.metadata))delete f.metadata.user_id;return!1}if(!k(f.metadata))f.metadata={};let D=f.metadata;if(k(D))D.user_id=E;return!0}var dE=["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"],uE=["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"],p_=["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 gE(f){return f.output_config?.format?.type==="json_schema"}function nE(f){return Array.isArray(f.tools)&&f.tools.length>0&&Array.isArray(f.system)&&k(f.thinking)&&k(f.context_management)&&k(f.output_config)&&k(f.diagnostics)}function rE(f,_=[]){let E=f?nE(f)?[...dE]:gE(f)?[...uE]:[...p_]:[...p_];if(f?.speed==="fast")E.push(C_);for(let D of _){let m=D.trim();if(m)E.push(m)}return[...new Set(E)].join(",")}function sE(){switch(process.platform){case"darwin":return"MacOS";case"win32":return"Windows";case"linux":return"Linux";case"freebsd":return"FreeBSD";default:return"Unknown"}}function cE(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";case"ia32":return"x32";default:return process.arch}}function Am(f,_,E={}){let D=E.identity??d_(_),$=[...(f.get("anthropic-beta")??"").split(",").map((C)=>C.trim()).filter(Boolean),...E.extraBetas??[]];return f.set("accept","application/json"),f.set("authorization",`Bearer ${_}`),f.set("content-type","application/json"),f.set("user-agent",U_),f.set("anthropic-beta",rE(E.body,$)),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",v_()),f.set("x-claude-code-session-id",D.sessionId),f.set("x-stainless-arch",cE()),f.set("x-stainless-lang","js"),f.set("x-stainless-os",sE()),f.set("x-stainless-package-version",L_),f.set("x-stainless-retry-count","0"),f.set("x-stainless-runtime","node"),f.set("x-stainless-runtime-version",A_),f.set("x-stainless-timeout","600"),f.delete("x-api-key"),f}var tE=["model","messages","system","tools","tool_choice","metadata","max_tokens","temperature","thinking","context_management","output_config","diagnostics","stream","speed"];function u_(f){let _={};for(let E of tE)if(Object.hasOwn(f,E))_[E]=f[E];for(let[E,D]of Object.entries(f))if(!Object.hasOwn(_,E))_[E]=D;return _}import{createHash as aE}from"node:crypto";var oE=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 g_(){return function(f){let{exports:{mem:_,xxh32:E,xxh64:D,init32:m,update32:$,digest32:C,init64:M,update64:L,digest64:A}}=f,U=new Uint8Array(_.buffer);function N(O,G){if(_.buffer.byteLength<O+G){let zf=Math.ceil((O+G-_.buffer.byteLength)/65536);_.grow(zf),U=new Uint8Array(_.buffer)}}function K(O,G,zf,z0,J0,Y0){N(O);let c=new Uint8Array(O);return U.set(c),zf(0,G),c.set(U.subarray(0,O)),{update(g){let Jf;return U.set(c),typeof g=="string"?(N(3*g.length,O),Jf=S.encodeInto(g,U.subarray(O)).written):(N(g.byteLength,O),U.set(g,O),Jf=g.byteLength),z0(0,O,Jf),c.set(U.subarray(0,O)),this},digest:()=>(U.set(c),Y0(J0(0)))}}function j(O){return O>>>0}let R=2n**64n-1n;function J(O){return O&R}let S=new TextEncoder,v=0,d=0n;function u(O,G=v){return N(3*O.length,0),j(E(0,S.encodeInto(O,U).written,G))}function mf(O,G=d){return N(3*O.length,0),J(D(0,S.encodeInto(O,U).written,G))}return{h32:u,h32ToString:(O,G=v)=>u(O,G).toString(16).padStart(8,"0"),h32Raw:(O,G=v)=>(N(O.byteLength,0),U.set(O),j(E(0,O.byteLength,G))),create32:(O=v)=>K(48,O,m,$,C,j),h64:mf,h64ToString:(O,G=d)=>mf(O,G).toString(16).padStart(16,"0"),h64Raw:(O,G=d)=>(N(O.byteLength,0),U.set(O),J(D(0,O.byteLength,G))),create64:(O=d)=>K(88,O,M,L,A,J)}}((await WebAssembly.instantiate(oE)).instance)}var eE=0x6e52736ac806831en,fD="cch=00000;";var kf=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=([0-9a-f]{5});/,_D=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=00000;/,n_=null,yf=null;async function ED(){if(yf)return;n_??=(async()=>{yf=(await g_()).h64Raw})(),await n_}async function DD(f){return await ED(),((yf?.(f,eE)??0n)&0xfffffn).toString(16).padStart(5,"0")}function mD(f){return f.replace(kf,`$1${fD}`)}function r_(f){return kf.exec(f)?.[2]??null}async function s_(f){if(!kf.test(f))return f;let _=mD(f),E=await DD(new TextEncoder().encode(_));return _.replace(_D,`$1cch=${E};`)}function $D(f=q,_=new Date){if(f===q)return Xf;return aE("sha256").update(f).digest("hex").slice(0,3)}function bm(f,_=q,E,D=new Date){let m=$D(_,D);return`x-anthropic-billing-header: cc_version=${_}.${m}; cc_entrypoint=${E}; cch=00000;`}var jm="claude-cachekeep",df=3600000,pf=300000,CD=60000,Gm="extended-cache-ttl-2025-04-11",MD=32,c_=16777216,LD=2*df,AD="## Claude Cache Keep Status",UD="## Claude Cache Keep Enabled",OD="## Claude Cache Keep Disabled",SD="## Claude Cache Keep Usage",HD="Usage: `/claude-cachekeep`, `/claude-cachekeep off`, or `/claude-cachekeep HH-HH`.";function Nf(f){return String(f).padStart(2,"0")}function ND(f){let _=f.trim();if(!_)return{type:"status"};if(_==="off")return{type:"disable"};let E=/^(\d{1,2})-(\d{1,2})$/.exec(_);if(!E)return{type:"usage"};let D=Number(E[1]),m=Number(E[2]);if(!Number.isInteger(D)||!Number.isInteger(m)||D<0||D>23||m<0||m>23||D===m)return{type:"usage"};return{type:"window",startHour:D,endHour:m}}function uf(f){let _=Number(f?.cacheKeep?.startHour),E=Number(f?.cacheKeep?.endHour);if(!Number.isInteger(_)||!Number.isInteger(E)||_<0||_>23||E<0||E>23||_===E)return;return{startHour:_,endHour:E}}function a_(f){return f?.cacheKeep?.enabled===!0&&!!uf(f)}function bD(f){return a_(f)&&f?.claudeCache?.enabled===!0&&f.claudeCache.mode==="hybrid"}function t_(f,_=new Date){if(!f)return!1;let E=_.getHours();if(f.startHour<f.endHour)return E>=f.startHour&&E<f.endHour;return E>=f.startHour||E<f.endHour}function o_(f=new Date){return`${f.getFullYear()}-${Nf(f.getMonth()+1)}-${Nf(f.getDate())}`}function vf(f,_=new Date){if(f&&f.startHour>f.endHour&&_.getHours()<f.endHour){let E=new Date(_);return E.setDate(E.getDate()-1),o_(E)}return o_(_)}function Hf(f){let _=f.window?`${Nf(f.window.startHour)}-${Nf(f.window.endHour)}`:"not configured",E=[`Cache keep: ${f.enabled?"enabled":"disabled"}`,`Window: ${_}`,"Mode requirement: `/claude-cache mode hybrid` must be active."];if(typeof f.hybridActive==="boolean")E.push(`Hybrid active: ${f.hybridActive?"yes":"no"}`);if(typeof f.trackedSessions==="number")E.push(`Tracked sessions: ${f.trackedSessions}`);if(f.nextPrewarmAt)E.push(`Next prewarm: ${new Date(f.nextPrewarmAt).toLocaleString()}`);return E.join(`
|
|
13
|
-
`)}function
|
|
10
|
+
`);if(_.type==="mode")return[l_,"",`Mode updated to \`${_.mode}\`.`,"",_f({enabled:E,mode:_.mode})].join(`
|
|
11
|
+
`);return[TE,"",qE,"",_f({enabled:E,mode:D})].join(`
|
|
12
|
+
`)}import{randomBytes as iE,randomUUID as v_}from"node:crypto";var yE=1000,l=new Map;function Ef(f,_,E){if(!f.has(_)&&f.size>=yE){let D=f.keys().next().value;if(D!==void 0)f.delete(D)}f.set(_,E)}function d_(f){let _=f||"anonymous",E=l.get(_);if(E)return E;let D={deviceId:iE(32).toString("hex"),sessionId:v_()};return Ef(l,_,D),D}var lE=86400000,kE=300000,yf=new Map,k_=new Map;async function pE(f,_){if(!f.startsWith("sk-ant-oat"))return null;let E=new AbortController,D=setTimeout(()=>E.abort(),5000);try{let m=new URL("https://api.anthropic.com/api/claude_cli/bootstrap");if(m.searchParams.set("entrypoint",M_),_)m.searchParams.set("model",_);let $=await fetch(m,{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/${T}`},signal:E.signal});if(!$.ok)return null;let M=(await $.json().catch(()=>null))?.oauth_account?.account_uuid;return typeof M==="string"&&M?M:null}catch{return null}finally{clearTimeout(D)}}async function M1(f,_){let E=d_(f);if(!f.startsWith("sk-ant-oat"))return E;let D=Date.now(),m=k_.get(f);if(m&&m.expiresAt>D){if(!m.accountUuid)return E;let A=`account:${m.accountUuid}`,U=l.get(A);if(U)return Ef(l,f,U),U}let $=yf.get(f);if(!$)$=pE(f,_),yf.set(f,$);let C=await $.finally(()=>{yf.delete(f)});if(Ef(k_,f,{accountUuid:C,expiresAt:D+(C?lE:kE)}),!C)return E;let M=`account:${C}`,L=l.get(M);if(L)return Ef(l,f,L),L;return E.accountUuid=C,Ef(l,M,E),E}function k(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function vE(f){if(!f.accountUuid)return null;return JSON.stringify({device_id:f.deviceId,account_uuid:f.accountUuid,session_id:f.sessionId})}function L1(f,_){let E=vE(_);if(!E){if(k(f.metadata))delete f.metadata.user_id;return!1}if(!k(f.metadata))f.metadata={};let D=f.metadata;if(k(D))D.user_id=E;return!0}var dE=["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"],uE=["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"],p_=["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 gE(f){return f.output_config?.format?.type==="json_schema"}function nE(f){return Array.isArray(f.tools)&&f.tools.length>0&&Array.isArray(f.system)&&k(f.thinking)&&k(f.context_management)&&k(f.output_config)&&k(f.diagnostics)}function rE(f,_=[]){let E=f?nE(f)?[...dE]:gE(f)?[...uE]:[...p_]:[...p_];if(f?.speed==="fast")E.push(C_);for(let D of _){let m=D.trim();if(m)E.push(m)}return[...new Set(E)].join(",")}function sE(){switch(process.platform){case"darwin":return"MacOS";case"win32":return"Windows";case"linux":return"Linux";case"freebsd":return"FreeBSD";default:return"Unknown"}}function cE(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";case"ia32":return"x32";default:return process.arch}}function A1(f,_,E={}){let D=E.identity??d_(_),$=[...(f.get("anthropic-beta")??"").split(",").map((C)=>C.trim()).filter(Boolean),...E.extraBetas??[]];return f.set("accept","application/json"),f.set("authorization",`Bearer ${_}`),f.set("content-type","application/json"),f.set("user-agent",U_),f.set("anthropic-beta",rE(E.body,$)),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",v_()),f.set("x-claude-code-session-id",D.sessionId),f.set("x-stainless-arch",cE()),f.set("x-stainless-lang","js"),f.set("x-stainless-os",sE()),f.set("x-stainless-package-version",L_),f.set("x-stainless-retry-count","0"),f.set("x-stainless-runtime","node"),f.set("x-stainless-runtime-version",A_),f.set("x-stainless-timeout","600"),f.delete("x-api-key"),f}var tE=["model","messages","system","tools","tool_choice","metadata","max_tokens","temperature","thinking","context_management","output_config","diagnostics","stream","speed"];function u_(f){let _={};for(let E of tE)if(Object.hasOwn(f,E))_[E]=f[E];for(let[E,D]of Object.entries(f))if(!Object.hasOwn(_,E))_[E]=D;return _}import{createHash as aE}from"node:crypto";var oE=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 g_(){return function(f){let{exports:{mem:_,xxh32:E,xxh64:D,init32:m,update32:$,digest32:C,init64:M,update64:L,digest64:A}}=f,U=new Uint8Array(_.buffer);function N(O,G){if(_.buffer.byteLength<O+G){let zf=Math.ceil((O+G-_.buffer.byteLength)/65536);_.grow(zf),U=new Uint8Array(_.buffer)}}function K(O,G,zf,z0,J0,Y0){N(O);let c=new Uint8Array(O);return U.set(c),zf(0,G),c.set(U.subarray(0,O)),{update(g){let Jf;return U.set(c),typeof g=="string"?(N(3*g.length,O),Jf=S.encodeInto(g,U.subarray(O)).written):(N(g.byteLength,O),U.set(g,O),Jf=g.byteLength),z0(0,O,Jf),c.set(U.subarray(0,O)),this},digest:()=>(U.set(c),Y0(J0(0)))}}function j(O){return O>>>0}let R=2n**64n-1n;function J(O){return O&R}let S=new TextEncoder,v=0,d=0n;function u(O,G=v){return N(3*O.length,0),j(E(0,S.encodeInto(O,U).written,G))}function mf(O,G=d){return N(3*O.length,0),J(D(0,S.encodeInto(O,U).written,G))}return{h32:u,h32ToString:(O,G=v)=>u(O,G).toString(16).padStart(8,"0"),h32Raw:(O,G=v)=>(N(O.byteLength,0),U.set(O),j(E(0,O.byteLength,G))),create32:(O=v)=>K(48,O,m,$,C,j),h64:mf,h64ToString:(O,G=d)=>mf(O,G).toString(16).padStart(16,"0"),h64Raw:(O,G=d)=>(N(O.byteLength,0),U.set(O),J(D(0,O.byteLength,G))),create64:(O=d)=>K(88,O,M,L,A,J)}}((await WebAssembly.instantiate(oE)).instance)}var eE=0x6e52736ac806831en,fD="cch=00000;";var kf=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=([0-9a-f]{5});/,_D=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=00000;/,n_=null,lf=null;async function ED(){if(lf)return;n_??=(async()=>{lf=(await g_()).h64Raw})(),await n_}async function DD(f){return await ED(),((lf?.(f,eE)??0n)&0xfffffn).toString(16).padStart(5,"0")}function mD(f){return f.replace(kf,`$1${fD}`)}function r_(f){return kf.exec(f)?.[2]??null}async function s_(f){if(!kf.test(f))return f;let _=mD(f),E=await DD(new TextEncoder().encode(_));return _.replace(_D,`$1cch=${E};`)}function $D(f=T,_=new Date){if(f===T)return Xf;return aE("sha256").update(f).digest("hex").slice(0,3)}function F1(f,_=T,E,D=new Date){let m=$D(_,D);return`x-anthropic-billing-header: cc_version=${_}.${m}; cc_entrypoint=${E}; cch=00000;`}var j1="claude-cachekeep",df=3600000,pf=300000,CD=60000,G1="extended-cache-ttl-2025-04-11",MD=32,c_=16777216,LD=2*df,AD="## Claude Cache Keep Status",UD="## Claude Cache Keep Enabled",OD="## Claude Cache Keep Disabled",SD="## Claude Cache Keep Usage",HD="Usage: `/claude-cachekeep`, `/claude-cachekeep off`, or `/claude-cachekeep HH-HH`.";function Nf(f){return String(f).padStart(2,"0")}function ND(f){let _=f.trim();if(!_)return{type:"status"};if(_==="off")return{type:"disable"};let E=/^(\d{1,2})-(\d{1,2})$/.exec(_);if(!E)return{type:"usage"};let D=Number(E[1]),m=Number(E[2]);if(!Number.isInteger(D)||!Number.isInteger(m)||D<0||D>23||m<0||m>23||D===m)return{type:"usage"};return{type:"window",startHour:D,endHour:m}}function uf(f){let _=Number(f?.cacheKeep?.startHour),E=Number(f?.cacheKeep?.endHour);if(!Number.isInteger(_)||!Number.isInteger(E)||_<0||_>23||E<0||E>23||_===E)return;return{startHour:_,endHour:E}}function a_(f){return f?.cacheKeep?.enabled===!0&&!!uf(f)}function FD(f){return a_(f)&&f?.claudeCache?.enabled===!0&&f.claudeCache.mode==="hybrid"}function t_(f,_=new Date){if(!f)return!1;let E=_.getHours();if(f.startHour<f.endHour)return E>=f.startHour&&E<f.endHour;return E>=f.startHour||E<f.endHour}function o_(f=new Date){return`${f.getFullYear()}-${Nf(f.getMonth()+1)}-${Nf(f.getDate())}`}function vf(f,_=new Date){if(f&&f.startHour>f.endHour&&_.getHours()<f.endHour){let E=new Date(_);return E.setDate(E.getDate()-1),o_(E)}return o_(_)}function Hf(f){let _=f.window?`${Nf(f.window.startHour)}-${Nf(f.window.endHour)}`:"not configured",E=[`Cache keep: ${f.enabled?"enabled":"disabled"}`,`Window: ${_}`,"Mode requirement: `/claude-cache mode hybrid` must be active."];if(typeof f.hybridActive==="boolean")E.push(`Hybrid active: ${f.hybridActive?"yes":"no"}`);if(typeof f.trackedSessions==="number")E.push(`Tracked sessions: ${f.trackedSessions}`);if(f.nextPrewarmAt)E.push(`Next prewarm: ${new Date(f.nextPrewarmAt).toLocaleString()}`);return E.join(`
|
|
13
|
+
`)}function z1(f){let _=ND(f.argumentsText),E={enabled:f.enabled??!1,window:f.window,trackedSessions:f.trackedSessions,nextPrewarmAt:f.nextPrewarmAt,hybridActive:f.hybridActive};if(_.type==="status")return[AD,"",Hf(E)].join(`
|
|
14
14
|
`);if(_.type==="disable")return[OD,"",Hf({...E,enabled:!1})].join(`
|
|
15
15
|
`);if(_.type==="window")return[UD,"",Hf({...E,enabled:!0,window:{startHour:_.startHour,endHour:_.endHour}})].join(`
|
|
16
16
|
`);return[SD,"",HD,"",Hf(E)].join(`
|
|
17
|
-
`)}function gf(f){if(!f||typeof f!=="object")return!1;if(Array.isArray(f))return f.some(gf);let _=f,E=_.cache_control;if(E&&typeof E==="object"&&E.type==="ephemeral")return!0;return Object.values(_).some(gf)}async function
|
|
18
|
-
`)}function
|
|
19
|
-
`);if(_.type==="disable")return[YD,"",
|
|
20
|
-
`);return[WD,"",XD,"",
|
|
21
|
-
`)}function f0(f){return f.length<=16?f:`${f.slice(0,12)}…`}function xD(f){let _=f.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!_)return"session-unknown";return _.length<=80?_:_.slice(0,80)}function D0(f){return KD("sha256").update(f).digest("hex")}function QD(f){return r_(f)}function ID(f,_){if(f==null)return null;if(f===_)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:f.length,currentBytes:_.length};let E=0;while(E<f.length&&E<_.length&&f[E]===_[E])E+=1;let D=f.length-1,m=_.length-1;while(D>=E&&m>=E&&f[D]===_[m])D-=1,m-=1;return{changed:!0,firstByte:E,lastPreviousByte:D,lastCurrentByte:m,changedPreviousBytes:D-E+1,changedCurrentBytes:m-E+1,previousBytes:f.length,currentBytes:_.length}}function PD(f){try{let _=JSON.parse(f);return _!=null&&typeof _==="object"&&!Array.isArray(_)?_:null}catch(_){return
|
|
17
|
+
`)}function gf(f){if(!f||typeof f!=="object")return!1;if(Array.isArray(f))return f.some(gf);let _=f,E=_.cache_control;if(E&&typeof E==="object"&&E.type==="ephemeral")return!0;return Object.values(_).some(gf)}async function bD(f){let _;try{_=JSON.parse(f)}catch{return{ok:!1,reason:"body is not valid JSON"}}if(!gf(_))return{ok:!1,reason:"body has no explicit cache breakpoints"};let E=structuredClone(_);if(E.max_tokens=0,delete E.stream,E.thinking?.type==="enabled")delete E.thinking;if(E.output_config?.format)delete E.output_config;let $=E.tool_choice;if($?.type==="tool"||$?.type==="any")delete E.tool_choice;return{ok:!0,bodyText:await s_(JSON.stringify(u_(E)))}}class BD{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)})})},CD),"unref"in this.timer)this.timer.unref()}stop(){if(this.timer)clearInterval(this.timer);this.timer=null}stats(f,_=this.options.now?.()??Date.now()){let E=vf(f,new Date(_)),D=[...this.targets.values()].filter(($)=>$.dayKey===E),m=D.length?Math.min(...D.map(($)=>$.cacheExpiresAt-pf)):void 0;return{trackedSessions:D.length,nextPrewarmAt:m}}trackedCount(){return this.targets.size}totalBodyBytes(){return[...this.targets.values()].reduce((f,_)=>f+_.bodyText.length,0)}evictOldestTarget(){let f=this.targets.keys().next().value;if(f!==void 0)this.targets.delete(f)}pruneTargets(f,_){for(let[E,D]of this.targets){if(_&&D.dayKey!==_){this.targets.delete(E);continue}if(f-D.cacheExpiresAt>LD)this.targets.delete(E)}while(this.targets.size>MD)this.evictOldestTarget();while(this.totalBodyBytes()>c_){let E=this.targets.size;if(this.evictOldestTarget(),this.targets.size===E)break}}track(f){if(!f.sessionId)return{tracked:!1,reason:"missing session id"};if(!a_(f.storage))return{tracked:!1,reason:"cachekeep disabled"};if(f.cacheMode!=="hybrid")return{tracked:!1,reason:"cache mode is not hybrid"};if(f.bodyText.length>c_)return{tracked:!1,reason:"body exceeds cachekeep memory budget"};let _=this.options.now?.()??Date.now(),E=uf(f.storage);if(!t_(E,new Date(_)))return{tracked:!1,reason:"outside configured window"};let D=vf(E,new Date(_));if(this.pruneTargets(_,D),this.targets.has(f.sessionId))this.targets.delete(f.sessionId);let m={};return f.headers.forEach(($,C)=>{m[C]=$}),this.targets.set(f.sessionId,{id:f.sessionId,url:f.url,headers:m,bodyText:f.bodyText,cacheExpiresAt:_+df,dayKey:D}),this.pruneTargets(_,D),this.start(),{tracked:!0}}async tick(){let f=await this.options.loadStorage(),_=uf(f),E=this.options.now?.()??Date.now(),D=vf(_,new Date(E));if(this.pruneTargets(E,D),!this.targets.size){this.stop();return}if(!FD(f))return;if(!t_(_,new Date(E)))return;let m=E+pf;for(let $ of this.targets.values()){if($.cacheExpiresAt>m)continue;await this.prewarm($,E)}}async prewarm(f,_){let E=await bD(f.bodyText);if(!E.ok){this.options.log?.("[cachekeep] prewarm skipped",{session:f.id,reason:E.reason}),this.targets.delete(f.id);return}let D=this.options.fetchImpl??fetch,m={...f,bodyText:E.bodyText},$=this.options.prepareHeaders?await this.options.prepareHeaders(new Headers(f.headers),m):new Headers(f.headers);$.delete("content-length"),$.delete("transfer-encoding");let C=await D(f.url,{method:"POST",headers:$,body:E.bodyText});if(!C.ok){this.options.log?.("[cachekeep] prewarm failed",{session:f.id,status:C.status,body:await C.text().catch(()=>"")}),f.cacheExpiresAt=_+pf+300000;return}await C.body?.cancel().catch(()=>{}),f.cacheExpiresAt=_+df,this.options.log?.("[cachekeep] prewarm succeeded",{session:f.id})}}import{createHash as KD}from"node:crypto";import{mkdir as jD,writeFile as nf}from"node:fs/promises";import{tmpdir as GD}from"node:os";import{join as _0}from"node:path";var x1="claude-dump",zD="## Claude Dump Status",JD="## Claude Dump Enabled",YD="## Claude Dump Disabled",WD="## Claude Dump Usage",XD="Usage: `/claude-dump`, `/claude-dump on`, or `/claude-dump off`.",ZD="OPENCODE_ANTHROPIC_AUTH_DUMP_DIR",hD=_0(GD(),"opencode-anthropic-auth-dumps"),bf=!1,e_=0;function Q1(f){bf=f}function E0(){return process.env[ZD]||hD}function VD(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&_[0]==="on")return{type:"enable"};if(_.length===1&&_[0]==="off")return{type:"disable"};return{type:"usage"}}function Ff(f){let _=f?.enabled??bf;return[zD,"",`- Enabled: ${_?"enabled":"disabled"}`,`- Directory: ${E0()}`,"- 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 I1(f){let _=VD(f.argumentsText),E=f.enabled??bf;if(_.type==="status")return Ff({enabled:E});if(_.type==="enable")return[JD,"",Ff({enabled:!0})].join(`
|
|
19
|
+
`);if(_.type==="disable")return[YD,"",Ff({enabled:!1})].join(`
|
|
20
|
+
`);return[WD,"",XD,"",Ff({enabled:E})].join(`
|
|
21
|
+
`)}function f0(f){return f.length<=16?f:`${f.slice(0,12)}…`}function xD(f){let _=f.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!_)return"session-unknown";return _.length<=80?_:_.slice(0,80)}function D0(f){return KD("sha256").update(f).digest("hex")}function QD(f){return r_(f)}function ID(f,_){if(f==null)return null;if(f===_)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:f.length,currentBytes:_.length};let E=0;while(E<f.length&&E<_.length&&f[E]===_[E])E+=1;let D=f.length-1,m=_.length-1;while(D>=E&&m>=E&&f[D]===_[m])D-=1,m-=1;return{changed:!0,firstByte:E,lastPreviousByte:D,lastCurrentByte:m,changedPreviousBytes:D-E+1,changedCurrentBytes:m-E+1,previousBytes:f.length,currentBytes:_.length}}function PD(f){try{let _=JSON.parse(f);return _!=null&&typeof _==="object"&&!Array.isArray(_)?_:null}catch(_){return F(`dump body parse failed: ${_ instanceof Error?_.message:String(_)}`),null}}function rf(f){return D0(JSON.stringify(f))}function RD(f){let _=PD(f);if(!_)return{parseable:!1};let E=Array.isArray(_.messages)?_.messages:[],D=Array.isArray(_.system)?_.system:[],m=E[0],$=E.slice(1);return{parseable:!0,model:typeof _.model==="string"?_.model:void 0,stream:_.stream,systemCount:D.length,messagesCount:E.length,systemHash:rf(D),message0Hash:m===void 0?null:rf(m),message0Bytes:m===void 0?0:JSON.stringify(m).length,messagesAfter0Hash:rf($),messagesAfter0Bytes:JSON.stringify($).length,cch:QD(f)}}function sf(f){if(Array.isArray(f))return f.map(sf);if(f==null||typeof f!=="object")return f;let _={};for(let[E,D]of Object.entries(f)){let m=E.toLowerCase();if(m==="authorization"||m==="x-api-key"||m==="cookie"||m==="set-cookie"){_[E]="[redacted]";continue}_[E]=sf(D)}return _}async function m0(f){if(!bf)return;e_+=1;let _=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(e_).padStart(5,"0")}-${xD(f.affinity)}-${f.transport}-p${f.protocol}-${f.mode}`,E=E0(),D=_0(E,_);try{await jD(E,{recursive:!0});let m={id:_,createdAt:new Date().toISOString(),session:f0(f.affinity),transport:f.transport,protocol:f.protocol,mode:f.mode,status:f.status,bodyBytes:f.bodyText.length,relayBytes:f.relayBytes,bodyHash:D0(f.bodyText),diff:ID(f.previousBodyText,f.bodyText),body:RD(f.bodyText),files:{body:`${D}.body.json`,relay:`${D}.relay.json`,metadata:`${D}.meta.json`}};await Promise.all([nf(`${D}.body.json`,f.bodyText,"utf8"),nf(`${D}.relay.json`,`${JSON.stringify(sf(f.payload),null,2)}
|
|
22
22
|
`,"utf8"),nf(`${D}.meta.json`,`${JSON.stringify(m,null,2)}
|
|
23
|
-
`,"utf8")]),
|
|
24
|
-
`)}function
|
|
23
|
+
`,"utf8")]),F(`dumped request id=${_} session=${f0(f.affinity)} body=${D}.body.json meta=${D}.meta.json`)}catch(m){F(`dump failed: ${m instanceof Error?m.message:String(m)}`)}}var R1="claude-fast";var Kf=!1;function T1(){return Kf}function q1(f){Kf=f}function TD(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&_[0]==="on")return{type:"enable"};if(_.length===1&&_[0]==="off")return{type:"disable"};return{type:"usage"}}function Bf(f){return["## Claude Fast Mode Status","",`- Enabled: ${f?.enabled??Kf?"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 w1(f){let _=TD(f.argumentsText),E=f.enabled??Kf;if(_.type==="status")return Bf({enabled:E});if(_.type==="enable")return["## Claude Fast Mode Enabled","",Bf({enabled:!0})].join(`
|
|
25
25
|
`);if(_.type==="disable")return["## Claude Fast Mode Disabled","",Bf({enabled:!1})].join(`
|
|
26
26
|
`);return["## Claude Fast Mode Usage","","Usage: `/claude-fast`, `/claude-fast on`, or `/claude-fast off`.","",Bf({enabled:E})].join(`
|
|
27
|
-
`)}var Df="claude-killswitch";function
|
|
27
|
+
`)}var Df="claude-killswitch";function qD(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&_[0]==="on")return{type:"on"};if(_.length===1&&_[0]==="off")return{type:"off"};if(_[0]==="set"){let E=[];for(let D=1;D<_.length;D++){let m=_[D]?.match(/^([^:]+):(\d+),(\d+)$/);if(!m)return{type:"usage"};let[,$,C,M]=m;E.push({account:$,fh:Number.parseInt(C,10),sd:Number.parseInt(M,10)})}if(E.length===0)return{type:"usage"};return{type:"set",entries:E}}return{type:"usage"}}function jf(f,_){let E=f.enabled===!0,D=["## Killswitch","",`Status: **${E?"ON":"OFF"}**`];if(E){D.push(""),D.push("| Account | 5h threshold | 1w threshold |"),D.push("| ------- | ------------ | ------------ |");let m=f.main??{},$=m.five_hour??m["5h"]??Z.five_hour,C=m.seven_day??m["1w"]??Z.seven_day;D.push(`| main | ≥ ${$}% | ≥ ${C}% |`);for(let M of _){let L=f.accounts?.[M]??f.main??{},A=L.five_hour??L["5h"]??Z.five_hour,U=L.seven_day??L["1w"]??Z.seven_day;D.push(`| ${M} | ≥ ${A}% | ≥ ${U}% |`)}}return D.join(`
|
|
28
28
|
`)}var $0=["## Killswitch Commands","","```",`/${Df} — show status`,`/${Df} on — enable with current or default thresholds`,`/${Df} off — disable`,`/${Df} set all:5,10 — set all accounts to 5h≥5%, 1w≥10%`,`/${Df} set main:3,8 work-alt:5,10 — per-account`,"```"].join(`
|
|
29
|
-
`);function
|
|
29
|
+
`);function l1(f){let _=qD(f.argumentsText);if(_.type==="status")return{text:`${jf(f.config,f.accountIds)}
|
|
30
30
|
|
|
31
31
|
${$0}`};if(_.type==="on"){let D={...f.config,enabled:!0,main:f.config.main??{five_hour:Z.five_hour,seven_day:Z.seven_day}};return{text:`## Killswitch Enabled
|
|
32
32
|
|
|
@@ -34,15 +34,15 @@ ${jf(D,f.accountIds)}`,updatedConfig:D}}if(_.type==="off")return{text:"## Killsw
|
|
|
34
34
|
|
|
35
35
|
${jf(m,f.accountIds)}`,updatedConfig:m}}return{text:`${jf(f.config,f.accountIds)}
|
|
36
36
|
|
|
37
|
-
${$0}`}}var wD=["claude-fable-5","claude-mythos-5"],
|
|
37
|
+
${$0}`}}var wD=["claude-fable-5","claude-mythos-5"],p1={type:"adaptive",display:"summarized"},v1={input:10,output:50,cacheRead:1,cacheWrite5m:12.5,cacheWrite1h:20},d1=1e6,u1=128000,g1="2026-06-09",n1={["claude-fable-5"]:{id:"claude-fable-5",name:"Claude Fable 5"},["claude-mythos-5"]:{id:"claude-mythos-5",name:"Claude Mythos 5",limited:!0}};function r1(f){return typeof f==="string"&&wD.some((_)=>f===_||f.startsWith(`${_}-`))}import{createHash as iD}from"node:crypto";var yD=globalThis.setTimeout;function I(f){return iD("sha256").update(f).digest("hex").slice(0,16)}class w{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 _=T_(f.storage);if(_)this.main={quota:_.quota,refreshAfter:wf(_.quota,f.storage,_.checkedAt),checkedAt:_.checkedAt},this.mainTokenFp=_.tokenFingerprint??null;let E=f.storage?.quota?.mainLastQuotaApiError;if(E&&r(E,this.now()))this.mainLastApiError=E}getMain(f){if(f&&this.main&&this.mainTokenFp&&this.mainTokenFp!==I(f))this.main=null,this.mainTokenFp=null;return this.main}getFallback(f,_){let E=this.fallbacks.get(f)??null;if(!_||!E)return E;if(this.fallbackTokenFps.get(f)!==I(_))return this.fallbacks.delete(f),this.fallbackTokenFps.delete(f),null;return E}getAllFallbacks(){return this.fallbacks}setMain(f,_){this.mainTokenFp=I(f),this.main=_}setFallback(f,_,E){if(this.fallbacks.set(f,_),E)this.fallbackTokenFps.set(f,I(E));else this.fallbackTokenFps.delete(f)}async refreshMain(f){let _=I(f);if(this.mainTokenFp&&this.mainTokenFp!==_)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,_){let E=w.fallbackInflightKey(f,_),D=this.inflightFallbacks.get(E);if(D)return D;if(this.isFallbackBackedOff(f,_)){let $=this.getFallback(f,_);if($)return $.quota;throw Error("Quota API rate-limited — try again later")}let m=this._fetchFallback(f,_);return this.inflightFallbacks.set(E,m),m}async refreshAllFallbacks(f){let _=this.now();for(let E of f){if(E.enabled===!1)continue;if(!E.access)continue;let D=this.getFallback(E.id,E.access);if(D&&_<D.refreshAfter)continue;try{await this.refreshFallback(E.id,E.access)}catch{}}}refreshMainInBackground(f){if(this.inflightMain)return;if(this.isBackedOff())return;this.refreshMain(f).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale(f,_){let E=this.getFallback(f,_);if(!E)return!0;return this.now()>=E.refreshAfter}shouldRefreshOnRequestCount(f){let _=q_(this.storage);if(_<=0)return!1;return f>0&&f%_===0}needsRefresh(f){return this.isMainStale()||this.shouldRefreshOnRequestCount(f)}updateStorage(f){this.storage=f}seedFallbacksFromAccounts(f){let _=X(this.storage);for(let E of f){if(E.enabled===!1)continue;if(this.getFallback(E.id,E.access))continue;if(!E.quota)continue;let D=Math.max(E.quota.five_hour?.checkedAt??0,E.quota.seven_day?.checkedAt??0);if(D<=0)continue;this.setFallback(E.id,{quota:E.quota,refreshAfter:D+_,checkedAt:D},E.access)}}isBackedOff(){return r(this.mainLastApiError,this.now())}isFallbackBackedOff(f,_){if(_){if(this.fallbackErrorTokenFps.get(f)!==I(_))return!1}return r(this.fallbackApiErrors.get(f),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(f,_){return JSON.stringify([f,I(_)])}static quotaLockName(f){return`opencode-fallback-quota-refresh-${f.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch(f){let _=async()=>{let D=this.now()-this.lastApiCallAt;if(D<w.API_CALL_GAP_MS)await new Promise((m)=>{let $=yD(m,w.API_CALL_GAP_MS-D);if(typeof $==="object"&&"unref"in $)$.unref()});return this.lastApiCallAt=this.now(),f()},E=this.apiGate.then(_,_);return this.apiGate=E.catch(()=>{}),E}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 _=await Lf({name:"opencode-main-quota-refresh",ttlMs:30000});if(!_){if(this.main)return this.main.quota;throw Error("Quota refresh is already in progress")}try{let E=await Uf({accessToken:f,fetchImpl:this.fetchImpl,now:this.now}),D=this.now();return this.mainTokenFp=I(f),this.main={quota:E,refreshAfter:wf(E,this.storage,D),checkedAt:D},this.mainLastApiError=void 0,this.onMainQuotaFetched?.(E,D,this.mainTokenFp),E}catch(E){throw this._handleMainFetchError(E),E}finally{await _.release()}}finally{this.inflightMain=null}})}async _fetchFallback(f,_){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff(f,_)){let D=this.getFallback(f,_);if(D)return D.quota;throw Error("Quota API rate-limited — try again later")}let E=await Lf({name:w.quotaLockName(f),ttlMs:30000});if(!E){let D=this.getFallback(f,_);if(D)return D.quota;throw Error("Quota refresh is already in progress")}try{let D=await Uf({accessToken:_,fetchImpl:this.fetchImpl,now:this.now}),m=this.now();return this.setFallback(f,{quota:D,refreshAfter:m+X(this.storage),checkedAt:m},_),this.fallbackApiErrors.delete(f),this.fallbackErrorTokenFps.delete(f),D}finally{await E.release()}}catch(E){throw this._handleFallbackFetchError(f,_,E),E}finally{this.inflightFallbacks.delete(w.fallbackInflightKey(f,_))}})}static isAuthError(f){let _=f instanceof Error?f.message:String(f);return/quota check failed: 401\b/.test(_)}_handleMainFetchError(f){if(w.isAuthError(f))return;this.mainLastApiError=Af({error:f,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(f,_,E){if(w.isAuthError(E))return;let D=I(_),m=this.fallbackErrorTokenFps.get(f)===D?this.fallbackApiErrors.get(f):void 0;this.fallbackApiErrors.set(f,Af({error:E,now:this.now(),previous:m})),this.fallbackErrorTokenFps.set(f,D)}}var e1="claude-quota",C0={five_hour:"5h",seven_day:"1w"};function M0(f){return`${Math.round(f*10)/10}%`}function cf(f,_){let E=Math.max(0,_-f),D=Math.floor(E/60000);if(D<1)return"just now";if(D===1)return"1m ago";if(D<60)return`${D}m ago`;let m=Math.floor(D/60),$=D%60;if($===0)return`${m}h ago`;return`${m}h ${$}m ago`}function lD(f,_){let E=Date.parse(f);if(!Number.isFinite(E))return f;let D=E-_;if(D<=0)return"now";let m=Math.max(1,Math.ceil(D/60000));if(m<60)return`in ${m}m`;let $=Math.floor(m/60),C=m%60;if(C===0)return`in ${$}h`;return`in ${$}h ${C}m`}function kD(f,_){if(!f)return"";return`, resets ${lD(f,_)}`}function L0(f,_,E){if(!_)return` - ${C0[f]}: unknown`;return[` - ${C0[f]}: ${M0(_.remainingPercent)} remaining`,` (${M0(_.usedPercent)} used`,`${kD(_.resetsAt,E)}, checked ${cf(_.checkedAt,E)})`].join("")}function pD(f){return f.label?.trim()||f.id}function vD(f){return f.lastQuotaRefreshError?.message??f.lastRefreshError?.message}function f$(f,_=new Map){if(!f?.accounts.length)return[];return f.accounts.filter(x).map((E)=>{let D=_.get(E.id)??vD(E);return{name:pD(E),role:"fallback",enabled:E.enabled!==!1,quota:E.quota,lastRefreshedAt:E.lastRefreshedAt,...D&&{error:D}}})}function _$(f){let _=f.now??Date.now(),E=["## Claude Quotas",""];if(f.refreshedAt)E.push(`Refreshed: ${cf(f.refreshedAt,_)}`,"");if(!f.accounts.length)return E.push("No Claude OAuth accounts found yet."),E.join(`
|
|
38
38
|
`);for(let D of f.accounts){let m=D.role==="main"?"main":"fallback",$=D.enabled===!1?" disabled":"";if(E.push(`### ${D.name} (${m}${$})`),D.lastRefreshedAt)E.push(` - Last token refresh: ${cf(D.lastRefreshedAt,_)}`);if(D.error)E.push(` - Error: ${D.error}`);E.push(L0("five_hour",D.quota?.five_hour,_)),E.push(L0("seven_day",D.quota?.seven_day,_)),E.push("")}return E.join(`
|
|
39
|
-
`).trimEnd()}import{Buffer as F0}from"node:buffer";import{createHash as dD,randomBytes as uD}from"node:crypto";class of extends Error{}class af extends Error{code="ECONNRESET";syscall="websocket";closeCode;closeReason;wasClean;constructor(f,_){super(f);this.name="RelayWebSocketConnectionResetError",this.closeCode=_?.code,this.closeReason=_?.reason,this.wasClean=_?.wasClean}}var P=new Map,p=new Map,A0=new Set,gD=7200000,nD=1800000,rD=128,sD=32,U0=0;function tf(){return U0+=1,`req_${Date.now().toString(36)}_${U0.toString(36)}`}function Gf(f){if(A0.has(f))return;A0.add(f),b(f)}function C$(f){let _=f?.relay;if(!_)return Gf("disabled: no relay config found"),null;if(_.enabled!==!0)return Gf("disabled: relay.enabled is not true"),null;if(!_.url?.trim()||!_.token?.trim())return Gf("disabled: missing relay url or token"),null;let E=_.transport==="http"?"http":"websocket";return Gf(`configured transport=${E} protocol=${E==="websocket"?2:1} url=${_.url.trim()} fallbackToDirect=${_.fallbackToDirect!==!1}`),{enabled:!0,url:_.url.trim(),token:_.token.trim(),fallbackToDirect:_.fallbackToDirect!==!1,transport:E}}function M$(){return uD(32).toString("base64url")}function cD(f){return`sha256:${dD("sha256").update(f).digest("hex")}`}function O0(f,_){let E=0,D=Math.min(f.length,_.length);while(E<D&&f.charCodeAt(E)===_.charCodeAt(E))E++;let m=f.length,$=_.length;while(m>E&&$>E&&f.charCodeAt(m-1)===_.charCodeAt($-1))m--,$--;return{start:E,deleteCount:m-E,insert:_.slice(E,$)}}function tD(f){return f.deleteCount===0&&f.insert.length===0}function S0(f){let _=f.match(/\bcch=([0-9a-f]{5});/),E=_?.[1];if(!E||_.index==null)return null;let D=_.index+4;return{start:D,end:D+E.length,token:E}}function oD(f,_,E,D){return`${f.slice(0,_)}${D}${f.slice(E)}`}function B0(f,_){let E=S0(f),D=S0(_);if(E&&D&&E.start===D.start&&E.end-E.start===D.end-D.start&&E.token!==D.token){let m={start:E.start,deleteCount:E.end-E.start,insert:D.token},$=oD(f,E.start,E.end,D.token),C=O0($,_);return tD(C)?m:[m,C]}return O0(f,_)}function aD(f,_){if(typeof _!=="string")return!1;try{let E=f instanceof Request?new URL(f.url):new URL(f.toString());return E.pathname==="/v1/messages"||E.pathname==="/messages"}catch{return!1}}function eD(f){let _={};for(let[E,D]of f.entries()){if(E==="x-session-affinity"||E==="x-opencode-session")continue;_[E]=D}return _}async function H0(f,_,E){let D=F(),m=JSON.stringify(_);return s("http_payload_stringify",{session:B(_.affinity),ms:Y(F()-D),relayBytes:m.length,mode:_.mode}),fetch(f.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":f.token},body:m,signal:E??void 0})}function B(f){return f.length>12?`${f.slice(0,12)}…`:f}function F(){return performance.now()}function Y(f){return Math.round(f*10)/10}function f1(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function s(f,_){if(!f1())return;b(`[perf] relay ${f} ${JSON.stringify(_)}`)}function _1(f){let{input:_,init:E,headers:D,bodyText:m,affinity:$,previous:C,nextHash:M}=f,L=_ instanceof Request?_.url:_.toString(),A={protocol:1,type:"request",affinity:$,upstream:{url:L,method:E?.method||(_ instanceof Request?_.method:"POST"),headers:eD(D)},next_hash:M};return C?{...A,mode:"patch",base_hash:C.hash,revision:C.revision+1,patch:B0(C.body,m)}:{...A,mode:"full_sync",revision:1,body:m}}function ef(f,_){return{protocol:f.protocol,type:"request",affinity:f.affinity,upstream:f.upstream,next_hash:f.next_hash,mode:"full_sync",revision:1,body:_}}function K0(f,_,E,D){let m=Date.now();P.delete(f),P.set(f,{body:_,hash:E,revision:D,updatedAt:m}),f_(m)}async function N0(f){let{config:_,payload:E,bodyText:D,fallback:m,signal:$}=f,C=E,M=await H0(_,C,$);if(M.status===409&&C.mode==="patch")b(`state mismatch from relay session=${B(C.affinity)}; retrying full_sync`),await M.body?.cancel().catch(()=>{}),C=ef(C,D),M=await H0(_,C,$);if(!M.ok&&M.status>=500&&_.fallbackToDirect)return b(`relay returned ${M.status}; falling back direct session=${B(C.affinity)}`),await M.body?.cancel().catch(()=>{}),{response:await m(),payload:C,transport:"http",protocol:C.protocol,usedRelay:!1};return{response:M,payload:C,transport:"http",protocol:C.protocol,usedRelay:!0}}function E1(f,_){let E=new URL(f);return E.protocol=E.protocol==="http:"?"ws:":"wss:",E.pathname="/ws",E.searchParams.set("token",_),E.toString()}function D1(f){return new Uint8Array(F0.from(f,"base64"))}function m1(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(F0.from(String(f)))}function $1(f){return JSON.parse(f)}function b0(f){let _=f,E=[`code=${_.code??"unknown"}`,`wasClean=${_.wasClean??"unknown"}`];if(_.reason)E.push(`reason=${JSON.stringify(_.reason)}`);return E.join(" ")}function C1(f){let _=f.message||"relay websocket error";return f.status?`relay websocket error ${f.status}: ${_}`:_}class j0{config;affinity;socket;connecting;queue=Promise.resolve();pending;serverState;lastUsedAt=Date.now();constructor(f,_){this.config=f,this.affinity=_}touch(f=Date.now()){this.lastUsedAt=f}canEvict(f=Date.now()){return!this.pending&&!this.connecting&&f-this.lastUsedAt>nD}dispose(){this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0}send(f,_,E=!1){this.touch();let D=F(),m=this.queue.catch(()=>{}).then(()=>this.startQueued(f,_,D,E)),$=m.then(async({response:C,getPayload:M})=>({response:await C,payload:M(),transport:"websocket",protocol:2,usedRelay:!0}));return this.queue=m.then(({done:C})=>C.catch(()=>{}),()=>{}),$}async startQueued(f,_,E,D){let m=F();await this.ensureConnected();let $=F(),C=P.get(this.affinity),M=this.serverState?.hash,L={...f,protocol:2,id:tf()};if(L.mode==="patch"&&(!M||M!==L.base_hash))L.mode="full_sync",L.revision=(this.serverState?.revision??0)+1,delete L.base_hash,delete L.patch,L.body=_;if(L.mode==="patch"&&C)L.patch=B0(C.body,_);b(`perf websocket send_start session=${B(this.affinity)} request=${L.id} mode=${L.mode} queueMs=${Y($-E)} connectMs=${Y($-m)} bodyBytes=${_.length} relayBytes=${JSON.stringify(L).length}`);let A=L,U=this.sendPayload(L,_,D);U.done.catch(()=>{});let N=U.done,K=U.response.catch((R)=>{if(!(R instanceof of)||L.mode!=="patch")throw R;let J=ef(L,_);J.protocol=2,J.id=tf(),J.revision=(this.serverState?.revision??0)+1,A=J;let S=this.sendPayload(J,_,D);return S.done.catch(()=>{}),N=S.done,S.response}),j=K.then(()=>N,()=>N.catch(()=>{}));return{response:K,done:j,getPayload:()=>A}}async ensureConnected(){if(this.socket?.readyState===WebSocket.OPEN&&this.serverState!==void 0)return;if(this.connecting)return await this.connecting;this.connecting=new Promise((f,_)=>{let E=E1(this.config.url,this.config.token),D=new URL(E);D.searchParams.set("affinity",this.affinity);let m=new WebSocket(D.toString());this.socket=m,this.serverState=void 0;let $=setTimeout(()=>{m.close(),_(Error("relay websocket ready timed out"))},15000);m.addEventListener("message",(C)=>{try{if(typeof C.data!=="string"){this.handleBinaryChunk(C.data);return}let M=$1(C.data);if(M.type==="ready"){clearTimeout($),this.serverState=M.state,f();return}this.handleMessage(M)}catch(M){clearTimeout($),_(M),this.failPending(M),m.close()}}),m.addEventListener("error",()=>{clearTimeout($);let C=new af("relay websocket error");_(C),this.failPending(C)}),m.addEventListener("close",(C)=>{if(clearTimeout($),this.socket===m)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,L=M?"closed after response_start before stream bytes":"closed before response";if(this.retryPendingBeforeResponse(this.pending,L,C))return;let A=M?new af("relay websocket closed during response stream",C):Error("relay websocket closed before response");b(`websocket ${M?"closed during response stream":"closed before response without retry"} session=${B(this.affinity)} request=${this.pending.payload.id} chunks=${this.pending.streamChunkCount} bytes=${this.pending.streamByteCount} ${b0(C)}`),this.failPending(A)}})}).finally(()=>{this.connecting=void 0}),await this.connecting}sendPayload(f,_,E){let D=this.socket;if(!D||D.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");let m=F(),$,C,M=new Promise((A,U)=>{$=A,C=U});return{response:new Promise((A,U)=>{let N={payload:f,bodyText:_,resolve:A,reject:U,streamDone:!1,accepted:!1,responseStarted:!1,resolveDone:$,rejectDone:C,sentAt:m,optimisticResponse:E,streamChunkCount:0,streamByteCount:0,retryAttempts:0,retryingBeforeResponse:!1};if(this.pending=N,this.resetPendingTimeout(N),D.send(JSON.stringify(f)),E)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,_,E){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 D=f.retryAttempts,m=f.payload.id;return b(`websocket ${_}; reconnecting and retrying full_sync session=${B(this.affinity)} request=${m} retry=${D} chunks=${f.streamChunkCount} bytes=${f.streamByteCount}${E?` ${b0(E)}`:""}`),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 $=ef(f.payload,f.bodyText);$.protocol=2,$.id=tf(),$.revision=(this.serverState?.revision??0)+1,f.payload=$,f.accepted=!1,f.acceptedAt=void 0,f.responseStartedAt=void 0,f.sentAt=F(),f.retryingBeforeResponse=!1;let C=this.socket;if(!C||C.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");this.resetPendingTimeout(f),b(`perf websocket retry_send session=${B(this.affinity)} request=${$.id} previous=${m} mode=full_sync retry=${D} bodyBytes=${f.bodyText.length} relayBytes=${JSON.stringify($).length}`),C.send(JSON.stringify($))}catch($){if(f.retryingBeforeResponse=!1,this.pending===f)this.failPending($)}})(),!0}enqueueStreamChunk(f,_){f.streamChunkCount+=1,f.streamByteCount+=_.byteLength,f.streamController?.enqueue(_)}handleBinaryChunk(f){let _=this.pending;if(!_?.responseStarted)return;this.enqueueStreamChunk(_,m1(f))}resolvePendingResponse(f,_,E,D){if(f.responseStarted)return;f.responseStarted=!0;let m=new ReadableStream({start:($)=>{f.streamController=$},cancel:()=>{this.socket?.close()}});f.resolve(new Response(m,{status:_,statusText:E,headers:D}))}handleMessage(f){if(f.type==="keepalive"){if(this.pending)this.resetPendingTimeout(this.pending);return}let _=this.pending;if(!_)return;if("id"in f&&f.id&&f.id!==_.payload.id)return;if(f.type==="accepted"){let E=F();_.accepted=!0,_.acceptedAt=E,b(`perf websocket accepted session=${B(this.affinity)} request=${_.payload.id} sentMs=${Y(E-_.sentAt)} mode=${_.payload.mode}`),this.serverState={hash:f.hash,revision:f.revision},K0(this.affinity,_.bodyText,f.hash,f.revision),this.resetPendingTimeout(_);return}if(f.type==="response_start"){let E=F();if(_.responseStartedAt=E,b(`perf websocket response_start session=${B(this.affinity)} request=${_.payload.id} sentMs=${Y(E-_.sentAt)} upstreamMs=${_.acceptedAt==null?"unknown":Y(E-_.acceptedAt)} status=${f.status}`),clearTimeout(_.timeout),this.resolvePendingResponse(_,f.status,f.statusText,f.headers),_.optimisticResponse&&f.status>=400)_.streamController?.enqueue(new TextEncoder().encode(`event: error
|
|
39
|
+
`).trimEnd()}import{Buffer as b0}from"node:buffer";import{createHash as dD,randomBytes as uD}from"node:crypto";class of extends Error{}class af extends Error{code="ECONNRESET";syscall="websocket";closeCode;closeReason;wasClean;constructor(f,_){super(f);this.name="RelayWebSocketConnectionResetError",this.closeCode=_?.code,this.closeReason=_?.reason,this.wasClean=_?.wasClean}}var P=new Map,p=new Map,A0=new Set,gD=7200000,nD=1800000,rD=128,sD=32,U0=0;function tf(){return U0+=1,`req_${Date.now().toString(36)}_${U0.toString(36)}`}function Gf(f){if(A0.has(f))return;A0.add(f),F(f)}function M$(f){let _=f?.relay;if(!_)return Gf("disabled: no relay config found"),null;if(_.enabled!==!0)return Gf("disabled: relay.enabled is not true"),null;if(!_.url?.trim()||!_.token?.trim())return Gf("disabled: missing relay url or token"),null;let E=_.transport==="http"?"http":"websocket";return Gf(`configured transport=${E} protocol=${E==="websocket"?2:1} url=${_.url.trim()} fallbackToDirect=${_.fallbackToDirect!==!1}`),{enabled:!0,url:_.url.trim(),token:_.token.trim(),fallbackToDirect:_.fallbackToDirect!==!1,transport:E}}function L$(){return uD(32).toString("base64url")}function cD(f){return`sha256:${dD("sha256").update(f).digest("hex")}`}function O0(f,_){let E=0,D=Math.min(f.length,_.length);while(E<D&&f.charCodeAt(E)===_.charCodeAt(E))E++;let m=f.length,$=_.length;while(m>E&&$>E&&f.charCodeAt(m-1)===_.charCodeAt($-1))m--,$--;return{start:E,deleteCount:m-E,insert:_.slice(E,$)}}function tD(f){return f.deleteCount===0&&f.insert.length===0}function S0(f){let _=f.match(/\bcch=([0-9a-f]{5});/),E=_?.[1];if(!E||_.index==null)return null;let D=_.index+4;return{start:D,end:D+E.length,token:E}}function oD(f,_,E,D){return`${f.slice(0,_)}${D}${f.slice(E)}`}function B0(f,_){let E=S0(f),D=S0(_);if(E&&D&&E.start===D.start&&E.end-E.start===D.end-D.start&&E.token!==D.token){let m={start:E.start,deleteCount:E.end-E.start,insert:D.token},$=oD(f,E.start,E.end,D.token),C=O0($,_);return tD(C)?m:[m,C]}return O0(f,_)}function aD(f,_){if(typeof _!=="string")return!1;try{let E=f instanceof Request?new URL(f.url):new URL(f.toString());return E.pathname==="/v1/messages"||E.pathname==="/messages"}catch{return!1}}function eD(f){let _={};for(let[E,D]of f.entries()){if(E==="x-session-affinity"||E==="x-opencode-session")continue;_[E]=D}return _}async function H0(f,_,E){let D=b(),m=JSON.stringify(_);return s("http_payload_stringify",{session:B(_.affinity),ms:Y(b()-D),relayBytes:m.length,mode:_.mode}),fetch(f.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":f.token},body:m,signal:E??void 0})}function B(f){return f.length>12?`${f.slice(0,12)}…`:f}function b(){return performance.now()}function Y(f){return Math.round(f*10)/10}function fm(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function s(f,_){if(!fm())return;F(`[perf] relay ${f} ${JSON.stringify(_)}`)}function _m(f){let{input:_,init:E,headers:D,bodyText:m,affinity:$,previous:C,nextHash:M}=f,L=_ instanceof Request?_.url:_.toString(),A={protocol:1,type:"request",affinity:$,upstream:{url:L,method:E?.method||(_ instanceof Request?_.method:"POST"),headers:eD(D)},next_hash:M};return C?{...A,mode:"patch",base_hash:C.hash,revision:C.revision+1,patch:B0(C.body,m)}:{...A,mode:"full_sync",revision:1,body:m}}function ef(f,_){return{protocol:f.protocol,type:"request",affinity:f.affinity,upstream:f.upstream,next_hash:f.next_hash,mode:"full_sync",revision:1,body:_}}function K0(f,_,E,D){let m=Date.now();P.delete(f),P.set(f,{body:_,hash:E,revision:D,updatedAt:m}),f_(m)}async function N0(f){let{config:_,payload:E,bodyText:D,fallback:m,signal:$}=f,C=E,M=await H0(_,C,$);if(M.status===409&&C.mode==="patch")F(`state mismatch from relay session=${B(C.affinity)}; retrying full_sync`),await M.body?.cancel().catch(()=>{}),C=ef(C,D),M=await H0(_,C,$);if(!M.ok&&M.status>=500&&_.fallbackToDirect)return F(`relay returned ${M.status}; falling back direct session=${B(C.affinity)}`),await M.body?.cancel().catch(()=>{}),{response:await m(),payload:C,transport:"http",protocol:C.protocol,usedRelay:!1};return{response:M,payload:C,transport:"http",protocol:C.protocol,usedRelay:!0}}function Em(f,_){let E=new URL(f);return E.protocol=E.protocol==="http:"?"ws:":"wss:",E.pathname="/ws",E.searchParams.set("token",_),E.toString()}function Dm(f){return new Uint8Array(b0.from(f,"base64"))}function mm(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(b0.from(String(f)))}function $m(f){return JSON.parse(f)}function F0(f){let _=f,E=[`code=${_.code??"unknown"}`,`wasClean=${_.wasClean??"unknown"}`];if(_.reason)E.push(`reason=${JSON.stringify(_.reason)}`);return E.join(" ")}function Cm(f){let _=f.message||"relay websocket error";return f.status?`relay websocket error ${f.status}: ${_}`:_}class j0{config;affinity;socket;connecting;queue=Promise.resolve();pending;serverState;lastUsedAt=Date.now();constructor(f,_){this.config=f,this.affinity=_}touch(f=Date.now()){this.lastUsedAt=f}canEvict(f=Date.now()){return!this.pending&&!this.connecting&&f-this.lastUsedAt>nD}dispose(){this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0}send(f,_,E=!1){this.touch();let D=b(),m=this.queue.catch(()=>{}).then(()=>this.startQueued(f,_,D,E)),$=m.then(async({response:C,getPayload:M})=>({response:await C,payload:M(),transport:"websocket",protocol:2,usedRelay:!0}));return this.queue=m.then(({done:C})=>C.catch(()=>{}),()=>{}),$}async startQueued(f,_,E,D){let m=b();await this.ensureConnected();let $=b(),C=P.get(this.affinity),M=this.serverState?.hash,L={...f,protocol:2,id:tf()};if(L.mode==="patch"&&(!M||M!==L.base_hash))L.mode="full_sync",L.revision=(this.serverState?.revision??0)+1,delete L.base_hash,delete L.patch,L.body=_;if(L.mode==="patch"&&C)L.patch=B0(C.body,_);F(`perf websocket send_start session=${B(this.affinity)} request=${L.id} mode=${L.mode} queueMs=${Y($-E)} connectMs=${Y($-m)} bodyBytes=${_.length} relayBytes=${JSON.stringify(L).length}`);let A=L,U=this.sendPayload(L,_,D);U.done.catch(()=>{});let N=U.done,K=U.response.catch((R)=>{if(!(R instanceof of)||L.mode!=="patch")throw R;let J=ef(L,_);J.protocol=2,J.id=tf(),J.revision=(this.serverState?.revision??0)+1,A=J;let S=this.sendPayload(J,_,D);return S.done.catch(()=>{}),N=S.done,S.response}),j=K.then(()=>N,()=>N.catch(()=>{}));return{response:K,done:j,getPayload:()=>A}}async ensureConnected(){if(this.socket?.readyState===WebSocket.OPEN&&this.serverState!==void 0)return;if(this.connecting)return await this.connecting;this.connecting=new Promise((f,_)=>{let E=Em(this.config.url,this.config.token),D=new URL(E);D.searchParams.set("affinity",this.affinity);let m=new WebSocket(D.toString());this.socket=m,this.serverState=void 0;let $=setTimeout(()=>{m.close(),_(Error("relay websocket ready timed out"))},15000);m.addEventListener("message",(C)=>{try{if(typeof C.data!=="string"){this.handleBinaryChunk(C.data);return}let M=$m(C.data);if(M.type==="ready"){clearTimeout($),this.serverState=M.state,f();return}this.handleMessage(M)}catch(M){clearTimeout($),_(M),this.failPending(M),m.close()}}),m.addEventListener("error",()=>{clearTimeout($);let C=new af("relay websocket error");_(C),this.failPending(C)}),m.addEventListener("close",(C)=>{if(clearTimeout($),this.socket===m)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,L=M?"closed after response_start before stream bytes":"closed before response";if(this.retryPendingBeforeResponse(this.pending,L,C))return;let A=M?new af("relay websocket closed during response stream",C):Error("relay websocket closed before response");F(`websocket ${M?"closed during response stream":"closed before response without retry"} session=${B(this.affinity)} request=${this.pending.payload.id} chunks=${this.pending.streamChunkCount} bytes=${this.pending.streamByteCount} ${F0(C)}`),this.failPending(A)}})}).finally(()=>{this.connecting=void 0}),await this.connecting}sendPayload(f,_,E){let D=this.socket;if(!D||D.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");let m=b(),$,C,M=new Promise((A,U)=>{$=A,C=U});return{response:new Promise((A,U)=>{let N={payload:f,bodyText:_,resolve:A,reject:U,streamDone:!1,accepted:!1,responseStarted:!1,resolveDone:$,rejectDone:C,sentAt:m,optimisticResponse:E,streamChunkCount:0,streamByteCount:0,retryAttempts:0,retryingBeforeResponse:!1};if(this.pending=N,this.resetPendingTimeout(N),D.send(JSON.stringify(f)),E)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,_,E){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 D=f.retryAttempts,m=f.payload.id;return F(`websocket ${_}; reconnecting and retrying full_sync session=${B(this.affinity)} request=${m} retry=${D} chunks=${f.streamChunkCount} bytes=${f.streamByteCount}${E?` ${F0(E)}`:""}`),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 $=ef(f.payload,f.bodyText);$.protocol=2,$.id=tf(),$.revision=(this.serverState?.revision??0)+1,f.payload=$,f.accepted=!1,f.acceptedAt=void 0,f.responseStartedAt=void 0,f.sentAt=b(),f.retryingBeforeResponse=!1;let C=this.socket;if(!C||C.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");this.resetPendingTimeout(f),F(`perf websocket retry_send session=${B(this.affinity)} request=${$.id} previous=${m} mode=full_sync retry=${D} bodyBytes=${f.bodyText.length} relayBytes=${JSON.stringify($).length}`),C.send(JSON.stringify($))}catch($){if(f.retryingBeforeResponse=!1,this.pending===f)this.failPending($)}})(),!0}enqueueStreamChunk(f,_){f.streamChunkCount+=1,f.streamByteCount+=_.byteLength,f.streamController?.enqueue(_)}handleBinaryChunk(f){let _=this.pending;if(!_?.responseStarted)return;this.enqueueStreamChunk(_,mm(f))}resolvePendingResponse(f,_,E,D){if(f.responseStarted)return;f.responseStarted=!0;let m=new ReadableStream({start:($)=>{f.streamController=$},cancel:()=>{this.socket?.close()}});f.resolve(new Response(m,{status:_,statusText:E,headers:D}))}handleMessage(f){if(f.type==="keepalive"){if(this.pending)this.resetPendingTimeout(this.pending);return}let _=this.pending;if(!_)return;if("id"in f&&f.id&&f.id!==_.payload.id)return;if(f.type==="accepted"){let E=b();_.accepted=!0,_.acceptedAt=E,F(`perf websocket accepted session=${B(this.affinity)} request=${_.payload.id} sentMs=${Y(E-_.sentAt)} mode=${_.payload.mode}`),this.serverState={hash:f.hash,revision:f.revision},K0(this.affinity,_.bodyText,f.hash,f.revision),this.resetPendingTimeout(_);return}if(f.type==="response_start"){let E=b();if(_.responseStartedAt=E,F(`perf websocket response_start session=${B(this.affinity)} request=${_.payload.id} sentMs=${Y(E-_.sentAt)} upstreamMs=${_.acceptedAt==null?"unknown":Y(E-_.acceptedAt)} status=${f.status}`),clearTimeout(_.timeout),this.resolvePendingResponse(_,f.status,f.statusText,f.headers),_.optimisticResponse&&f.status>=400)_.streamController?.enqueue(new TextEncoder().encode(`event: error
|
|
40
40
|
data: ${JSON.stringify({type:"error",error:{type:"relay_upstream_error",message:`Relay upstream returned HTTP ${f.status}`}})}
|
|
41
41
|
|
|
42
|
-
`)),this.finishPending();return}if(f.type==="chunk"){this.enqueueStreamChunk(_,
|
|
42
|
+
`)),this.finishPending();return}if(f.type==="chunk"){this.enqueueStreamChunk(_,Dm(f.base64));return}if(f.type==="done"){this.finishPending(f);return}if(f.type==="error"){if(_.optimisticResponse&&_.responseStartedAt!=null){F(`websocket relay error during optimistic response session=${B(this.affinity)} request=${_.payload.id} status=${f.status} message=${f.message||"unknown"} chunks=${_.streamChunkCount} bytes=${_.streamByteCount}`),_.streamController?.enqueue(new TextEncoder().encode(`event: error
|
|
43
43
|
data: ${JSON.stringify({type:"error",error:{type:"relay_error",message:f.message||"relay error"}})}
|
|
44
44
|
|
|
45
|
-
`)),this.finishPending(),this.socket?.close();return}if(f.status===409&&this.retryPendingBeforeResponse(_,f.message||"state mismatch"))return;let E=f.status===409?new of(f.message||"state mismatch"):Error(
|
|
45
|
+
`)),this.finishPending(),this.socket?.close();return}if(f.status===409&&this.retryPendingBeforeResponse(_,f.message||"state mismatch"))return;let E=f.status===409?new of(f.message||"state mismatch"):Error(Cm(f));this.failPending(E)}}finishPending(f){let _=this.pending;if(!_)return;let E=b(),D=f&&"frames"in f?` upstreamChunks=${f.upstreamChunks??"unknown"} upstreamBytes=${f.upstreamBytes??"unknown"} frames=${f.frames} frameBytes=${f.frameBytes??"unknown"}`:"";if(F(`perf websocket done session=${B(this.affinity)} request=${_.payload.id} sentMs=${Y(E-_.sentAt)} streamMs=${_.responseStartedAt==null?"unknown":Y(E-_.responseStartedAt)} chunks=${_.streamChunkCount} bytes=${_.streamByteCount}${D}`),clearTimeout(_.timeout),!_.streamDone)_.streamDone=!0,_.streamController?.close();_.resolveDone(),this.pending=void 0}failPending(f){let _=this.pending;if(!_)return;if(clearTimeout(_.timeout),this.pending=void 0,_.responseStarted)_.streamController?.error(f);else _.reject(f);_.rejectDone(f)}}function f_(f=Date.now()){for(let[_,E]of P)if(f-E.updatedAt>gD)P.delete(_);while(P.size>rD){let _=P.keys().next().value;if(_===void 0)break;P.delete(_)}for(let[_,E]of p)if(E.canEvict(f))E.dispose(),p.delete(_);while(p.size>sD){let _=!1;for(let[E,D]of p){if(!D.canEvict(f))continue;D.dispose(),p.delete(E),_=!0;break}if(!_)break}}function Mm(f,_){f_();let E=p.get(_);if(E)return E.touch(),E;let D=new j0(f,_);return p.set(_,D),f_(),D}async function A$(f){let{config:_,input:E,init:D,headers:m,body:$,fallback:C,affinity:M,optimisticResponse:L}=f;if(!_||!aD(E,$))return C();let A=M||m.get("x-session-affinity")||m.get("x-opencode-session");if(!A)return F("skipping relay: missing x-session-affinity header"),C();let U=$,N=b(),K=cD(U);s("hash_body",{session:B(A),ms:Y(b()-N),bodyBytes:U.length});let j=P.get(A),R=b(),J=_m({input:E,init:D,headers:m,bodyText:U,affinity:A,previous:j,nextHash:K});s("create_payload",{session:B(A),ms:Y(b()-R),mode:J.mode,bodyBytes:U.length,previousBytes:j?.body.length});try{let S,v=b();if(_.transport==="websocket")try{S=await Mm(_,A).send(J,U,L===!0)}catch(O){F(`websocket relay failed session=${B(A)}; trying http relay: ${O instanceof Error?O.message:String(O)}`),S=await N0({config:_,payload:J,bodyText:U,fallback:C,signal:D?.signal})}else S=await N0({config:_,payload:J,bodyText:U,fallback:C,signal:D?.signal});if(s("send",{session:B(A),ms:Y(b()-v),transport:S.transport,protocol:S.protocol,mode:S.payload.mode,status:S.response.status,usedRelay:S.usedRelay}),!S.usedRelay)return S.response;if(S.transport==="http")K0(A,U,S.payload.next_hash,S.payload.revision);let d=b(),u=JSON.stringify(S.payload).length;s("payload_stringify",{session:B(A),ms:Y(b()-d),relayBytes:u}),F(`used relay transport=${S.transport} protocol=${S.protocol} mode=${S.payload.mode} status=${S.response.status} session=${B(A)} bodyBytes=${U.length} relayBytes=${u}`);let mf=b();return await m0({affinity:A,transport:S.transport,protocol:S.protocol,mode:S.payload.mode,status:S.response.status,bodyText:U,previousBodyText:j?.body,payload:S.payload,relayBytes:u}),s("dump",{session:B(A),ms:Y(b()-mf),enabled:!0}),S.response}catch(S){if(!_.fallbackToDirect)throw F(`relay failed session=${B(A)} and fallbackToDirect=false: ${S instanceof Error?S.message:String(S)}`),S;return F(`relay failed; falling back direct session=${B(A)}: ${S instanceof Error?S.message:String(S)}`),C()}}var U$=`
|
|
46
46
|
async function hashBody(body) {
|
|
47
47
|
const bytes = new TextEncoder().encode(body)
|
|
48
48
|
const digest = await crypto.subtle.digest('SHA-256', bytes)
|
|
@@ -401,9 +401,9 @@ export default {
|
|
|
401
401
|
}
|
|
402
402
|
},
|
|
403
403
|
}
|
|
404
|
-
`;var
|
|
405
|
-
`)}function b$(f){let _=
|
|
404
|
+
`;var H$="claude-routing",E_=["main-first","fallback-first"],D_="main-first",G0="Usage: `/claude-routing`, `/claude-routing main-first`, or `/claude-routing fallback-first`.";function Lm(f){return typeof f==="string"&&E_.includes(f)?f:D_}function N$(f){return Lm(f?.routing?.mode)}async function F$(f,_=z()){let E=await h(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.routing={...E.routing??{},mode:f},await Q(E,_),E}function Am(f){let _=f.trim().toLowerCase().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&E_.includes(_[0]))return{type:"mode",mode:_[0]};if(_.length===2&&_[0]==="mode"&&E_.includes(_[1]))return{type:"mode",mode:_[1]};return{type:"usage"}}function Um(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 __(f){let _=f?.mode??D_;return["## Claude Routing Status","",`- Mode: \`${_}\``,`- Behavior: ${Um(_)}`,"",G0].join(`
|
|
405
|
+
`)}function b$(f){let _=Am(f.argumentsText),E=f.mode??D_;if(_.type==="status")return __({mode:E});if(_.type==="mode")return["## Claude Routing Updated","",`Mode updated to \`${_.mode}\`.`,"",...__({mode:_.mode}).split(`
|
|
406
406
|
`).slice(2)].join(`
|
|
407
407
|
`);return["## Claude Routing Usage","",G0,"",...__({mode:E}).split(`
|
|
408
408
|
`).slice(2)].join(`
|
|
409
|
-
`)}export{
|
|
409
|
+
`)}export{Om as a,C_ as b,Sm as c,Hm as d,Nm as e,Fm as f,bm as g,M_ as h,Bm as i,Km as j,i as k,N_ as l,Ym as m,Wm as n,V as o,x as p,Tm as q,v0 as r,qm as s,z as t,h as u,Q as v,bE as w,Lf as x,wm as y,KE as z,im as A,ym as B,lm as C,km as D,pm as E,vm as F,dm as G,um as H,gm as I,R_ as J,WE as K,o as L,hf as M,nm as N,w_ as O,XE as P,rm as Q,sm as R,cm as S,tm as T,IE as U,em as V,f1 as W,_1 as X,E1 as Y,wE as Z,D1 as _,s_ as $,F1 as aa,M1 as ba,L1 as ca,A1 as da,u_ as ea,j1 as fa,G1 as ga,ND as ha,uf as ia,a_ as ja,FD as ka,z1 as la,BD as ma,x1 as na,Q1 as oa,VD as pa,I1 as qa,R1 as ra,T1 as sa,q1 as ta,TD as ua,w1 as va,Df as wa,l1 as xa,p1 as ya,v1 as za,d1 as Aa,u1 as Ba,g1 as Ca,n1 as Da,r1 as Ea,w as Fa,e1 as Ga,f$ as Ha,_$ as Ia,M$ as Ja,L$ as Ka,A$ as La,U$ as Ma,H$ as Na,N$ as Oa,F$ as Pa,Am as Qa,b$ as Ra};
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
|
-
import{$ as
|
|
1
|
+
import{$ as $j,A as Uj,Aa as lj,B as Bj,Ba as ij,C as F1,Ca as uj,D as Cj,Da as nj,E as x1,Ea as Kj,F as Hj,Fa as cj,G as Fj,Ga as O1,H as xj,Ha as oj,I as T1,Ia as rj,J as e0,Ja as A1,K as Tj,L as B0,La as sj,M as q1,N as qj,Na as P1,O as k0,Oa as f1,P as y0,Pa as tj,Q as j1,Qa as aj,R as Ej,Ra as k1,S as Rj,T as vj,U as Sj,V as J1,W as C0,X as H0,Y as b0,Z as Aj,_ as $1,a as s1,aa as Vj,b as t1,ba as E1,c as E0,ca as Wj,d as R0,da as Xj,e as a1,ea as Gj,f as q0,fa as V1,g as _j,ga as fj,h as e1,ha as kj,i as jj,ia as yj,j as Jj,ja as bj,k as U1,ka as R1,l as Lj,la as hj,m as B1,ma as mj,n as C1,na as W1,o as q,oa as X1,p as j0,pa as gj,q as A0,qa as v1,r as H1,ra as G1,s as Qj,sa as Z1,t as wj,ta as K1,u as b,ua as pj,va as S1,w as f0,wa as Y1,x as Mj,xa as dj,y as t0,ya as Zj,z as a0,za as h0}from"./index-hjkkewsy.js";import{Va as ej}from"./index-99mvcpj7.js";import{randomUUID as yJ}from"node:crypto";function M0(j){return typeof j==="object"&&j!==null}function XJ(j){if(Array.isArray(j))return j;if(M0(j)&&Array.isArray(j.data))return j.data;return[]}function GJ(j){if(!M0(j)||!M0(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function b1(j){if(!M0(j)||!M0(j.info))return null;let $=j.info,J=M0($.model)?$.model:void 0,W=typeof $.agent==="string"?$.agent:void 0,V=typeof J?.providerID==="string"?J.providerID:typeof $.providerID==="string"?$.providerID:void 0,O=typeof J?.modelID==="string"?J.modelID:typeof $.modelID==="string"?$.modelID:void 0,Q=typeof J?.variant==="string"?J.variant:typeof $.variant==="string"?$.variant:void 0;if(!W&&(!V||!O)&&!Q)return null;let v={};if(W)v.agent=W;if(V&&O)v.model={providerID:V,modelID:O};if(Q)v.variant=Q;return v}function h1(j,$){return{agent:j.agent??$.agent,model:j.model??$.model,variant:j.variant??$.variant}}function m1(j){return Boolean(j.agent&&j.model&&j.variant)}async function g1(j,$){if(!j||!$)return null;let J=j;if(typeof J.session?.messages!=="function")return null;let W=[];try{W=XJ(await Promise.resolve(J.session.messages({path:{id:$},query:{limit:100}})))}catch{return null}if(W.length===0)return null;let V={};for(let O=W.length-1;O>=0;O--){if(GJ(W[O])!=="assistant")continue;let Q=b1(W[O]);if(!Q)continue;if(V=h1(V,Q),m1(V))return V}for(let O=W.length-1;O>=0;O--){let Q=b1(W[O]);if(!Q)continue;if(V=h1(V,Q),m1(V))return V}if(!V.agent&&!V.model&&!V.variant)return null;return V}function p1(j,$){let J=new Map,W=0,V=0,O=0,Q=0,v=0,u=(h)=>{let A=performance.now(),c=j(h);return v+=performance.now()-A,O++,c};return{call:(h)=>{if(!$.enabled())return u(h);let A=J.get(h);if(A!==void 0)return V++,J.delete(h),J.set(h,A),A;let c=u(h),t=h.length+c.length;if(t>$.maxBytes)return c;J.set(h,c),W+=t;while(W>$.maxBytes&&J.size>1){let p=J.keys().next().value,G0=J.get(p)??"";J.delete(p),W-=p.length+G0.length,Q++}return c},stats:()=>({hits:V,misses:O,evictions:Q,entries:J.size,cacheBytes:W,computeMsTotal:v})}}function d1(j){return`${s1}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function Yj(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}var ZJ=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function l1(j){let $=Yj(j);if($.startsWith("aft_"))return $;if(ZJ.has($))return`aft_${$}`;return null}function _1(j,$){let J=new Headers;if(j instanceof Request)j.headers.forEach((V,O)=>{J.set(O,V)});let W=$?.headers;if(W){if(W instanceof Headers)W.forEach((V,O)=>{J.set(O,V)});else if(Array.isArray(W))for(let V of W){let[O,Q]=V;if(typeof Q<"u")J.set(O,String(Q))}else for(let[V,O]of Object.entries(W))if(typeof O<"u")J.set(V,String(O))}return J}function s0(j){return j.set("anthropic-beta",E0(j.get("anthropic-beta"),[t1])),j}function v0(j,$,J={}){return Xj(j,$,J)}function KJ(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map(($)=>({...$,name:$.name?d1($.name):$.name}));if(j.messages&&Array.isArray(j.messages))j.messages=j.messages.map(($)=>{if($.content&&Array.isArray($.content))$.content=$.content.map((J)=>{if(J.type==="tool_use"&&J.name)return{...J,name:d1(J.name)};return J});return $});return JSON.stringify(Gj(j))}function I1(j){return j.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,($,J,W)=>{if(J)return`"name": "${l1(W)??Yj(W)}"`;let V=l1(W);return V?`"name": "${V}"`:$})}function i1(j,$=!1){if($)return{ready:I1(j),pending:""};let J=j.length,W='"name"',V=Math.max(0,j.length-W.length+1);for(let Q=V;Q<j.length;Q++)if(W.startsWith(j.slice(Q))){J=Math.min(J,Q);break}let O=j.lastIndexOf(W);if(O!==-1){let Q=j.slice(O);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(Q))J=Math.min(J,O)}if(J<j.length)return{ready:I1(j.slice(0,J)),pending:j.slice(J)};return{ready:I1(j),pending:""}}function L1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function Oj(j){let $=j?.trim();if(!$)return null;try{let J=new URL($);if(J.protocol!=="http:"&&J.protocol!=="https:"||J.username||J.password)return null;return J}catch{return null}}function YJ(){return Oj(process.env.ANTHROPIC_BASE_URL)}function Q1(j,$={}){let J=null;try{if(typeof j==="string"||j instanceof URL)J=new URL(j.toString());else if(j instanceof Request)J=new URL(j.url)}catch{J=null}if(!J)return{input:j,url:null};let W=J.href,V=$.baseURL?Oj($.baseURL):YJ();if(V){if(J.protocol=V.protocol,J.host=V.host,$.baseURL)J.pathname=`${V.pathname.replace(/\/$/,"")}${J.pathname}`}if(J.pathname.endsWith("/v1/messages")&&!J.searchParams.has("beta"))J.searchParams.set("beta","true");if(J.href===W)return{input:j,url:J};return{input:j instanceof Request?new Request(J.toString(),j):J,url:J}}function OJ(j){let W=j.split(/\n\n+/).filter((V)=>{if(V.includes(a1))return!1;for(let O of jj)if(V.includes(O))return!1;return!0}).join(`
|
|
2
2
|
|
|
3
|
-
`);for(let Z of a1)D=D.replace(Z.match,Z.replacement);return D.trim()}var ZJ=8388608;function VJ(){return process.env.OPENCODE_ANTHROPIC_AUTH_MEMO!=="0"}var XJ=m1(GJ,{maxBytes:ZJ,enabled:VJ});function p0(j){return XJ.call(j)}function h(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function WJ(j){let J={type:"text",text:M0};if(j==null)return[J];if(typeof j==="string"){let D=p0(j);if(D===M0)return[J];return[J,{type:"text",text:D}]}if(h(j)){let D=typeof j.type==="string"?j.type:"text",Z=typeof j.text==="string"?j.text:"";return[J,{...j,type:D,text:p0(Z)}]}if(!Array.isArray(j))return[J];let $=j.map((D)=>{if(typeof D==="string")return{type:"text",text:p0(D)};if(h(D)&&D.type==="text"&&typeof D.text==="string")return{...D,type:"text",text:p0(D.text)};return{type:"text",text:String(D)}});if($[0]?.text===M0)return $;return[J,...$]}var Zj={type:"ephemeral",ttl:"1h"},YJ=20;function KJ(j){if(h(j.cache_control))return j.cache_control;if(h(j.cacheControl))return j.cacheControl;return null}function u0(j,J){if(!h(j))return!1;return delete j.cacheControl,j.cache_control=J?{...Zj}:{type:"ephemeral"},!0}function p1(j){if(!h(j))return;delete j.cache_control,delete j.cacheControl}function PJ(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function l0(j,J){if(!h(j))return;let $=KJ(j);if($?.type!=="ephemeral")return;if(J)$.ttl="1h";else delete $.ttl}function l1(j,J){if(Array.isArray(j.system))for(let $ of j.system)l0($,J);else l0(j.system,J);if(!Array.isArray(j.messages))return;for(let $ of j.messages)if(l0($,J),h($)&&Array.isArray($.content))for(let D of $.content)l0(D,J)}function IJ(j,J){if(Array.isArray(j.system))for(let $ of j.system)J($);else J(j.system);if(!Array.isArray(j.messages))return;for(let $ of j.messages)if(J($),h($)&&Array.isArray($.content))for(let D of $.content)J(D)}function Vj(j){p1(j),IJ(j,p1)}function OJ(j){Vj(j),j.cache_control={...Zj}}function zJ(j){return h(j)&&j.type!=="thinking"&&j.type!=="redacted_thinking"}function _1(j){let J=PJ(j.content);if(!J?.length)return;let $=J.filter(zJ);if(!$.length)return;return{content:J,cacheableBlocks:$}}function _J(j){if(!h(j))return!1;let J=_1(j);if(!J)return!1;return j.content=J.content,u0(J.cacheableBlocks[0],!0)}function d0(j){if(!h(j))return!1;let J=_1(j);if(!J)return!1;let $=J.cacheableBlocks[J.cacheableBlocks.length-1];return j.content=J.content,u0($,!0)}function LJ(j){if(!h(j))return!1;return(_1(j)?.cacheableBlocks.length??0)>1}function QJ(j){if(!h(j))return 0;let J=j.content;if(Array.isArray(J))return J.length;if(J==null)return 0;return 1}function UJ(j){let J=[],$=0;return j.forEach((D,Z)=>{let P=QJ(D);if(h(D)&&D.role==="user"&&P>0)J.push({index:Z,blockPosition:$+P-1});$+=P}),J}function FJ(j){let J=UJ(j),$=[...J].reverse().find((v)=>v.index>1);if(!$)return{latest:void 0,bridge:void 0};let D=[...J].reverse().find((v)=>v.index<$.index),Z=D?$.blockPosition-D.blockPosition+1:0,P=D&&D.index>1&&Z>YJ?D:void 0;return{latest:$,bridge:P}}function d1(j){if(Array.isArray(j.system)){let J=j.system.findIndex((Z)=>h(Z)&&Z.text===M0),$=j.system.slice(J>=0?J+1:0).filter(h),D=$[$.length-1];u0(D,!0)}else u0(j.system,!0)}function NJ(j){if(Vj(j),!Array.isArray(j.messages)){d1(j);return}let{latest:J,bridge:$}=FJ(j.messages);if(!$)d1(j);let D=LJ(j.messages[0]);if(D)_J(j.messages[0]);if(d0(j.messages[0]),!D)d0(j.messages[1]);if($)d0(j.messages[$.index]);if(J)d0(j.messages[J.index])}function HJ(j){if(!$j(j.model))return!1;let J=Object.hasOwn(j,"thinking");return delete j.thinking,J}function BJ(j,J){if(!J.enabled){l1(j,!1),delete j.cache_control,delete j.cacheControl;return}if(J.mode==="automatic"){OJ(j);return}if(J.mode==="hybrid"){NJ(j);return}l1(j,!0),delete j.cacheControl}function vJ(j){if(!Array.isArray(j.messages))return;while(j.messages.length){let J=j.messages[j.messages.length-1];if(!h(J)||J.role!=="assistant")break;j.messages.pop()}}function E(){return performance.now()}function t(j){return Math.round(j*10)/10}function u1(j){let J=0,$=0,D=0,Z=Array.isArray(j.messages)?j.messages:[];J=Z.length;for(let P of Z){if(!P||typeof P!=="object")continue;let v=P.content;if(!Array.isArray(v))continue;$+=v.length;for(let m of v)if(m&&typeof m==="object"&&m.type==="tool_use")D++}return{messageCount:J,contentBlockCount:$,toolDefinitionCount:Array.isArray(j.tools)?j.tools.length:0,toolUseCount:D,systemBlockCount:Array.isArray(j.system)?j.system.length:0}}async function L1(j,J={}){try{let $=E(),D=JSON.parse(j);J.perf?.("parse",{ms:t(E()-$),inputBytes:j.length,...u1(D)});let Z=E(),P=Array.isArray(D.messages)?D.messages.length:void 0;vJ(D);let v=Array.isArray(D.messages)?D.messages.length:void 0;J.perf?.("strip_trailing_assistant",{ms:t(E()-Z),removedMessages:typeof P==="number"&&typeof v==="number"?P-v:void 0});let m=E(),j0=HJ(D);J.perf?.("model_normalize",{ms:t(E()-m),model:typeof D.model==="string"?D.model:void 0,removedFableThinking:j0,hasOutputConfig:Object.hasOwn(D,"output_config")});let a=E(),s=Array.isArray(D.messages)&&D.messages.some((z0)=>z0.role==="user")?t1(D.messages,void 0,o1):null;J.perf?.("billing_header",{ms:t(E()-a),hasBillingHeader:Boolean(s)});let p=E();if(D.system=WJ(D.system),J.perf?.("system_identity",{ms:t(E()-p),systemBlockCount:Array.isArray(D.system)?D.system.length:0}),s&&Array.isArray(D.system))D.system.unshift({type:"text",text:s});let y=E();if(BJ(D,{enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.perf?.("cache_strategy",{ms:t(E()-y),enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.fastModeEnabled&&C0(D.model))D.speed="fast";else if(D.speed==="fast")delete D.speed;let u=E();if(J.identity)e1(D,J.identity);J.perf?.("metadata",{ms:t(E()-u),hasAccountUuid:Boolean(J.identity?.accountUuid)});let o=E(),i=$J(D);J.perf?.("prefix_tools_stringify",{ms:t(E()-o),outputBytesBeforeSign:i.length,...u1(D)});let Y0=E(),D0=await s1(i);return J.perf?.("cch_sign",{ms:t(E()-Y0),outputBytes:D0.length}),D0}catch{return j}}function E0(j,J={}){if(!j.body)return j;let $=j.body.getReader(),D=new TextDecoder,Z=new TextEncoder,P="",v=0,m=0,j0=0,a=0,s=0,p=!1,y=!1,u=E(),o=E(),i=()=>{if(y)return;y=!0,$.releaseLock()},Y0=(c={})=>({chunks:v,pulls:m,inputBytes:j0,outputBytes:a,pendingChars:P.length,rewriteMs:t(s),totalMs:t(E()-o),...c}),D0=(c,v0={})=>{J.perf?.(c,Y0(v0))};J.perf?.("stream_tool_prefix_wrapper_created",{status:j.status,hasBody:!0});let z0=new ReadableStream({async pull(c){if(m++,!p)p=!0,D0("stream_tool_prefix_first_pull");let v0=E();try{let{done:V0,value:x0}=await $.read(),m0=t(E()-v0);if(V0){let _0=E(),G=h1(`${P}${D.decode()}`,!0);if(s+=E()-_0,G.ready){let V=Z.encode(G.ready);a+=V.byteLength,c.enqueue(V)}D0("stream_tool_prefix_rewrite",{readMs:m0}),i(),c.close();return}v++,j0+=x0.byteLength;let W1=P+D.decode(x0,{stream:!0}),Y1=E(),X0=h1(W1);if(s+=E()-Y1,P=X0.pending,X0.ready){let _0=Z.encode(X0.ready);a+=_0.byteLength,c.enqueue(_0)}let q0=E();if(v===1||v%25===0||q0-u>5000)u=q0,D0("stream_tool_prefix_progress",{readMs:m0,lastChunkBytes:x0.byteLength})}catch(V0){throw D0("stream_tool_prefix_error",{error:V0 instanceof Error?V0.message:String(V0)}),i(),V0}},async cancel(c){D0("stream_tool_prefix_cancel",{reason:c instanceof Error?c.message:String(c)});try{await $.cancel(c)}finally{i()}}});return new Response(z0,{status:j.status,statusText:j.statusText,headers:j.headers})}var qJ="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",MJ=60000,TJ=60000,CJ=5000,Xj=200,oj=240,wJ=oj,EJ=1,Wj=!1;function X1(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function N(){return performance.now()}function S(j){return Math.round(j*10)/10}function Yj(j){return Math.floor(Math.random()*Math.max(0,j))}function SJ(){if(Wj||!1||!X1())return;Wj=!0;let j=100,J=250,$=N()+j;setInterval(()=>{let D=N(),Z=D-$;if($=D+j,Z<J)return;C("[perf] opencode event_loop_lag",{lagMs:S(Z),thresholdMs:J})},j).unref?.()}function AJ(j){let J=N(),$={requestId:String(EJ++),start:J,last:J,mark(D,Z){let P=N();if(X1())C("[perf] opencode request stage",{requestId:$.requestId,stage:D,deltaMs:S(P-$.last),totalMs:S(P-$.start),...Z});$.last=P},done(D,Z){let P=N();if(X1())C("[perf] opencode request done",{requestId:$.requestId,stage:D,deltaMs:S(P-$.last),totalMs:S(P-$.start),...Z});$.last=P}};if(X1())C("[perf] opencode request start",{requestId:$.requestId,...j});return $}async function I0(j,J,$){let D=j.client.session,Z=await y1(j.client,J),P={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:$,ignored:!0}]}};if(Z?.agent)P.body.agent=Z.agent;if(Z?.model)P.body.model=Z.model;if(Z?.variant)P.body.variant=Z.variant;if(typeof D?.promptAsync==="function"){await D.promptAsync(P);return}if(typeof D?.prompt==="function"){await Promise.resolve(D.prompt(P));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function O0(){throw Error(qJ)}function RJ(j){if(j.sessionID==null)return!1;let J=j.model;return J?.providerID==="anthropic"||J?.api?.npm==="@ai-sdk/anthropic"||J?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function fJ(j){if(j.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return j.push(Kj),!0}var kJ={input:0,output:0,cache:{read:0,write:0}};function yJ(j){let J=j["claude-opus-4-8"]??j["claude-opus-4-5"]??Object.values(j)[0];if(!J)return j;return{...j,...Object.fromEntries(Object.values(hj).map(($)=>[$.id,{...J,id:$.id,name:$.name,api:J.api?{...J.api,id:$.id}:void 0,cost:{input:y0.input,output:y0.output,cache:{read:y0.cacheRead,write:y0.cacheWrite5m}},limit:{...J.limit??{},context:mj,output:bj},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:gj}]))}}function mJ(j){return Object.fromEntries(Object.entries(j).map(([J,$])=>[J,{...$,cost:kJ}]))}var rJ=async(j)=>{SJ();let{client:J}=j,$=Oj(),D=await k($),Z=new pj({storage:D,onMainQuotaFetched:async(G,V,K)=>{try{let _=await k($)??{version:1,accounts:[]};_.quota=_.quota??{},_.quota.mainQuota=G,_.quota.mainQuotaCheckedAt=V,_.quota.mainQuotaToken=K,_.quota.mainLastQuotaApiError=void 0,await A0(_,$,{mainQuota:!0})}catch(_){C("[quota] failed to persist main quota",{error:_ instanceof Error?_.message:String(_)})}},onApiError:async(G)=>{try{let V=await k($)??{version:1,accounts:[]};V.quota=V.quota??{},V.quota.mainLastQuotaApiError=G,await A0(V,$,{mainQuota:!0})}catch(V){C("[quota] failed to persist backoff state",{error:V instanceof Error?V.message:String(V)})}}}),P=new Mj({quotaManager:Z,onFallbackStorageChanged:()=>{s()}});P.startBackgroundRefresh();let v=null,m=new Rj({loadStorage:()=>k($),prepareHeaders:async(G,V)=>{if(!y)return G;let K=await y();if(K.type!=="oauth")return G;if(!K.access||K.expires&&K.expires<Date.now()){if(!v)return G;K.access=await v()}if(!K.access)return G;try{let _=JSON.parse(V.bodyText),L=await q1(K.access,typeof _.model==="string"?_.model:void 0);if(G.delete("anthropic-beta"),w0(G,K.access,{body:_,identity:L}),G.set("anthropic-beta",T0(G.get("anthropic-beta"),[Cj])),_.speed==="fast")i0(G)}catch{w0(G,K.access)}return G},log:C});k0({enabled:n0(D),mode:c0(D)}),j1(H1(D)),D1(B1(D));let j0={activeId:"main",route:"main"};function a(G,V){j0={activeId:V.activeId,route:V.route};let K=Z.getMain(V.mainAccessToken),_=Z.getLastApiError(),L=G?.refresh?.mainLastRefreshError,A={main:{quota:K?.quota??null,quotaBackedOff:Z.isBackedOff(),quotaBackoffUntil:_?.nextRetryAt,refreshBackedOff:L?N0(L,V.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:L?.nextRetryAt},fallbacks:(G?.accounts??[]).filter((w)=>w.enabled!==!1&&e(w)).map((w)=>({id:w.id,label:w.label,quota:w.access?Z.getFallback(w.id,w.access)?.quota??null:null,enabled:w.enabled!==!1})),activeId:V.activeId,route:V.route,relay:(()=>{let w=w1(G);return w?{enabled:!0,transport:w.transport??"http"}:null})(),fastMode:$1(),cacheKeep:{enabled:M1(G),window:G?.cacheKeep?.startHour!=null&&G?.cacheKeep?.endHour!=null?`${G.cacheKeep.startHour}-${G.cacheKeep.endHour}`:void 0,trackedSessions:m.trackedCount()},lastUpdated:Date.now()};cj(A).catch((w)=>C("[sidebar] state write failed",{error:w instanceof Error?w.message:String(w)}))}async function s(){let G=await k($),V,K;if(y)try{let _=await y();V=_.access,K=_.refresh}catch{}a(G,{activeId:j0.activeId,route:j0.route,mainAccessToken:V,mainRefreshToken:K})}function p(G,V){if(!V)return;if(G?.quota?.enabled!==!0)return;if(Z.getMain(V))return;if(u)return;u=!0,Z.refreshMain(V).then(()=>s()).catch(()=>{}).finally(()=>{u=!1})}let y=null,u=!1,o=null,i=0;function Y0(G){let V=G?.refresh?.refreshBeforeExpiryMinutes??wJ;return Math.max(oj,V)*60000}function D0(G){return G?.refresh?.enabled!==!1}async function z0(G){if(!G)return;let V=await k($),K=V?.refresh?.mainLastRefreshError;if(!V?.refresh||!K?.tokenHash)return;let _=o0(G);if(K.tokenHash===_)return;if(K.nextRetryAt&&K.nextRetryAt>Date.now()){C("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:K.nextRetryAt,retryCount:K.retryCount,remainingMs:K.nextRetryAt-Date.now()});return}V.refresh.mainLastRefreshError=void 0,await A0(V,$,{mainRefresh:!0}),C("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:K.checkedAt,previousNextRetryAt:K.nextRetryAt,previousRetryCount:K.retryCount})}async function c(){let G=[];if(y)try{let L=await y();if(L.type==="oauth"&&L.access){let A=await Z.refreshMain(L.access);G.push({name:"OpenCode anthropic",role:"main",quota:A})}else if(L.type==="oauth")G.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(L){let A=L instanceof Error?L.message:String(L);G.push({name:"OpenCode anthropic",role:"main",error:A.includes("429")?"Usage API rate limited — try again in a moment":A})}let{storage:V,errors:K}=await P.refreshQuotaForAllAccounts({force:!0}),_=new Map(K.map((L)=>[L.accountId,L.message]));if(G.push(...lj(V,_)),!y)G.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return dj({accounts:G,refreshedAt:Date.now()})}async function v0(G){let V=Tj(G);if(V.type==="enable"||V.type==="disable"){let A=V.type==="enable",w=await _j(A),n=c0(w);return k0({enabled:A,mode:n}),s0({argumentsText:G,enabled:A,mode:n})}if(V.type==="mode"){let A=await Lj(V.mode),w=n0(A);return k0({enabled:w,mode:V.mode}),s0({argumentsText:G,enabled:w,mode:V.mode})}let K=await k($),_=n0(K),L=c0(K);return k0({enabled:_,mode:L}),s0({argumentsText:G,enabled:_,mode:L})}async function V0(G){let V=wj(G),K=await k($);if(V.type==="window")K=await Fj(V.startHour,V.endHour);else if(V.type==="disable")K=await Nj(!1);let _=Ej(K),L=m.stats(_);return Aj({argumentsText:G,enabled:Sj(K),window:_,hybridActive:M1(K),trackedSessions:L.trackedSessions,nextPrewarmAt:L.nextPrewarmAt})}async function x0(G){let V=fj(G);if(V.type==="enable"||V.type==="disable"){let L=V.type==="enable";return await Qj(L),j1(L),T1({argumentsText:G,enabled:L})}let K=await k($),_=H1(K);return j1(_),T1({argumentsText:G,enabled:_})}async function m0(G){let V=kj(G);if(V.type==="enable"||V.type==="disable"){let L=V.type==="enable";return await Uj(L),D1(L),C1({argumentsText:G,enabled:L})}let K=await k($),_=B1(K);return D1(_),C1({argumentsText:G,enabled:_})}async function W1(G){let V=nj(G);if(V.type==="mode")return await ij(V.mode),S1({argumentsText:G,mode:V.mode});let K=await k();return S1({argumentsText:G,mode:E1(K)})}function Y1(G,V=10){let K=Math.max(0,Math.min(Math.round(G/100*V),V));return"█".repeat(K)+"░".repeat(V-K)}function X0(G,V){return`${G} ${Y1(V)} ${String(Math.round(V)).padStart(3)}%`}function q0(G){if(!G)return"";let V=new Date(G).getTime();if(Number.isNaN(V))return"";let K=V-Date.now();if(K<=0)return"resets now";let _=Math.floor(K/60000);if(_<1)return"resets <1m";if(_<60)return`resets ${_}m`;let L=Math.floor(_/60),A=_%60;return A>0?`resets ${L}h${A}m`:`resets ${L}h`}function _0(G,V,K){let _=[],L=0;if(G){let{five_hour:n,seven_day:J0}=G;if(n||J0){let Z0=K==="main"?"active":"idle",K0=q0(n?.resetsAt),L0=[`main · ${Z0}${K0?` (${K0})`:""}`];if(n)L0.push(X0("5h",n.usedPercent)),L=Math.max(L,n.usedPercent);if(J0)L0.push(X0("7d",J0.usedPercent)),L=Math.max(L,J0.usedPercent);_.push(L0.join(`
|
|
4
|
-
`))}
|
|
5
|
-
`))}if(!_.length)return;let A=_.join(`
|
|
3
|
+
`);for(let V of Jj)W=W.replace(V.match,V.replacement);return W.trim()}var PJ=8388608;function zJ(){return process.env.OPENCODE_ANTHROPIC_AUTH_MEMO!=="0"}var DJ=p1(OJ,{maxBytes:PJ,enabled:zJ});function u0(j){return DJ.call(j)}function d(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function NJ(j){let $={type:"text",text:q0};if(j==null)return[$];if(typeof j==="string"){let W=u0(j);if(W===q0)return[$];return[$,{type:"text",text:W}]}if(d(j)){let W=typeof j.type==="string"?j.type:"text",V=typeof j.text==="string"?j.text:"";return[$,{...j,type:W,text:u0(V)}]}if(!Array.isArray(j))return[$];let J=j.map((W)=>{if(typeof W==="string")return{type:"text",text:u0(W)};if(d(W)&&W.type==="text"&&typeof W.text==="string")return{...W,type:"text",text:u0(W.text)};return{type:"text",text:String(W)}});if(J[0]?.text===q0)return J;return[$,...J]}var Pj={type:"ephemeral",ttl:"1h"},IJ=20;function _J(j){if(d(j.cache_control))return j.cache_control;if(d(j.cacheControl))return j.cacheControl;return null}function r0(j,$){if(!d(j))return!1;return delete j.cacheControl,j.cache_control=$?{...Pj}:{type:"ephemeral"},!0}function u1(j){if(!d(j))return;delete j.cache_control,delete j.cacheControl}function LJ(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function n0(j,$){if(!d(j))return;let J=_J(j);if(J?.type!=="ephemeral")return;if($)J.ttl="1h";else delete J.ttl}function n1(j,$){if(Array.isArray(j.system))for(let J of j.system)n0(J,$);else n0(j.system,$);if(!Array.isArray(j.messages))return;for(let J of j.messages)if(n0(J,$),d(J)&&Array.isArray(J.content))for(let W of J.content)n0(W,$)}function QJ(j,$){if(Array.isArray(j.system))for(let J of j.system)$(J);else $(j.system);if(!Array.isArray(j.messages))return;for(let J of j.messages)if($(J),d(J)&&Array.isArray(J.content))for(let W of J.content)$(W)}function zj(j){u1(j),QJ(j,u1)}function wJ(j){zj(j),j.cache_control={...Pj}}function MJ(j){return d(j)&&j.type!=="thinking"&&j.type!=="redacted_thinking"}function w1(j){let $=LJ(j.content);if(!$?.length)return;let J=$.filter(MJ);if(!J.length)return;return{content:$,cacheableBlocks:J}}function UJ(j){if(!d(j))return!1;let $=w1(j);if(!$)return!1;return j.content=$.content,r0($.cacheableBlocks[0],!0)}function c0(j){if(!d(j))return!1;let $=w1(j);if(!$)return!1;let J=$.cacheableBlocks[$.cacheableBlocks.length-1];return j.content=$.content,r0(J,!0)}function BJ(j){if(!d(j))return!1;return(w1(j)?.cacheableBlocks.length??0)>1}function CJ(j){if(!d(j))return 0;let $=j.content;if(Array.isArray($))return $.length;if($==null)return 0;return 1}function HJ(j){let $=[],J=0;return j.forEach((W,V)=>{let O=CJ(W);if(d(W)&&W.role==="user"&&O>0)$.push({index:V,blockPosition:J+O-1});J+=O}),$}function FJ(j){let $=HJ(j),J=[...$].reverse().find((Q)=>Q.index>1);if(!J)return{latest:void 0,bridge:void 0};let W=[...$].reverse().find((Q)=>Q.index<J.index),V=W?J.blockPosition-W.blockPosition+1:0,O=W&&W.index>1&&V>IJ?W:void 0;return{latest:J,bridge:O}}function c1(j){if(Array.isArray(j.system)){let $=j.system.findIndex((V)=>d(V)&&V.text===q0),J=j.system.slice($>=0?$+1:0).filter(d),W=J[J.length-1];r0(W,!0)}else r0(j.system,!0)}function xJ(j){if(zj(j),!Array.isArray(j.messages)){c1(j);return}let{latest:$,bridge:J}=FJ(j.messages);if(!J)c1(j);let W=BJ(j.messages[0]);if(W)UJ(j.messages[0]);if(c0(j.messages[0]),!W)c0(j.messages[1]);if(J)c0(j.messages[J.index]);if($)c0(j.messages[$.index])}function TJ(j){if(!Kj(j.model))return null;let $=Object.hasOwn(j,"thinking");return j.thinking={...Zj},{replacedExisting:$}}function qJ(j,$){if(!$.enabled){n1(j,!1),delete j.cache_control,delete j.cacheControl;return}if($.mode==="automatic"){wJ(j);return}if($.mode==="hybrid"){xJ(j);return}n1(j,!0),delete j.cacheControl}function EJ(j){if(!Array.isArray(j.messages))return;while(j.messages.length){let $=j.messages[j.messages.length-1];if(!d($)||$.role!=="assistant")break;j.messages.pop()}}function R(){return performance.now()}function e(j){return Math.round(j*10)/10}function o1(j){let $=0,J=0,W=0,V=Array.isArray(j.messages)?j.messages:[];$=V.length;for(let O of V){if(!O||typeof O!=="object")continue;let Q=O.content;if(!Array.isArray(Q))continue;J+=Q.length;for(let v of Q)if(v&&typeof v==="object"&&v.type==="tool_use")W++}return{messageCount:$,contentBlockCount:J,toolDefinitionCount:Array.isArray(j.tools)?j.tools.length:0,toolUseCount:W,systemBlockCount:Array.isArray(j.system)?j.system.length:0}}async function M1(j,$={}){try{let J=R(),W=JSON.parse(j);$.perf?.("parse",{ms:e(R()-J),inputBytes:j.length,...o1(W)});let V=R(),O=Array.isArray(W.messages)?W.messages.length:void 0;EJ(W);let Q=Array.isArray(W.messages)?W.messages.length:void 0;$.perf?.("strip_trailing_assistant",{ms:e(R()-V),removedMessages:typeof O==="number"&&typeof Q==="number"?O-Q:void 0});let v=R(),u=TJ(W);$.perf?.("model_normalize",{ms:e(R()-v),model:typeof W.model==="string"?W.model:void 0,fableMythosThinkingDisplay:u?"summarized":void 0,replacedFableMythosThinking:u?.replacedExisting??!1,hasOutputConfig:Object.hasOwn(W,"output_config")});let n=R(),r=Array.isArray(W.messages)&&W.messages.some((V0)=>V0.role==="user")?Vj(W.messages,void 0,e1):null;$.perf?.("billing_header",{ms:e(R()-n),hasBillingHeader:Boolean(r)});let h=R();if(W.system=NJ(W.system),$.perf?.("system_identity",{ms:e(R()-h),systemBlockCount:Array.isArray(W.system)?W.system.length:0}),r&&Array.isArray(W.system))W.system.unshift({type:"text",text:r});let A=R();if(qJ(W,{enabled:$.cache1hEnabled??!1,mode:$.cache1hMode??"explicit"}),$.perf?.("cache_strategy",{ms:e(R()-A),enabled:$.cache1hEnabled??!1,mode:$.cache1hMode??"explicit"}),$.fastModeEnabled&&R0(W.model))W.speed="fast";else if(W.speed==="fast")delete W.speed;let c=R();if($.identity)Wj(W,$.identity);$.perf?.("metadata",{ms:e(R()-c),hasAccountUuid:Boolean($.identity?.accountUuid)});let t=R(),p=KJ(W);$.perf?.("prefix_tools_stringify",{ms:e(R()-t),outputBytesBeforeSign:p.length,...o1(W)});let G0=R(),I0=await $j(p);return $.perf?.("cch_sign",{ms:e(R()-G0),outputBytes:I0.length}),I0}catch{return j}}var RJ=new TextEncoder;function vJ(){return{pending:"",events:0,parseErrors:0,eventCounts:{},typeCounts:{},deltaTypeCounts:{},contentBlockTypeCounts:{},textDeltaBytes:0,thinkingDeltaBytes:0,inputJsonDeltaBytes:0,signatureDeltaBytes:0,redactedThinkingBytes:0}}function o0(j,$){if(!$)return;j[$]=(j[$]??0)+1}function z0(j){return RJ.encode(j).byteLength}function U0(j){return j&&typeof j==="object"&&!Array.isArray(j)?j:void 0}function X0(j,$){let J=j?.[$];return typeof J==="string"?J:void 0}function SJ(j,$){let J=j?.[$];return typeof J==="number"?J:void 0}function AJ(j){if(!j.trim())return null;let $,J=[];for(let h of j.split(/\r?\n/)){if(h.startsWith("event:")){$=h.slice(6).trim();continue}if(h.startsWith("data:")){let A=h.slice(5);J.push(A.startsWith(" ")?A.slice(1):A)}}let W=J.join(`
|
|
4
|
+
`),V={event:$,rawBytes:z0(j),dataBytes:z0(W)};if(!W||W==="[DONE]")return V.type=W==="[DONE]"?"done":void 0,V.event??=V.type,V;let O;try{O=JSON.parse(W)}catch{return V}let Q=U0(O),v=U0(Q?.delta),u=U0(Q?.content_block),n=U0(Q?.message),r=U0(Q?.usage)??U0(n?.usage);if(V.type=X0(Q,"type"),V.event??=V.type,V.index=SJ(Q,"index"),V.contentBlockType=X0(u,"type"),V.deltaType=X0(v,"type"),V.stopReason=X0(Q,"stop_reason"),V.deltaType==="text_delta")V.textDeltaBytes=z0(X0(v,"text")??"");if(V.deltaType==="thinking_delta")V.thinkingDeltaBytes=z0(X0(v,"thinking")??"");if(V.deltaType==="input_json_delta")V.inputJsonDeltaBytes=z0(X0(v,"partial_json")??"");if(V.deltaType==="signature_delta")V.signatureDeltaBytes=z0(X0(v,"signature")??"");if(V.contentBlockType==="redacted_thinking")V.redactedThinkingBytes=z0(X0(u,"data")??"");if(r)V.stopReason??=X0(n,"stop_reason");return V}function fJ(j){let $=j.indexOf(`
|
|
6
5
|
|
|
7
|
-
`),
|
|
6
|
+
`),J=j.indexOf(`\r
|
|
7
|
+
\r
|
|
8
|
+
`);if($===-1)return J===-1?null:{index:J,length:4};if(J===-1||$<J)return{index:$,length:2};return{index:J,length:4}}function r1(j,$){if(!$)return;j.pending+=$;while(!0){let J=fJ(j.pending);if(!J)break;let W=j.pending.slice(0,J.index);j.pending=j.pending.slice(J.index+J.length);let V=AJ(W);if(!V)continue;if(j.events++,o0(j.eventCounts,V.event??"unknown"),o0(j.typeCounts,V.type),o0(j.deltaTypeCounts,V.deltaType),o0(j.contentBlockTypeCounts,V.contentBlockType),j.textDeltaBytes+=V.textDeltaBytes??0,j.thinkingDeltaBytes+=V.thinkingDeltaBytes??0,j.inputJsonDeltaBytes+=V.inputJsonDeltaBytes??0,j.signatureDeltaBytes+=V.signatureDeltaBytes??0,j.redactedThinkingBytes+=V.redactedThinkingBytes??0,j.last=V,V.dataBytes>0&&!V.type&&!V.event)j.parseErrors++}}function kJ(j){return{sseEvents:j.events,ssePendingChars:j.pending.length,sseParseErrors:j.parseErrors,sseEventCounts:{...j.eventCounts},sseTypeCounts:{...j.typeCounts},sseDeltaTypeCounts:{...j.deltaTypeCounts},sseContentBlockTypeCounts:{...j.contentBlockTypeCounts},sseTextDeltaBytes:j.textDeltaBytes,sseThinkingDeltaBytes:j.thinkingDeltaBytes,sseInputJsonDeltaBytes:j.inputJsonDeltaBytes,sseSignatureDeltaBytes:j.signatureDeltaBytes,sseRedactedThinkingBytes:j.redactedThinkingBytes,sseLastEvent:j.last?{...j.last}:void 0}}function S0(j,$={}){if(!j.body)return j;let J=j.body.getReader(),W=new TextDecoder,V=new TextEncoder,O="",Q=0,v=0,u=0,n=0,r=0,h=!1,A=!1,c=R(),t=R(),p=$.perf?vJ():void 0,G0=()=>{if(A)return;A=!0,J.releaseLock()},I0=(s={})=>({chunks:Q,pulls:v,inputBytes:u,outputBytes:n,pendingChars:O.length,rewriteMs:e(r),totalMs:e(R()-t),...p?kJ(p):{},...s}),V0=(s,F0={})=>{$.perf?.(s,I0(F0))};$.perf?.("stream_tool_prefix_wrapper_created",{status:j.status,hasBody:!0});let D1=new ReadableStream({async pull(s){if(v++,!h)h=!0,V0("stream_tool_prefix_first_pull");let F0=R();try{let{done:K0,value:x0}=await J.read(),m0=e(R()-F0);if(K0){let G=W.decode();if(p)r1(p,G);let P=R(),N=i1(`${O}${G}`,!0);if(r+=R()-P,N.ready){let I=V.encode(N.ready);n+=I.byteLength,s.enqueue(I)}V0("stream_tool_prefix_rewrite",{readMs:m0}),G0(),s.close();return}Q++,u+=x0.byteLength;let g0=W.decode(x0,{stream:!0});if(p)r1(p,g0);let _0=O+g0,p0=R(),T0=i1(_0);if(r+=R()-p0,O=T0.pending,T0.ready){let G=V.encode(T0.ready);n+=G.byteLength,s.enqueue(G)}let X=R();if(Q===1||Q%25===0||X-c>5000)c=X,V0("stream_tool_prefix_progress",{readMs:m0,lastChunkBytes:x0.byteLength})}catch(K0){throw V0("stream_tool_prefix_error",{error:K0 instanceof Error?K0.message:String(K0)}),G0(),K0}},async cancel(s){V0("stream_tool_prefix_cancel",{reason:s instanceof Error?s.message:String(s)});try{await J.cancel(s)}finally{G0()}}});return new Response(D1,{status:j.status,statusText:j.statusText,headers:j.headers})}var bJ="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",hJ=60000,mJ=60000,gJ=5000,Dj=200,jJ=240,pJ=jJ,dJ=1,Nj=!1;function z1(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function U(){return performance.now()}function S(j){return Math.round(j*10)/10}function Ij(j){return Math.floor(Math.random()*Math.max(0,j))}function lJ(){if(Nj||!1||!z1())return;Nj=!0;let j=100,$=250,J=U()+j;setInterval(()=>{let W=U(),V=W-J;if(J=W+j,V<$)return;q("[perf] opencode event_loop_lag",{lagMs:S(V),thresholdMs:$})},j).unref?.()}function iJ(j){let $=U(),J={requestId:String(dJ++),start:$,last:$,mark(W,V){let O=U();if(z1())q("[perf] opencode request stage",{requestId:J.requestId,stage:W,deltaMs:S(O-J.last),totalMs:S(O-J.start),...V});J.last=O},done(W,V){let O=U();if(z1())q("[perf] opencode request done",{requestId:J.requestId,stage:W,deltaMs:S(O-J.last),totalMs:S(O-J.start),...V});J.last=O}};if(z1())q("[perf] opencode request start",{requestId:J.requestId,...j});return J}async function D0(j,$,J){let W=j.client.session,V=await g1(j.client,$),O={path:{id:$},body:{noReply:!0,parts:[{type:"text",text:J,ignored:!0}]}};if(V?.agent)O.body.agent=V.agent;if(V?.model)O.body.model=V.model;if(V?.variant)O.body.variant=V.variant;if(typeof W?.promptAsync==="function"){await W.promptAsync(O);return}if(typeof W?.prompt==="function"){await Promise.resolve(W.prompt(O));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function N0(){throw Error(bJ)}function uJ(j){if(j.sessionID==null)return!1;let $=j.model;return $?.providerID==="anthropic"||$?.api?.npm==="@ai-sdk/anthropic"||$?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function nJ(j){if(j.some(($)=>$.includes("<use_parallel_tool_calls>")))return!1;return j.push(_j),!0}var cJ={input:0,output:0,cache:{read:0,write:0}};function oJ(j){let $=j["claude-opus-4-8"]??j["claude-opus-4-5"]??Object.values(j)[0];if(!$)return j;return{...j,...Object.fromEntries(Object.values(nj).map((J)=>[J.id,{...$,id:J.id,name:J.name,api:$.api?{...$.api,id:J.id}:void 0,cost:{input:h0.input,output:h0.output,cache:{read:h0.cacheRead,write:h0.cacheWrite5m}},limit:{...$.limit??{},context:lj,output:ij},capabilities:{...$.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:uj}]))}}function rJ(j){return Object.fromEntries(Object.entries(j).map(([$,J])=>[$,{...J,cost:cJ}]))}var Z3=async(j)=>{lJ();let{client:$}=j,J=wj(),W=await b(J),V=new cj({storage:W,onMainQuotaFetched:async(X,G,P)=>{try{let N=await b(J)??{version:1,accounts:[]};N.quota=N.quota??{},N.quota.mainQuota=X,N.quota.mainQuotaCheckedAt=G,N.quota.mainQuotaToken=P,N.quota.mainLastQuotaApiError=void 0,await f0(N,J,{mainQuota:!0})}catch(N){q("[quota] failed to persist main quota",{error:N instanceof Error?N.message:String(N)})}},onApiError:async(X)=>{try{let G=await b(J)??{version:1,accounts:[]};G.quota=G.quota??{},G.quota.mainLastQuotaApiError=X,await f0(G,J,{mainQuota:!0})}catch(G){q("[quota] failed to persist backoff state",{error:G instanceof Error?G.message:String(G)})}}}),O=new Sj({quotaManager:V,onFallbackStorageChanged:()=>{r()}});O.startBackgroundRefresh();let Q=null,v=new mj({loadStorage:()=>b(J),prepareHeaders:async(X,G)=>{if(!A)return X;let P=await A();if(P.type!=="oauth")return X;if(!P.access||P.expires&&P.expires<Date.now()){if(!Q)return X;P.access=await Q()}if(!P.access)return X;try{let N=JSON.parse(G.bodyText),I=await E1(P.access,typeof N.model==="string"?N.model:void 0);if(X.delete("anthropic-beta"),v0(X,P.access,{body:N,identity:I}),X.set("anthropic-beta",E0(X.get("anthropic-beta"),[fj])),N.speed==="fast")s0(X)}catch{v0(X,P.access)}return X},log:q});b0({enabled:t0(W),mode:a0(W)}),X1(F1(W)),K1(x1(W));let u={activeId:"main",route:"main"};function n(X,G){u={activeId:G.activeId,route:G.route};let P=V.getMain(G.mainAccessToken),N=V.getLastApiError(),I=X?.refresh?.mainLastRefreshError,f={main:{quota:P?.quota??null,quotaBackedOff:V.isBackedOff(),quotaBackoffUntil:N?.nextRetryAt,refreshBackedOff:I?B0(I,G.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:I?.nextRetryAt},fallbacks:(X?.accounts??[]).filter((E)=>E.enabled!==!1&&j0(E)).map((E)=>({id:E.id,label:E.label,quota:E.access?V.getFallback(E.id,E.access)?.quota??null:null,enabled:E.enabled!==!1})),activeId:G.activeId,route:G.route,relay:(()=>{let E=A1(X);return E?{enabled:!0,transport:E.transport??"http"}:null})(),fastMode:Z1(),cacheKeep:{enabled:R1(X),window:X?.cacheKeep?.startHour!=null&&X?.cacheKeep?.endHour!=null?`${X.cacheKeep.startHour}-${X.cacheKeep.endHour}`:void 0,trackedSessions:v.trackedCount()},lastUpdated:Date.now()};ej(f).catch((E)=>q("[sidebar] state write failed",{error:E instanceof Error?E.message:String(E)}))}async function r(){let X=await b(J),G,P;if(A)try{let N=await A();G=N.access,P=N.refresh}catch{}n(X,{activeId:u.activeId,route:u.route,mainAccessToken:G,mainRefreshToken:P})}function h(X,G){if(!G)return;if(X?.quota?.enabled!==!0)return;if(V.getMain(G))return;if(c)return;c=!0,V.refreshMain(G).then(()=>r()).catch(()=>{}).finally(()=>{c=!1})}let A=null,c=!1,t=null,p=0;function G0(X){let G=X?.refresh?.refreshBeforeExpiryMinutes??pJ;return Math.max(jJ,G)*60000}function I0(X){return X?.refresh?.enabled!==!1}async function V0(X){if(!X)return;let G=await b(J),P=G?.refresh?.mainLastRefreshError;if(!G?.refresh||!P?.tokenHash)return;let N=e0(X);if(P.tokenHash===N)return;if(P.nextRetryAt&&P.nextRetryAt>Date.now()){q("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:P.nextRetryAt,retryCount:P.retryCount,remainingMs:P.nextRetryAt-Date.now()});return}G.refresh.mainLastRefreshError=void 0,await f0(G,J,{mainRefresh:!0}),q("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:P.checkedAt,previousNextRetryAt:P.nextRetryAt,previousRetryCount:P.retryCount})}async function D1(){let X=[];if(A)try{let I=await A();if(I.type==="oauth"&&I.access){let f=await V.refreshMain(I.access);X.push({name:"OpenCode anthropic",role:"main",quota:f})}else if(I.type==="oauth")X.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(I){let f=I instanceof Error?I.message:String(I);X.push({name:"OpenCode anthropic",role:"main",error:f.includes("429")?"Usage API rate limited — try again in a moment":f})}let{storage:G,errors:P}=await O.refreshQuotaForAllAccounts({force:!0}),N=new Map(P.map((I)=>[I.accountId,I.message]));if(X.push(...oj(G,N)),!A)X.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return rj({accounts:X,refreshedAt:Date.now()})}async function s(X){let G=Aj(X);if(G.type==="enable"||G.type==="disable"){let f=G.type==="enable",E=await Uj(f),o=a0(E);return b0({enabled:f,mode:o}),$1({argumentsText:X,enabled:f,mode:o})}if(G.type==="mode"){let f=await Bj(G.mode),E=t0(f);return b0({enabled:E,mode:G.mode}),$1({argumentsText:X,enabled:E,mode:G.mode})}let P=await b(J),N=t0(P),I=a0(P);return b0({enabled:N,mode:I}),$1({argumentsText:X,enabled:N,mode:I})}async function F0(X){let G=kj(X),P=await b(J);if(G.type==="window")P=await Fj(G.startHour,G.endHour);else if(G.type==="disable")P=await xj(!1);let N=yj(P),I=v.stats(N);return hj({argumentsText:X,enabled:bj(P),window:N,hybridActive:R1(P),trackedSessions:I.trackedSessions,nextPrewarmAt:I.nextPrewarmAt})}async function K0(X){let G=gj(X);if(G.type==="enable"||G.type==="disable"){let I=G.type==="enable";return await Cj(I),X1(I),v1({argumentsText:X,enabled:I})}let P=await b(J),N=F1(P);return X1(N),v1({argumentsText:X,enabled:N})}async function x0(X){let G=pj(X);if(G.type==="enable"||G.type==="disable"){let I=G.type==="enable";return await Hj(I),K1(I),S1({argumentsText:X,enabled:I})}let P=await b(J),N=x1(P);return K1(N),S1({argumentsText:X,enabled:N})}async function m0(X){let G=aj(X);if(G.type==="mode")return await tj(G.mode),k1({argumentsText:X,mode:G.mode});let P=await b();return k1({argumentsText:X,mode:f1(P)})}function g0(X,G=10){let P=Math.max(0,Math.min(Math.round(X/100*G),G));return"█".repeat(P)+"░".repeat(G-P)}function _0(X,G){return`${X} ${g0(G)} ${String(Math.round(G)).padStart(3)}%`}function p0(X){if(!X)return"";let G=new Date(X).getTime();if(Number.isNaN(G))return"";let P=G-Date.now();if(P<=0)return"resets now";let N=Math.floor(P/60000);if(N<1)return"resets <1m";if(N<60)return`resets ${N}m`;let I=Math.floor(N/60),f=N%60;return f>0?`resets ${I}h${f}m`:`resets ${I}h`}function T0(X,G,P){let N=[],I=0;if(X){let{five_hour:o,seven_day:J0}=X;if(o||J0){let Z0=P==="main"?"active":"idle",O0=p0(o?.resetsAt),L0=[`main · ${Z0}${O0?` (${O0})`:""}`];if(o)L0.push(_0("5h",o.usedPercent)),I=Math.max(I,o.usedPercent);if(J0)L0.push(_0("7d",J0.usedPercent)),I=Math.max(I,J0.usedPercent);N.push(L0.join(`
|
|
9
|
+
`))}}if(G?.length)for(let o of G){let J0=o.quota;if(!J0)continue;let{five_hour:Y0,seven_day:Z0}=J0;if(!Y0&&!Z0)continue;let O0=o.label||"alt",d0=P===o.id?"active":"idle",Q0=p0(Y0?.resetsAt),P0=[`${O0} · ${d0}${Q0?` (${Q0})`:""}`];if(Y0)P0.push(_0("5h",Y0.usedPercent)),I=Math.max(I,Y0.usedPercent);if(Z0)P0.push(_0("7d",Z0.usedPercent)),I=Math.max(I,Z0.usedPercent);N.push(P0.join(`
|
|
10
|
+
`))}if(!N.length)return;let f=N.join(`
|
|
8
11
|
|
|
9
|
-
`)&&R.length<65536){let{done:X,value:H}=await z.read();if(X)break;if(T.push(H),I+=H.byteLength,R+=W.decode(H,{stream:!0}),J0(R))break}if(J0(R))return await z.cancel().catch(()=>{}),O?.mark("inspect_stream_first_event",{ms:S(N()-q),bytes:I,rateLimited:!0}),{response:Y,rateLimited:!0};let M=new ReadableStream({start(X){for(let H of T)X.enqueue(H)},async pull(X){let{done:H,value:U}=await z.read();if(H){X.close();return}X.enqueue(U)},cancel(X){return z.cancel(X)}});return O?.mark("inspect_stream_first_event",{ms:S(N()-q),bytes:I,rateLimited:!1}),{response:new Response(M,{status:Y.status,statusText:Y.statusText,headers:Y.headers}),rateLimited:!1}}async function L0(Y,O,q,z,T="api_fallback",W){let R=N(),I=I1(Y,O),M=n(I);I.delete("x-parent-session-id"),I.delete("x-session-affinity"),I.delete("x-opencode-session");let X=O?.body,H=typeof X==="string"?X.length:void 0;if(X&&typeof X==="string"){let l=N(),x=(()=>{if(!$1())return!1;try{return C0(JSON.parse(X).model)}catch{return!1}})();if(X=await L1(X,{cache1hEnabled:!M&&H0(),cache1hMode:B0(),fastModeEnabled:x,perf:(Q,F)=>z?.mark(`rewrite_body_${Q}`,{route:T,...F})}),K0(I,q),I.set("anthropic-beta",T0(I.get("anthropic-beta"),[])),x)i0(I);z?.mark("rewrite_body",{route:T,ms:S(N()-l),originalBytes:H,rewrittenBytes:X.length,cacheEnabled:!M&&H0(),cacheMode:B0(),fastModeEnabled:x,subagent:M})}else K0(I,q);let U=z1(Y,{baseURL:q.baseURL}),B=N(),b=await fetch(U.input,{...O,body:X,headers:I,...O1()&&{tls:{rejectUnauthorized:!1}}});return z?.mark("send_headers_received",{route:T,ms:S(N()-B),status:b.status,relayConfigured:!1,totalSendWithAccessMs:S(N()-R),baseURL:q.baseURL}),b}async function b0(Y,O,q,z,T="unknown",W){let R=N(),I=W,M=async()=>{return I??=await k($),I},X=I1(Y,O),H=X.get("x-session-affinity")||X.get("x-opencode-session"),U=n(X);X.delete("x-parent-session-id"),X.delete("x-session-affinity"),X.delete("x-opencode-session");let B=O?.body,b;if(B&&typeof B==="string"){let $0=N();try{let G0=JSON.parse(B);if(typeof G0.model==="string")b=G0.model}catch{}z?.mark("model_parse_for_identity",{route:T,ms:S(N()-$0),bodyBytes:B.length})}let l=N(),x=await q1(q,b);z?.mark("resolve_claude_code_identity",{route:T,ms:S(N()-l),hasAccountUuid:Boolean(x.accountUuid)});let Q=typeof B==="string"?B.length:void 0;if(B&&typeof B==="string"){let $0=N(),G0=(()=>{if(!$1())return!1;try{return C0(JSON.parse(B).model)}catch{return!1}})();B=await L1(B,{cache1hEnabled:!U&&H0(),cache1hMode:B0(),fastModeEnabled:G0,identity:x,perf:(sj,tj)=>z?.mark(`rewrite_body_${sj}`,{route:T,...tj})});let U0=N();try{w0(X,q,{body:JSON.parse(B),identity:x}),z?.mark("set_oauth_headers_body_parse",{route:T,ms:S(N()-U0),bodyBytes:B.length,parsed:!0})}catch{w0(X,q,{identity:x}),z?.mark("set_oauth_headers_body_parse",{route:T,ms:S(N()-U0),bodyBytes:B.length,parsed:!1})}if(G0)i0(X);z?.mark("rewrite_body",{route:T,ms:S(N()-$0),originalBytes:Q,rewrittenBytes:B.length,cacheEnabled:!U&&H0(),cacheMode:B0(),fastModeEnabled:G0,subagent:U})}let F=z1(Y);if(T==="main"&&typeof B==="string"&&!U&&H0()&&B0()==="hybrid"){let $0=await M(),G0=N(),U0=m.track({sessionId:H,url:F.url?.toString()??F.input.toString(),headers:X,bodyText:B,storage:$0,cacheMode:"hybrid"});z?.mark("cachekeep_track",{session:H,ms:S(N()-G0),tracked:U0.tracked,reason:U0.tracked?void 0:U0.reason,bodyBytes:B.length})}let f=()=>fetch(F.input,{...O,body:B,headers:X,...O1()&&{tls:{rejectUnauthorized:!1}}}),r=w1(await M()),g=N(),d=await uj({config:r,input:F.input,init:O,headers:X,body:B,fallback:f,affinity:H,optimisticResponse:r?.transport==="websocket"});return z?.mark("send_headers_received",{route:T,ms:S(N()-g),status:d.status,relayConfigured:r!=null,totalSendWithAccessMs:S(N()-R)}),d}async function rj(Y){if(!Y)return!1;try{return await Z.refreshMain(Y),K1(Y)}catch{return!1}}async function g0(Y,O={}){let q=await P.getUsableFallbackAccounts(Y),z=new Map(q.map((W)=>[W.id,W])),T=[];for(let W of Y?.accounts??[]){if(e(W)){let R=z.get(W.id);if(R)T.push(R);continue}if(O.includeApiRoutes===!0&&S0(W)&&W.enabled!==!1&&W.apiKey&&N1(W.baseURL))T.push(W)}if(!f0(Y))return T;return T.filter((W)=>e(W)?r0(Q0(W),Y,W.id):!0)}async function h0(Y,O,q,z,T,W,R){if(!q.length)return T??null;let I=R?.returnLastOnExhausted??!0;await T?.body?.cancel().catch(()=>{});let M=T??null;for(let[X,H]of q.entries()){let U;if(S0(H)){if(!H.apiKey)continue;U=await L0(Y,O,H,W,`api_fallback_${X}`,z)}else{let b=H.access;if(!b)continue;U=await b0(Y,O,b,W,`fallback_${X}`,z)}M=U;let B=v1(U.status,z);if(!B){let b=await Z0(U,W);U=b.response,M=U,B=b.rateLimited}if(!B){if(await P.markUsed(H),R?.onSuccess?.(H),e(H)&&H.access&&Z.shouldRefreshOnRequestCount(i))Z.refreshFallback(H.id,H.access).then(()=>R?.onSuccess?.(H)).catch(()=>{});return U}if(X<q.length-1||!I)await U.body?.cancel().catch(()=>{})}return I?M:null}async function aj(Y,O,q,z,T,W,R,I){if(!w(Y,O?.body))return q;let M=N(),X=W??await k($);if(T?.mark("fallback_load_storage",{ms:S(N()-M),cached:!!W}),!(X?.accounts??[]).some((Q)=>Q.enabled!==!1&&(e(Q)||S0(Q)&&Boolean(Q.apiKey)&&N1(Q.baseURL))))return q;let U=q,B=v1(U.status,X),b=A1(U,!1);if(!B){let Q=await Z0(U,T);U=Q.response,B=Q.rateLimited,b=A1(U,Q.rateLimited)}if(!B)return U;let l=!1;if(z)l=z.some(S0);else if(b)l=await rj(R);let x=z;if(!x){let Q=N();x=await g0(X,{includeApiRoutes:l}),T?.mark("fallback_get_accounts",{ms:S(N()-Q),accounts:x.length})}if(f0(X)){let Q=x.length;if(x=x.filter((F)=>e(F)?r0(Q0(F),X,F.id):!0),x.length<Q)C("[killswitch] filtered fallbacks",{before:Q,after:x.length})}return await h0(Y,O,x,X,U,T,{onSuccess:I})??U}return{apiKey:"",async fetch(Y,O){let q=O?.body,z=AJ({bodyBytes:typeof q==="string"?q.length:void 0}),T=N(),W=await G();if(z.mark("get_auth",{ms:S(N()-T),authType:W.type,hasAccess:Boolean(W.access)}),W.type!=="oauth"){let Q=await fetch(Y,O);return z.done("non_oauth_passthrough",{status:Q.status}),Q}await z0(W.refresh);let R=N(),I=await k();z.mark("load_storage",{ms:S(N()-R)}),Z.updateStorage(I),Z.seedFallbacksFromAccounts((I?.accounts??[]).filter(e));let M=w(Y,O?.body);if(M)i++;if(M&&W.access&&(!W.expires||W.expires>Date.now()))p(I,W.access);let X=(Q,F)=>a(I,{activeId:Q,route:F,mainAccessToken:W.access,mainRefreshToken:W.refresh}),H;if(M&&E1(I)==="fallback-first")try{let Q=N();H=await g0(I,{includeApiRoutes:K1(W.access)}),z.mark("fallback_first_get_accounts",{ms:S(N()-Q),accounts:H.length});let F=await h0(Y,O,H,I,void 0,z,{returnLastOnExhausted:!1,onSuccess:(f)=>X(f.id,"fallback-first")});if(F)return z.done("return_fallback_first",{status:F.status}),E0(F,{perf:(f,r)=>z.mark(f,r)});H=void 0}catch(Q){z.mark("fallback_first_error",{error:Q instanceof Error?Q.message:String(Q)})}if(!W.access||!W.expires||W.expires<Date.now()){let F=(await k())?.refresh?.mainLastRefreshError;if(W.refresh&&F&&N0(F,W.refresh,Date.now()))throw C("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:F.nextRetryAt,retryCount:F.retryCount,expiresInMs:W.expires?W.expires-Date.now():void 0}),Error(x1(F,Date.now()));C("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(W.access),expiresInMs:W.expires?W.expires-Date.now():void 0,expiredAgoMs:W.expires&&W.expires<Date.now()?Date.now()-W.expires:void 0});let f=N();W.access=await L(),z.mark("refresh_main_access",{ms:S(N()-f)})}if(!W.access)throw z.done("missing_access_error"),Error("OAuth access token is missing after refresh");function U(){if(I?.quota?.showToasts!==!0)return;let Q=Z.getMain();if(!Q)return;let F=(I?.accounts??[]).filter((g)=>g.enabled!==!1&&e(g)).map((g)=>({...g,quota:Z.getFallback(g.id,g.access)?.quota??g.quota})),f=R0(Q.quota,I),r;if(f)r="main";else r=F.find((g)=>R0(g.quota,I))?.id??"main";_0(Q.quota,F,r)}if(M&&W0(I))try{let Q=N(),F=Z.getMain(W.access),f=F?.quota;if(!f)f=await Z.refreshMain(W.access),F=Z.getMain(W.access),U();else if(Z.needsRefresh(i))if(P0(f))f=await Z.refreshMain(W.access),F=Z.getMain(W.access);else Z.refreshMain(W.access).then(()=>{s(),U()}).catch(()=>{});if(a(I,{activeId:"main",route:"main",mainAccessToken:W.access,mainRefreshToken:W.refresh}),z.mark("main_quota_for_routing",{ms:S(N()-Q),passes:R0(f,I)}),!R0(f,I)){let r=N();H=await g0(I,{includeApiRoutes:Boolean(F&&F.refreshAfter>Date.now()&&P0(F.quota))}),z.mark("preselect_fallback_accounts",{ms:S(N()-r),accounts:H.length});let g=await h0(Y,O,H,I,void 0,z,{onSuccess:(d)=>X(d.id,"fallback")});if(g)return z.done("return_preselected_fallback",{status:g.status}),E0(g,{perf:(d,$0)=>z.mark(d,$0)})}}catch(Q){z.mark("main_quota_for_routing_error",{error:Q instanceof Error?Q.message:String(Q)})}let B=Z.getMain(W.access)?.quota;if(I?.quota?.failClosedOnUnknownQuota&&!B&&Z.isBackedOff()){let Q=Z.getLastApiError(),F=Q?Bj(Q,Date.now()):"Quota API unavailable";return C("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:Q?.nextRetryAt,retryCount:Q?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:F}}),{status:429,headers:{"content-type":"application/json","retry-after":String(Q?.nextRetryAt?Math.max(1,Math.ceil((Q.nextRetryAt-Date.now())/1000)):60)}})}if(f0(I)){if(Z.needsRefresh(i))try{let F=(I?.accounts??[]).filter((f)=>f.enabled!==!1&&e(f)&&Boolean(f.access));await Promise.all([Z.refreshMain(W.access),Z.refreshAllFallbacks(F)])}catch(F){C("[quota] killswitch refresh failed",{error:F instanceof Error?F.message:String(F),backedOff:Z.isBackedOff()})}B=Z.getMain(W.access)?.quota}if(f0(I)&&!r0(B,I)){let F=w(Y,O?.body)?await g0(I,{includeApiRoutes:K1(W.access)}):[];if(F.length>0){C("[route] skipping main (killswitch), trying fallbacks");let d=await h0(Y,O,F,I,void 0,z,{onSuccess:($0)=>X($0.id,"fallback")});if(d)return z.done("return_killswitch_fallback",{status:d.status}),E0(d,{perf:($0,G0)=>z.mark($0,G0)})}let f=Date.now(),r=(I?.accounts??[]).filter((d)=>d.enabled!==!1&&e(d)).map((d)=>({...d,quota:Q0(d)})),g=vj(B,r,f);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:`Killswitch: no routable accounts. Retry in ${Math.floor(g/60)}m ${g%60}s.`}}),{status:429,headers:{"content-type":"application/json","retry-after":String(g)}})}let b=await b0(Y,O,W.access,z,"main",I),l=!1,x=await aj(Y,O,b,H,z,I,W.access,(Q)=>{l=!0,X(Q.id,"fallback")});if(!l)X("main","main");return z.done("return_response",{status:x.status}),E0(x,{perf:(Q,F)=>z.mark(Q,F)})}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let G=await U1("max");return{url:G.url,instructions:"Paste the authorization code here:",method:"code",callback:async(V)=>{return F1(V,G.verifier,G.redirectUri,G.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let G=await U1("console");return{url:G.url,instructions:"Paste the authorization code here:",method:"code",callback:async(V)=>{let K=await F1(V,G.verifier,G.redirectUri,G.state);if(K.type==="failed")return K;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${K.access}`}}).then((L)=>L.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{rJ as AnthropicAuthPlugin};
|
|
12
|
+
`),E=I>=90?"error":I>=70?"warning":"info";$.tui?.showToast?.({body:{title:"Claude Quota",message:f,variant:E,duration:E==="error"?8000:5000}})?.catch?.(()=>{})}return{config:async(X)=>{X.command={...X.command??{},[J1]:{template:J1,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[V1]:{template:V1,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[O1]:{template:O1,description:"Show current Claude OAuth quota usage for all accounts."},[W1]:{template:W1,description:"Show or toggle Anthropic request dump capture for debugging."},[G1]:{template:G1,description:"Show or toggle Anthropic fast mode for supported Opus models."},[P1]:{template:P1,description:"Show or change Claude account routing between main-first and fallback-first."},[Y1]:{template:Y1,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."}}},"experimental.chat.system.transform":async(X,G)=>{if(!uJ(X))return;nJ(G.system)},provider:{id:"anthropic",async models(X,G){let P=oJ(X.models);if(G.auth?.type!=="oauth"||!Qj(W??{}))return P;return rJ(P)}},"command.execute.before":async(X)=>{if(X.command===J1)await D0(j,X.sessionID,await s(X.arguments)),N0();if(X.command===V1)await D0(j,X.sessionID,await F0(X.arguments)),N0();if(X.command===O1){await D0(j,X.sessionID,await D1());let G=await b(),P=A?await A().catch(()=>{return}):void 0;n(G,{activeId:"main",route:"main",mainAccessToken:P?.access,mainRefreshToken:P?.refresh}),N0()}if(X.command===W1)await D0(j,X.sessionID,await K0(X.arguments)),N0();if(X.command===G1)await D0(j,X.sessionID,await x0(X.arguments)),N0();if(X.command===P1)await D0(j,X.sessionID,await m0(X.arguments)),N0();if(X.command===Y1){let G=await b(),P=Rj(G),N=(G?.accounts??[]).filter((f)=>f.enabled!==!1).map((f)=>f.id),I=dj({argumentsText:X.arguments,config:P,accountIds:N});if(I.updatedConfig)await vj(I.updatedConfig);await D0(j,X.sessionID,I.text),N0()}},auth:{provider:"anthropic",async loader(X,G){A=X;let P=await X();if(P.type==="oauth"){let f=function(){if(t)clearInterval(t),t=null;let Y=async()=>{try{let D=await b(J);if(!I0(D))return;let F=await X();if(F.type!=="oauth")return;if(await V0(F.refresh),!F.expires)return;let _=F.expires-Date.now(),T=G0(D);if(_>T)return;if(q("[refresh] opencode main oauth background due",{expiresInMs:_,refreshBeforeMs:T}),F.refresh&&B0(D?.refresh?.mainLastRefreshError,F.refresh,Date.now())){q("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:D?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:D?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:_});return}if(F.refresh&&D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===e0(F.refresh))return;await I();let K=await X();q("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:K.expires?K.expires-Date.now():void 0})}catch(D){q("[refresh] opencode main oauth refresh failed",{message:D instanceof Error?D.message:String(D)})}};if(t=setInterval(()=>{Y()},hJ+Ij(mJ)),"unref"in t)t.unref()},E=function(Y,D){if(Y instanceof Request&&Y.body)return!1;return D==null||typeof D==="string"},o=function(Y){return Y.has("x-parent-session-id")},J0=function(Y){return Y.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(Y)},Y0=function(Y){return Y?.quota?.enabled===!0},O0=function(Y,D){if(Y.delete("authorization"),Y.delete("x-api-key"),D.authHeader==="x-api-key")Y.set("x-api-key",D.apiKey??"");else Y.set("Authorization",`Bearer ${D.apiKey??""}`);Y.set("Content-Type","application/json")},Q0=function(Y){return V.getFallback(Y.id,Y.access)?.quota??Y.quota},P0=function(Y){return Object.values(Y??{}).some((D)=>D&&D.remainingPercent<=0)},y1=function(Y,D){return Y.status===429||D},N1=function(Y){if(!Y)return!1;let D=V.getMain(Y);return Boolean(D&&D.refreshAfter>Date.now()&&P0(D.quota))},N=null;async function I(){if(!N)N=(async()=>{let F=null,_=null,T=null;async function K(z){let x=await b(J)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};x.refresh=x.refresh??{},z(x),await f0(x,J,{mainRefresh:!0})}async function k(z){let x=Date.now()+gJ;while(Date.now()<x){await new Promise((w)=>setTimeout(w,Dj+Ij(Dj)));let Z=await X();if(Z.type!=="oauth"||!Z.access)continue;if((Z.access!==z.access||Z.refresh!==z.refresh||(Z.expires??0)>(z.expires??0)+60000)&&(!Z.expires||Z.expires>Date.now()))return q("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:Z.expires?Z.expires-Date.now():void 0}),Z.access}return null}for(let z=0;z<=2;z++){let x=null;try{if(z>0){let H=500*2**(z-1);await new Promise((L)=>setTimeout(L,H))}if(x=await X(),!x.refresh)throw Error("Token refresh failed: missing refresh token");let Z=await b(J),B=e0(x.refresh),w=Z?.refresh?.mainLastRefreshError;if(q("[refresh] opencode main oauth refresh check",{attempt:z,expiresInMs:x.expires?x.expires-Date.now():void 0,hasBackoff:Boolean(w),backoffActive:w?B0(w,x.refresh,Date.now()):!1,retryCount:w?.retryCount,nextRetryAt:w?.nextRetryAt}),w&&B0(w,x.refresh,Date.now()))throw q("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:w.nextRetryAt,retryCount:w.retryCount}),Error(q1(w,Date.now()));if(Z?.refresh?.mainRefreshLeaseUntil&&Z.refresh.mainRefreshLeaseUntil>Date.now()&&Z.refresh.mainRefreshLeaseTokenHash===B){q("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:Z.refresh.mainRefreshLeaseUntil});let H=await k(x);if(H)return H;throw Error("Claude OAuth refresh is already in progress")}let C=await Mj({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!C){q("[refresh] opencode main oauth refresh skipped file lock");let H=await k(x);if(H)return H;throw Error("Claude OAuth refresh is already in progress")}T=C.release,F=yJ(),_=B,await K((H)=>{H.refresh=H.refresh??{},H.refresh.mainRefreshLeaseId=F??void 0,H.refresh.mainRefreshLeaseUntil=Date.now()+120000,H.refresh.mainRefreshLeaseTokenHash=B});let m=await b(J);if(q("[refresh] opencode main oauth refresh lease acquired",{attempt:z,leaseUntil:Date.now()+120000}),m?.refresh?.mainRefreshLeaseId!==F||m.refresh.mainRefreshLeaseTokenHash!==B)throw Error("Claude OAuth refresh is already in progress");q("[refresh] opencode main oauth refresh request start",{attempt:z});let l=await Lj({refreshToken:x.refresh,maxRetries:0});return await $.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:l.refresh,access:l.access,expires:l.expires}}),await K((H)=>{if(!H?.refresh)return;if(H.refresh.mainLastRefreshError=void 0,H.refresh.mainRefreshLeaseId===F)H.refresh.mainRefreshLeaseId=void 0,H.refresh.mainRefreshLeaseUntil=void 0,H.refresh.mainRefreshLeaseTokenHash=void 0}),q("[refresh] opencode main oauth refresh succeeded",{attempt:z,expiresInMs:l.expires-Date.now()}),l.access}catch(Z){let B=Z instanceof Error&&(Z.message.includes("fetch failed")||("code"in Z)&&(Z.code==="ECONNRESET"||Z.code==="ECONNREFUSED"||Z.code==="ETIMEDOUT"||Z.code==="UND_ERR_CONNECT_TIMEOUT"));if(z<2&&(B||Z instanceof U1&&Z.status>=500))continue;q("[refresh] opencode main oauth refresh attempt failed",{attempt:z,error:Z instanceof Error?Z.message:String(Z),transient:B});let w=x?.refresh;if(w&&Z instanceof U1)await K((C)=>{C.refresh=C.refresh??{},C.refresh.mainLastRefreshError=Tj({error:Z,now:Date.now(),refreshToken:w,previous:C.refresh.mainLastRefreshError})});throw Z}finally{if(F)await K((Z)=>{if(!Z?.refresh)return;if(Z.refresh.mainRefreshLeaseId===F&&Z.refresh.mainRefreshLeaseTokenHash===_)Z.refresh.mainRefreshLeaseId=void 0,Z.refresh.mainRefreshLeaseUntil=void 0,Z.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await T?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{N=null});return N}Q=I,f(),V.seedFallbacksFromAccounts((W?.accounts??[]).filter(j0)),n(W,{activeId:"main",route:"main",mainAccessToken:P.access,mainRefreshToken:P.refresh});async function Z0(Y,D){if(!Y.body||Y.status!==200)return D?.mark("inspect_stream_skip",{status:Y.status}),{response:Y,rateLimited:!1};if(Y.headers.get("x-cortexkit-relay-optimistic")==="true")return D?.mark("inspect_stream_skip",{status:Y.status,reason:"optimistic_relay"}),{response:Y,rateLimited:!1};let F=U(),_=Y.body.getReader(),T=[],K=new TextDecoder,k="",z=0;while(!k.includes(`
|
|
13
|
+
|
|
14
|
+
`)&&k.length<65536){let{done:Z,value:B}=await _.read();if(Z)break;if(T.push(B),z+=B.byteLength,k+=K.decode(B,{stream:!0}),J0(k))break}if(J0(k))return await _.cancel().catch(()=>{}),D?.mark("inspect_stream_first_event",{ms:S(U()-F),bytes:z,rateLimited:!0}),{response:Y,rateLimited:!0};let x=new ReadableStream({start(Z){for(let B of T)Z.enqueue(B)},async pull(Z){let{done:B,value:w}=await _.read();if(B){Z.close();return}Z.enqueue(w)},cancel(Z){return _.cancel(Z)}});return D?.mark("inspect_stream_first_event",{ms:S(U()-F),bytes:z,rateLimited:!1}),{response:new Response(x,{status:Y.status,statusText:Y.statusText,headers:Y.headers}),rateLimited:!1}}async function L0(Y,D,F,_,T="api_fallback",K){let k=U(),z=_1(Y,D),x=o(z);z.delete("x-parent-session-id"),z.delete("x-session-affinity"),z.delete("x-opencode-session");let Z=D?.body,B=typeof Z==="string"?Z.length:void 0;if(Z&&typeof Z==="string"){let l=U(),H=(()=>{if(!Z1())return!1;try{return R0(JSON.parse(Z).model)}catch{return!1}})();if(Z=await M1(Z,{cache1hEnabled:!x&&C0(),cache1hMode:H0(),fastModeEnabled:H,perf:(L,M)=>_?.mark(`rewrite_body_${L}`,{route:T,...M})}),O0(z,F),z.set("anthropic-beta",E0(z.get("anthropic-beta"),[])),H)s0(z);_?.mark("rewrite_body",{route:T,ms:S(U()-l),originalBytes:B,rewrittenBytes:Z.length,cacheEnabled:!x&&C0(),cacheMode:H0(),fastModeEnabled:H,subagent:x})}else O0(z,F);let w=Q1(Y,{baseURL:F.baseURL}),C=U(),m=await fetch(w.input,{...D,body:Z,headers:z,...L1()&&{tls:{rejectUnauthorized:!1}}});return _?.mark("send_headers_received",{route:T,ms:S(U()-C),status:m.status,relayConfigured:!1,totalSendWithAccessMs:S(U()-k),baseURL:F.baseURL}),m}async function d0(Y,D,F,_,T="unknown",K){let k=U(),z=K,x=async()=>{return z??=await b(J),z},Z=_1(Y,D),B=Z.get("x-session-affinity")||Z.get("x-opencode-session"),w=o(Z);Z.delete("x-parent-session-id"),Z.delete("x-session-affinity"),Z.delete("x-opencode-session");let C=D?.body,m;if(C&&typeof C==="string"){let $0=U();try{let W0=JSON.parse(C);if(typeof W0.model==="string")m=W0.model}catch{}_?.mark("model_parse_for_identity",{route:T,ms:S(U()-$0),bodyBytes:C.length})}let l=U(),H=await E1(F,m);_?.mark("resolve_claude_code_identity",{route:T,ms:S(U()-l),hasAccountUuid:Boolean(H.accountUuid)});let L=typeof C==="string"?C.length:void 0;if(C&&typeof C==="string"){let $0=U(),W0=(()=>{if(!Z1())return!1;try{return R0(JSON.parse(C).model)}catch{return!1}})();C=await M1(C,{cache1hEnabled:!w&&C0(),cache1hMode:H0(),fastModeEnabled:W0,identity:H,perf:(VJ,WJ)=>_?.mark(`rewrite_body_${VJ}`,{route:T,...WJ})});let w0=U();try{v0(Z,F,{body:JSON.parse(C),identity:H}),_?.mark("set_oauth_headers_body_parse",{route:T,ms:S(U()-w0),bodyBytes:C.length,parsed:!0})}catch{v0(Z,F,{identity:H}),_?.mark("set_oauth_headers_body_parse",{route:T,ms:S(U()-w0),bodyBytes:C.length,parsed:!1})}if(W0)s0(Z);_?.mark("rewrite_body",{route:T,ms:S(U()-$0),originalBytes:L,rewrittenBytes:C.length,cacheEnabled:!w&&C0(),cacheMode:H0(),fastModeEnabled:W0,subagent:w})}let M=Q1(Y);if(T==="main"&&typeof C==="string"&&!w&&C0()&&H0()==="hybrid"){let $0=await x(),W0=U(),w0=v.track({sessionId:B,url:M.url?.toString()??M.input.toString(),headers:Z,bodyText:C,storage:$0,cacheMode:"hybrid"});_?.mark("cachekeep_track",{session:B,ms:S(U()-W0),tracked:w0.tracked,reason:w0.tracked?void 0:w0.reason,bodyBytes:C.length})}let y=()=>fetch(M.input,{...D,body:C,headers:Z,...L1()&&{tls:{rejectUnauthorized:!1}}}),a=A1(await x()),g=U(),i=await sj({config:a,input:M.input,init:D,headers:Z,body:C,fallback:y,affinity:B,optimisticResponse:a?.transport==="websocket"});return _?.mark("send_headers_received",{route:T,ms:S(U()-g),status:i.status,relayConfigured:a!=null,totalSendWithAccessMs:S(U()-k)}),i}async function JJ(Y){if(!Y)return!1;try{return await V.refreshMain(Y),N1(Y)}catch{return!1}}async function l0(Y,D={}){let F=await O.getUsableFallbackAccounts(Y),_=new Map(F.map((K)=>[K.id,K])),T=[];for(let K of Y?.accounts??[]){if(j0(K)){let k=_.get(K.id);if(k)T.push(k);continue}if(D.includeApiRoutes===!0&&A0(K)&&K.enabled!==!1&&K.apiKey&&H1(K.baseURL))T.push(K)}if(!y0(Y))return T;return T.filter((K)=>j0(K)?j1(Q0(K),Y,K.id):!0)}async function i0(Y,D,F,_,T,K,k){if(!F.length)return T??null;let z=k?.returnLastOnExhausted??!0;await T?.body?.cancel().catch(()=>{});let x=T??null;for(let[Z,B]of F.entries()){let w;if(A0(B)){if(!B.apiKey)continue;w=await L0(Y,D,B,K,`api_fallback_${Z}`,_)}else{let m=B.access;if(!m)continue;w=await d0(Y,D,m,K,`fallback_${Z}`,_)}x=w;let C=T1(w.status,_);if(!C){let m=await Z0(w,K);w=m.response,x=w,C=m.rateLimited}if(!C){if(await O.markUsed(B),k?.onSuccess?.(B),j0(B)&&B.access&&V.shouldRefreshOnRequestCount(p))V.refreshFallback(B.id,B.access).then(()=>k?.onSuccess?.(B)).catch(()=>{});return w}if(Z<F.length-1||!z)await w.body?.cancel().catch(()=>{})}return z?x:null}async function $J(Y,D,F,_,T,K,k,z){if(!E(Y,D?.body))return F;let x=U(),Z=K??await b(J);if(T?.mark("fallback_load_storage",{ms:S(U()-x),cached:!!K}),!(Z?.accounts??[]).some((L)=>L.enabled!==!1&&(j0(L)||A0(L)&&Boolean(L.apiKey)&&H1(L.baseURL))))return F;let w=F,C=T1(w.status,Z),m=y1(w,!1);if(!C){let L=await Z0(w,T);w=L.response,C=L.rateLimited,m=y1(w,L.rateLimited)}if(!C)return w;let l=!1;if(_)l=_.some(A0);else if(m)l=await JJ(k);let H=_;if(!H){let L=U();H=await l0(Z,{includeApiRoutes:l}),T?.mark("fallback_get_accounts",{ms:S(U()-L),accounts:H.length})}if(y0(Z)){let L=H.length;if(H=H.filter((M)=>j0(M)?j1(Q0(M),Z,M.id):!0),H.length<L)q("[killswitch] filtered fallbacks",{before:L,after:H.length})}return await i0(Y,D,H,Z,w,T,{onSuccess:z})??w}return{apiKey:"",async fetch(Y,D){let F=D?.body,_=iJ({bodyBytes:typeof F==="string"?F.length:void 0}),T=U(),K=await X();if(_.mark("get_auth",{ms:S(U()-T),authType:K.type,hasAccess:Boolean(K.access)}),K.type!=="oauth"){let L=await fetch(Y,D);return _.done("non_oauth_passthrough",{status:L.status}),L}await V0(K.refresh);let k=U(),z=await b();_.mark("load_storage",{ms:S(U()-k)}),V.updateStorage(z),V.seedFallbacksFromAccounts((z?.accounts??[]).filter(j0));let x=E(Y,D?.body);if(x)p++;if(x&&K.access&&(!K.expires||K.expires>Date.now()))h(z,K.access);let Z=(L,M)=>n(z,{activeId:L,route:M,mainAccessToken:K.access,mainRefreshToken:K.refresh}),B;if(x&&f1(z)==="fallback-first")try{let L=U();B=await l0(z,{includeApiRoutes:N1(K.access)}),_.mark("fallback_first_get_accounts",{ms:S(U()-L),accounts:B.length});let M=await i0(Y,D,B,z,void 0,_,{returnLastOnExhausted:!1,onSuccess:(y)=>Z(y.id,"fallback-first")});if(M)return _.done("return_fallback_first",{status:M.status}),S0(M,{perf:(y,a)=>_.mark(y,a)});B=void 0}catch(L){_.mark("fallback_first_error",{error:L instanceof Error?L.message:String(L)})}if(!K.access||!K.expires||K.expires<Date.now()){let M=(await b())?.refresh?.mainLastRefreshError;if(K.refresh&&M&&B0(M,K.refresh,Date.now()))throw q("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:M.nextRetryAt,retryCount:M.retryCount,expiresInMs:K.expires?K.expires-Date.now():void 0}),Error(q1(M,Date.now()));q("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(K.access),expiresInMs:K.expires?K.expires-Date.now():void 0,expiredAgoMs:K.expires&&K.expires<Date.now()?Date.now()-K.expires:void 0});let y=U();K.access=await I(),_.mark("refresh_main_access",{ms:S(U()-y)})}if(!K.access)throw _.done("missing_access_error"),Error("OAuth access token is missing after refresh");function w(){if(z?.quota?.showToasts!==!0)return;let L=V.getMain();if(!L)return;let M=(z?.accounts??[]).filter((g)=>g.enabled!==!1&&j0(g)).map((g)=>({...g,quota:V.getFallback(g.id,g.access)?.quota??g.quota})),y=k0(L.quota,z),a;if(y)a="main";else a=M.find((g)=>k0(g.quota,z))?.id??"main";T0(L.quota,M,a)}if(x&&Y0(z))try{let L=U(),M=V.getMain(K.access),y=M?.quota;if(!y)y=await V.refreshMain(K.access),M=V.getMain(K.access),w();else if(V.needsRefresh(p))if(P0(y))y=await V.refreshMain(K.access),M=V.getMain(K.access);else V.refreshMain(K.access).then(()=>{r(),w()}).catch(()=>{});if(n(z,{activeId:"main",route:"main",mainAccessToken:K.access,mainRefreshToken:K.refresh}),_.mark("main_quota_for_routing",{ms:S(U()-L),passes:k0(y,z)}),!k0(y,z)){let a=U();B=await l0(z,{includeApiRoutes:Boolean(M&&M.refreshAfter>Date.now()&&P0(M.quota))}),_.mark("preselect_fallback_accounts",{ms:S(U()-a),accounts:B.length});let g=await i0(Y,D,B,z,void 0,_,{onSuccess:(i)=>Z(i.id,"fallback")});if(g)return _.done("return_preselected_fallback",{status:g.status}),S0(g,{perf:(i,$0)=>_.mark(i,$0)})}}catch(L){_.mark("main_quota_for_routing_error",{error:L instanceof Error?L.message:String(L)})}let C=V.getMain(K.access)?.quota;if(z?.quota?.failClosedOnUnknownQuota&&!C&&V.isBackedOff()){let L=V.getLastApiError(),M=L?qj(L,Date.now()):"Quota API unavailable";return q("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:L?.nextRetryAt,retryCount:L?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:M}}),{status:429,headers:{"content-type":"application/json","retry-after":String(L?.nextRetryAt?Math.max(1,Math.ceil((L.nextRetryAt-Date.now())/1000)):60)}})}if(y0(z)){if(V.needsRefresh(p))try{let M=(z?.accounts??[]).filter((y)=>y.enabled!==!1&&j0(y)&&Boolean(y.access));await Promise.all([V.refreshMain(K.access),V.refreshAllFallbacks(M)])}catch(M){q("[quota] killswitch refresh failed",{error:M instanceof Error?M.message:String(M),backedOff:V.isBackedOff()})}C=V.getMain(K.access)?.quota}if(y0(z)&&!j1(C,z)){let M=E(Y,D?.body)?await l0(z,{includeApiRoutes:N1(K.access)}):[];if(M.length>0){q("[route] skipping main (killswitch), trying fallbacks");let i=await i0(Y,D,M,z,void 0,_,{onSuccess:($0)=>Z($0.id,"fallback")});if(i)return _.done("return_killswitch_fallback",{status:i.status}),S0(i,{perf:($0,W0)=>_.mark($0,W0)})}let y=Date.now(),a=(z?.accounts??[]).filter((i)=>i.enabled!==!1&&j0(i)).map((i)=>({...i,quota:Q0(i)})),g=Ej(C,a,y);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:`Killswitch: no routable accounts. Retry in ${Math.floor(g/60)}m ${g%60}s.`}}),{status:429,headers:{"content-type":"application/json","retry-after":String(g)}})}let m=await d0(Y,D,K.access,_,"main",z),l=!1,H=await $J(Y,D,m,B,_,z,K.access,(L)=>{l=!0,Z(L.id,"fallback")});if(!l)Z("main","main");return _.done("return_response",{status:H.status}),S0(H,{perf:(L,M)=>_.mark(L,M)})}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let X=await B1("max");return{url:X.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{return C1(G,X.verifier,X.redirectUri,X.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let X=await B1("console");return{url:X.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{let P=await C1(G,X.verifier,X.redirectUri,X.state);if(P.type==="failed")return P;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${P.access}`}}).then((I)=>I.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{Z3 as AnthropicAuthPlugin};
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Sa as a,Ta as b,Ua as c,Va as d,Wa as e,Xa as f}from"./index-99mvcpj7.js";export{d as setSidebarState,e as resolveActiveAccount,a as getSidebarStateFile,c as getSidebarState,f as getCollapsedQuotaSummary,b as DEFAULT_SIDEBAR_STATE};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-anthropic-auth",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
"@opencode-ai/plugin": "*"
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@cortexkit/anthropic-auth-core": "1.9.
|
|
54
|
+
"@cortexkit/anthropic-auth-core": "1.9.1",
|
|
55
55
|
"@opentui/core": ">=0.3.1",
|
|
56
56
|
"@opentui/solid": ">=0.3.1",
|
|
57
57
|
"solid-js": "^1.9.10"
|