@cortexkit/opencode-anthropic-auth 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import{$ as C1,A as i1,B as c1,Ba as b0,C as n1,Ca as Z1,D as r0,Da as zj,E as v0,Ea as Qj,F as o1,Fa as $1,G as Z0,H as s0,I as r1,J as P0,K as O0,L as q0,M as s1,N as t1,O as a1,P as e1,Q as C0,R as E0,S as x0,T as I0,U as jj,V as S0,W as U1,X as F1,Y as t0,Z as v1,_ as q1,a as _1,aa as R0,b as L1,ba as Gj,c as B0,ca as Jj,d as M0,da as Zj,e as w1,ea as $j,f as X0,fa as a0,g as b1,ga as Dj,h as H1,ha as Vj,i as B1,ia as T0,j as M1,ja as y0,k as u0,ka as Xj,l as h1,la as e0,m as i0,ma as A0,n as c0,na as j1,o as v,oa as f0,p as g1,pa as Kj,q as R,qa as G1,r as W0,ra as k0,s as p1,sa as Yj,t as U0,ta as Wj,u as F0,ua as m0,v as d1,va as Pj,w as l1,wa as Oj,x as n0,xa as J1,y as u1,z as o0,za as Ij}from"./index-ykvgffhr.js";import{Ja as Nj}from"./index-q0d64q8d.js";import{randomUUID as oj}from"node:crypto";function J0(j){return typeof j==="object"&&j!==null}function Ej(j){if(Array.isArray(j))return j;if(J0(j)&&Array.isArray(j.data))return j.data;return[]}function xj(j){if(!J0(j)||!J0(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function X1(j){if(!J0(j)||!J0(j.info))return null;let G=j.info,J=J0(G.model)?G.model:void 0,D=typeof G.agent==="string"?G.agent:void 0,$=typeof J?.providerID==="string"?J.providerID:typeof G.providerID==="string"?G.providerID:void 0,P=typeof J?.modelID==="string"?J.modelID:typeof G.modelID==="string"?G.modelID:void 0,F=typeof J?.variant==="string"?J.variant:typeof G.variant==="string"?G.variant:void 0;if(!D&&(!$||!P)&&!F)return null;let l={};if(D)l.agent=D;if($&&P)l.model={providerID:$,modelID:P};if(F)l.variant=F;return l}function K1(j,G){return{agent:j.agent??G.agent,model:j.model??G.model,variant:j.variant??G.variant}}function Y1(j){return Boolean(j.agent&&j.model&&j.variant)}async function W1(j,G){if(!j||!G)return null;let J=j;if(typeof J.session?.messages!=="function")return null;let D=[];try{D=Ej(await Promise.resolve(J.session.messages({path:{id:G},query:{limit:100}})))}catch{return null}if(D.length===0)return null;let $={};for(let P=D.length-1;P>=0;P--){if(xj(D[P])!=="assistant")continue;let F=X1(D[P]);if(!F)continue;if($=K1($,F),Y1($))return $}for(let P=D.length-1;P>=0;P--){let F=X1(D[P]);if(!F)continue;if($=K1($,F),Y1($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}function P1(j){return`${_1}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function E1(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}var Sj=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function O1(j){let G=E1(j);if(G.startsWith("aft_"))return G;if(Sj.has(G))return`aft_${G}`;return null}function x1(j,G){let J=new Headers;if(j instanceof Request)j.headers.forEach(($,P)=>{J.set(P,$)});let D=G?.headers;if(D){if(D instanceof Headers)D.forEach(($,P)=>{J.set(P,$)});else if(Array.isArray(D))for(let $ of D){let[P,F]=$;if(typeof F<"u")J.set(P,String(F))}else for(let[$,P]of Object.entries(D))if(typeof P<"u")J.set($,String(P))}return J}function d0(j){return j.set("anthropic-beta",B0(j.get("anthropic-beta"),[L1])),j}function K0(j,G,J={}){return q1(j,G,J)}function Rj(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((G)=>({...G,name:G.name?P1(G.name):G.name}));if(j.messages&&Array.isArray(j.messages))j.messages=j.messages.map((G)=>{if(G.content&&Array.isArray(G.content))G.content=G.content.map((J)=>{if(J.type==="tool_use"&&J.name)return{...J,name:P1(J.name)};return J});return G});return JSON.stringify(C1(j))}function p0(j){return j.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(G,J,D)=>{if(J)return`"name": "${O1(D)??E1(D)}"`;let $=O1(D);return $?`"name": "${$}"`:G})}function I1(j,G=!1){if(G)return{ready:p0(j),pending:""};let J=j.length,D='"name"',$=Math.max(0,j.length-D.length+1);for(let F=$;F<j.length;F++)if(D.startsWith(j.slice(F))){J=Math.min(J,F);break}let P=j.lastIndexOf(D);if(P!==-1){let F=j.slice(P);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(F))J=Math.min(J,P)}if(J<j.length)return{ready:p0(j.slice(0,J)),pending:j.slice(J)};return{ready:p0(j),pending:""}}function S1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function Tj(){let j=process.env.ANTHROPIC_BASE_URL?.trim();if(!j)return null;try{let G=new URL(j);if(G.protocol!=="http:"&&G.protocol!=="https:"||G.username||G.password)return null;return G}catch{return null}}function R1(j){let G=null;try{if(typeof j==="string"||j instanceof URL)G=new URL(j.toString());else if(j instanceof Request)G=new URL(j.url)}catch{G=null}if(!G)return{input:j,url:null};let J=G.href,D=Tj();if(D)G.protocol=D.protocol,G.host=D.host;if(G.pathname==="/v1/messages"&&!G.searchParams.has("beta"))G.searchParams.set("beta","true");if(G.href===J)return{input:j,url:G};return{input:j instanceof Request?new Request(G.toString(),j):G,url:G}}function _0(j){let D=j.split(/\n\n+/).filter(($)=>{if($.includes(w1))return!1;for(let P of B1)if($.includes(P))return!1;return!0}).join(`
1
+ import{$ as t1,A as Oj,Aa as mj,B as F1,Ba as bj,C as _j,Ca as Dj,D as N1,Da as hj,E as Lj,Ea as $1,F as Qj,Fa as gj,G as Uj,Ga as lj,H as H1,Ha as E1,I as o0,J as Bj,Ja as pj,K as B0,L as x1,La as V1,M as vj,Ma as w1,N as R0,Na as dj,O as f0,Oa as ij,P as r0,Pa as S1,Q as Fj,R as Nj,S as Hj,T as xj,U as s0,V as v0,W as F0,X as y0,Y as Mj,Z as t0,_ as s1,a as i1,aa as M1,b as u1,ba as a1,c as q0,ca as e1,d as C0,da as jj,e as n1,ea as a0,f as T0,fa as Tj,g as Wj,ga as qj,h as c1,ha as Cj,i as o1,ia as Ej,j as r1,ja as T1,k as Q1,ka as wj,l as Yj,la as Sj,m as U1,ma as e0,n as B1,na as j1,o as C,oa as Aj,p as c,pa as q1,q as S0,qa as D1,r as v1,ra as G1,s as Pj,sa as J1,t as y,ta as Rj,ua as C1,v as A0,va as Z1,w as zj,wa as fj,x as n0,xa as k0,y as c0,ya as yj,z as Ij,za as kj}from"./index-gcmgg93d.js";import{Ta as uj}from"./index-s5ckbbqq.js";import{randomUUID as UD}from"node:crypto";function U0(j){return typeof j==="object"&&j!==null}function tj(j){if(Array.isArray(j))return j;if(U0(j)&&Array.isArray(j.data))return j.data;return[]}function aj(j){if(!U0(j)||!U0(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function R1(j){if(!U0(j)||!U0(j.info))return null;let D=j.info,G=U0(D.model)?D.model:void 0,Z=typeof D.agent==="string"?D.agent:void 0,$=typeof G?.providerID==="string"?G.providerID:typeof D.providerID==="string"?D.providerID:void 0,z=typeof G?.modelID==="string"?G.modelID:typeof D.modelID==="string"?D.modelID:void 0,M=typeof G?.variant==="string"?G.variant:typeof D.variant==="string"?D.variant:void 0;if(!Z&&(!$||!z)&&!M)return null;let h={};if(Z)h.agent=Z;if($&&z)h.model={providerID:$,modelID:z};if(M)h.variant=M;return h}function f1(j,D){return{agent:j.agent??D.agent,model:j.model??D.model,variant:j.variant??D.variant}}function y1(j){return Boolean(j.agent&&j.model&&j.variant)}async function k1(j,D){if(!j||!D)return null;let G=j;if(typeof G.session?.messages!=="function")return null;let Z=[];try{Z=tj(await Promise.resolve(G.session.messages({path:{id:D},query:{limit:100}})))}catch{return null}if(Z.length===0)return null;let $={};for(let z=Z.length-1;z>=0;z--){if(aj(Z[z])!=="assistant")continue;let M=R1(Z[z]);if(!M)continue;if($=f1($,M),y1($))return $}for(let z=Z.length-1;z>=0;z--){let M=R1(Z[z]);if(!M)continue;if($=f1($,M),y1($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}function m1(j){return`${i1}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function Gj(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}var ej=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function b1(j){let D=Gj(j);if(D.startsWith("aft_"))return D;if(ej.has(D))return`aft_${D}`;return null}function z1(j,D){let G=new Headers;if(j instanceof Request)j.headers.forEach(($,z)=>{G.set(z,$)});let Z=D?.headers;if(Z){if(Z instanceof Headers)Z.forEach(($,z)=>{G.set(z,$)});else if(Array.isArray(Z))for(let $ of Z){let[z,M]=$;if(typeof M<"u")G.set(z,String(M))}else for(let[$,z]of Object.entries(Z))if(typeof z<"u")G.set($,String(z))}return G}function u0(j){return j.set("anthropic-beta",q0(j.get("anthropic-beta"),[u1])),j}function E0(j,D,G={}){return e1(j,D,G)}function jD(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((D)=>({...D,name:D.name?m1(D.name):D.name}));if(j.messages&&Array.isArray(j.messages))j.messages=j.messages.map((D)=>{if(D.content&&Array.isArray(D.content))D.content=D.content.map((G)=>{if(G.type==="tool_use"&&G.name)return{...G,name:m1(G.name)};return G});return D});return JSON.stringify(jj(j))}function P1(j){return j.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(D,G,Z)=>{if(G)return`"name": "${b1(Z)??Gj(Z)}"`;let $=b1(Z);return $?`"name": "${$}"`:D})}function h1(j,D=!1){if(D)return{ready:P1(j),pending:""};let G=j.length,Z='"name"',$=Math.max(0,j.length-Z.length+1);for(let M=$;M<j.length;M++)if(Z.startsWith(j.slice(M))){G=Math.min(G,M);break}let z=j.lastIndexOf(Z);if(z!==-1){let M=j.slice(z);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(M))G=Math.min(G,z)}if(G<j.length)return{ready:P1(j.slice(0,G)),pending:j.slice(G)};return{ready:P1(j),pending:""}}function I1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function Jj(j){let D=j?.trim();if(!D)return null;try{let G=new URL(D);if(G.protocol!=="http:"&&G.protocol!=="https:"||G.username||G.password)return null;return G}catch{return null}}function DD(){return Jj(process.env.ANTHROPIC_BASE_URL)}function O1(j,D={}){let G=null;try{if(typeof j==="string"||j instanceof URL)G=new URL(j.toString());else if(j instanceof Request)G=new URL(j.url)}catch{G=null}if(!G)return{input:j,url:null};let Z=G.href,$=D.baseURL?Jj(D.baseURL):DD();if($){if(G.protocol=$.protocol,G.host=$.host,D.baseURL)G.pathname=`${$.pathname.replace(/\/$/,"")}${G.pathname}`}if(G.pathname.endsWith("/v1/messages")&&!G.searchParams.has("beta"))G.searchParams.set("beta","true");if(G.href===Z)return{input:j,url:G};return{input:j instanceof Request?new Request(G.toString(),j):G,url:G}}function l0(j){let Z=j.split(/\n\n+/).filter(($)=>{if($.includes(n1))return!1;for(let z of o1)if($.includes(z))return!1;return!0}).join(`
2
2
 
3
- `);for(let $ of M1)D=D.replace($.match,$.replacement);return D.trim()}function y(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function yj(j){let G={type:"text",text:X0};if(j==null)return[G];if(typeof j==="string"){let D=_0(j);if(D===X0)return[G];return[G,{type:"text",text:D}]}if(y(j)){let D=typeof j.type==="string"?j.type:"text",$=typeof j.text==="string"?j.text:"";return[G,{...j,type:D,text:_0($)}]}if(!Array.isArray(j))return[G];let J=j.map((D)=>{if(typeof D==="string")return{type:"text",text:_0(D)};if(y(D)&&D.type==="text"&&typeof D.text==="string")return{...D,type:"text",text:_0(D.text)};return{type:"text",text:String(D)}});if(J[0]?.text===X0)return J;return[G,...J]}var T1={type:"ephemeral",ttl:"1h"},Aj=20;function fj(j){if(y(j.cache_control))return j.cache_control;if(y(j.cacheControl))return j.cacheControl;return null}function H0(j,G){if(!y(j))return!1;return delete j.cacheControl,j.cache_control=G?{...T1}:{type:"ephemeral"},!0}function z1(j){if(!y(j))return;delete j.cache_control,delete j.cacheControl}function kj(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function L0(j,G){if(!y(j))return;let J=fj(j);if(J?.type!=="ephemeral")return;if(G)J.ttl="1h";else delete J.ttl}function Q1(j,G){if(Array.isArray(j.system))for(let J of j.system)L0(J,G);else L0(j.system,G);if(!Array.isArray(j.messages))return;for(let J of j.messages)if(L0(J,G),y(J)&&Array.isArray(J.content))for(let D of J.content)L0(D,G)}function mj(j,G){if(Array.isArray(j.system))for(let J of j.system)G(J);else G(j.system);if(!Array.isArray(j.messages))return;for(let J of j.messages)if(G(J),y(J)&&Array.isArray(J.content))for(let D of J.content)G(D)}function y1(j){z1(j),mj(j,z1)}function bj(j){y1(j),j.cache_control={...T1}}function hj(j){return y(j)&&j.type!=="thinking"&&j.type!=="redacted_thinking"}function l0(j){let G=kj(j.content);if(!G?.length)return;let J=G.filter(hj);if(!J.length)return;return{content:G,cacheableBlocks:J}}function gj(j){if(!y(j))return!1;let G=l0(j);if(!G)return!1;return j.content=G.content,H0(G.cacheableBlocks[0],!0)}function w0(j){if(!y(j))return!1;let G=l0(j);if(!G)return!1;let J=G.cacheableBlocks[G.cacheableBlocks.length-1];return j.content=G.content,H0(J,!0)}function pj(j){if(!y(j))return!1;return(l0(j)?.cacheableBlocks.length??0)>1}function dj(j){if(!y(j))return 0;let G=j.content;if(Array.isArray(G))return G.length;if(G==null)return 0;return 1}function lj(j){let G=[],J=0;return j.forEach((D,$)=>{let P=dj(D);if(y(D)&&D.role==="user"&&P>0)G.push({index:$,blockPosition:J+P-1});J+=P}),G}function uj(j){let G=lj(j),J=[...G].reverse().find((F)=>F.index>1);if(!J)return{latest:void 0,bridge:void 0};let D=[...G].reverse().find((F)=>F.index<J.index),$=D?J.blockPosition-D.blockPosition+1:0,P=D&&D.index>1&&$>Aj?D:void 0;return{latest:J,bridge:P}}function N1(j){if(Array.isArray(j.system)){let G=j.system.findIndex(($)=>y($)&&$.text===X0),J=j.system.slice(G>=0?G+1:0).filter(y),D=J[J.length-1];H0(D,!0)}else H0(j.system,!0)}function ij(j){if(y1(j),!Array.isArray(j.messages)){N1(j);return}let{latest:G,bridge:J}=uj(j.messages);if(!J)N1(j);let D=pj(j.messages[0]);if(D)gj(j.messages[0]);if(w0(j.messages[0]),!D)w0(j.messages[1]);if(J)w0(j.messages[J.index]);if(G)w0(j.messages[G.index])}function cj(j,G){if(!G.enabled){Q1(j,!1),delete j.cache_control,delete j.cacheControl;return}if(G.mode==="automatic"){bj(j);return}if(G.mode==="hybrid"){ij(j);return}Q1(j,!0),delete j.cacheControl}function nj(j){if(!Array.isArray(j.messages))return;while(j.messages.length){let G=j.messages[j.messages.length-1];if(!y(G)||G.role!=="assistant")break;j.messages.pop()}}async function A1(j,G={}){try{let J=JSON.parse(j);nj(J);let D=Array.isArray(J.messages)&&J.messages.some(($)=>$.role==="user")?F1(J.messages,void 0,H1):null;if(J.system=yj(J.system),D&&Array.isArray(J.system))J.system.unshift({type:"text",text:D});if(cj(J,{enabled:G.cache1hEnabled??!1,mode:G.cache1hMode??"explicit"}),G.fastModeEnabled&&M0(J.model))J.speed="fast";else if(J.speed==="fast")delete J.speed;if(G.identity)v1(J,G.identity);return await U1(Rj(J))}catch{return j}}function Y0(j){if(!j.body)return j;let G=j.body.getReader(),J=new TextDecoder,D=new TextEncoder,$="",P=new ReadableStream({async pull(F){let{done:l,value:$0}=await G.read();if(l){let z0=I1(`${$}${J.decode()}`,!0);if(z0.ready)F.enqueue(D.encode(z0.ready));F.close();return}let o=$+J.decode($0,{stream:!0}),r=I1(o);if($=r.pending,r.ready)F.enqueue(D.encode(r.ready))}});return new Response(P,{status:j.status,statusText:j.statusText,headers:j.headers})}var rj="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",sj=60000,tj=60000,aj=5000,f1=200,_j=240,ej=_j,jG=1,k1=!1;function h0(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function q(){return performance.now()}function A(j){return Math.round(j*10)/10}function m1(j){return Math.floor(Math.random()*Math.max(0,j))}function GG(){if(k1||!1||!h0())return;k1=!0;let j=100,G=250,J=q()+j;setInterval(()=>{let D=q(),$=D-J;if(J=D+j,$<G)return;v("[perf] opencode event_loop_lag",{lagMs:A($),thresholdMs:G})},j).unref?.()}function JG(j){let G=q(),J={requestId:String(jG++),start:G,last:G,mark(D,$){let P=q();if(h0())v("[perf] opencode request stage",{requestId:J.requestId,stage:D,deltaMs:A(P-J.last),totalMs:A(P-J.start),...$});J.last=P},done(D,$){let P=q();if(h0())v("[perf] opencode request done",{requestId:J.requestId,stage:D,deltaMs:A(P-J.last),totalMs:A(P-J.start),...$});J.last=P}};if(h0())v("[perf] opencode request start",{requestId:J.requestId,...j});return J}async function a(j,G,J){let D=j.client.session,$=await W1(j.client,G),P={path:{id:G},body:{noReply:!0,parts:[{type:"text",text:J,ignored:!0}]}};if($?.agent)P.body.agent=$.agent;if($?.model)P.body.model=$.model;if($?.variant)P.body.variant=$.variant;if(typeof D?.promptAsync==="function"){await D.promptAsync(P);return}if(typeof D?.prompt==="function"){await Promise.resolve(D.prompt(P));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function e(){throw Error(rj)}function ZG(j){if(j.sessionID==null)return!1;let G=j.model;return G?.providerID==="anthropic"||G?.api?.npm==="@ai-sdk/anthropic"||G?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function $G(j){if(j.some((G)=>G.includes("<use_parallel_tool_calls>")))return!1;return j.push(b1),!0}var zG=async(j)=>{GG();let{client:G}=j,J=g1(),D=await R(J),$=new Wj({storage:D,onMainQuotaFetched:async(Z,V,K)=>{try{let Y=await R(J)??{version:1,accounts:[]};Y.quota=Y.quota??{},Y.quota.mainQuota=Z,Y.quota.mainQuotaCheckedAt=V,Y.quota.mainQuotaToken=K,Y.quota.mainLastQuotaApiError=void 0,await W0(Y,J)}catch(Y){v("[quota] failed to persist main quota",{error:Y instanceof Error?Y.message:String(Y)})}},onApiError:async(Z)=>{try{let V=await R(J)??{version:1,accounts:[]};V.quota=V.quota??{},V.quota.mainLastQuotaApiError=Z,await W0(V,J)}catch(V){v("[quota] failed to persist backoff state",{error:V instanceof Error?V.message:String(V)})}}}),P=new e1({quotaManager:$,onFallbackStorageChanged:()=>{r()}});P.startBackgroundRefresh();let F=null,l=new Vj({loadStorage:()=>R(J),prepareHeaders:async(Z,V)=>{if(!u)return Z;let K=await u();if(K.type!=="oauth")return Z;if(!K.access||K.expires&&K.expires<Date.now()){if(!F)return Z;K.access=await F()}if(!K.access)return Z;try{let Y=JSON.parse(V.bodyText),O=await t0(K.access,typeof Y.model==="string"?Y.model:void 0);if(Z.delete("anthropic-beta"),K0(Z,K.access,{body:Y,identity:O}),Z.set("anthropic-beta",B0(Z.get("anthropic-beta"),[Gj])),Y.speed==="fast")d0(Z)}catch{K0(Z,K.access)}return Z},log:v});I0({enabled:U0(D),mode:F0(D)}),y0(n0(D)),f0(o0(D));let $0={activeId:"main",route:"main"};function o(Z,V){$0={activeId:V.activeId,route:V.route};let K=$.getMain(V.mainAccessToken),Y=$.getLastApiError(),O=Z?.refresh?.mainLastRefreshError,x={main:{quota:K?.quota??null,quotaBackedOff:$.isBackedOff(),quotaBackoffUntil:Y?.nextRetryAt,refreshBackedOff:O?Z0(O,V.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:O?.nextRetryAt},fallbacks:(Z?.accounts??[]).filter((C)=>C.enabled!==!1).map((C)=>({id:C.id,label:C.label,quota:C.access?$.getFallback(C.id,C.access)?.quota??null:null,enabled:C.enabled!==!1})),activeId:V.activeId,route:V.route,relay:(()=>{let C=J1(Z);return C?{enabled:!0,transport:C.transport??"http"}:null})(),fastMode:j1(),cacheKeep:{enabled:a0(Z),window:Z?.cacheKeep?.startHour!=null&&Z?.cacheKeep?.endHour!=null?`${Z.cacheKeep.startHour}-${Z.cacheKeep.endHour}`:void 0,trackedSessions:l.trackedCount()},lastUpdated:Date.now()};Nj(x).catch((C)=>v("[sidebar] state write failed",{error:C instanceof Error?C.message:String(C)}))}async function r(){let Z=await R(J),V,K;if(u)try{let Y=await u();V=Y.access,K=Y.refresh}catch{}o(Z,{activeId:$0.activeId,route:$0.route,mainAccessToken:V,mainRefreshToken:K})}function z0(Z,V){if(!V)return;if(Z?.quota?.enabled!==!0)return;if($.getMain(V))return;if(g0)return;g0=!0,$.refreshMain(V).then(()=>r()).catch(()=>{}).finally(()=>{g0=!1})}let u=null,g0=!1,j0=null,Q0=0;function Lj(Z){let V=Z?.refresh?.refreshBeforeExpiryMinutes??ej;return Math.max(_j,V)*60000}function wj(Z){return Z?.refresh?.enabled!==!1}async function D1(Z){if(!Z)return;let V=await R(J),K=V?.refresh?.mainLastRefreshError;if(!V?.refresh||!K?.tokenHash)return;let Y=v0(Z);if(K.tokenHash===Y)return;if(K.nextRetryAt&&K.nextRetryAt>Date.now()){v("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:K.nextRetryAt,retryCount:K.retryCount,remainingMs:K.nextRetryAt-Date.now()});return}V.refresh.mainLastRefreshError=void 0,await W0(V,J),v("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:K.checkedAt,previousNextRetryAt:K.nextRetryAt,previousRetryCount:K.retryCount})}async function Hj(){let Z=[];if(u)try{let O=await u();if(O.type==="oauth"&&O.access){let x=await $.refreshMain(O.access);Z.push({name:"OpenCode anthropic",role:"main",quota:x})}else if(O.type==="oauth")Z.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(O){let x=O instanceof Error?O.message:String(O);Z.push({name:"OpenCode anthropic",role:"main",error:x.includes("429")?"Usage API rate limited — try again in a moment":x})}let{storage:V,errors:K}=await P.refreshQuotaForAllAccounts({force:!0}),Y=new Map(K.map((O)=>[O.accountId,O.message]));if(Z.push(...Pj(V,Y)),!u)Z.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return Oj({accounts:Z,refreshedAt:Date.now()})}async function Bj(Z){let V=jj(Z);if(V.type==="enable"||V.type==="disable"){let x=V.type==="enable",C=await d1(x),h=F0(C);return I0({enabled:x,mode:h}),S0({argumentsText:Z,enabled:x,mode:h})}if(V.type==="mode"){let x=await l1(V.mode),C=U0(x);return I0({enabled:C,mode:V.mode}),S0({argumentsText:Z,enabled:C,mode:V.mode})}let K=await R(J),Y=U0(K),O=F0(K);return I0({enabled:Y,mode:O}),S0({argumentsText:Z,enabled:Y,mode:O})}async function Mj(Z){let V=Jj(Z),K=await R(J);if(V.type==="window")K=await c1(V.startHour,V.endHour);else if(V.type==="disable")K=await n1(!1);let Y=Zj(K),O=l.stats(Y);return Dj({argumentsText:Z,enabled:$j(K),window:Y,hybridActive:a0(K),trackedSessions:O.trackedSessions,nextPrewarmAt:O.nextPrewarmAt})}async function Uj(Z){let V=Xj(Z);if(V.type==="enable"||V.type==="disable"){let O=V.type==="enable";return await u1(O),y0(O),e0({argumentsText:Z,enabled:O})}let K=await R(J),Y=n0(K);return y0(Y),e0({argumentsText:Z,enabled:Y})}async function Fj(Z){let V=Kj(Z);if(V.type==="enable"||V.type==="disable"){let O=V.type==="enable";return await i1(O),f0(O),G1({argumentsText:Z,enabled:O})}let K=await R(J),Y=o0(K);return f0(Y),G1({argumentsText:Z,enabled:Y})}async function vj(Z){let V=Qj(Z);if(V.type==="mode")return await zj(V.mode),$1({argumentsText:Z,mode:V.mode});let K=await R();return $1({argumentsText:Z,mode:Z1(K)})}function qj(Z,V=10){let K=Math.max(0,Math.min(Math.round(Z/100*V),V));return"█".repeat(K)+"░".repeat(V-K)}function N0(Z,V){return`${Z} ${qj(V)} ${String(Math.round(V)).padStart(3)}%`}function V1(Z){if(!Z)return"";let V=new Date(Z).getTime();if(Number.isNaN(V))return"";let K=V-Date.now();if(K<=0)return"resets now";let Y=Math.floor(K/60000);if(Y<1)return"resets <1m";if(Y<60)return`resets ${Y}m`;let O=Math.floor(Y/60),x=Y%60;return x>0?`resets ${O}h${x}m`:`resets ${O}h`}function Cj(Z,V,K){let Y=[],O=0;if(Z){let{five_hour:h,seven_day:p}=Z;if(h||p){let i=K==="main"?"active":"idle",s=V1(h?.resetsAt),n=[`main · ${i}${s?` (${s})`:""}`];if(h)n.push(N0("5h",h.usedPercent)),O=Math.max(O,h.usedPercent);if(p)n.push(N0("7d",p.usedPercent)),O=Math.max(O,p.usedPercent);Y.push(n.join(`
4
- `))}}if(V?.length)for(let h of V){let p=h.quota;if(!p)continue;let{five_hour:c,seven_day:i}=p;if(!c&&!i)continue;let s=h.label||"alt",D0=K===h.id?"active":"idle",t=V1(c?.resetsAt),V0=[`${s} · ${D0}${t?` (${t})`:""}`];if(c)V0.push(N0("5h",c.usedPercent)),O=Math.max(O,c.usedPercent);if(i)V0.push(N0("7d",i.usedPercent)),O=Math.max(O,i.usedPercent);Y.push(V0.join(`
5
- `))}if(!Y.length)return;let x=Y.join(`
3
+ `);for(let $ of r1)Z=Z.replace($.match,$.replacement);return Z.trim()}function b(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function GD(j){let D={type:"text",text:T0};if(j==null)return[D];if(typeof j==="string"){let Z=l0(j);if(Z===T0)return[D];return[D,{type:"text",text:Z}]}if(b(j)){let Z=typeof j.type==="string"?j.type:"text",$=typeof j.text==="string"?j.text:"";return[D,{...j,type:Z,text:l0($)}]}if(!Array.isArray(j))return[D];let G=j.map((Z)=>{if(typeof Z==="string")return{type:"text",text:l0(Z)};if(b(Z)&&Z.type==="text"&&typeof Z.text==="string")return{...Z,type:"text",text:l0(Z.text)};return{type:"text",text:String(Z)}});if(G[0]?.text===T0)return G;return[D,...G]}var Zj={type:"ephemeral",ttl:"1h"},JD=20;function ZD(j){if(b(j.cache_control))return j.cache_control;if(b(j.cacheControl))return j.cacheControl;return null}function i0(j,D){if(!b(j))return!1;return delete j.cacheControl,j.cache_control=D?{...Zj}:{type:"ephemeral"},!0}function g1(j){if(!b(j))return;delete j.cache_control,delete j.cacheControl}function $D(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function p0(j,D){if(!b(j))return;let G=ZD(j);if(G?.type!=="ephemeral")return;if(D)G.ttl="1h";else delete G.ttl}function l1(j,D){if(Array.isArray(j.system))for(let G of j.system)p0(G,D);else p0(j.system,D);if(!Array.isArray(j.messages))return;for(let G of j.messages)if(p0(G,D),b(G)&&Array.isArray(G.content))for(let Z of G.content)p0(Z,D)}function VD(j,D){if(Array.isArray(j.system))for(let G of j.system)D(G);else D(j.system);if(!Array.isArray(j.messages))return;for(let G of j.messages)if(D(G),b(G)&&Array.isArray(G.content))for(let Z of G.content)D(Z)}function $j(j){g1(j),VD(j,g1)}function XD(j){$j(j),j.cache_control={...Zj}}function KD(j){return b(j)&&j.type!=="thinking"&&j.type!=="redacted_thinking"}function _1(j){let D=$D(j.content);if(!D?.length)return;let G=D.filter(KD);if(!G.length)return;return{content:D,cacheableBlocks:G}}function WD(j){if(!b(j))return!1;let D=_1(j);if(!D)return!1;return j.content=D.content,i0(D.cacheableBlocks[0],!0)}function d0(j){if(!b(j))return!1;let D=_1(j);if(!D)return!1;let G=D.cacheableBlocks[D.cacheableBlocks.length-1];return j.content=D.content,i0(G,!0)}function YD(j){if(!b(j))return!1;return(_1(j)?.cacheableBlocks.length??0)>1}function PD(j){if(!b(j))return 0;let D=j.content;if(Array.isArray(D))return D.length;if(D==null)return 0;return 1}function zD(j){let D=[],G=0;return j.forEach((Z,$)=>{let z=PD(Z);if(b(Z)&&Z.role==="user"&&z>0)D.push({index:$,blockPosition:G+z-1});G+=z}),D}function ID(j){let D=zD(j),G=[...D].reverse().find((M)=>M.index>1);if(!G)return{latest:void 0,bridge:void 0};let Z=[...D].reverse().find((M)=>M.index<G.index),$=Z?G.blockPosition-Z.blockPosition+1:0,z=Z&&Z.index>1&&$>JD?Z:void 0;return{latest:G,bridge:z}}function p1(j){if(Array.isArray(j.system)){let D=j.system.findIndex(($)=>b($)&&$.text===T0),G=j.system.slice(D>=0?D+1:0).filter(b),Z=G[G.length-1];i0(Z,!0)}else i0(j.system,!0)}function OD(j){if($j(j),!Array.isArray(j.messages)){p1(j);return}let{latest:D,bridge:G}=ID(j.messages);if(!G)p1(j);let Z=YD(j.messages[0]);if(Z)WD(j.messages[0]);if(d0(j.messages[0]),!Z)d0(j.messages[1]);if(G)d0(j.messages[G.index]);if(D)d0(j.messages[D.index])}function _D(j){if(!Dj(j.model))return!1;let D=Object.hasOwn(j,"thinking");return delete j.thinking,D}function LD(j,D){if(!D.enabled){l1(j,!1),delete j.cache_control,delete j.cacheControl;return}if(D.mode==="automatic"){XD(j);return}if(D.mode==="hybrid"){OD(j);return}l1(j,!0),delete j.cacheControl}function QD(j){if(!Array.isArray(j.messages))return;while(j.messages.length){let D=j.messages[j.messages.length-1];if(!b(D)||D.role!=="assistant")break;j.messages.pop()}}function w(){return performance.now()}function n(j){return Math.round(j*10)/10}function d1(j){let D=0,G=0,Z=0,$=Array.isArray(j.messages)?j.messages:[];D=$.length;for(let z of $){if(!z||typeof z!=="object")continue;let M=z.content;if(!Array.isArray(M))continue;G+=M.length;for(let h of M)if(h&&typeof h==="object"&&h.type==="tool_use")Z++}return{messageCount:D,contentBlockCount:G,toolDefinitionCount:Array.isArray(j.tools)?j.tools.length:0,toolUseCount:Z,systemBlockCount:Array.isArray(j.system)?j.system.length:0}}async function L1(j,D={}){try{let G=w(),Z=JSON.parse(j);D.perf?.("parse",{ms:n(w()-G),inputBytes:j.length,...d1(Z)});let $=w(),z=Array.isArray(Z.messages)?Z.messages.length:void 0;QD(Z);let M=Array.isArray(Z.messages)?Z.messages.length:void 0;D.perf?.("strip_trailing_assistant",{ms:n(w()-$),removedMessages:typeof z==="number"&&typeof M==="number"?z-M:void 0});let h=w(),J0=_D(Z);D.perf?.("model_normalize",{ms:n(w()-h),model:typeof Z.model==="string"?Z.model:void 0,removedFableThinking:J0,hasOutputConfig:Object.hasOwn(Z,"output_config")});let o=w(),r=Array.isArray(Z.messages)&&Z.messages.some((I0)=>I0.role==="user")?t1(Z.messages,void 0,c1):null;D.perf?.("billing_header",{ms:n(w()-o),hasBillingHeader:Boolean(r)});let z0=w();if(Z.system=GD(Z.system),D.perf?.("system_identity",{ms:n(w()-z0),systemBlockCount:Array.isArray(Z.system)?Z.system.length:0}),r&&Array.isArray(Z.system))Z.system.unshift({type:"text",text:r});let p=w();if(LD(Z,{enabled:D.cache1hEnabled??!1,mode:D.cache1hMode??"explicit"}),D.perf?.("cache_strategy",{ms:n(w()-p),enabled:D.cache1hEnabled??!1,mode:D.cache1hMode??"explicit"}),D.fastModeEnabled&&C0(Z.model))Z.speed="fast";else if(Z.speed==="fast")delete Z.speed;let Z0=w();if(D.identity)a1(Z,D.identity);D.perf?.("metadata",{ms:n(w()-Z0),hasAccountUuid:Boolean(D.identity?.accountUuid)});let e=w(),s=jD(Z);D.perf?.("prefix_tools_stringify",{ms:n(w()-e),outputBytesBeforeSign:s.length,...d1(Z)});let N0=w(),j0=await s1(s);return D.perf?.("cch_sign",{ms:n(w()-N0),outputBytes:j0.length}),j0}catch{return j}}function w0(j,D={}){if(!j.body)return j;let G=j.body.getReader(),Z=new TextDecoder,$=new TextEncoder,z="",M=0,h=0,J0=0,o=0,r=0,z0=!1,p=!1,Z0=w(),e=w(),s=()=>{if(p)return;p=!0,G.releaseLock()},N0=(i={})=>({chunks:M,pulls:h,inputBytes:J0,outputBytes:o,pendingChars:z.length,rewriteMs:n(r),totalMs:n(w()-e),...i}),j0=(i,H0={})=>{D.perf?.(i,N0(H0))};D.perf?.("stream_tool_prefix_wrapper_created",{status:j.status,hasBody:!0});let I0=new ReadableStream({async pull(i){if(h++,!z0)z0=!0,j0("stream_tool_prefix_first_pull");let H0=w();try{let{done:$0,value:x0}=await G.read(),m0=n(w()-H0);if($0){let O0=w(),J=h1(`${z}${Z.decode()}`,!0);if(r+=w()-O0,J.ready){let V=$.encode(J.ready);o+=V.byteLength,i.enqueue(V)}j0("stream_tool_prefix_rewrite",{readMs:m0}),s(),i.close();return}M++,J0+=x0.byteLength;let K1=z+Z.decode(x0,{stream:!0}),W1=w(),V0=h1(K1);if(r+=w()-W1,z=V0.pending,V0.ready){let O0=$.encode(V0.ready);o+=O0.byteLength,i.enqueue(O0)}let M0=w();if(M===1||M%25===0||M0-Z0>5000)Z0=M0,j0("stream_tool_prefix_progress",{readMs:m0,lastChunkBytes:x0.byteLength})}catch($0){throw j0("stream_tool_prefix_error",{error:$0 instanceof Error?$0.message:String($0)}),s(),$0}},async cancel(i){j0("stream_tool_prefix_cancel",{reason:i instanceof Error?i.message:String(i)});try{await G.cancel(i)}finally{s()}}});return new Response(I0,{status:j.status,statusText:j.statusText,headers:j.headers})}var BD="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",vD=60000,FD=60000,ND=5000,Vj=200,nj=240,HD=nj,xD=1,Xj=!1;function X1(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function v(){return performance.now()}function S(j){return Math.round(j*10)/10}function Kj(j){return Math.floor(Math.random()*Math.max(0,j))}function MD(){if(Xj||!1||!X1())return;Xj=!0;let j=100,D=250,G=v()+j;setInterval(()=>{let Z=v(),$=Z-G;if(G=Z+j,$<D)return;C("[perf] opencode event_loop_lag",{lagMs:S($),thresholdMs:D})},j).unref?.()}function TD(j){let D=v(),G={requestId:String(xD++),start:D,last:D,mark(Z,$){let z=v();if(X1())C("[perf] opencode request stage",{requestId:G.requestId,stage:Z,deltaMs:S(z-G.last),totalMs:S(z-G.start),...$});G.last=z},done(Z,$){let z=v();if(X1())C("[perf] opencode request done",{requestId:G.requestId,stage:Z,deltaMs:S(z-G.last),totalMs:S(z-G.start),...$});G.last=z}};if(X1())C("[perf] opencode request start",{requestId:G.requestId,...j});return G}async function Y0(j,D,G){let Z=j.client.session,$=await k1(j.client,D),z={path:{id:D},body:{noReply:!0,parts:[{type:"text",text:G,ignored:!0}]}};if($?.agent)z.body.agent=$.agent;if($?.model)z.body.model=$.model;if($?.variant)z.body.variant=$.variant;if(typeof Z?.promptAsync==="function"){await Z.promptAsync(z);return}if(typeof Z?.prompt==="function"){await Promise.resolve(Z.prompt(z));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function P0(){throw Error(BD)}function qD(j){if(j.sessionID==null)return!1;let D=j.model;return D?.providerID==="anthropic"||D?.api?.npm==="@ai-sdk/anthropic"||D?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function CD(j){if(j.some((D)=>D.includes("<use_parallel_tool_calls>")))return!1;return j.push(Wj),!0}var ED={input:0,output:0,cache:{read:0,write:0}};function wD(j){let D=j["claude-opus-4-8"]??j["claude-opus-4-5"]??Object.values(j)[0];if(!D)return j;return{...j,...Object.fromEntries(Object.values(bj).map((G)=>[G.id,{...D,id:G.id,name:G.name,cost:{input:k0.input,output:k0.output,cache:{read:k0.cacheRead,write:k0.cacheWrite5m}},limit:{...D.limit??{},context:yj,output:kj},capabilities:{...D.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:mj}]))}}function SD(j){return Object.fromEntries(Object.entries(j).map(([D,G])=>[D,{...G,cost:ED}]))}var lD=async(j)=>{MD();let{client:D}=j,G=Pj(),Z=await y(G),$=new hj({storage:Z,onMainQuotaFetched:async(J,V,Y)=>{try{let _=await y(G)??{version:1,accounts:[]};_.quota=_.quota??{},_.quota.mainQuota=J,_.quota.mainQuotaCheckedAt=V,_.quota.mainQuotaToken=Y,_.quota.mainLastQuotaApiError=void 0,await A0(_,G,{mainQuota:!0})}catch(_){C("[quota] failed to persist main quota",{error:_ instanceof Error?_.message:String(_)})}},onApiError:async(J)=>{try{let V=await y(G)??{version:1,accounts:[]};V.quota=V.quota??{},V.quota.mainLastQuotaApiError=J,await A0(V,G,{mainQuota:!0})}catch(V){C("[quota] failed to persist backoff state",{error:V instanceof Error?V.message:String(V)})}}}),z=new xj({quotaManager:$,onFallbackStorageChanged:()=>{r()}});z.startBackgroundRefresh();let M=null,h=new Sj({loadStorage:()=>y(G),prepareHeaders:async(J,V)=>{if(!p)return J;let Y=await p();if(Y.type!=="oauth")return J;if(!Y.access||Y.expires&&Y.expires<Date.now()){if(!M)return J;Y.access=await M()}if(!Y.access)return J;try{let _=JSON.parse(V.bodyText),L=await M1(Y.access,typeof _.model==="string"?_.model:void 0);if(J.delete("anthropic-beta"),E0(J,Y.access,{body:_,identity:L}),J.set("anthropic-beta",q0(J.get("anthropic-beta"),[Tj])),_.speed==="fast")u0(J)}catch{E0(J,Y.access)}return J},log:C});y0({enabled:n0(Z),mode:c0(Z)}),j1(F1(Z)),J1(N1(Z));let J0={activeId:"main",route:"main"};function o(J,V){J0={activeId:V.activeId,route:V.route};let Y=$.getMain(V.mainAccessToken),_=$.getLastApiError(),L=J?.refresh?.mainLastRefreshError,A={main:{quota:Y?.quota??null,quotaBackedOff:$.isBackedOff(),quotaBackoffUntil:_?.nextRetryAt,refreshBackedOff:L?B0(L,V.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:L?.nextRetryAt},fallbacks:(J?.accounts??[]).filter((E)=>E.enabled!==!1&&c(E)).map((E)=>({id:E.id,label:E.label,quota:E.access?$.getFallback(E.id,E.access)?.quota??null:null,enabled:E.enabled!==!1})),activeId:V.activeId,route:V.route,relay:(()=>{let E=E1(J);return E?{enabled:!0,transport:E.transport??"http"}:null})(),fastMode:G1(),cacheKeep:{enabled:T1(J),window:J?.cacheKeep?.startHour!=null&&J?.cacheKeep?.endHour!=null?`${J.cacheKeep.startHour}-${J.cacheKeep.endHour}`:void 0,trackedSessions:h.trackedCount()},lastUpdated:Date.now()};uj(A).catch((E)=>C("[sidebar] state write failed",{error:E instanceof Error?E.message:String(E)}))}async function r(){let J=await y(G),V,Y;if(p)try{let _=await p();V=_.access,Y=_.refresh}catch{}o(J,{activeId:J0.activeId,route:J0.route,mainAccessToken:V,mainRefreshToken:Y})}function z0(J,V){if(!V)return;if(J?.quota?.enabled!==!0)return;if($.getMain(V))return;if(Z0)return;Z0=!0,$.refreshMain(V).then(()=>r()).catch(()=>{}).finally(()=>{Z0=!1})}let p=null,Z0=!1,e=null,s=0;function N0(J){let V=J?.refresh?.refreshBeforeExpiryMinutes??HD;return Math.max(nj,V)*60000}function j0(J){return J?.refresh?.enabled!==!1}async function I0(J){if(!J)return;let V=await y(G),Y=V?.refresh?.mainLastRefreshError;if(!V?.refresh||!Y?.tokenHash)return;let _=o0(J);if(Y.tokenHash===_)return;if(Y.nextRetryAt&&Y.nextRetryAt>Date.now()){C("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:Y.nextRetryAt,retryCount:Y.retryCount,remainingMs:Y.nextRetryAt-Date.now()});return}V.refresh.mainLastRefreshError=void 0,await A0(V,G,{mainRefresh:!0}),C("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:Y.checkedAt,previousNextRetryAt:Y.nextRetryAt,previousRetryCount:Y.retryCount})}async function i(){let J=[];if(p)try{let L=await p();if(L.type==="oauth"&&L.access){let A=await $.refreshMain(L.access);J.push({name:"OpenCode anthropic",role:"main",quota:A})}else if(L.type==="oauth")J.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(L){let A=L instanceof Error?L.message:String(L);J.push({name:"OpenCode anthropic",role:"main",error:A.includes("429")?"Usage API rate limited — try again in a moment":A})}let{storage:V,errors:Y}=await z.refreshQuotaForAllAccounts({force:!0}),_=new Map(Y.map((L)=>[L.accountId,L.message]));if(J.push(...gj(V,_)),!p)J.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return lj({accounts:J,refreshedAt:Date.now()})}async function H0(J){let V=Mj(J);if(V.type==="enable"||V.type==="disable"){let A=V.type==="enable",E=await Ij(A),d=c0(E);return y0({enabled:A,mode:d}),t0({argumentsText:J,enabled:A,mode:d})}if(V.type==="mode"){let A=await Oj(V.mode),E=n0(A);return y0({enabled:E,mode:V.mode}),t0({argumentsText:J,enabled:E,mode:V.mode})}let Y=await y(G),_=n0(Y),L=c0(Y);return y0({enabled:_,mode:L}),t0({argumentsText:J,enabled:_,mode:L})}async function $0(J){let V=qj(J),Y=await y(G);if(V.type==="window")Y=await Qj(V.startHour,V.endHour);else if(V.type==="disable")Y=await Uj(!1);let _=Cj(Y),L=h.stats(_);return wj({argumentsText:J,enabled:Ej(Y),window:_,hybridActive:T1(Y),trackedSessions:L.trackedSessions,nextPrewarmAt:L.nextPrewarmAt})}async function x0(J){let V=Aj(J);if(V.type==="enable"||V.type==="disable"){let L=V.type==="enable";return await _j(L),j1(L),q1({argumentsText:J,enabled:L})}let Y=await y(G),_=F1(Y);return j1(_),q1({argumentsText:J,enabled:_})}async function m0(J){let V=Rj(J);if(V.type==="enable"||V.type==="disable"){let L=V.type==="enable";return await Lj(L),J1(L),C1({argumentsText:J,enabled:L})}let Y=await y(G),_=N1(Y);return J1(_),C1({argumentsText:J,enabled:_})}async function K1(J){let V=ij(J);if(V.type==="mode")return await dj(V.mode),S1({argumentsText:J,mode:V.mode});let Y=await y();return S1({argumentsText:J,mode:w1(Y)})}function W1(J,V=10){let Y=Math.max(0,Math.min(Math.round(J/100*V),V));return"█".repeat(Y)+"░".repeat(V-Y)}function V0(J,V){return`${J} ${W1(V)} ${String(Math.round(V)).padStart(3)}%`}function M0(J){if(!J)return"";let V=new Date(J).getTime();if(Number.isNaN(V))return"";let Y=V-Date.now();if(Y<=0)return"resets now";let _=Math.floor(Y/60000);if(_<1)return"resets <1m";if(_<60)return`resets ${_}m`;let L=Math.floor(_/60),A=_%60;return A>0?`resets ${L}h${A}m`:`resets ${L}h`}function O0(J,V,Y){let _=[],L=0;if(J){let{five_hour:d,seven_day:t}=J;if(d||t){let G0=Y==="main"?"active":"idle",K0=M0(d?.resetsAt),_0=[`main · ${G0}${K0?` (${K0})`:""}`];if(d)_0.push(V0("5h",d.usedPercent)),L=Math.max(L,d.usedPercent);if(t)_0.push(V0("7d",t.usedPercent)),L=Math.max(L,t.usedPercent);_.push(_0.join(`
4
+ `))}}if(V?.length)for(let d of V){let t=d.quota;if(!t)continue;let{five_hour:X0,seven_day:G0}=t;if(!X0&&!G0)continue;let K0=d.label||"alt",b0=Y===d.id?"active":"idle",L0=M0(X0?.resetsAt),W0=[`${K0} · ${b0}${L0?` (${L0})`:""}`];if(X0)W0.push(V0("5h",X0.usedPercent)),L=Math.max(L,X0.usedPercent);if(G0)W0.push(V0("7d",G0.usedPercent)),L=Math.max(L,G0.usedPercent);_.push(W0.join(`
5
+ `))}if(!_.length)return;let A=_.join(`
6
6
 
7
- `),C=O>=90?"error":O>=70?"warning":"info";G.tui?.showToast?.({body:{title:"Claude Quota",message:x,variant:C,duration:C==="error"?8000:5000}})?.catch?.(()=>{})}return{config:async(Z)=>{Z.command={...Z.command??{},[C0]:{template:C0,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[R0]:{template:R0,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[m0]:{template:m0,description:"Show current Claude OAuth quota usage for all accounts."},[T0]:{template:T0,description:"Show or toggle Anthropic request dump capture for debugging."},[A0]:{template:A0,description:"Show or toggle Anthropic fast mode for supported Opus models."},[b0]:{template:b0,description:"Show or change Claude account routing between main-first and fallback-first."},[k0]:{template:k0,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."}}},"experimental.chat.system.transform":async(Z,V)=>{if(!ZG(Z))return;$G(V.system)},"command.execute.before":async(Z)=>{if(Z.command===C0)await a(j,Z.sessionID,await Bj(Z.arguments)),e();if(Z.command===R0)await a(j,Z.sessionID,await Mj(Z.arguments)),e();if(Z.command===m0){await a(j,Z.sessionID,await Hj());let V=await R(),K=u?await u().catch(()=>{return}):void 0;o(V,{activeId:"main",route:"main",mainAccessToken:K?.access,mainRefreshToken:K?.refresh}),e()}if(Z.command===T0)await a(j,Z.sessionID,await Uj(Z.arguments)),e();if(Z.command===A0)await a(j,Z.sessionID,await Fj(Z.arguments)),e();if(Z.command===b0)await a(j,Z.sessionID,await vj(Z.arguments)),e();if(Z.command===k0){let V=await R(),K=t1(V),Y=(V?.accounts??[]).filter((x)=>x.enabled!==!1).map((x)=>x.id),O=Yj({argumentsText:Z.arguments,config:K,accountIds:Y});if(O.updatedConfig)await a1(O.updatedConfig);await a(j,Z.sessionID,O.text),e()}},auth:{provider:"anthropic",async loader(Z,V){u=Z;let K=await Z();if(K.type==="oauth"){let x=function(){if(j0)clearInterval(j0),j0=null;let I=async()=>{try{let N=await R(J);if(!wj(N))return;let M=await Z();if(M.type!=="oauth")return;if(await D1(M.refresh),!M.expires)return;let _=M.expires-Date.now(),S=Lj(N);if(_>S)return;if(v("[refresh] opencode main oauth background due",{expiresInMs:_,refreshBeforeMs:S}),M.refresh&&Z0(N?.refresh?.mainLastRefreshError,M.refresh,Date.now())){v("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:N?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:N?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:_});return}if(M.refresh&&N?.refresh?.mainRefreshLeaseUntil&&N.refresh.mainRefreshLeaseUntil>Date.now()&&N.refresh.mainRefreshLeaseTokenHash===v0(M.refresh))return;await O();let z=await Z();v("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:z.expires?z.expires-Date.now():void 0})}catch(N){v("[refresh] opencode main oauth refresh failed",{message:N instanceof Error?N.message:String(N)})}};if(j0=setInterval(()=>{I()},sj+m1(tj)),"unref"in j0)j0.unref()},C=function(I,N){if(I instanceof Request&&I.body)return!1;return N==null||typeof N==="string"},h=function(I){return I.has("x-parent-session-id")},p=function(I){return I.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(I)},c=function(I){return I?.quota?.enabled===!0},n=function(I){return $.getFallback(I.id,I.access)?.quota??I.quota};for(let I of Object.values(V.models))I.cost={input:0,output:0,cache:{read:0,write:0}};let Y=null;async function O(){if(!Y)Y=(async()=>{let M=null,_=null,S=null;async function z(W){let B=await R(J)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};B.refresh=B.refresh??{},W(B),await W0(B,J)}async function T(W){let B=Date.now()+aj;while(Date.now()<B){await new Promise((L)=>setTimeout(L,f1+m1(f1)));let X=await Z();if(X.type!=="oauth"||!X.access)continue;if((X.access!==W.access||X.refresh!==W.refresh||(X.expires??0)>(W.expires??0)+60000)&&(!X.expires||X.expires>Date.now()))return v("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:X.expires?X.expires-Date.now():void 0}),X.access}return null}for(let W=0;W<=2;W++){let B=null;try{if(W>0){let E=500*2**(W-1);await new Promise((H)=>setTimeout(H,E))}if(B=await Z(),!B.refresh)throw Error("Token refresh failed: missing refresh token");let X=await R(J),w=v0(B.refresh),L=X?.refresh?.mainLastRefreshError;if(v("[refresh] opencode main oauth refresh check",{attempt:W,expiresInMs:B.expires?B.expires-Date.now():void 0,hasBackoff:Boolean(L),backoffActive:L?Z0(L,B.refresh,Date.now()):!1,retryCount:L?.retryCount,nextRetryAt:L?.nextRetryAt}),L&&Z0(L,B.refresh,Date.now()))throw v("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:L.nextRetryAt,retryCount:L.retryCount}),Error(s0(L,Date.now()));if(X?.refresh?.mainRefreshLeaseUntil&&X.refresh.mainRefreshLeaseUntil>Date.now()&&X.refresh.mainRefreshLeaseTokenHash===w){v("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:X.refresh.mainRefreshLeaseUntil});let E=await T(B);if(E)return E;throw Error("Claude OAuth refresh is already in progress")}let Q=await p1({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!Q){v("[refresh] opencode main oauth refresh skipped file lock");let E=await T(B);if(E)return E;throw Error("Claude OAuth refresh is already in progress")}S=Q.release,M=oj(),_=w,await z((E)=>{E.refresh=E.refresh??{},E.refresh.mainRefreshLeaseId=M??void 0,E.refresh.mainRefreshLeaseUntil=Date.now()+120000,E.refresh.mainRefreshLeaseTokenHash=w});let g=await R(J);if(v("[refresh] opencode main oauth refresh lease acquired",{attempt:W,leaseUntil:Date.now()+120000}),g?.refresh?.mainRefreshLeaseId!==M||g.refresh.mainRefreshLeaseTokenHash!==w)throw Error("Claude OAuth refresh is already in progress");v("[refresh] opencode main oauth refresh request start",{attempt:W});let m=await h1({refreshToken:B.refresh,maxRetries:0});return await G.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:m.refresh,access:m.access,expires:m.expires}}),await z((E)=>{if(!E?.refresh)return;if(E.refresh.mainLastRefreshError=void 0,E.refresh.mainRefreshLeaseId===M)E.refresh.mainRefreshLeaseId=void 0,E.refresh.mainRefreshLeaseUntil=void 0,E.refresh.mainRefreshLeaseTokenHash=void 0}),v("[refresh] opencode main oauth refresh succeeded",{attempt:W,expiresInMs:m.expires-Date.now()}),m.access}catch(X){let w=X instanceof Error&&(X.message.includes("fetch failed")||("code"in X)&&(X.code==="ECONNRESET"||X.code==="ECONNREFUSED"||X.code==="ETIMEDOUT"||X.code==="UND_ERR_CONNECT_TIMEOUT"));if(W<2&&(w||X instanceof u0&&X.status>=500))continue;v("[refresh] opencode main oauth refresh attempt failed",{attempt:W,error:X instanceof Error?X.message:String(X),transient:w});let L=B?.refresh;if(L&&X instanceof u0)await z((Q)=>{Q.refresh=Q.refresh??{},Q.refresh.mainLastRefreshError=o1({error:X,now:Date.now(),refreshToken:L,previous:Q.refresh.mainLastRefreshError})});throw X}finally{if(M)await z((X)=>{if(!X?.refresh)return;if(X.refresh.mainRefreshLeaseId===M&&X.refresh.mainRefreshLeaseTokenHash===_)X.refresh.mainRefreshLeaseId=void 0,X.refresh.mainRefreshLeaseUntil=void 0,X.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await S?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{Y=null});return Y}F=O,x(),$.seedFallbacksFromAccounts(D?.accounts??[]),o(D,{activeId:"main",route:"main",mainAccessToken:K.access,mainRefreshToken:K.refresh});async function i(I,N){if(!I.body||I.status!==200)return N?.mark("inspect_stream_skip",{status:I.status}),{response:I,rateLimited:!1};if(I.headers.get("x-cortexkit-relay-optimistic")==="true")return N?.mark("inspect_stream_skip",{status:I.status,reason:"optimistic_relay"}),{response:I,rateLimited:!1};let M=q(),_=I.body.getReader(),S=[],z=new TextDecoder,T="",W=0;while(!T.includes(`
7
+ `),E=L>=90?"error":L>=70?"warning":"info";D.tui?.showToast?.({body:{title:"Claude Quota",message:A,variant:E,duration:E==="error"?8000:5000}})?.catch?.(()=>{})}return{config:async(J)=>{J.command={...J.command??{},[s0]:{template:s0,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[a0]:{template:a0,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[$1]:{template:$1,description:"Show current Claude OAuth quota usage for all accounts."},[e0]:{template:e0,description:"Show or toggle Anthropic request dump capture for debugging."},[D1]:{template:D1,description:"Show or toggle Anthropic fast mode for supported Opus models."},[V1]:{template:V1,description:"Show or change Claude account routing between main-first and fallback-first."},[Z1]:{template:Z1,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."}}},"experimental.chat.system.transform":async(J,V)=>{if(!qD(J))return;CD(V.system)},provider:{id:"anthropic",async models(J,V){let Y=wD(J.models);if(V.auth?.type!=="oauth")return Y;return SD(Y)}},"command.execute.before":async(J)=>{if(J.command===s0)await Y0(j,J.sessionID,await H0(J.arguments)),P0();if(J.command===a0)await Y0(j,J.sessionID,await $0(J.arguments)),P0();if(J.command===$1){await Y0(j,J.sessionID,await i());let V=await y(),Y=p?await p().catch(()=>{return}):void 0;o(V,{activeId:"main",route:"main",mainAccessToken:Y?.access,mainRefreshToken:Y?.refresh}),P0()}if(J.command===e0)await Y0(j,J.sessionID,await x0(J.arguments)),P0();if(J.command===D1)await Y0(j,J.sessionID,await m0(J.arguments)),P0();if(J.command===V1)await Y0(j,J.sessionID,await K1(J.arguments)),P0();if(J.command===Z1){let V=await y(),Y=Nj(V),_=(V?.accounts??[]).filter((A)=>A.enabled!==!1).map((A)=>A.id),L=fj({argumentsText:J.arguments,config:Y,accountIds:_});if(L.updatedConfig)await Hj(L.updatedConfig);await Y0(j,J.sessionID,L.text),P0()}},auth:{provider:"anthropic",async loader(J,V){p=J;let Y=await J();if(Y.type==="oauth"){let A=function(){if(e)clearInterval(e),e=null;let W=async()=>{try{let I=await y(G);if(!j0(I))return;let x=await J();if(x.type!=="oauth")return;if(await I0(x.refresh),!x.expires)return;let O=x.expires-Date.now(),q=N0(I);if(O>q)return;if(C("[refresh] opencode main oauth background due",{expiresInMs:O,refreshBeforeMs:q}),x.refresh&&B0(I?.refresh?.mainLastRefreshError,x.refresh,Date.now())){C("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:I?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:I?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:O});return}if(x.refresh&&I?.refresh?.mainRefreshLeaseUntil&&I.refresh.mainRefreshLeaseUntil>Date.now()&&I.refresh.mainRefreshLeaseTokenHash===o0(x.refresh))return;await L();let K=await J();C("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:K.expires?K.expires-Date.now():void 0})}catch(I){C("[refresh] opencode main oauth refresh failed",{message:I instanceof Error?I.message:String(I)})}};if(e=setInterval(()=>{W()},vD+Kj(FD)),"unref"in e)e.unref()},E=function(W,I){if(W instanceof Request&&W.body)return!1;return I==null||typeof I==="string"},d=function(W){return W.has("x-parent-session-id")},t=function(W){return W.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(W)},X0=function(W){return W?.quota?.enabled===!0},K0=function(W,I){if(W.delete("authorization"),W.delete("x-api-key"),I.authHeader==="x-api-key")W.set("x-api-key",I.apiKey??"");else W.set("Authorization",`Bearer ${I.apiKey??""}`);W.set("Content-Type","application/json")},L0=function(W){return $.getFallback(W.id,W.access)?.quota??W.quota},W0=function(W){return Object.values(W??{}).some((I)=>I&&I.remainingPercent<=0)},A1=function(W,I){return W.status===429||I},Y1=function(W){if(!W)return!1;let I=$.getMain(W);return Boolean(I&&I.refreshAfter>Date.now()&&W0(I.quota))},_=null;async function L(){if(!_)_=(async()=>{let x=null,O=null,q=null;async function K(P){let T=await y(G)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};T.refresh=T.refresh??{},P(T),await A0(T,G,{mainRefresh:!0})}async function R(P){let T=Date.now()+ND;while(Date.now()<T){await new Promise((U)=>setTimeout(U,Vj+Kj(Vj)));let X=await J();if(X.type!=="oauth"||!X.access)continue;if((X.access!==P.access||X.refresh!==P.refresh||(X.expires??0)>(P.expires??0)+60000)&&(!X.expires||X.expires>Date.now()))return C("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:X.expires?X.expires-Date.now():void 0}),X.access}return null}for(let P=0;P<=2;P++){let T=null;try{if(P>0){let H=500*2**(P-1);await new Promise((Q)=>setTimeout(Q,H))}if(T=await J(),!T.refresh)throw Error("Token refresh failed: missing refresh token");let X=await y(G),F=o0(T.refresh),U=X?.refresh?.mainLastRefreshError;if(C("[refresh] opencode main oauth refresh check",{attempt:P,expiresInMs:T.expires?T.expires-Date.now():void 0,hasBackoff:Boolean(U),backoffActive:U?B0(U,T.refresh,Date.now()):!1,retryCount:U?.retryCount,nextRetryAt:U?.nextRetryAt}),U&&B0(U,T.refresh,Date.now()))throw C("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:U.nextRetryAt,retryCount:U.retryCount}),Error(x1(U,Date.now()));if(X?.refresh?.mainRefreshLeaseUntil&&X.refresh.mainRefreshLeaseUntil>Date.now()&&X.refresh.mainRefreshLeaseTokenHash===F){C("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:X.refresh.mainRefreshLeaseUntil});let H=await R(T);if(H)return H;throw Error("Claude OAuth refresh is already in progress")}let N=await zj({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!N){C("[refresh] opencode main oauth refresh skipped file lock");let H=await R(T);if(H)return H;throw Error("Claude OAuth refresh is already in progress")}q=N.release,x=UD(),O=F,await K((H)=>{H.refresh=H.refresh??{},H.refresh.mainRefreshLeaseId=x??void 0,H.refresh.mainRefreshLeaseUntil=Date.now()+120000,H.refresh.mainRefreshLeaseTokenHash=F});let k=await y(G);if(C("[refresh] opencode main oauth refresh lease acquired",{attempt:P,leaseUntil:Date.now()+120000}),k?.refresh?.mainRefreshLeaseId!==x||k.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Claude OAuth refresh is already in progress");C("[refresh] opencode main oauth refresh request start",{attempt:P});let g=await Yj({refreshToken:T.refresh,maxRetries:0});return await D.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:g.refresh,access:g.access,expires:g.expires}}),await K((H)=>{if(!H?.refresh)return;if(H.refresh.mainLastRefreshError=void 0,H.refresh.mainRefreshLeaseId===x)H.refresh.mainRefreshLeaseId=void 0,H.refresh.mainRefreshLeaseUntil=void 0,H.refresh.mainRefreshLeaseTokenHash=void 0}),C("[refresh] opencode main oauth refresh succeeded",{attempt:P,expiresInMs:g.expires-Date.now()}),g.access}catch(X){let F=X instanceof Error&&(X.message.includes("fetch failed")||("code"in X)&&(X.code==="ECONNRESET"||X.code==="ECONNREFUSED"||X.code==="ETIMEDOUT"||X.code==="UND_ERR_CONNECT_TIMEOUT"));if(P<2&&(F||X instanceof Q1&&X.status>=500))continue;C("[refresh] opencode main oauth refresh attempt failed",{attempt:P,error:X instanceof Error?X.message:String(X),transient:F});let U=T?.refresh;if(U&&X instanceof Q1)await K((N)=>{N.refresh=N.refresh??{},N.refresh.mainLastRefreshError=Bj({error:X,now:Date.now(),refreshToken:U,previous:N.refresh.mainLastRefreshError})});throw X}finally{if(x)await K((X)=>{if(!X?.refresh)return;if(X.refresh.mainRefreshLeaseId===x&&X.refresh.mainRefreshLeaseTokenHash===O)X.refresh.mainRefreshLeaseId=void 0,X.refresh.mainRefreshLeaseUntil=void 0,X.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await q?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{_=null});return _}M=L,A(),$.seedFallbacksFromAccounts((Z?.accounts??[]).filter(c)),o(Z,{activeId:"main",route:"main",mainAccessToken:Y.access,mainRefreshToken:Y.refresh});async function G0(W,I){if(!W.body||W.status!==200)return I?.mark("inspect_stream_skip",{status:W.status}),{response:W,rateLimited:!1};if(W.headers.get("x-cortexkit-relay-optimistic")==="true")return I?.mark("inspect_stream_skip",{status:W.status,reason:"optimistic_relay"}),{response:W,rateLimited:!1};let x=v(),O=W.body.getReader(),q=[],K=new TextDecoder,R="",P=0;while(!R.includes(`
8
8
 
9
- `)&&T.length<65536){let{done:X,value:w}=await _.read();if(X)break;if(S.push(w),W+=w.byteLength,T+=z.decode(w,{stream:!0}),p(T))break}if(p(T))return await _.cancel().catch(()=>{}),N?.mark("inspect_stream_first_event",{ms:A(q()-M),bytes:W,rateLimited:!0}),{response:I,rateLimited:!0};let B=new ReadableStream({start(X){for(let w of S)X.enqueue(w)},async pull(X){let{done:w,value:L}=await _.read();if(w){X.close();return}X.enqueue(L)},cancel(X){return _.cancel(X)}});return N?.mark("inspect_stream_first_event",{ms:A(q()-M),bytes:W,rateLimited:!1}),{response:new Response(B,{status:I.status,statusText:I.statusText,headers:I.headers}),rateLimited:!1}}async function s(I,N,M,_,S="unknown",z){let T=q(),W=z,B=async()=>{return W??=await R(J),W},X=x1(I,N),w=X.get("x-session-affinity")||X.get("x-opencode-session"),L=h(X);X.delete("x-parent-session-id"),X.delete("x-session-affinity"),X.delete("x-opencode-session");let Q=N?.body,g;if(Q&&typeof Q==="string")try{let b=JSON.parse(Q);if(typeof b.model==="string")g=b.model}catch{}let m=await t0(M,g),E=typeof Q==="string"?Q.length:void 0;if(Q&&typeof Q==="string"){let b=q(),G0=(()=>{if(!j1())return!1;try{return M0(JSON.parse(Q).model)}catch{return!1}})();Q=await A1(Q,{cache1hEnabled:!L&&E0(),cache1hMode:x0(),fastModeEnabled:G0,identity:m});try{K0(X,M,{body:JSON.parse(Q),identity:m})}catch{K0(X,M,{identity:m})}if(G0)d0(X);_?.mark("rewrite_body",{route:S,ms:A(q()-b),originalBytes:E,rewrittenBytes:Q.length,cacheEnabled:!L&&E0(),cacheMode:x0(),fastModeEnabled:G0,subagent:L})}let H=R1(I);if(S==="main"&&typeof Q==="string"&&!L&&E0()&&x0()==="hybrid"){let b=await B();if(l.track({sessionId:w,url:H.url?.toString()??H.input.toString(),headers:X,bodyText:Q,storage:b,cacheMode:"hybrid"}).tracked)_?.mark("cachekeep_track",{session:w})}let U=()=>fetch(H.input,{...N,body:Q,headers:X,...S1()&&{tls:{rejectUnauthorized:!1}}}),k=J1(await B()),d=q(),f=await Ij({config:k,input:H.input,init:N,headers:X,body:Q,fallback:U,affinity:w,optimisticResponse:k?.transport==="websocket"});return _?.mark("send_headers_received",{route:S,ms:A(q()-d),status:f.status,relayConfigured:k!=null,totalSendWithAccessMs:A(q()-T)}),f}async function D0(I){let N=await P.getUsableFallbackAccounts(I);if(!O0(I))return N;return N.filter((M)=>q0(n(M),I,M.id))}async function t(I,N,M,_,S,z,T){if(!M.length)return S??null;let W=T?.returnLastOnExhausted??!0;await S?.body?.cancel().catch(()=>{});let B=S??null;for(let[X,w]of M.entries()){let L=w.access;if(!L)continue;let Q=await s(I,N,L,z,`fallback_${X}`,_);B=Q;let g=r0(Q.status,_);if(!g){let m=await i(Q,z);Q=m.response,B=Q,g=m.rateLimited}if(!g){if(await P.markUsed(w),T?.onSuccess?.(w),L&&$.shouldRefreshOnRequestCount(Q0))$.refreshFallback(w.id,L).then(()=>T?.onSuccess?.(w)).catch(()=>{});return Q}if(X<M.length-1||!W)await Q.body?.cancel().catch(()=>{})}return W?B:null}async function V0(I,N,M,_,S,z,T){if(!C(I,N?.body))return M;let W=q(),B=z??await R(J);S?.mark("fallback_load_storage",{ms:A(q()-W),cached:!!z});let X=M,w=r0(X.status,B);if(!w){let Q=await i(X,S);X=Q.response,w=Q.rateLimited}if(!w)return X;let L=_;if(!L){let Q=q();L=await P.getUsableFallbackAccounts(),S?.mark("fallback_get_accounts",{ms:A(q()-Q),accounts:L.length})}if(O0(B)){let Q=L.length;if(L=L.filter((g)=>q0(n(g),B,g.id)),L.length<Q)v("[killswitch] filtered fallbacks",{before:Q,after:L.length})}return await t(I,N,L,B,X,S,{onSuccess:T})??X}return{apiKey:"",async fetch(I,N){let M=N?.body,_=JG({bodyBytes:typeof M==="string"?M.length:void 0}),S=q(),z=await Z();if(_.mark("get_auth",{ms:A(q()-S),authType:z.type,hasAccess:Boolean(z.access)}),z.type!=="oauth"){let H=await fetch(I,N);return _.done("non_oauth_passthrough",{status:H.status}),H}await D1(z.refresh);let T=q(),W=await R();_.mark("load_storage",{ms:A(q()-T)}),$.updateStorage(W),$.seedFallbacksFromAccounts(W?.accounts??[]);let B=C(I,N?.body);if(B)Q0++;if(B&&z.access&&(!z.expires||z.expires>Date.now()))z0(W,z.access);let X=(H,U)=>o(W,{activeId:H,route:U,mainAccessToken:z.access,mainRefreshToken:z.refresh}),w;if(B&&Z1(W)==="fallback-first")try{let H=q();w=await D0(W),_.mark("fallback_first_get_accounts",{ms:A(q()-H),accounts:w.length});let U=await t(I,N,w,W,void 0,_,{returnLastOnExhausted:!1,onSuccess:(k)=>X(k.id,"fallback-first")});if(U)return _.done("return_fallback_first",{status:U.status}),Y0(U);w=[]}catch(H){_.mark("fallback_first_error",{error:H instanceof Error?H.message:String(H)})}if(!z.access||!z.expires||z.expires<Date.now()){let U=(await R())?.refresh?.mainLastRefreshError;if(z.refresh&&U&&Z0(U,z.refresh,Date.now()))throw v("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:U.nextRetryAt,retryCount:U.retryCount,expiresInMs:z.expires?z.expires-Date.now():void 0}),Error(s0(U,Date.now()));v("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(z.access),expiresInMs:z.expires?z.expires-Date.now():void 0,expiredAgoMs:z.expires&&z.expires<Date.now()?Date.now()-z.expires:void 0});let k=q();z.access=await O(),_.mark("refresh_main_access",{ms:A(q()-k)})}if(!z.access)throw _.done("missing_access_error"),Error("OAuth access token is missing after refresh");function L(){if(W?.quota?.showToasts!==!0)return;let H=$.getMain();if(!H)return;let U=(W?.accounts??[]).filter((f)=>f.enabled!==!1).map((f)=>({...f,quota:$.getFallback(f.id,f.access)?.quota??f.quota})),k=P0(H.quota,W),d;if(k)d="main";else d=U.find((f)=>P0(f.quota,W))?.id??"main";Cj(H.quota,U,d)}if(B&&c(W))try{let H=q(),U=$.getMain(z.access)?.quota;if(!U)U=await $.refreshMain(z.access),L();else if($.needsRefresh(Q0))$.refreshMain(z.access).then(()=>{r(),L()}).catch(()=>{});if(o(W,{activeId:"main",route:"main",mainAccessToken:z.access,mainRefreshToken:z.refresh}),_.mark("main_quota_for_routing",{ms:A(q()-H),passes:P0(U,W)}),!P0(U,W)){let k=q();w=await D0(W),_.mark("preselect_fallback_accounts",{ms:A(q()-k),accounts:w.length});let d=await t(I,N,w,W,void 0,_,{onSuccess:(f)=>X(f.id,"fallback")});if(d)return _.done("return_preselected_fallback",{status:d.status}),Y0(d)}}catch(H){_.mark("main_quota_for_routing_error",{error:H instanceof Error?H.message:String(H)})}let Q=$.getMain(z.access)?.quota;if(W?.quota?.failClosedOnUnknownQuota&&!Q&&$.isBackedOff()){let H=$.getLastApiError(),U=H?r1(H,Date.now()):"Quota API unavailable";return v("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:H?.nextRetryAt,retryCount:H?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:U}}),{status:429,headers:{"content-type":"application/json","retry-after":String(H?.nextRetryAt?Math.max(1,Math.ceil((H.nextRetryAt-Date.now())/1000)):60)}})}if(O0(W)){if($.needsRefresh(Q0))try{let U=(W?.accounts??[]).filter((k)=>k.enabled!==!1&&k.access);await Promise.all([$.refreshMain(z.access),$.refreshAllFallbacks(U)])}catch(U){v("[quota] killswitch refresh failed",{error:U instanceof Error?U.message:String(U),backedOff:$.isBackedOff()})}Q=$.getMain(z.access)?.quota}if(O0(W)&&!q0(Q,W)){let U=C(I,N?.body)?await D0(W):[];if(U.length>0){v("[route] skipping main (killswitch), trying fallbacks");let b=await t(I,N,U,W,void 0,_,{onSuccess:(G0)=>X(G0.id,"fallback")});if(b)return _.done("return_killswitch_fallback",{status:b.status}),Y0(b)}let k=Date.now(),d=(W?.accounts??[]).filter((b)=>b.enabled!==!1).map((b)=>({...b,quota:n(b)})),f=s1(Q,d,k);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:`Killswitch: no routable accounts. Retry in ${Math.floor(f/60)}m ${f%60}s.`}}),{status:429,headers:{"content-type":"application/json","retry-after":String(f)}})}let g=await s(I,N,z.access,_,"main",W),m=!1,E=await V0(I,N,g,w,_,W,(H)=>{m=!0,X(H.id,"fallback")});if(!m)X("main","main");return _.done("return_response",{status:E.status}),Y0(E)}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let Z=await i0("max");return{url:Z.url,instructions:"Paste the authorization code here:",method:"code",callback:async(V)=>{return c0(V,Z.verifier,Z.redirectUri,Z.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let Z=await i0("console");return{url:Z.url,instructions:"Paste the authorization code here:",method:"code",callback:async(V)=>{let K=await c0(V,Z.verifier,Z.redirectUri,Z.state);if(K.type==="failed")return K;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${K.access}`}}).then((O)=>O.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{zG as AnthropicAuthPlugin};
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};
@@ -45,3 +45,8 @@ export declare function resolveActiveAccount(state: SidebarState): {
45
45
  name: string;
46
46
  quota: AccountQuota | null;
47
47
  };
48
+ export declare function getCollapsedQuotaSummary(quota: AccountQuota | null): {
49
+ fiveHourUsedPercent: number | null;
50
+ sevenDayUsedPercent: number | null;
51
+ text: string | null;
52
+ };
@@ -1 +1 @@
1
- import{Ga as a,Ha as b,Ia as c,Ja as d,Ka as e}from"./index-q0d64q8d.js";export{d as setSidebarState,e as resolveActiveAccount,a as getSidebarStateFile,c as getSidebarState,b as DEFAULT_SIDEBAR_STATE};
1
+ import{Qa as a,Ra as b,Sa as c,Ta as d,Ua as e,Va as f}from"./index-s5ckbbqq.js";export{d as setSidebarState,e as resolveActiveAccount,a as getSidebarStateFile,c as getSidebarState,f as getCollapsedQuotaSummary,b as DEFAULT_SIDEBAR_STATE};
@@ -38,7 +38,9 @@ export declare function isInsecure(): boolean;
38
38
  * for all API requests flowing through the fetch wrapper.
39
39
  * Returns the modified input and URL (if applicable).
40
40
  */
41
- export declare function rewriteUrl(input: FetchInput): {
41
+ export declare function rewriteUrl(input: FetchInput, options?: {
42
+ baseURL?: string;
43
+ }): {
42
44
  input: FetchInput;
43
45
  url: URL | null;
44
46
  };
@@ -70,14 +72,18 @@ export declare function prependClaudeCodeIdentity(system: unknown): SystemBlock[
70
72
  /**
71
73
  * Rewrite the full request body: sanitize system prompt and prefix tool names.
72
74
  */
75
+ type RewritePerfCallback = (stage: string, data?: Record<string, unknown>) => void;
73
76
  export declare function rewriteRequestBody(body: string, options?: {
74
77
  cache1hEnabled?: boolean;
75
78
  cache1hMode?: Cache1hMode;
76
79
  fastModeEnabled?: boolean;
77
80
  identity?: ClaudeCodeIdentity;
81
+ perf?: RewritePerfCallback;
78
82
  }): Promise<string>;
79
83
  /**
80
84
  * Create a streaming response that strips the tool prefix from tool names.
81
85
  */
82
- export declare function createStrippedStream(response: Response): Response;
86
+ export declare function createStrippedStream(response: Response, options?: {
87
+ perf?: RewritePerfCallback;
88
+ }): Response;
83
89
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-anthropic-auth",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -51,7 +51,7 @@
51
51
  "@opencode-ai/plugin": "*"
52
52
  },
53
53
  "dependencies": {
54
- "@cortexkit/anthropic-auth-core": "1.7.0",
54
+ "@cortexkit/anthropic-auth-core": "1.8.0",
55
55
  "@opentui/core": ">=0.3.1",
56
56
  "@opentui/solid": ">=0.3.1",
57
57
  "solid-js": "^1.9.10"
@@ -105,3 +105,21 @@ export function resolveActiveAccount(state: SidebarState): {
105
105
  }
106
106
  return { id: 'main', name: 'main', quota: state.main.quota }
107
107
  }
108
+
109
+ export function getCollapsedQuotaSummary(quota: AccountQuota | null): {
110
+ fiveHourUsedPercent: number | null
111
+ sevenDayUsedPercent: number | null
112
+ text: string | null
113
+ } {
114
+ const fiveHourUsedPercent = quota?.five_hour?.usedPercent ?? null
115
+ const sevenDayUsedPercent = quota?.seven_day?.usedPercent ?? null
116
+ if (fiveHourUsedPercent == null && sevenDayUsedPercent == null) {
117
+ return { fiveHourUsedPercent, sevenDayUsedPercent, text: null }
118
+ }
119
+
120
+ return {
121
+ fiveHourUsedPercent,
122
+ sevenDayUsedPercent,
123
+ text: `5h: ${fiveHourUsedPercent == null ? '—' : `${Math.round(fiveHourUsedPercent)}%`} 7d: ${sevenDayUsedPercent == null ? '—' : `${Math.round(sevenDayUsedPercent)}%`}`,
124
+ }
125
+ }
package/src/tui.tsx CHANGED
@@ -1,19 +1,20 @@
1
1
  /** @jsxImportSource @opentui/solid */
2
2
 
3
- import { readFileSync } from 'node:fs'
4
- import { dirname, join } from 'node:path'
5
- import { fileURLToPath } from 'node:url'
6
3
  import type {
7
4
  TuiPlugin,
8
5
  TuiPluginApi,
9
6
  TuiPluginModule,
10
7
  } from '@opencode-ai/plugin/tui'
8
+ import { readFileSync } from 'node:fs'
9
+ import { dirname, join } from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
11
  import { For, type JSX, Show, createSignal, onCleanup } from 'solid-js'
12
12
 
13
13
  import {
14
14
  type AccountQuota,
15
15
  DEFAULT_SIDEBAR_STATE,
16
16
  type SidebarState,
17
+ getCollapsedQuotaSummary,
17
18
  getSidebarState,
18
19
  resolveActiveAccount,
19
20
  } from './sidebar-state.js'
@@ -281,8 +282,16 @@ function QuotaSidebar(props: { api: TuiPluginApi }) {
281
282
  const headerLabel = () =>
282
283
  !hasData() ? 'CLAUDE' : collapsed() ? '\u25b6 CLAUDE' : '\u25bc CLAUDE'
283
284
  const activeAccount = () => resolveActiveAccount(state())
284
- const activeFiveHourPct = () =>
285
- activeAccount().quota?.five_hour?.usedPercent ?? null
285
+ const activeQuotaSummary = () =>
286
+ getCollapsedQuotaSummary(activeAccount().quota)
287
+ const activeQuotaTone = (): Tone => {
288
+ const summary = activeQuotaSummary()
289
+ const values = [
290
+ summary.fiveHourUsedPercent,
291
+ summary.sevenDayUsedPercent,
292
+ ].filter((value): value is number => value != null)
293
+ return values.length > 0 ? usageTone(Math.max(...values)) : 'muted'
294
+ }
286
295
 
287
296
  const quotaBackedOff = () => state().main.quotaBackedOff === true
288
297
  const refreshBackedOff = () => state().main.refreshBackedOff === true
@@ -343,33 +352,16 @@ function QuotaSidebar(props: { api: TuiPluginApi }) {
343
352
  </Show>
344
353
  </box>
345
354
 
346
- {/* Collapsed: active account 5h quota + dot, plus fast-mode when on */}
355
+ {/* Collapsed: active account 5h + 7d quota, plus fast-mode when on */}
347
356
  <Show when={collapsed() && hasData()}>
348
357
  <CollapsedRow theme={theme()} label={activeAccount().name}>
349
358
  <Show
350
- when={activeFiveHourPct() != null}
359
+ when={activeQuotaSummary().text != null}
351
360
  fallback={<text fg={theme().textMuted}>{'\u2014'}</text>}
352
361
  >
353
- <box flexDirection='row'>
354
- <text
355
- fg={toneColor(
356
- theme(),
357
- usageTone(activeFiveHourPct() as number),
358
- )}
359
- >
360
- <b>
361
- {`${String(Math.round(activeFiveHourPct() as number)).padStart(3)}%`}
362
- </b>
363
- </text>
364
- <text
365
- fg={toneColor(
366
- theme(),
367
- usageTone(activeFiveHourPct() as number),
368
- )}
369
- >
370
- {' \u25cf'}
371
- </text>
372
- </box>
362
+ <text fg={toneColor(theme(), activeQuotaTone())}>
363
+ <b>{activeQuotaSummary().text}</b>
364
+ </text>
373
365
  </Show>
374
366
  </CollapsedRow>
375
367
  <Show when={state().fastMode}>
@@ -1,2 +0,0 @@
1
- import{mkdir as K,readFile as M,writeFile as O}from"node:fs/promises";import{tmpdir as P}from"node:os";import{dirname as Q,join as H}from"node:path";var W="OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE",X=H(P(),"opencode-anthropic-auth"),Y=H(X,"sidebar-state.json");function J(){return process.env[W]||Y}var Z={main:{quota:null},fallbacks:[],activeId:void 0,route:"main",relay:null,fastMode:!1,lastUpdated:0};async function N(){try{let q=await M(J(),"utf8");return JSON.parse(q)}catch{return Z}}async function V(q){try{let z=J();await K(Q(z),{recursive:!0}),await O(z,JSON.stringify(q),"utf8")}catch{}}function g(q){let z=q.activeId;if(z&&z!=="main"){let C=q.fallbacks.find((G)=>G.enabled&&G.id===z);if(C)return{id:C.id,name:C.label??C.id,quota:C.quota}}return{id:"main",name:"main",quota:q.main.quota}}
2
- export{J as Ga,Z as Ha,N as Ia,V as Ja,g as Ka};