@cortexkit/opencode-anthropic-auth 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -196,6 +196,9 @@ Example:
196
196
  "claudeFast": {
197
197
  "enabled": false
198
198
  },
199
+ "costZeroing": {
200
+ "enabled": true
201
+ },
199
202
  "relay": {
200
203
  "enabled": false,
201
204
  "url": "https://opencode-anthropic-relay.example.workers.dev",
@@ -207,7 +210,7 @@ Example:
207
210
  }
208
211
  ```
209
212
 
210
- The `routing` block controls `/claude-routing`, `claudeCache` controls `/claude-cache`, `cacheKeep` controls `/claude-cachekeep`, and `claudeFast` controls `/claude-fast`. Set `quota.showToasts` to `true` to opt into OpenCode quota toast notifications after quota refreshes. The `main` field identifies OpenCode's primary auth entry; Pi keeps primary OAuth credentials in Pi's own credential store, but uses the same sidecar shape for CortexKit settings and fallback account labels.
213
+ The `routing` block controls `/claude-routing`, `claudeCache` controls `/claude-cache`, `cacheKeep` controls `/claude-cachekeep`, and `claudeFast` controls `/claude-fast`. OpenCode zeroes Anthropic OAuth model costs by default because OAuth usage is quota-based; set `costZeroing.enabled` to `false` only if you want OpenCode to display the provider's model pricing instead. Set `quota.showToasts` to `true` to opt into OpenCode quota toast notifications after quota refreshes. The `main` field identifies OpenCode's primary auth entry; Pi keeps primary OAuth credentials in Pi's own credential store, but uses the same sidecar shape for CortexKit settings and fallback account labels.
211
214
 
212
215
  Runtime data is stored separately in `anthropic-auth-state.json`: fallback OAuth tokens, API-route keys, token refresh backoff, quota snapshots, and quota API backoff. Background refresh and quota checks write only the state file, so editing `anthropic-auth.json` does not get overwritten by another running plugin instance.
213
216
 
@@ -235,7 +238,7 @@ Prefer npm? Use `npx -y @cortexkit/opencode-anthropic-auth ...` with the same su
235
238
 
236
239
  API fallback routes use `Authorization: Bearer <key>` by default and rewrite requests to the configured Anthropic-compatible base URL. For Kie, use `https://api.kie.ai/claude` as the base URL; the plugin appends `/v1/messages` automatically. API-key routes are only eligible after direct evidence that the main OAuth quota is exhausted: a fresh token-bound quota snapshot at 0% remaining, or an actual main OAuth model response with HTTP 429 / streaming rate-limit error followed by a live quota check that confirms 0% remaining. Low-but-nonzero quota, stale cached quota, unconfirmed 429s, 401, or 403 do not trigger API-key routes. API-route keys are stored in `anthropic-auth-state.json`, while `anthropic-auth.json` keeps the route label, type, enabled flag, base URL, and auth-header mode.
237
240
 
238
- OpenCode cost accounting stays simple: when the native Anthropic auth entry is OAuth, OpenCode sees zero-cost Claude OAuth models. If a request falls through to an API-key route, token accounting is still recorded, but OpenCode's built-in dollar cost is not route-aware.
241
+ OpenCode cost accounting stays simple: when the native Anthropic auth entry is OAuth, OpenCode sees zero-cost Claude OAuth models by default. If a request falls through to an API-key route, token accounting is still recorded, but OpenCode's built-in dollar cost is not route-aware. Advanced users can set `costZeroing.enabled` to `false` to show Anthropic model pricing for OAuth sessions too.
239
242
 
240
243
  For Pi fallback accounts, write the same account JSON shape to `~/.pi/agent/anthropic-auth.json`. The CLI helper currently lives in the OpenCode package, so you can also point it at Pi's sidecar path when logging in a fallback account:
241
244
 
@@ -593,19 +596,19 @@ This repo uses CortexKit's tag-driven release workflow.
593
596
  Preview a release:
594
597
 
595
598
  ```bash
596
- ./scripts/release.sh 1.8.0 --dry
599
+ ./scripts/release.sh 1.9.0 --dry
597
600
  ```
598
601
 
599
602
  Create and push the release tag:
600
603
 
601
604
  ```bash
602
- ./scripts/release.sh 1.8.0
605
+ ./scripts/release.sh 1.9.0
603
606
  ```
604
607
 
605
608
  Wait for GitHub Actions:
606
609
 
607
610
  ```bash
608
- ./scripts/wait-release.sh v1.8.0
611
+ ./scripts/wait-release.sh v1.9.0
609
612
  ```
610
613
 
611
614
  The release workflow runs checks, publishes the core, OpenCode, and Pi packages to npm with provenance, and creates the GitHub release.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{Ia as I,Ka as $,m as w,n as k,p as A,r as R,s as d,t as l,u as p}from"./index-gcmgg93d.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:
2
+ import{Ja as I,La as $,m as w,n as k,p as A,r as R,t as d,u as l,v as p}from"./index-taa0ezxk.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,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"],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",bm="You are a Claude agent, built on Anthropic's Claude Agent SDK.",Fm=["<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 q="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 b_ from"node:fs";import*as F_ from"node:os";import*as B_ from"node:path";var x0=B_.join(F_.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{b_.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?`
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"],O1="mcp_";var C_="fast-mode-2026-02-01";function S1(f,_){let E=(f??"").split(",").map((D)=>D.trim()).filter(Boolean);return[...new Set([...E,..._])].join(",")}function H1(f){return typeof f==="string"&&(f.startsWith("claude-opus-4-6")||f.startsWith("claude-opus-4-7")||f.startsWith("claude-opus-4-8"))}var N1="You are OpenCode",b1="You are a Claude agent, built on Anthropic's Claude Agent SDK.",F1=["<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 q="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",B1=["github.com/anomalyco/opencode","opencode.ai/docs"],K1=[{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 Y1(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 W1(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 b_ from"node:fs";import*as F_ from"node:os";import*as B_ from"node:path";var x0=B_.join(F_.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{b_.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 b(f,_){V(`[relay] ${f}`,_)}if(!K_)process.on("exit",Zf);import{createHash as h_,randomUUID as Rf}from"node:crypto";import{mkdir as q0,readFile as xf,rename as T0,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 l0=globalThis.setTimeout.bind(globalThis),y0=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 qm(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}}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 qf(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,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 T(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:T({...C,mainLastRefreshError:L.lastRefreshError,mainRefreshLeaseId:L.refreshLeaseId,mainRefreshLeaseUntil:L.refreshLeaseUntil,mainRefreshLeaseTokenHash:L.refreshLeaseTokenHash}),quota:T({...$,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(qf(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 T({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 T({apiKey:f.apiKey,lastUsed:f.lastUsed});return T({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?T({enabled:f.refresh.enabled,intervalMinutes:f.refresh.intervalMinutes,refreshBeforeExpiryMinutes:f.refresh.refreshBeforeExpiryMinutes}):void 0,E=f.quota?T({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,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:T({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 q0(V_(f),{recursive:!0});let E=`${f}.${Rf()}.tmp`;await Qf(E,`${JSON.stringify(_,null,2)}
4
+ `),t.length>=I0)Zf();else P0()}catch{}}function b(f,_){V(`[relay] ${f}`,_)}if(!K_)process.on("exit",Zf);import{createHash as h_,randomUUID as Rf}from"node:crypto";import{mkdir as q0,readFile as xf,rename as T0,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 l0=globalThis.setTimeout.bind(globalThis),y0=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 q1(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 T1(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 qf(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 T(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:T({...C,mainLastRefreshError:L.lastRefreshError,mainRefreshLeaseId:L.refreshLeaseId,mainRefreshLeaseUntil:L.refreshLeaseUntil,mainRefreshLeaseTokenHash:L.refreshLeaseTokenHash}),quota:T({...$,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(qf(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 T({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 T({apiKey:f.apiKey,lastUsed:f.lastUsed});return T({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?T({enabled:f.refresh.enabled,intervalMinutes:f.refresh.intervalMinutes,refreshBeforeExpiryMinutes:f.refresh.refreshBeforeExpiryMinutes}):void 0,E=f.quota?T({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:T({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 q0(V_(f),{recursive:!0});let E=`${f}.${Rf()}.tmp`;await Qf(E,`${JSON.stringify(_,null,2)}
5
5
  `,{encoding:"utf8",mode:384}),await T0(E,f)}async function Q(f,_=z()){let D={...await AE(_),...SE(f)};await If(_,D),await If(qf(_),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 bE(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 FE(f,_=z(),E={mainQuota:!0,mainRefresh:!0,accounts:!0}){let D=qf(_),m=(await Mf(D)).value,$=H(m)?{...m,version:1}:{version:1};if(E.mainQuota)NE($,f);if(E.mainRefresh)bE($,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 Tm(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 wm(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 im(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 ym(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 km(f){return f?.claudeFast?.enabled===!0}async function pm(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 vm(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 dm(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 um(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 gm(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 nm(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 rm(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 sm(f){return f?.killswitch??{enabled:!1}}async function cm(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 am="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 em(){return Of}function f1(){return Sf}function _1(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 E1(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(`
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 Dm(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
10
  `);if(_.type==="mode")return[y_,"",`Mode updated to \`${_.mode}\`.`,"",_f({enabled:E,mode:_.mode})].join(`
11
11
  `);return[qE,"",TE,"",_f({enabled:E,mode:D})].join(`
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 C1(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 M1(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 L1(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 N1(f,_=q,E,D=new Date){let m=$D(_,D);return`x-anthropic-billing-header: cc_version=${_}.${m}; cc_entrypoint=${E}; cch=00000;`}var K1="claude-cachekeep",df=3600000,pf=300000,CD=60000,j1="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 G1(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(`
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 zm(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 FD(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(!bD(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 FD(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 V1="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"),Ff=!1,e_=0;function x1(f){Ff=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 bf(f){let _=f?.enabled??Ff;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 Q1(f){let _=VD(f.argumentsText),E=f.enabled??Ff;if(_.type==="status")return bf({enabled:E});if(_.type==="enable")return[JD,"",bf({enabled:!0})].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 FD(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(!bD(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 FD(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 xm="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"),Ff=!1,e_=0;function Qm(f){Ff=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 bf(f){let _=f?.enabled??Ff;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 Im(f){let _=VD(f.argumentsText),E=f.enabled??Ff;if(_.type==="status")return bf({enabled:E});if(_.type==="enable")return[JD,"",bf({enabled:!0})].join(`
19
19
  `);if(_.type==="disable")return[YD,"",bf({enabled:!1})].join(`
20
20
  `);return[WD,"",XD,"",bf({enabled:E})].join(`
21
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 b(`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(!Ff)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")]),b(`dumped request id=${_} session=${f0(f.affinity)} body=${D}.body.json meta=${D}.meta.json`)}catch(m){b(`dump failed: ${m instanceof Error?m.message:String(m)}`)}}var P1="claude-fast";var Kf=!1;function R1(){return Kf}function q1(f){Kf=f}function qD(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 T1(f){let _=qD(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(`
23
+ `,"utf8")]),b(`dumped request id=${_} session=${f0(f.affinity)} body=${D}.body.json meta=${D}.meta.json`)}catch(m){b(`dump failed: ${m instanceof Error?m.message:String(m)}`)}}var Rm="claude-fast";var Kf=!1;function qm(){return Kf}function Tm(f){Kf=f}function qD(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 wm(f){let _=qD(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
27
  `)}var Df="claude-killswitch";function TD(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 l1(f){let _=TD(f.argumentsText);if(_.type==="status")return{text:`${jf(f.config,f.accountIds)}
29
+ `);function ym(f){let _=TD(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"],k1={input:10,output:50,cacheRead:1,cacheWrite5m:12.5,cacheWrite1h:20},p1=1e6,v1=128000,d1="2026-06-09",u1={["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 g1(f){return typeof f==="string"&&wD.some((_)=>f===_||f.startsWith(`${_}-`))}import{createHash as iD}from"node:crypto";var lD=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 _=q_(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 _=T_(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 $=lD(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 o1="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 yD(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 ${yD(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 a1(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 e1(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(`
37
+ ${$0}`}}var wD=["claude-fable-5","claude-mythos-5"],pm={input:10,output:50,cacheRead:1,cacheWrite5m:12.5,cacheWrite1h:20},vm=1e6,dm=128000,um="2026-06-09",gm={["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 nm(f){return typeof f==="string"&&wD.some((_)=>f===_||f.startsWith(`${_}-`))}import{createHash as iD}from"node:crypto";var lD=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 _=q_(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 _=T_(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 $=lD(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 am="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 yD(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 ${yD(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 em(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$(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 $$(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 C$(){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 fm(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function s(f,_){if(!fm())return;b(`[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")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 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(F0.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(F0.from(String(f)))}function $m(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 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=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=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");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(_,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=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 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
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(_,Dm(f.base64));return}if(f.type==="done"){this.finishPending();return}if(f.type==="error"){if(_.optimisticResponse&&_.responseStartedAt!=null){b(`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
42
+ `)),this.finishPending();return}if(f.type==="chunk"){this.enqueueStreamChunk(_,D1(f.base64));return}if(f.type==="done"){this.finishPending(f);return}if(f.type==="error"){if(_.optimisticResponse&&_.responseStartedAt!=null){b(`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(Cm(f));this.failPending(E)}}finishPending(){let f=this.pending;if(!f)return;let _=F();if(b(`perf websocket done session=${B(this.affinity)} request=${f.payload.id} sentMs=${Y(_-f.sentAt)} streamMs=${f.responseStartedAt==null?"unknown":Y(_-f.responseStartedAt)} chunks=${f.streamChunkCount} bytes=${f.streamByteCount}`),clearTimeout(f.timeout),!f.streamDone)f.streamDone=!0,f.streamController?.close();f.resolveDone(),this.pending=void 0}failPending(f){let _=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 M$(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 b("skipping relay: missing x-session-affinity header"),C();let U=$,N=F(),K=cD(U);s("hash_body",{session:B(A),ms:Y(F()-N),bodyBytes:U.length});let j=P.get(A),R=F(),J=_m({input:E,init:D,headers:m,bodyText:U,affinity:A,previous:j,nextHash:K});s("create_payload",{session:B(A),ms:Y(F()-R),mode:J.mode,bodyBytes:U.length,previousBytes:j?.body.length});try{let S,v=F();if(_.transport==="websocket")try{S=await Mm(_,A).send(J,U,L===!0)}catch(O){b(`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(F()-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=F(),u=JSON.stringify(S.payload).length;s("payload_stringify",{session:B(A),ms:Y(F()-d),relayBytes:u}),b(`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=F();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(F()-mf),enabled:!0}),S.response}catch(S){if(!_.fallbackToDirect)throw b(`relay failed session=${B(A)} and fallbackToDirect=false: ${S instanceof Error?S.message:String(S)}`),S;return b(`relay failed; falling back direct session=${B(A)}: ${S instanceof Error?S.message:String(S)}`),C()}}var L$=`
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(C1(f));this.failPending(E)}}finishPending(f){let _=this.pending;if(!_)return;let E=F(),D=f&&"frames"in f?` upstreamChunks=${f.upstreamChunks??"unknown"} upstreamBytes=${f.upstreamBytes??"unknown"} frames=${f.frames} frameBytes=${f.frameBytes??"unknown"}`:"";if(b(`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 M1(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 L$(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 b("skipping relay: missing x-session-affinity header"),C();let U=$,N=F(),K=cD(U);s("hash_body",{session:B(A),ms:Y(F()-N),bodyBytes:U.length});let j=P.get(A),R=F(),J=_1({input:E,init:D,headers:m,bodyText:U,affinity:A,previous:j,nextHash:K});s("create_payload",{session:B(A),ms:Y(F()-R),mode:J.mode,bodyBytes:U.length,previousBytes:j?.body.length});try{let S,v=F();if(_.transport==="websocket")try{S=await M1(_,A).send(J,U,L===!0)}catch(O){b(`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(F()-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=F(),u=JSON.stringify(S.payload).length;s("payload_stringify",{session:B(A),ms:Y(F()-d),relayBytes:u}),b(`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=F();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(F()-mf),enabled:!0}),S.response}catch(S){if(!_.fallbackToDirect)throw b(`relay failed session=${B(A)} and fallbackToDirect=false: ${S instanceof Error?S.message:String(S)}`),S;return b(`relay failed; falling back direct session=${B(A)}: ${S instanceof Error?S.message:String(S)}`),C()}}var A$=`
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)
@@ -130,6 +130,73 @@ function deferWorkerTask(task) {
130
130
  return new Promise((resolve) => setTimeout(resolve, 0)).then(task)
131
131
  }
132
132
 
133
+ const WEBSOCKET_STREAM_FLUSH_BYTES = 1024
134
+ const WEBSOCKET_STREAM_FLUSH_MS = 20
135
+
136
+ function createWebSocketStreamCoalescer(socket, options = {}) {
137
+ const flushBytes = options.flushBytes || WEBSOCKET_STREAM_FLUSH_BYTES
138
+ const flushMs = options.flushMs ?? WEBSOCKET_STREAM_FLUSH_MS
139
+ let chunks = []
140
+ let byteLength = 0
141
+ let flushTimer = null
142
+ const stats = {
143
+ upstreamChunks: 0,
144
+ upstreamBytes: 0,
145
+ frames: 0,
146
+ frameBytes: 0,
147
+ }
148
+
149
+ const clearFlushTimer = () => {
150
+ if (flushTimer === null) return
151
+ clearTimeout(flushTimer)
152
+ flushTimer = null
153
+ }
154
+
155
+ const mergeChunks = () => {
156
+ if (chunks.length === 1) return chunks[0]
157
+ const frame = new Uint8Array(byteLength)
158
+ let offset = 0
159
+ for (const chunk of chunks) {
160
+ frame.set(chunk, offset)
161
+ offset += chunk.byteLength
162
+ }
163
+ return frame
164
+ }
165
+
166
+ const flush = () => {
167
+ clearFlushTimer()
168
+ if (byteLength === 0) return
169
+ const frame = mergeChunks()
170
+ chunks = []
171
+ byteLength = 0
172
+ socket.send(frame)
173
+ stats.frames += 1
174
+ stats.frameBytes += frame.byteLength
175
+ }
176
+
177
+ const scheduleFlush = () => {
178
+ if (flushTimer !== null) return
179
+ flushTimer = setTimeout(flush, flushMs)
180
+ }
181
+
182
+ return {
183
+ push(value) {
184
+ const chunk = value instanceof Uint8Array ? value : new Uint8Array(value)
185
+ if (chunk.byteLength === 0) return
186
+ stats.upstreamChunks += 1
187
+ stats.upstreamBytes += chunk.byteLength
188
+ chunks.push(chunk)
189
+ byteLength += chunk.byteLength
190
+ if (byteLength >= flushBytes) flush()
191
+ else scheduleFlush()
192
+ },
193
+ flush,
194
+ stats() {
195
+ return { ...stats, pendingBytes: byteLength }
196
+ },
197
+ }
198
+ }
199
+
133
200
  function checkpointWebSocketState(env, payload, body, nextState) {
134
201
  return deferWorkerTask(async () => {
135
202
  try {
@@ -200,6 +267,7 @@ async function handleWebSocket(socket, env, ctx, payload, getState, setState) {
200
267
  clearInterval(heartbeat)
201
268
  }
202
269
  }, 15000)
270
+ let streamCoalescer = null
203
271
  try {
204
272
  const result = await prepareWebSocketUpstream(env, getState(), payload)
205
273
  if (result.error) {
@@ -229,14 +297,20 @@ async function handleWebSocket(socket, env, ctx, payload, getState, setState) {
229
297
 
230
298
  const reader = upstream.body?.getReader()
231
299
  if (reader) {
300
+ streamCoalescer = createWebSocketStreamCoalescer(socket)
232
301
  while (true) {
233
302
  const { done, value } = await reader.read()
234
303
  if (done) break
235
- socket.send(value)
304
+ streamCoalescer.push(value)
236
305
  }
306
+ streamCoalescer.flush()
237
307
  }
238
- socket.send(JSON.stringify({ protocol: 2, type: 'done', id: payload.id }))
308
+ const stats = streamCoalescer?.stats?.() || {}
309
+ socket.send(JSON.stringify({ protocol: 2, type: 'done', id: payload.id, ...stats }))
239
310
  } catch (error) {
311
+ try {
312
+ streamCoalescer?.flush?.()
313
+ } catch {}
240
314
  socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: 500, message: error instanceof Error ? error.message : String(error) }))
241
315
  } finally {
242
316
  clearInterval(heartbeat)
@@ -327,9 +401,9 @@ export default {
327
401
  }
328
402
  },
329
403
  }
330
- `;var O$="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 S$(f){return Lm(f?.routing?.mode)}async function H$(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(`
331
- `)}function N$(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(`
404
+ `;var S$="claude-routing",E_=["main-first","fallback-first"],D_="main-first",G0="Usage: `/claude-routing`, `/claude-routing main-first`, or `/claude-routing fallback-first`.";function L1(f){return typeof f==="string"&&E_.includes(f)?f:D_}function H$(f){return L1(f?.routing?.mode)}async function N$(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 A1(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 U1(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: ${U1(_)}`,"",G0].join(`
405
+ `)}function b$(f){let _=A1(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(`
332
406
  `).slice(2)].join(`
333
407
  `);return["## Claude Routing Usage","",G0,"",...__({mode:E}).split(`
334
408
  `).slice(2)].join(`
335
- `)}export{Om as a,C_ as b,Sm as c,Hm as d,Nm as e,bm as f,Fm 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,qm as q,v0 as r,z as s,h as t,Q as u,FE as v,Lf as w,Tm as x,KE as y,wm as z,im as A,lm as B,ym as C,km as D,pm as E,vm as F,dm as G,um as H,R_ as I,WE as J,o as K,hf as L,gm as M,w_ as N,XE as O,nm as P,rm as Q,sm as R,cm as S,IE as T,am as U,em as V,f1 as W,_1 as X,wE as Y,E1 as Z,s_ as _,N1 as $,C1 as aa,M1 as ba,L1 as ca,u_ as da,K1 as ea,j1 as fa,ND as ga,uf as ha,a_ as ia,bD as ja,G1 as ka,BD as la,V1 as ma,x1 as na,VD as oa,Q1 as pa,P1 as qa,R1 as ra,q1 as sa,qD as ta,T1 as ua,Df as va,l1 as wa,k1 as xa,p1 as ya,v1 as za,d1 as Aa,u1 as Ba,g1 as Ca,w as Da,o1 as Ea,a1 as Fa,e1 as Ga,$$ as Ha,C$ as Ia,M$ as Ja,L$ as Ka,O$ as La,S$ as Ma,H$ as Na,Am as Oa,N$ as Pa};
409
+ `)}export{O1 as a,C_ as b,S1 as c,H1 as d,N1 as e,b1 as f,F1 as g,M_ as h,B1 as i,K1 as j,i as k,N_ as l,Y1 as m,W1 as n,V as o,x as p,q1 as q,v0 as r,T1 as s,z as t,h as u,Q as v,FE as w,Lf as x,w1 as y,KE as z,i1 as A,l1 as B,y1 as C,k1 as D,p1 as E,v1 as F,d1 as G,u1 as H,g1 as I,R_ as J,WE as K,o as L,hf as M,n1 as N,w_ as O,XE as P,r1 as Q,s1 as R,c1 as S,t1 as T,IE as U,e1 as V,fm as W,_m as X,Em as Y,wE as Z,Dm as _,s_ as $,bm as aa,Mm as ba,Lm as ca,Am as da,u_ as ea,jm as fa,Gm as ga,ND as ha,uf as ia,a_ as ja,bD as ka,zm as la,BD as ma,xm as na,Qm as oa,VD as pa,Im as qa,Rm as ra,qm as sa,Tm as ta,qD as ua,wm as va,Df as wa,ym as xa,pm as ya,vm as za,dm as Aa,um as Ba,gm as Ca,nm as Da,w as Ea,am as Fa,em as Ga,f$ as Ha,C$ as Ia,M$ as Ja,L$ as Ka,A$ as La,S$ as Ma,H$ as Na,N$ as Oa,A1 as Pa,b$ as Qa};
@@ -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 Qa,B as Ra,h as Sa,j as Ta,w as Ua,R as Va};
2
+ export{M as Ra,B as Sa,h as Ta,j as Ua,w as Va,R as Wa};
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import{$ as t1,A as Oj,Aa as mj,B as F1,Ba as bj,C as _j,Ca as Dj,D as N1,Da as hj,E as Lj,Ea as $1,F as Qj,Fa as gj,G as Uj,Ga as lj,H as H1,Ha as E1,I as o0,J as Bj,Ja as pj,K as B0,L as x1,La as V1,M as vj,Ma as w1,N as R0,Na as dj,O as f0,Oa as ij,P as r0,Pa as S1,Q as Fj,R as Nj,S as Hj,T as xj,U as s0,V as v0,W as F0,X as y0,Y as Mj,Z as t0,_ as s1,a as i1,aa as M1,b as u1,ba as a1,c as q0,ca as e1,d as C0,da as jj,e as n1,ea as a0,f as T0,fa as Tj,g as Wj,ga as qj,h as c1,ha as Cj,i as o1,ia as Ej,j as r1,ja as T1,k as Q1,ka as wj,l as Yj,la as Sj,m as U1,ma as e0,n as B1,na as j1,o as C,oa as Aj,p as c,pa as q1,q as S0,qa as D1,r as v1,ra as G1,s as Pj,sa as J1,t as y,ta as Rj,ua as C1,v as A0,va as Z1,w as zj,wa as fj,x as n0,xa as k0,y as c0,ya as yj,z as Ij,za as kj}from"./index-gcmgg93d.js";import{Ta as uj}from"./index-s5ckbbqq.js";import{randomUUID as UD}from"node:crypto";function U0(j){return typeof j==="object"&&j!==null}function tj(j){if(Array.isArray(j))return j;if(U0(j)&&Array.isArray(j.data))return j.data;return[]}function aj(j){if(!U0(j)||!U0(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function R1(j){if(!U0(j)||!U0(j.info))return null;let D=j.info,G=U0(D.model)?D.model:void 0,Z=typeof D.agent==="string"?D.agent:void 0,$=typeof G?.providerID==="string"?G.providerID:typeof D.providerID==="string"?D.providerID:void 0,z=typeof G?.modelID==="string"?G.modelID:typeof D.modelID==="string"?D.modelID:void 0,M=typeof G?.variant==="string"?G.variant:typeof D.variant==="string"?D.variant:void 0;if(!Z&&(!$||!z)&&!M)return null;let h={};if(Z)h.agent=Z;if($&&z)h.model={providerID:$,modelID:z};if(M)h.variant=M;return h}function f1(j,D){return{agent:j.agent??D.agent,model:j.model??D.model,variant:j.variant??D.variant}}function y1(j){return Boolean(j.agent&&j.model&&j.variant)}async function k1(j,D){if(!j||!D)return null;let G=j;if(typeof G.session?.messages!=="function")return null;let Z=[];try{Z=tj(await Promise.resolve(G.session.messages({path:{id:D},query:{limit:100}})))}catch{return null}if(Z.length===0)return null;let $={};for(let z=Z.length-1;z>=0;z--){if(aj(Z[z])!=="assistant")continue;let M=R1(Z[z]);if(!M)continue;if($=f1($,M),y1($))return $}for(let z=Z.length-1;z>=0;z--){let M=R1(Z[z]);if(!M)continue;if($=f1($,M),y1($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}function m1(j){return`${i1}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function Gj(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}var ej=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function b1(j){let D=Gj(j);if(D.startsWith("aft_"))return D;if(ej.has(D))return`aft_${D}`;return null}function z1(j,D){let G=new Headers;if(j instanceof Request)j.headers.forEach(($,z)=>{G.set(z,$)});let Z=D?.headers;if(Z){if(Z instanceof Headers)Z.forEach(($,z)=>{G.set(z,$)});else if(Array.isArray(Z))for(let $ of Z){let[z,M]=$;if(typeof M<"u")G.set(z,String(M))}else for(let[$,z]of Object.entries(Z))if(typeof z<"u")G.set($,String(z))}return G}function u0(j){return j.set("anthropic-beta",q0(j.get("anthropic-beta"),[u1])),j}function E0(j,D,G={}){return e1(j,D,G)}function jD(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((D)=>({...D,name:D.name?m1(D.name):D.name}));if(j.messages&&Array.isArray(j.messages))j.messages=j.messages.map((D)=>{if(D.content&&Array.isArray(D.content))D.content=D.content.map((G)=>{if(G.type==="tool_use"&&G.name)return{...G,name:m1(G.name)};return G});return D});return JSON.stringify(jj(j))}function P1(j){return j.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(D,G,Z)=>{if(G)return`"name": "${b1(Z)??Gj(Z)}"`;let $=b1(Z);return $?`"name": "${$}"`:D})}function h1(j,D=!1){if(D)return{ready:P1(j),pending:""};let G=j.length,Z='"name"',$=Math.max(0,j.length-Z.length+1);for(let M=$;M<j.length;M++)if(Z.startsWith(j.slice(M))){G=Math.min(G,M);break}let z=j.lastIndexOf(Z);if(z!==-1){let M=j.slice(z);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(M))G=Math.min(G,z)}if(G<j.length)return{ready:P1(j.slice(0,G)),pending:j.slice(G)};return{ready:P1(j),pending:""}}function I1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function Jj(j){let D=j?.trim();if(!D)return null;try{let G=new URL(D);if(G.protocol!=="http:"&&G.protocol!=="https:"||G.username||G.password)return null;return G}catch{return null}}function DD(){return Jj(process.env.ANTHROPIC_BASE_URL)}function O1(j,D={}){let G=null;try{if(typeof j==="string"||j instanceof URL)G=new URL(j.toString());else if(j instanceof Request)G=new URL(j.url)}catch{G=null}if(!G)return{input:j,url:null};let Z=G.href,$=D.baseURL?Jj(D.baseURL):DD();if($){if(G.protocol=$.protocol,G.host=$.host,D.baseURL)G.pathname=`${$.pathname.replace(/\/$/,"")}${G.pathname}`}if(G.pathname.endsWith("/v1/messages")&&!G.searchParams.has("beta"))G.searchParams.set("beta","true");if(G.href===Z)return{input:j,url:G};return{input:j instanceof Request?new Request(G.toString(),j):G,url:G}}function l0(j){let Z=j.split(/\n\n+/).filter(($)=>{if($.includes(n1))return!1;for(let z of o1)if($.includes(z))return!1;return!0}).join(`
1
+ import{$ as s1,A as _j,Aa as bj,B as Lj,Ba as gj,C as H1,Ca as hj,D as Qj,Da as $j,E as B1,Ea as pj,F as Uj,Fa as Z1,G as Fj,Ga as lj,H as Nj,Ha as dj,I as v1,Ia as w1,J as o0,K as Hj,Ka as uj,L as N0,M as x1,Ma as V1,N as Bj,Na as E1,O as R0,Oa as ij,P as f0,Pa as nj,Q as r0,Qa as S1,R as vj,S as xj,T as qj,U as Mj,V as a0,W as H0,X as B0,Y as k0,Z as Tj,_ as s0,a as i1,aa as t1,b as n1,ba as q1,c as T0,ca as e1,d as C0,da as jj,e as c1,ea as Jj,f as M0,fa as t0,g as Kj,ga as Cj,h as o1,ha as wj,i as r1,ia as Ej,j as a1,ja as Sj,k as Q1,ka as M1,l as Pj,la as Aj,m as U1,ma as Rj,n as F1,na as e0,o as C,oa as j1,p as e,pa as fj,q as S0,qa as T1,r as N1,ra as J1,s as Ij,sa as $1,t as Oj,ta as D1,u as k,ua as kj,va as C1,w as A0,wa as G1,x as zj,xa as yj,y as n0,ya as y0,z as c0,za as mj}from"./index-taa0ezxk.js";import{Ua as cj}from"./index-zf02be7y.js";import{randomUUID as xJ}from"node:crypto";function F0(j){return typeof j==="object"&&j!==null}function ej(j){if(Array.isArray(j))return j;if(F0(j)&&Array.isArray(j.data))return j.data;return[]}function jJ(j){if(!F0(j)||!F0(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function R1(j){if(!F0(j)||!F0(j.info))return null;let J=j.info,$=F0(J.model)?J.model:void 0,D=typeof J.agent==="string"?J.agent:void 0,Z=typeof $?.providerID==="string"?$.providerID:typeof J.providerID==="string"?J.providerID:void 0,P=typeof $?.modelID==="string"?$.modelID:typeof J.modelID==="string"?J.modelID:void 0,v=typeof $?.variant==="string"?$.variant:typeof J.variant==="string"?J.variant:void 0;if(!D&&(!Z||!P)&&!v)return null;let m={};if(D)m.agent=D;if(Z&&P)m.model={providerID:Z,modelID:P};if(v)m.variant=v;return m}function f1(j,J){return{agent:j.agent??J.agent,model:j.model??J.model,variant:j.variant??J.variant}}function k1(j){return Boolean(j.agent&&j.model&&j.variant)}async function y1(j,J){if(!j||!J)return null;let $=j;if(typeof $.session?.messages!=="function")return null;let D=[];try{D=ej(await Promise.resolve($.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(D.length===0)return null;let Z={};for(let P=D.length-1;P>=0;P--){if(jJ(D[P])!=="assistant")continue;let v=R1(D[P]);if(!v)continue;if(Z=f1(Z,v),k1(Z))return Z}for(let P=D.length-1;P>=0;P--){let v=R1(D[P]);if(!v)continue;if(Z=f1(Z,v),k1(Z))return Z}if(!Z.agent&&!Z.model&&!Z.variant)return null;return Z}function m1(j,J){let $=new Map,D=0,Z=0,P=0,v=0,m=0,j0=(p)=>{let y=performance.now(),u=j(p);return m+=performance.now()-y,P++,u};return{call:(p)=>{if(!J.enabled())return j0(p);let y=$.get(p);if(y!==void 0)return Z++,$.delete(p),$.set(p,y),y;let u=j0(p),o=p.length+u.length;if(o>J.maxBytes)return u;$.set(p,u),D+=o;while(D>J.maxBytes&&$.size>1){let i=$.keys().next().value,Y0=$.get(i)??"";$.delete(i),D-=i.length+Y0.length,v++}return u},stats:()=>({hits:Z,misses:P,evictions:v,entries:$.size,cacheBytes:D,computeMsTotal:m})}}function b1(j){return`${i1}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function Dj(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}var JJ=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function g1(j){let J=Dj(j);if(J.startsWith("aft_"))return J;if(JJ.has(J))return`aft_${J}`;return null}function I1(j,J){let $=new Headers;if(j instanceof Request)j.headers.forEach((Z,P)=>{$.set(P,Z)});let D=J?.headers;if(D){if(D instanceof Headers)D.forEach((Z,P)=>{$.set(P,Z)});else if(Array.isArray(D))for(let Z of D){let[P,v]=Z;if(typeof v<"u")$.set(P,String(v))}else for(let[Z,P]of Object.entries(D))if(typeof P<"u")$.set(Z,String(P))}return $}function i0(j){return j.set("anthropic-beta",T0(j.get("anthropic-beta"),[n1])),j}function w0(j,J,$={}){return jj(j,J,$)}function $J(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((J)=>({...J,name:J.name?b1(J.name):J.name}));if(j.messages&&Array.isArray(j.messages))j.messages=j.messages.map((J)=>{if(J.content&&Array.isArray(J.content))J.content=J.content.map(($)=>{if($.type==="tool_use"&&$.name)return{...$,name:b1($.name)};return $});return J});return JSON.stringify(Jj(j))}function P1(j){return j.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(J,$,D)=>{if($)return`"name": "${g1(D)??Dj(D)}"`;let Z=g1(D);return Z?`"name": "${Z}"`:J})}function h1(j,J=!1){if(J)return{ready:P1(j),pending:""};let $=j.length,D='"name"',Z=Math.max(0,j.length-D.length+1);for(let v=Z;v<j.length;v++)if(D.startsWith(j.slice(v))){$=Math.min($,v);break}let P=j.lastIndexOf(D);if(P!==-1){let v=j.slice(P);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(v))$=Math.min($,P)}if($<j.length)return{ready:P1(j.slice(0,$)),pending:j.slice($)};return{ready:P1(j),pending:""}}function O1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function Gj(j){let J=j?.trim();if(!J)return null;try{let $=new URL(J);if($.protocol!=="http:"&&$.protocol!=="https:"||$.username||$.password)return null;return $}catch{return null}}function DJ(){return Gj(process.env.ANTHROPIC_BASE_URL)}function z1(j,J={}){let $=null;try{if(typeof j==="string"||j instanceof URL)$=new URL(j.toString());else if(j instanceof Request)$=new URL(j.url)}catch{$=null}if(!$)return{input:j,url:null};let D=$.href,Z=J.baseURL?Gj(J.baseURL):DJ();if(Z){if($.protocol=Z.protocol,$.host=Z.host,J.baseURL)$.pathname=`${Z.pathname.replace(/\/$/,"")}${$.pathname}`}if($.pathname.endsWith("/v1/messages")&&!$.searchParams.has("beta"))$.searchParams.set("beta","true");if($.href===D)return{input:j,url:$};return{input:j instanceof Request?new Request($.toString(),j):$,url:$}}function GJ(j){let D=j.split(/\n\n+/).filter((Z)=>{if(Z.includes(c1))return!1;for(let P of r1)if(Z.includes(P))return!1;return!0}).join(`
2
2
 
3
- `);for(let $ of r1)Z=Z.replace($.match,$.replacement);return Z.trim()}function b(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function GD(j){let D={type:"text",text:T0};if(j==null)return[D];if(typeof j==="string"){let Z=l0(j);if(Z===T0)return[D];return[D,{type:"text",text:Z}]}if(b(j)){let Z=typeof j.type==="string"?j.type:"text",$=typeof j.text==="string"?j.text:"";return[D,{...j,type:Z,text:l0($)}]}if(!Array.isArray(j))return[D];let G=j.map((Z)=>{if(typeof Z==="string")return{type:"text",text:l0(Z)};if(b(Z)&&Z.type==="text"&&typeof Z.text==="string")return{...Z,type:"text",text:l0(Z.text)};return{type:"text",text:String(Z)}});if(G[0]?.text===T0)return G;return[D,...G]}var Zj={type:"ephemeral",ttl:"1h"},JD=20;function ZD(j){if(b(j.cache_control))return j.cache_control;if(b(j.cacheControl))return j.cacheControl;return null}function i0(j,D){if(!b(j))return!1;return delete j.cacheControl,j.cache_control=D?{...Zj}:{type:"ephemeral"},!0}function g1(j){if(!b(j))return;delete j.cache_control,delete j.cacheControl}function $D(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function p0(j,D){if(!b(j))return;let G=ZD(j);if(G?.type!=="ephemeral")return;if(D)G.ttl="1h";else delete G.ttl}function l1(j,D){if(Array.isArray(j.system))for(let G of j.system)p0(G,D);else p0(j.system,D);if(!Array.isArray(j.messages))return;for(let G of j.messages)if(p0(G,D),b(G)&&Array.isArray(G.content))for(let Z of G.content)p0(Z,D)}function VD(j,D){if(Array.isArray(j.system))for(let G of j.system)D(G);else D(j.system);if(!Array.isArray(j.messages))return;for(let G of j.messages)if(D(G),b(G)&&Array.isArray(G.content))for(let Z of G.content)D(Z)}function $j(j){g1(j),VD(j,g1)}function XD(j){$j(j),j.cache_control={...Zj}}function KD(j){return b(j)&&j.type!=="thinking"&&j.type!=="redacted_thinking"}function _1(j){let D=$D(j.content);if(!D?.length)return;let G=D.filter(KD);if(!G.length)return;return{content:D,cacheableBlocks:G}}function WD(j){if(!b(j))return!1;let D=_1(j);if(!D)return!1;return j.content=D.content,i0(D.cacheableBlocks[0],!0)}function d0(j){if(!b(j))return!1;let D=_1(j);if(!D)return!1;let G=D.cacheableBlocks[D.cacheableBlocks.length-1];return j.content=D.content,i0(G,!0)}function YD(j){if(!b(j))return!1;return(_1(j)?.cacheableBlocks.length??0)>1}function PD(j){if(!b(j))return 0;let D=j.content;if(Array.isArray(D))return D.length;if(D==null)return 0;return 1}function zD(j){let D=[],G=0;return j.forEach((Z,$)=>{let z=PD(Z);if(b(Z)&&Z.role==="user"&&z>0)D.push({index:$,blockPosition:G+z-1});G+=z}),D}function ID(j){let D=zD(j),G=[...D].reverse().find((M)=>M.index>1);if(!G)return{latest:void 0,bridge:void 0};let Z=[...D].reverse().find((M)=>M.index<G.index),$=Z?G.blockPosition-Z.blockPosition+1:0,z=Z&&Z.index>1&&$>JD?Z:void 0;return{latest:G,bridge:z}}function p1(j){if(Array.isArray(j.system)){let D=j.system.findIndex(($)=>b($)&&$.text===T0),G=j.system.slice(D>=0?D+1:0).filter(b),Z=G[G.length-1];i0(Z,!0)}else i0(j.system,!0)}function OD(j){if($j(j),!Array.isArray(j.messages)){p1(j);return}let{latest:D,bridge:G}=ID(j.messages);if(!G)p1(j);let Z=YD(j.messages[0]);if(Z)WD(j.messages[0]);if(d0(j.messages[0]),!Z)d0(j.messages[1]);if(G)d0(j.messages[G.index]);if(D)d0(j.messages[D.index])}function _D(j){if(!Dj(j.model))return!1;let D=Object.hasOwn(j,"thinking");return delete j.thinking,D}function LD(j,D){if(!D.enabled){l1(j,!1),delete j.cache_control,delete j.cacheControl;return}if(D.mode==="automatic"){XD(j);return}if(D.mode==="hybrid"){OD(j);return}l1(j,!0),delete j.cacheControl}function QD(j){if(!Array.isArray(j.messages))return;while(j.messages.length){let D=j.messages[j.messages.length-1];if(!b(D)||D.role!=="assistant")break;j.messages.pop()}}function w(){return performance.now()}function n(j){return Math.round(j*10)/10}function d1(j){let D=0,G=0,Z=0,$=Array.isArray(j.messages)?j.messages:[];D=$.length;for(let z of $){if(!z||typeof z!=="object")continue;let M=z.content;if(!Array.isArray(M))continue;G+=M.length;for(let h of M)if(h&&typeof h==="object"&&h.type==="tool_use")Z++}return{messageCount:D,contentBlockCount:G,toolDefinitionCount:Array.isArray(j.tools)?j.tools.length:0,toolUseCount:Z,systemBlockCount:Array.isArray(j.system)?j.system.length:0}}async function L1(j,D={}){try{let G=w(),Z=JSON.parse(j);D.perf?.("parse",{ms:n(w()-G),inputBytes:j.length,...d1(Z)});let $=w(),z=Array.isArray(Z.messages)?Z.messages.length:void 0;QD(Z);let M=Array.isArray(Z.messages)?Z.messages.length:void 0;D.perf?.("strip_trailing_assistant",{ms:n(w()-$),removedMessages:typeof z==="number"&&typeof M==="number"?z-M:void 0});let h=w(),J0=_D(Z);D.perf?.("model_normalize",{ms:n(w()-h),model:typeof Z.model==="string"?Z.model:void 0,removedFableThinking:J0,hasOutputConfig:Object.hasOwn(Z,"output_config")});let o=w(),r=Array.isArray(Z.messages)&&Z.messages.some((I0)=>I0.role==="user")?t1(Z.messages,void 0,c1):null;D.perf?.("billing_header",{ms:n(w()-o),hasBillingHeader:Boolean(r)});let z0=w();if(Z.system=GD(Z.system),D.perf?.("system_identity",{ms:n(w()-z0),systemBlockCount:Array.isArray(Z.system)?Z.system.length:0}),r&&Array.isArray(Z.system))Z.system.unshift({type:"text",text:r});let p=w();if(LD(Z,{enabled:D.cache1hEnabled??!1,mode:D.cache1hMode??"explicit"}),D.perf?.("cache_strategy",{ms:n(w()-p),enabled:D.cache1hEnabled??!1,mode:D.cache1hMode??"explicit"}),D.fastModeEnabled&&C0(Z.model))Z.speed="fast";else if(Z.speed==="fast")delete Z.speed;let Z0=w();if(D.identity)a1(Z,D.identity);D.perf?.("metadata",{ms:n(w()-Z0),hasAccountUuid:Boolean(D.identity?.accountUuid)});let e=w(),s=jD(Z);D.perf?.("prefix_tools_stringify",{ms:n(w()-e),outputBytesBeforeSign:s.length,...d1(Z)});let N0=w(),j0=await s1(s);return D.perf?.("cch_sign",{ms:n(w()-N0),outputBytes:j0.length}),j0}catch{return j}}function w0(j,D={}){if(!j.body)return j;let G=j.body.getReader(),Z=new TextDecoder,$=new TextEncoder,z="",M=0,h=0,J0=0,o=0,r=0,z0=!1,p=!1,Z0=w(),e=w(),s=()=>{if(p)return;p=!0,G.releaseLock()},N0=(i={})=>({chunks:M,pulls:h,inputBytes:J0,outputBytes:o,pendingChars:z.length,rewriteMs:n(r),totalMs:n(w()-e),...i}),j0=(i,H0={})=>{D.perf?.(i,N0(H0))};D.perf?.("stream_tool_prefix_wrapper_created",{status:j.status,hasBody:!0});let I0=new ReadableStream({async pull(i){if(h++,!z0)z0=!0,j0("stream_tool_prefix_first_pull");let H0=w();try{let{done:$0,value:x0}=await G.read(),m0=n(w()-H0);if($0){let O0=w(),J=h1(`${z}${Z.decode()}`,!0);if(r+=w()-O0,J.ready){let V=$.encode(J.ready);o+=V.byteLength,i.enqueue(V)}j0("stream_tool_prefix_rewrite",{readMs:m0}),s(),i.close();return}M++,J0+=x0.byteLength;let K1=z+Z.decode(x0,{stream:!0}),W1=w(),V0=h1(K1);if(r+=w()-W1,z=V0.pending,V0.ready){let O0=$.encode(V0.ready);o+=O0.byteLength,i.enqueue(O0)}let M0=w();if(M===1||M%25===0||M0-Z0>5000)Z0=M0,j0("stream_tool_prefix_progress",{readMs:m0,lastChunkBytes:x0.byteLength})}catch($0){throw j0("stream_tool_prefix_error",{error:$0 instanceof Error?$0.message:String($0)}),s(),$0}},async cancel(i){j0("stream_tool_prefix_cancel",{reason:i instanceof Error?i.message:String(i)});try{await G.cancel(i)}finally{s()}}});return new Response(I0,{status:j.status,statusText:j.statusText,headers:j.headers})}var BD="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",vD=60000,FD=60000,ND=5000,Vj=200,nj=240,HD=nj,xD=1,Xj=!1;function X1(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function v(){return performance.now()}function S(j){return Math.round(j*10)/10}function Kj(j){return Math.floor(Math.random()*Math.max(0,j))}function MD(){if(Xj||!1||!X1())return;Xj=!0;let j=100,D=250,G=v()+j;setInterval(()=>{let Z=v(),$=Z-G;if(G=Z+j,$<D)return;C("[perf] opencode event_loop_lag",{lagMs:S($),thresholdMs:D})},j).unref?.()}function TD(j){let D=v(),G={requestId:String(xD++),start:D,last:D,mark(Z,$){let z=v();if(X1())C("[perf] opencode request stage",{requestId:G.requestId,stage:Z,deltaMs:S(z-G.last),totalMs:S(z-G.start),...$});G.last=z},done(Z,$){let z=v();if(X1())C("[perf] opencode request done",{requestId:G.requestId,stage:Z,deltaMs:S(z-G.last),totalMs:S(z-G.start),...$});G.last=z}};if(X1())C("[perf] opencode request start",{requestId:G.requestId,...j});return G}async function Y0(j,D,G){let Z=j.client.session,$=await k1(j.client,D),z={path:{id:D},body:{noReply:!0,parts:[{type:"text",text:G,ignored:!0}]}};if($?.agent)z.body.agent=$.agent;if($?.model)z.body.model=$.model;if($?.variant)z.body.variant=$.variant;if(typeof Z?.promptAsync==="function"){await Z.promptAsync(z);return}if(typeof Z?.prompt==="function"){await Promise.resolve(Z.prompt(z));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function P0(){throw Error(BD)}function qD(j){if(j.sessionID==null)return!1;let D=j.model;return D?.providerID==="anthropic"||D?.api?.npm==="@ai-sdk/anthropic"||D?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function CD(j){if(j.some((D)=>D.includes("<use_parallel_tool_calls>")))return!1;return j.push(Wj),!0}var ED={input:0,output:0,cache:{read:0,write:0}};function wD(j){let D=j["claude-opus-4-8"]??j["claude-opus-4-5"]??Object.values(j)[0];if(!D)return j;return{...j,...Object.fromEntries(Object.values(bj).map((G)=>[G.id,{...D,id:G.id,name:G.name,cost:{input:k0.input,output:k0.output,cache:{read:k0.cacheRead,write:k0.cacheWrite5m}},limit:{...D.limit??{},context:yj,output:kj},capabilities:{...D.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:mj}]))}}function SD(j){return Object.fromEntries(Object.entries(j).map(([D,G])=>[D,{...G,cost:ED}]))}var lD=async(j)=>{MD();let{client:D}=j,G=Pj(),Z=await y(G),$=new hj({storage:Z,onMainQuotaFetched:async(J,V,Y)=>{try{let _=await y(G)??{version:1,accounts:[]};_.quota=_.quota??{},_.quota.mainQuota=J,_.quota.mainQuotaCheckedAt=V,_.quota.mainQuotaToken=Y,_.quota.mainLastQuotaApiError=void 0,await A0(_,G,{mainQuota:!0})}catch(_){C("[quota] failed to persist main quota",{error:_ instanceof Error?_.message:String(_)})}},onApiError:async(J)=>{try{let V=await y(G)??{version:1,accounts:[]};V.quota=V.quota??{},V.quota.mainLastQuotaApiError=J,await A0(V,G,{mainQuota:!0})}catch(V){C("[quota] failed to persist backoff state",{error:V instanceof Error?V.message:String(V)})}}}),z=new xj({quotaManager:$,onFallbackStorageChanged:()=>{r()}});z.startBackgroundRefresh();let M=null,h=new Sj({loadStorage:()=>y(G),prepareHeaders:async(J,V)=>{if(!p)return J;let Y=await p();if(Y.type!=="oauth")return J;if(!Y.access||Y.expires&&Y.expires<Date.now()){if(!M)return J;Y.access=await M()}if(!Y.access)return J;try{let _=JSON.parse(V.bodyText),L=await M1(Y.access,typeof _.model==="string"?_.model:void 0);if(J.delete("anthropic-beta"),E0(J,Y.access,{body:_,identity:L}),J.set("anthropic-beta",q0(J.get("anthropic-beta"),[Tj])),_.speed==="fast")u0(J)}catch{E0(J,Y.access)}return J},log:C});y0({enabled:n0(Z),mode:c0(Z)}),j1(F1(Z)),J1(N1(Z));let J0={activeId:"main",route:"main"};function o(J,V){J0={activeId:V.activeId,route:V.route};let Y=$.getMain(V.mainAccessToken),_=$.getLastApiError(),L=J?.refresh?.mainLastRefreshError,A={main:{quota:Y?.quota??null,quotaBackedOff:$.isBackedOff(),quotaBackoffUntil:_?.nextRetryAt,refreshBackedOff:L?B0(L,V.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:L?.nextRetryAt},fallbacks:(J?.accounts??[]).filter((E)=>E.enabled!==!1&&c(E)).map((E)=>({id:E.id,label:E.label,quota:E.access?$.getFallback(E.id,E.access)?.quota??null:null,enabled:E.enabled!==!1})),activeId:V.activeId,route:V.route,relay:(()=>{let E=E1(J);return E?{enabled:!0,transport:E.transport??"http"}:null})(),fastMode:G1(),cacheKeep:{enabled:T1(J),window:J?.cacheKeep?.startHour!=null&&J?.cacheKeep?.endHour!=null?`${J.cacheKeep.startHour}-${J.cacheKeep.endHour}`:void 0,trackedSessions:h.trackedCount()},lastUpdated:Date.now()};uj(A).catch((E)=>C("[sidebar] state write failed",{error:E instanceof Error?E.message:String(E)}))}async function r(){let J=await y(G),V,Y;if(p)try{let _=await p();V=_.access,Y=_.refresh}catch{}o(J,{activeId:J0.activeId,route:J0.route,mainAccessToken:V,mainRefreshToken:Y})}function z0(J,V){if(!V)return;if(J?.quota?.enabled!==!0)return;if($.getMain(V))return;if(Z0)return;Z0=!0,$.refreshMain(V).then(()=>r()).catch(()=>{}).finally(()=>{Z0=!1})}let p=null,Z0=!1,e=null,s=0;function N0(J){let V=J?.refresh?.refreshBeforeExpiryMinutes??HD;return Math.max(nj,V)*60000}function j0(J){return J?.refresh?.enabled!==!1}async function I0(J){if(!J)return;let V=await y(G),Y=V?.refresh?.mainLastRefreshError;if(!V?.refresh||!Y?.tokenHash)return;let _=o0(J);if(Y.tokenHash===_)return;if(Y.nextRetryAt&&Y.nextRetryAt>Date.now()){C("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:Y.nextRetryAt,retryCount:Y.retryCount,remainingMs:Y.nextRetryAt-Date.now()});return}V.refresh.mainLastRefreshError=void 0,await A0(V,G,{mainRefresh:!0}),C("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:Y.checkedAt,previousNextRetryAt:Y.nextRetryAt,previousRetryCount:Y.retryCount})}async function i(){let J=[];if(p)try{let L=await p();if(L.type==="oauth"&&L.access){let A=await $.refreshMain(L.access);J.push({name:"OpenCode anthropic",role:"main",quota:A})}else if(L.type==="oauth")J.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);J.push({name:"OpenCode anthropic",role:"main",error:A.includes("429")?"Usage API rate limited — try again in a moment":A})}let{storage:V,errors:Y}=await z.refreshQuotaForAllAccounts({force:!0}),_=new Map(Y.map((L)=>[L.accountId,L.message]));if(J.push(...gj(V,_)),!p)J.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return lj({accounts:J,refreshedAt:Date.now()})}async function H0(J){let V=Mj(J);if(V.type==="enable"||V.type==="disable"){let A=V.type==="enable",E=await Ij(A),d=c0(E);return y0({enabled:A,mode:d}),t0({argumentsText:J,enabled:A,mode:d})}if(V.type==="mode"){let A=await Oj(V.mode),E=n0(A);return y0({enabled:E,mode:V.mode}),t0({argumentsText:J,enabled:E,mode:V.mode})}let Y=await y(G),_=n0(Y),L=c0(Y);return y0({enabled:_,mode:L}),t0({argumentsText:J,enabled:_,mode:L})}async function $0(J){let V=qj(J),Y=await y(G);if(V.type==="window")Y=await Qj(V.startHour,V.endHour);else if(V.type==="disable")Y=await Uj(!1);let _=Cj(Y),L=h.stats(_);return wj({argumentsText:J,enabled:Ej(Y),window:_,hybridActive:T1(Y),trackedSessions:L.trackedSessions,nextPrewarmAt:L.nextPrewarmAt})}async function x0(J){let V=Aj(J);if(V.type==="enable"||V.type==="disable"){let L=V.type==="enable";return await _j(L),j1(L),q1({argumentsText:J,enabled:L})}let Y=await y(G),_=F1(Y);return j1(_),q1({argumentsText:J,enabled:_})}async function m0(J){let V=Rj(J);if(V.type==="enable"||V.type==="disable"){let L=V.type==="enable";return await Lj(L),J1(L),C1({argumentsText:J,enabled:L})}let Y=await y(G),_=N1(Y);return J1(_),C1({argumentsText:J,enabled:_})}async function K1(J){let V=ij(J);if(V.type==="mode")return await dj(V.mode),S1({argumentsText:J,mode:V.mode});let Y=await y();return S1({argumentsText:J,mode:w1(Y)})}function W1(J,V=10){let Y=Math.max(0,Math.min(Math.round(J/100*V),V));return"█".repeat(Y)+"░".repeat(V-Y)}function V0(J,V){return`${J} ${W1(V)} ${String(Math.round(V)).padStart(3)}%`}function M0(J){if(!J)return"";let V=new Date(J).getTime();if(Number.isNaN(V))return"";let Y=V-Date.now();if(Y<=0)return"resets now";let _=Math.floor(Y/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 O0(J,V,Y){let _=[],L=0;if(J){let{five_hour:d,seven_day:t}=J;if(d||t){let G0=Y==="main"?"active":"idle",K0=M0(d?.resetsAt),_0=[`main · ${G0}${K0?` (${K0})`:""}`];if(d)_0.push(V0("5h",d.usedPercent)),L=Math.max(L,d.usedPercent);if(t)_0.push(V0("7d",t.usedPercent)),L=Math.max(L,t.usedPercent);_.push(_0.join(`
4
- `))}}if(V?.length)for(let d of V){let t=d.quota;if(!t)continue;let{five_hour:X0,seven_day:G0}=t;if(!X0&&!G0)continue;let K0=d.label||"alt",b0=Y===d.id?"active":"idle",L0=M0(X0?.resetsAt),W0=[`${K0} · ${b0}${L0?` (${L0})`:""}`];if(X0)W0.push(V0("5h",X0.usedPercent)),L=Math.max(L,X0.usedPercent);if(G0)W0.push(V0("7d",G0.usedPercent)),L=Math.max(L,G0.usedPercent);_.push(W0.join(`
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
+ `))}}if(V?.length)for(let n of V){let J0=n.quota;if(!J0)continue;let{five_hour:W0,seven_day:Z0}=J0;if(!W0&&!Z0)continue;let K0=n.label||"alt",b0=K===n.id?"active":"idle",Q0=q0(W0?.resetsAt),P0=[`${K0} · ${b0}${Q0?` (${Q0})`:""}`];if(W0)P0.push(X0("5h",W0.usedPercent)),L=Math.max(L,W0.usedPercent);if(Z0)P0.push(X0("7d",Z0.usedPercent)),L=Math.max(L,Z0.usedPercent);_.push(P0.join(`
5
5
  `))}if(!_.length)return;let A=_.join(`
6
6
 
7
- `),E=L>=90?"error":L>=70?"warning":"info";D.tui?.showToast?.({body:{title:"Claude Quota",message:A,variant:E,duration:E==="error"?8000:5000}})?.catch?.(()=>{})}return{config:async(J)=>{J.command={...J.command??{},[s0]:{template:s0,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[a0]:{template:a0,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[$1]:{template:$1,description:"Show current Claude OAuth quota usage for all accounts."},[e0]:{template:e0,description:"Show or toggle Anthropic request dump capture for debugging."},[D1]:{template:D1,description:"Show or toggle Anthropic fast mode for supported Opus models."},[V1]:{template:V1,description:"Show or change Claude account routing between main-first and fallback-first."},[Z1]:{template:Z1,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."}}},"experimental.chat.system.transform":async(J,V)=>{if(!qD(J))return;CD(V.system)},provider:{id:"anthropic",async models(J,V){let Y=wD(J.models);if(V.auth?.type!=="oauth")return Y;return SD(Y)}},"command.execute.before":async(J)=>{if(J.command===s0)await Y0(j,J.sessionID,await H0(J.arguments)),P0();if(J.command===a0)await Y0(j,J.sessionID,await $0(J.arguments)),P0();if(J.command===$1){await Y0(j,J.sessionID,await i());let V=await y(),Y=p?await p().catch(()=>{return}):void 0;o(V,{activeId:"main",route:"main",mainAccessToken:Y?.access,mainRefreshToken:Y?.refresh}),P0()}if(J.command===e0)await Y0(j,J.sessionID,await x0(J.arguments)),P0();if(J.command===D1)await Y0(j,J.sessionID,await m0(J.arguments)),P0();if(J.command===V1)await Y0(j,J.sessionID,await K1(J.arguments)),P0();if(J.command===Z1){let V=await y(),Y=Nj(V),_=(V?.accounts??[]).filter((A)=>A.enabled!==!1).map((A)=>A.id),L=fj({argumentsText:J.arguments,config:Y,accountIds:_});if(L.updatedConfig)await Hj(L.updatedConfig);await Y0(j,J.sessionID,L.text),P0()}},auth:{provider:"anthropic",async loader(J,V){p=J;let Y=await J();if(Y.type==="oauth"){let A=function(){if(e)clearInterval(e),e=null;let W=async()=>{try{let I=await y(G);if(!j0(I))return;let x=await J();if(x.type!=="oauth")return;if(await I0(x.refresh),!x.expires)return;let O=x.expires-Date.now(),q=N0(I);if(O>q)return;if(C("[refresh] opencode main oauth background due",{expiresInMs:O,refreshBeforeMs:q}),x.refresh&&B0(I?.refresh?.mainLastRefreshError,x.refresh,Date.now())){C("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:I?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:I?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:O});return}if(x.refresh&&I?.refresh?.mainRefreshLeaseUntil&&I.refresh.mainRefreshLeaseUntil>Date.now()&&I.refresh.mainRefreshLeaseTokenHash===o0(x.refresh))return;await L();let K=await J();C("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:K.expires?K.expires-Date.now():void 0})}catch(I){C("[refresh] opencode main oauth refresh failed",{message:I instanceof Error?I.message:String(I)})}};if(e=setInterval(()=>{W()},vD+Kj(FD)),"unref"in e)e.unref()},E=function(W,I){if(W instanceof Request&&W.body)return!1;return I==null||typeof I==="string"},d=function(W){return W.has("x-parent-session-id")},t=function(W){return W.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(W)},X0=function(W){return W?.quota?.enabled===!0},K0=function(W,I){if(W.delete("authorization"),W.delete("x-api-key"),I.authHeader==="x-api-key")W.set("x-api-key",I.apiKey??"");else W.set("Authorization",`Bearer ${I.apiKey??""}`);W.set("Content-Type","application/json")},L0=function(W){return $.getFallback(W.id,W.access)?.quota??W.quota},W0=function(W){return Object.values(W??{}).some((I)=>I&&I.remainingPercent<=0)},A1=function(W,I){return W.status===429||I},Y1=function(W){if(!W)return!1;let I=$.getMain(W);return Boolean(I&&I.refreshAfter>Date.now()&&W0(I.quota))},_=null;async function L(){if(!_)_=(async()=>{let x=null,O=null,q=null;async function K(P){let T=await y(G)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};T.refresh=T.refresh??{},P(T),await A0(T,G,{mainRefresh:!0})}async function R(P){let T=Date.now()+ND;while(Date.now()<T){await new Promise((U)=>setTimeout(U,Vj+Kj(Vj)));let X=await J();if(X.type!=="oauth"||!X.access)continue;if((X.access!==P.access||X.refresh!==P.refresh||(X.expires??0)>(P.expires??0)+60000)&&(!X.expires||X.expires>Date.now()))return C("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:X.expires?X.expires-Date.now():void 0}),X.access}return null}for(let P=0;P<=2;P++){let T=null;try{if(P>0){let H=500*2**(P-1);await new Promise((Q)=>setTimeout(Q,H))}if(T=await J(),!T.refresh)throw Error("Token refresh failed: missing refresh token");let X=await y(G),F=o0(T.refresh),U=X?.refresh?.mainLastRefreshError;if(C("[refresh] opencode main oauth refresh check",{attempt:P,expiresInMs:T.expires?T.expires-Date.now():void 0,hasBackoff:Boolean(U),backoffActive:U?B0(U,T.refresh,Date.now()):!1,retryCount:U?.retryCount,nextRetryAt:U?.nextRetryAt}),U&&B0(U,T.refresh,Date.now()))throw C("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:U.nextRetryAt,retryCount:U.retryCount}),Error(x1(U,Date.now()));if(X?.refresh?.mainRefreshLeaseUntil&&X.refresh.mainRefreshLeaseUntil>Date.now()&&X.refresh.mainRefreshLeaseTokenHash===F){C("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:X.refresh.mainRefreshLeaseUntil});let H=await R(T);if(H)return H;throw Error("Claude OAuth refresh is already in progress")}let N=await zj({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!N){C("[refresh] opencode main oauth refresh skipped file lock");let H=await R(T);if(H)return H;throw Error("Claude OAuth refresh is already in progress")}q=N.release,x=UD(),O=F,await K((H)=>{H.refresh=H.refresh??{},H.refresh.mainRefreshLeaseId=x??void 0,H.refresh.mainRefreshLeaseUntil=Date.now()+120000,H.refresh.mainRefreshLeaseTokenHash=F});let k=await y(G);if(C("[refresh] opencode main oauth refresh lease acquired",{attempt:P,leaseUntil:Date.now()+120000}),k?.refresh?.mainRefreshLeaseId!==x||k.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Claude OAuth refresh is already in progress");C("[refresh] opencode main oauth refresh request start",{attempt:P});let g=await Yj({refreshToken:T.refresh,maxRetries:0});return await D.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:g.refresh,access:g.access,expires:g.expires}}),await K((H)=>{if(!H?.refresh)return;if(H.refresh.mainLastRefreshError=void 0,H.refresh.mainRefreshLeaseId===x)H.refresh.mainRefreshLeaseId=void 0,H.refresh.mainRefreshLeaseUntil=void 0,H.refresh.mainRefreshLeaseTokenHash=void 0}),C("[refresh] opencode main oauth refresh succeeded",{attempt:P,expiresInMs:g.expires-Date.now()}),g.access}catch(X){let F=X instanceof Error&&(X.message.includes("fetch failed")||("code"in X)&&(X.code==="ECONNRESET"||X.code==="ECONNREFUSED"||X.code==="ETIMEDOUT"||X.code==="UND_ERR_CONNECT_TIMEOUT"));if(P<2&&(F||X instanceof Q1&&X.status>=500))continue;C("[refresh] opencode main oauth refresh attempt failed",{attempt:P,error:X instanceof Error?X.message:String(X),transient:F});let U=T?.refresh;if(U&&X instanceof Q1)await K((N)=>{N.refresh=N.refresh??{},N.refresh.mainLastRefreshError=Bj({error:X,now:Date.now(),refreshToken:U,previous:N.refresh.mainLastRefreshError})});throw X}finally{if(x)await K((X)=>{if(!X?.refresh)return;if(X.refresh.mainRefreshLeaseId===x&&X.refresh.mainRefreshLeaseTokenHash===O)X.refresh.mainRefreshLeaseId=void 0,X.refresh.mainRefreshLeaseUntil=void 0,X.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await q?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{_=null});return _}M=L,A(),$.seedFallbacksFromAccounts((Z?.accounts??[]).filter(c)),o(Z,{activeId:"main",route:"main",mainAccessToken:Y.access,mainRefreshToken:Y.refresh});async function G0(W,I){if(!W.body||W.status!==200)return I?.mark("inspect_stream_skip",{status:W.status}),{response:W,rateLimited:!1};if(W.headers.get("x-cortexkit-relay-optimistic")==="true")return I?.mark("inspect_stream_skip",{status:W.status,reason:"optimistic_relay"}),{response:W,rateLimited:!1};let x=v(),O=W.body.getReader(),q=[],K=new TextDecoder,R="",P=0;while(!R.includes(`
7
+ `),w=L>=90?"error":L>=70?"warning":"info";J.tui?.showToast?.({body:{title:"Claude Quota",message:A,variant:w,duration:w==="error"?8000:5000}})?.catch?.(()=>{})}return{config:async(G)=>{G.command={...G.command??{},[a0]:{template:a0,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[t0]:{template:t0,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[Z1]:{template:Z1,description:"Show current Claude OAuth quota usage for all accounts."},[e0]:{template:e0,description:"Show or toggle Anthropic request dump capture for debugging."},[J1]:{template:J1,description:"Show or toggle Anthropic fast mode for supported Opus models."},[V1]:{template:V1,description:"Show or change Claude account routing between main-first and fallback-first."},[G1]:{template:G1,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."}}},"experimental.chat.system.transform":async(G,V)=>{if(!RJ(G))return;fJ(V.system)},provider:{id:"anthropic",async models(G,V){let K=yJ(G.models);if(V.auth?.type!=="oauth"||!Ij(D??{}))return K;return mJ(K)}},"command.execute.before":async(G)=>{if(G.command===a0)await I0(j,G.sessionID,await v0(G.arguments)),O0();if(G.command===t0)await I0(j,G.sessionID,await V0(G.arguments)),O0();if(G.command===Z1){await I0(j,G.sessionID,await c());let V=await k(),K=y?await y().catch(()=>{return}):void 0;a(V,{activeId:"main",route:"main",mainAccessToken:K?.access,mainRefreshToken:K?.refresh}),O0()}if(G.command===e0)await I0(j,G.sessionID,await x0(G.arguments)),O0();if(G.command===J1)await I0(j,G.sessionID,await m0(G.arguments)),O0();if(G.command===V1)await I0(j,G.sessionID,await W1(G.arguments)),O0();if(G.command===G1){let V=await k(),K=xj(V),_=(V?.accounts??[]).filter((A)=>A.enabled!==!1).map((A)=>A.id),L=yj({argumentsText:G.arguments,config:K,accountIds:_});if(L.updatedConfig)await qj(L.updatedConfig);await I0(j,G.sessionID,L.text),O0()}},auth:{provider:"anthropic",async loader(G,V){y=G;let K=await G();if(K.type==="oauth"){let A=function(){if(o)clearInterval(o),o=null;let Y=async()=>{try{let O=await k($);if(!D0(O))return;let q=await G();if(q.type!=="oauth")return;if(await z0(q.refresh),!q.expires)return;let z=q.expires-Date.now(),T=Y0(O);if(z>T)return;if(C("[refresh] opencode main oauth background due",{expiresInMs:z,refreshBeforeMs:T}),q.refresh&&N0(O?.refresh?.mainLastRefreshError,q.refresh,Date.now())){C("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:O?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:O?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:z});return}if(q.refresh&&O?.refresh?.mainRefreshLeaseUntil&&O.refresh.mainRefreshLeaseUntil>Date.now()&&O.refresh.mainRefreshLeaseTokenHash===o0(q.refresh))return;await L();let W=await G();C("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:W.expires?W.expires-Date.now():void 0})}catch(O){C("[refresh] opencode main oauth refresh failed",{message:O instanceof Error?O.message:String(O)})}};if(o=setInterval(()=>{Y()},MJ+Yj(TJ)),"unref"in o)o.unref()},w=function(Y,O){if(Y instanceof Request&&Y.body)return!1;return O==null||typeof O==="string"},n=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)},W0=function(Y){return Y?.quota?.enabled===!0},K0=function(Y,O){if(Y.delete("authorization"),Y.delete("x-api-key"),O.authHeader==="x-api-key")Y.set("x-api-key",O.apiKey??"");else Y.set("Authorization",`Bearer ${O.apiKey??""}`);Y.set("Content-Type","application/json")},Q0=function(Y){return Z.getFallback(Y.id,Y.access)?.quota??Y.quota},P0=function(Y){return Object.values(Y??{}).some((O)=>O&&O.remainingPercent<=0)},A1=function(Y,O){return Y.status===429||O},K1=function(Y){if(!Y)return!1;let O=Z.getMain(Y);return Boolean(O&&O.refreshAfter>Date.now()&&P0(O.quota))},_=null;async function L(){if(!_)_=(async()=>{let q=null,z=null,T=null;async function W(I){let M=await k($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};M.refresh=M.refresh??{},I(M),await A0(M,$,{mainRefresh:!0})}async function R(I){let M=Date.now()+CJ;while(Date.now()<M){await new Promise((U)=>setTimeout(U,Xj+Yj(Xj)));let X=await G();if(X.type!=="oauth"||!X.access)continue;if((X.access!==I.access||X.refresh!==I.refresh||(X.expires??0)>(I.expires??0)+60000)&&(!X.expires||X.expires>Date.now()))return C("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:X.expires?X.expires-Date.now():void 0}),X.access}return null}for(let I=0;I<=2;I++){let M=null;try{if(I>0){let x=500*2**(I-1);await new Promise((Q)=>setTimeout(Q,x))}if(M=await G(),!M.refresh)throw Error("Token refresh failed: missing refresh token");let X=await k($),H=o0(M.refresh),U=X?.refresh?.mainLastRefreshError;if(C("[refresh] opencode main oauth refresh check",{attempt:I,expiresInMs:M.expires?M.expires-Date.now():void 0,hasBackoff:Boolean(U),backoffActive:U?N0(U,M.refresh,Date.now()):!1,retryCount:U?.retryCount,nextRetryAt:U?.nextRetryAt}),U&&N0(U,M.refresh,Date.now()))throw C("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:U.nextRetryAt,retryCount:U.retryCount}),Error(x1(U,Date.now()));if(X?.refresh?.mainRefreshLeaseUntil&&X.refresh.mainRefreshLeaseUntil>Date.now()&&X.refresh.mainRefreshLeaseTokenHash===H){C("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:X.refresh.mainRefreshLeaseUntil});let x=await R(M);if(x)return x;throw Error("Claude OAuth refresh is already in progress")}let B=await zj({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!B){C("[refresh] opencode main oauth refresh skipped file lock");let x=await R(M);if(x)return x;throw Error("Claude OAuth refresh is already in progress")}T=B.release,q=xJ(),z=H,await W((x)=>{x.refresh=x.refresh??{},x.refresh.mainRefreshLeaseId=q??void 0,x.refresh.mainRefreshLeaseUntil=Date.now()+120000,x.refresh.mainRefreshLeaseTokenHash=H});let b=await k($);if(C("[refresh] opencode main oauth refresh lease acquired",{attempt:I,leaseUntil:Date.now()+120000}),b?.refresh?.mainRefreshLeaseId!==q||b.refresh.mainRefreshLeaseTokenHash!==H)throw Error("Claude OAuth refresh is already in progress");C("[refresh] opencode main oauth refresh request start",{attempt:I});let l=await Pj({refreshToken:M.refresh,maxRetries:0});return await J.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:l.refresh,access:l.access,expires:l.expires}}),await W((x)=>{if(!x?.refresh)return;if(x.refresh.mainLastRefreshError=void 0,x.refresh.mainRefreshLeaseId===q)x.refresh.mainRefreshLeaseId=void 0,x.refresh.mainRefreshLeaseUntil=void 0,x.refresh.mainRefreshLeaseTokenHash=void 0}),C("[refresh] opencode main oauth refresh succeeded",{attempt:I,expiresInMs:l.expires-Date.now()}),l.access}catch(X){let H=X instanceof Error&&(X.message.includes("fetch failed")||("code"in X)&&(X.code==="ECONNRESET"||X.code==="ECONNREFUSED"||X.code==="ETIMEDOUT"||X.code==="UND_ERR_CONNECT_TIMEOUT"));if(I<2&&(H||X instanceof Q1&&X.status>=500))continue;C("[refresh] opencode main oauth refresh attempt failed",{attempt:I,error:X instanceof Error?X.message:String(X),transient:H});let U=M?.refresh;if(U&&X instanceof Q1)await W((B)=>{B.refresh=B.refresh??{},B.refresh.mainLastRefreshError=Hj({error:X,now:Date.now(),refreshToken:U,previous:B.refresh.mainLastRefreshError})});throw X}finally{if(q)await W((X)=>{if(!X?.refresh)return;if(X.refresh.mainRefreshLeaseId===q&&X.refresh.mainRefreshLeaseTokenHash===z)X.refresh.mainRefreshLeaseId=void 0,X.refresh.mainRefreshLeaseUntil=void 0,X.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await T?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{_=null});return _}v=L,A(),Z.seedFallbacksFromAccounts((D?.accounts??[]).filter(e)),a(D,{activeId:"main",route:"main",mainAccessToken:K.access,mainRefreshToken:K.refresh});async function Z0(Y,O){if(!Y.body||Y.status!==200)return O?.mark("inspect_stream_skip",{status:Y.status}),{response:Y,rateLimited:!1};if(Y.headers.get("x-cortexkit-relay-optimistic")==="true")return O?.mark("inspect_stream_skip",{status:Y.status,reason:"optimistic_relay"}),{response:Y,rateLimited:!1};let q=N(),z=Y.body.getReader(),T=[],W=new TextDecoder,R="",I=0;while(!R.includes(`
8
8
 
9
- `)&&R.length<65536){let{done:X,value:F}=await O.read();if(X)break;if(q.push(F),P+=F.byteLength,R+=K.decode(F,{stream:!0}),t(R))break}if(t(R))return await O.cancel().catch(()=>{}),I?.mark("inspect_stream_first_event",{ms:S(v()-x),bytes:P,rateLimited:!0}),{response:W,rateLimited:!0};let T=new ReadableStream({start(X){for(let F of q)X.enqueue(F)},async pull(X){let{done:F,value:U}=await O.read();if(F){X.close();return}X.enqueue(U)},cancel(X){return O.cancel(X)}});return I?.mark("inspect_stream_first_event",{ms:S(v()-x),bytes:P,rateLimited:!1}),{response:new Response(T,{status:W.status,statusText:W.statusText,headers:W.headers}),rateLimited:!1}}async function _0(W,I,x,O,q="api_fallback",K){let R=v(),P=z1(W,I),T=d(P);P.delete("x-parent-session-id"),P.delete("x-session-affinity"),P.delete("x-opencode-session");let X=I?.body,F=typeof X==="string"?X.length:void 0;if(X&&typeof X==="string"){let g=v(),H=(()=>{if(!G1())return!1;try{return C0(JSON.parse(X).model)}catch{return!1}})();if(X=await L1(X,{cache1hEnabled:!T&&v0(),cache1hMode:F0(),fastModeEnabled:H,perf:(Q,B)=>O?.mark(`rewrite_body_${Q}`,{route:q,...B})}),K0(P,x),P.set("anthropic-beta",q0(P.get("anthropic-beta"),[])),H)u0(P);O?.mark("rewrite_body",{route:q,ms:S(v()-g),originalBytes:F,rewrittenBytes:X.length,cacheEnabled:!T&&v0(),cacheMode:F0(),fastModeEnabled:H,subagent:T})}else K0(P,x);let U=O1(W,{baseURL:x.baseURL}),N=v(),k=await fetch(U.input,{...I,body:X,headers:P,...I1()&&{tls:{rejectUnauthorized:!1}}});return O?.mark("send_headers_received",{route:q,ms:S(v()-N),status:k.status,relayConfigured:!1,totalSendWithAccessMs:S(v()-R),baseURL:x.baseURL}),k}async function b0(W,I,x,O,q="unknown",K){let R=v(),P=K,T=async()=>{return P??=await y(G),P},X=z1(W,I),F=X.get("x-session-affinity")||X.get("x-opencode-session"),U=d(X);X.delete("x-parent-session-id"),X.delete("x-session-affinity"),X.delete("x-opencode-session");let N=I?.body,k;if(N&&typeof N==="string"){let a=v();try{let D0=JSON.parse(N);if(typeof D0.model==="string")k=D0.model}catch{}O?.mark("model_parse_for_identity",{route:q,ms:S(v()-a),bodyBytes:N.length})}let g=v(),H=await M1(x,k);O?.mark("resolve_claude_code_identity",{route:q,ms:S(v()-g),hasAccountUuid:Boolean(H.accountUuid)});let Q=typeof N==="string"?N.length:void 0;if(N&&typeof N==="string"){let a=v(),D0=(()=>{if(!G1())return!1;try{return C0(JSON.parse(N).model)}catch{return!1}})();N=await L1(N,{cache1hEnabled:!U&&v0(),cache1hMode:F0(),fastModeEnabled:D0,identity:H,perf:(rj,sj)=>O?.mark(`rewrite_body_${rj}`,{route:q,...sj})});let Q0=v();try{E0(X,x,{body:JSON.parse(N),identity:H}),O?.mark("set_oauth_headers_body_parse",{route:q,ms:S(v()-Q0),bodyBytes:N.length,parsed:!0})}catch{E0(X,x,{identity:H}),O?.mark("set_oauth_headers_body_parse",{route:q,ms:S(v()-Q0),bodyBytes:N.length,parsed:!1})}if(D0)u0(X);O?.mark("rewrite_body",{route:q,ms:S(v()-a),originalBytes:Q,rewrittenBytes:N.length,cacheEnabled:!U&&v0(),cacheMode:F0(),fastModeEnabled:D0,subagent:U})}let B=O1(W);if(q==="main"&&typeof N==="string"&&!U&&v0()&&F0()==="hybrid"){let a=await T(),D0=v(),Q0=h.track({sessionId:F,url:B.url?.toString()??B.input.toString(),headers:X,bodyText:N,storage:a,cacheMode:"hybrid"});O?.mark("cachekeep_track",{session:F,ms:S(v()-D0),tracked:Q0.tracked,reason:Q0.tracked?void 0:Q0.reason,bodyBytes:N.length})}let f=()=>fetch(B.input,{...I,body:N,headers:X,...I1()&&{tls:{rejectUnauthorized:!1}}}),u=E1(await T()),m=v(),l=await pj({config:u,input:B.input,init:I,headers:X,body:N,fallback:f,affinity:F,optimisticResponse:u?.transport==="websocket"});return O?.mark("send_headers_received",{route:q,ms:S(v()-m),status:l.status,relayConfigured:u!=null,totalSendWithAccessMs:S(v()-R)}),l}async function cj(W){if(!W)return!1;try{return await $.refreshMain(W),Y1(W)}catch{return!1}}async function h0(W,I={}){let x=await z.getUsableFallbackAccounts(W),O=new Map(x.map((K)=>[K.id,K])),q=[];for(let K of W?.accounts??[]){if(c(K)){let R=O.get(K.id);if(R)q.push(R);continue}if(I.includeApiRoutes===!0&&S0(K)&&K.enabled!==!1&&K.apiKey&&v1(K.baseURL))q.push(K)}if(!f0(W))return q;return q.filter((K)=>c(K)?r0(L0(K),W,K.id):!0)}async function g0(W,I,x,O,q,K,R){if(!x.length)return q??null;let P=R?.returnLastOnExhausted??!0;await q?.body?.cancel().catch(()=>{});let T=q??null;for(let[X,F]of x.entries()){let U;if(S0(F)){if(!F.apiKey)continue;U=await _0(W,I,F,K,`api_fallback_${X}`,O)}else{let k=F.access;if(!k)continue;U=await b0(W,I,k,K,`fallback_${X}`,O)}T=U;let N=H1(U.status,O);if(!N){let k=await G0(U,K);U=k.response,T=U,N=k.rateLimited}if(!N){if(await z.markUsed(F),R?.onSuccess?.(F),c(F)&&F.access&&$.shouldRefreshOnRequestCount(s))$.refreshFallback(F.id,F.access).then(()=>R?.onSuccess?.(F)).catch(()=>{});return U}if(X<x.length-1||!P)await U.body?.cancel().catch(()=>{})}return P?T:null}async function oj(W,I,x,O,q,K,R,P){if(!E(W,I?.body))return x;let T=v(),X=K??await y(G);if(q?.mark("fallback_load_storage",{ms:S(v()-T),cached:!!K}),!(X?.accounts??[]).some((Q)=>Q.enabled!==!1&&(c(Q)||S0(Q)&&Boolean(Q.apiKey)&&v1(Q.baseURL))))return x;let U=x,N=H1(U.status,X),k=A1(U,!1);if(!N){let Q=await G0(U,q);U=Q.response,N=Q.rateLimited,k=A1(U,Q.rateLimited)}if(!N)return U;let g=!1;if(O)g=O.some(S0);else if(k)g=await cj(R);let H=O;if(!H){let Q=v();H=await h0(X,{includeApiRoutes:g}),q?.mark("fallback_get_accounts",{ms:S(v()-Q),accounts:H.length})}if(f0(X)){let Q=H.length;if(H=H.filter((B)=>c(B)?r0(L0(B),X,B.id):!0),H.length<Q)C("[killswitch] filtered fallbacks",{before:Q,after:H.length})}return await g0(W,I,H,X,U,q,{onSuccess:P})??U}return{apiKey:"",async fetch(W,I){let x=I?.body,O=TD({bodyBytes:typeof x==="string"?x.length:void 0}),q=v(),K=await J();if(O.mark("get_auth",{ms:S(v()-q),authType:K.type,hasAccess:Boolean(K.access)}),K.type!=="oauth"){let Q=await fetch(W,I);return O.done("non_oauth_passthrough",{status:Q.status}),Q}await I0(K.refresh);let R=v(),P=await y();O.mark("load_storage",{ms:S(v()-R)}),$.updateStorage(P),$.seedFallbacksFromAccounts((P?.accounts??[]).filter(c));let T=E(W,I?.body);if(T)s++;if(T&&K.access&&(!K.expires||K.expires>Date.now()))z0(P,K.access);let X=(Q,B)=>o(P,{activeId:Q,route:B,mainAccessToken:K.access,mainRefreshToken:K.refresh}),F;if(T&&w1(P)==="fallback-first")try{let Q=v();F=await h0(P,{includeApiRoutes:Y1(K.access)}),O.mark("fallback_first_get_accounts",{ms:S(v()-Q),accounts:F.length});let B=await g0(W,I,F,P,void 0,O,{returnLastOnExhausted:!1,onSuccess:(f)=>X(f.id,"fallback-first")});if(B)return O.done("return_fallback_first",{status:B.status}),w0(B,{perf:(f,u)=>O.mark(f,u)});F=void 0}catch(Q){O.mark("fallback_first_error",{error:Q instanceof Error?Q.message:String(Q)})}if(!K.access||!K.expires||K.expires<Date.now()){let B=(await y())?.refresh?.mainLastRefreshError;if(K.refresh&&B&&B0(B,K.refresh,Date.now()))throw C("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:B.nextRetryAt,retryCount:B.retryCount,expiresInMs:K.expires?K.expires-Date.now():void 0}),Error(x1(B,Date.now()));C("[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 f=v();K.access=await L(),O.mark("refresh_main_access",{ms:S(v()-f)})}if(!K.access)throw O.done("missing_access_error"),Error("OAuth access token is missing after refresh");function U(){if(P?.quota?.showToasts!==!0)return;let Q=$.getMain();if(!Q)return;let B=(P?.accounts??[]).filter((m)=>m.enabled!==!1&&c(m)).map((m)=>({...m,quota:$.getFallback(m.id,m.access)?.quota??m.quota})),f=R0(Q.quota,P),u;if(f)u="main";else u=B.find((m)=>R0(m.quota,P))?.id??"main";O0(Q.quota,B,u)}if(T&&X0(P))try{let Q=v(),B=$.getMain(K.access),f=B?.quota;if(!f)f=await $.refreshMain(K.access),B=$.getMain(K.access),U();else if($.needsRefresh(s))if(W0(f))f=await $.refreshMain(K.access),B=$.getMain(K.access);else $.refreshMain(K.access).then(()=>{r(),U()}).catch(()=>{});if(o(P,{activeId:"main",route:"main",mainAccessToken:K.access,mainRefreshToken:K.refresh}),O.mark("main_quota_for_routing",{ms:S(v()-Q),passes:R0(f,P)}),!R0(f,P)){let u=v();F=await h0(P,{includeApiRoutes:Boolean(B&&B.refreshAfter>Date.now()&&W0(B.quota))}),O.mark("preselect_fallback_accounts",{ms:S(v()-u),accounts:F.length});let m=await g0(W,I,F,P,void 0,O,{onSuccess:(l)=>X(l.id,"fallback")});if(m)return O.done("return_preselected_fallback",{status:m.status}),w0(m,{perf:(l,a)=>O.mark(l,a)})}}catch(Q){O.mark("main_quota_for_routing_error",{error:Q instanceof Error?Q.message:String(Q)})}let N=$.getMain(K.access)?.quota;if(P?.quota?.failClosedOnUnknownQuota&&!N&&$.isBackedOff()){let Q=$.getLastApiError(),B=Q?vj(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:B}}),{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(P)){if($.needsRefresh(s))try{let B=(P?.accounts??[]).filter((f)=>f.enabled!==!1&&c(f)&&Boolean(f.access));await Promise.all([$.refreshMain(K.access),$.refreshAllFallbacks(B)])}catch(B){C("[quota] killswitch refresh failed",{error:B instanceof Error?B.message:String(B),backedOff:$.isBackedOff()})}N=$.getMain(K.access)?.quota}if(f0(P)&&!r0(N,P)){let B=E(W,I?.body)?await h0(P,{includeApiRoutes:Y1(K.access)}):[];if(B.length>0){C("[route] skipping main (killswitch), trying fallbacks");let l=await g0(W,I,B,P,void 0,O,{onSuccess:(a)=>X(a.id,"fallback")});if(l)return O.done("return_killswitch_fallback",{status:l.status}),w0(l,{perf:(a,D0)=>O.mark(a,D0)})}let f=Date.now(),u=(P?.accounts??[]).filter((l)=>l.enabled!==!1&&c(l)).map((l)=>({...l,quota:L0(l)})),m=Fj(N,u,f);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:`Killswitch: no routable accounts. Retry in ${Math.floor(m/60)}m ${m%60}s.`}}),{status:429,headers:{"content-type":"application/json","retry-after":String(m)}})}let k=await b0(W,I,K.access,O,"main",P),g=!1,H=await oj(W,I,k,F,O,P,K.access,(Q)=>{g=!0,X(Q.id,"fallback")});if(!g)X("main","main");return O.done("return_response",{status:H.status}),w0(H,{perf:(Q,B)=>O.mark(Q,B)})}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let J=await U1("max");return{url:J.url,instructions:"Paste the authorization code here:",method:"code",callback:async(V)=>{return B1(V,J.verifier,J.redirectUri,J.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let J=await U1("console");return{url:J.url,instructions:"Paste the authorization code here:",method:"code",callback:async(V)=>{let Y=await B1(V,J.verifier,J.redirectUri,J.state);if(Y.type==="failed")return Y;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 ${Y.access}`}}).then((L)=>L.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{lD as AnthropicAuthPlugin};
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};
@@ -0,0 +1,23 @@
1
+ export type SanitizeMemoStats = {
2
+ hits: number;
3
+ misses: number;
4
+ evictions: number;
5
+ entries: number;
6
+ cacheBytes: number;
7
+ computeMsTotal: number;
8
+ };
9
+ /**
10
+ * Generic byte-bounded LRU memo for a pure `(key: string) => string` function.
11
+ * - Hit: move-to-end (true LRU recency).
12
+ * - Miss: compute (timed), insert, then evict oldest until total bytes <= budget.
13
+ * - Oversize (single entry > budget): compute but do not cache (no thrash).
14
+ * - Disabled: bypass the cache; still record misses/computeMs (measurable baseline).
15
+ * Byte size is approximated by UTF-16 length (key.length + value.length).
16
+ */
17
+ export declare function makeByteBoundedMemo(fn: (key: string) => string, opts: {
18
+ maxBytes: number;
19
+ enabled: () => boolean;
20
+ }): {
21
+ call: (key: string) => string;
22
+ stats: () => SanitizeMemoStats;
23
+ };
@@ -1 +1 @@
1
- import{Qa as a,Ra as b,Sa as c,Ta as d,Ua as e,Va as f}from"./index-s5ckbbqq.js";export{d as setSidebarState,e as resolveActiveAccount,a as getSidebarStateFile,c as getSidebarState,f as getCollapsedQuotaSummary,b as DEFAULT_SIDEBAR_STATE};
1
+ import{Ra as a,Sa as b,Ta as c,Ua as d,Va as e,Wa as f}from"./index-zf02be7y.js";export{d as setSidebarState,e as resolveActiveAccount,a as getSidebarStateFile,c as getSidebarState,f as getCollapsedQuotaSummary,b as DEFAULT_SIDEBAR_STATE};
@@ -45,20 +45,11 @@ export declare function rewriteUrl(input: FetchInput, options?: {
45
45
  url: URL | null;
46
46
  };
47
47
  /**
48
- * Sanitize OpenCode-branded strings from the system prompt text.
49
- *
50
- * 1. Removes the OPENCODE_IDENTITY paragraph.
51
- * 2. Removes any paragraph (text between blank lines) that contains
52
- * one of the PARAGRAPH_REMOVAL_ANCHORS — typically URLs that
53
- * identify OpenCode-specific content.
54
- * 3. Applies TEXT_REPLACEMENTS for inline occurrences of "OpenCode"
55
- * inside paragraphs we want to keep.
56
- *
57
- * This approach is resilient to upstream rewording of the OpenCode
58
- * prompt — as long as the anchor strings (URLs, etc.) still appear
59
- * somewhere in the paragraph, the removal works.
48
+ * Sanitize a system-prompt block. Memoised: the prompt is stable within a
49
+ * session, so the paragraph-filter + regex pass is skipped on cache hits.
60
50
  */
61
51
  export declare function sanitizeSystemText(text: string): string;
52
+ export declare function getSanitizeMemoStats(): import("./sanitize-memo").SanitizeMemoStats;
62
53
  type SystemBlock = {
63
54
  type: string;
64
55
  text: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-anthropic-auth",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
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.8.0",
54
+ "@cortexkit/anthropic-auth-core": "1.9.0",
55
55
  "@opentui/core": ">=0.3.1",
56
56
  "@opentui/solid": ">=0.3.1",
57
57
  "solid-js": "^1.9.10"