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