@cortexkit/opencode-anthropic-auth 1.9.1 → 1.9.3

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.
@@ -0,0 +1,2 @@
1
+ import{createRequire as q}from"node:module";var j=Object.create;var{getPrototypeOf:k,defineProperty:i,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,r=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?j(k(a)):{};let c=b||!a||!a.__esModule?i(d,"default",{value:a,enumerable:!0}):d;for(let e of l(a))if(!m.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0});if(f)g.set(a,c);return c};var s=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var u=q(import.meta.url);
2
+ export{r as db,s as eb,u as fb};
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
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(`
1
+ import{$ as mj,A as xj,Aa as rj,B as Tj,Ba as Pj,C as q1,Ca as p0,D as qj,Da as sj,E as E1,Ea as aj,F as Ej,Fa as tj,G as Rj,Ga as ej,H as vj,Ha as Oj,I as R1,Ia as zj,J as W1,Ja as jJ,K as Sj,Ka as N1,L as U0,La as JJ,M as v1,Ma as $J,N as Aj,Na as y1,O as fj,P as b0,Pa as VJ,Q as h0,R as X1,Ra as _1,S as kj,Sa as b1,T as yj,Ta as WJ,U as bj,Ua as XJ,V as hj,Va as h1,W as gj,X as G1,Y as B0,Z as F0,_ as g0,a as e1,aa as Z1,b as jj,ba as Xj,c as v0,ca as Gj,d as S0,da as S1,e as Jj,ea as Zj,f as E0,fa as Kj,g as Uj,ga as Yj,h as $j,ha as K1,i as Vj,ia as pj,j as Wj,ja as lj,k as C1,ka as dj,l as Bj,la as ij,m as H1,ma as A1,n as x1,na as uj,o as q,oa as cj,p as e,pa as Y1,q as k0,qa as P1,r as T1,ra as nj,s as Fj,sa as f1,t as Cj,ta as m0,u as h,ua as O1,va as z1,w as y0,wa as D1,x as Hj,xa as oj,y as $1,ya as k1,z as V1,za as I1}from"./index-68qrf9fn.js";import{Za as GJ}from"./index-9yjbmhf1.js";import"./index-agh52sak.js";import{randomUUID as uJ}from"node:crypto";function M0(j){return typeof j==="object"&&j!==null}function zJ(j){if(Array.isArray(j))return j;if(M0(j)&&Array.isArray(j.data))return j.data;return[]}function DJ(j){if(!M0(j)||!M0(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function m1(j){if(!M0(j)||!M0(j.info))return null;let J=j.info,$=M0(J.model)?J.model:void 0,W=typeof J.agent==="string"?J.agent:void 0,V=typeof $?.providerID==="string"?$.providerID:typeof J.providerID==="string"?J.providerID:void 0,z=typeof $?.modelID==="string"?$.modelID:typeof J.modelID==="string"?J.modelID:void 0,M=typeof $?.variant==="string"?$.variant:typeof J.variant==="string"?J.variant:void 0;if(!W&&(!V||!z)&&!M)return null;let S={};if(W)S.agent=W;if(V&&z)S.model={providerID:V,modelID:z};if(M)S.variant=M;return S}function p1(j,J){return{agent:j.agent??J.agent,model:j.model??J.model,variant:j.variant??J.variant}}function l1(j){return Boolean(j.agent&&j.model&&j.variant)}async function d1(j,J){if(!j||!J)return null;let $=j;if(typeof $.session?.messages!=="function")return null;let W=[];try{W=zJ(await Promise.resolve($.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(W.length===0)return null;let V={};for(let z=W.length-1;z>=0;z--){if(DJ(W[z])!=="assistant")continue;let M=m1(W[z]);if(!M)continue;if(V=p1(V,M),l1(V))return V}for(let z=W.length-1;z>=0;z--){let M=m1(W[z]);if(!M)continue;if(V=p1(V,M),l1(V))return V}if(!V.agent&&!V.model&&!V.variant)return null;return V}function i1(j,J){let $=new Map,W=0,V=0,z=0,M=0,S=0,r=(y)=>{let f=performance.now(),n=j(y);return S+=performance.now()-f,z++,n};return{call:(y)=>{if(!J.enabled())return r(y);let f=$.get(y);if(f!==void 0)return V++,$.delete(y),$.set(y,f),f;let n=r(y),a=y.length+n.length;if(a>J.maxBytes)return n;$.set(y,n),W+=a;while(W>J.maxBytes&&$.size>1){let d=$.keys().next().value,W0=$.get(d)??"";$.delete(d),W-=d.length+W0.length,M++}return n},stats:()=>({hits:V,misses:z,evictions:M,entries:$.size,cacheBytes:W,computeMsTotal:S})}}function u1(j){return`${e1}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function Dj(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}var IJ=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function c1(j){let J=Dj(j);if(J.startsWith("aft_"))return J;if(IJ.has(J))return`aft_${J}`;return null}function w1(j,J){let $=new Headers;if(j instanceof Request)j.headers.forEach((V,z)=>{$.set(z,V)});let W=J?.headers;if(W){if(W instanceof Headers)W.forEach((V,z)=>{$.set(z,V)});else if(Array.isArray(W))for(let V of W){let[z,M]=V;if(typeof M<"u")$.set(z,String(M))}else for(let[V,z]of Object.entries(W))if(typeof z<"u")$.set(V,String(z))}return $}function t0(j){return j.set("anthropic-beta",v0(j.get("anthropic-beta"),[jj])),j}function A0(j,J,$={}){return Kj(j,J,$)}function NJ(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((J)=>({...J,name:J.name?u1(J.name):J.name}));if(j.messages&&Array.isArray(j.messages))j.messages=j.messages.map((J)=>{if(J.content&&Array.isArray(J.content))J.content=J.content.map(($)=>{if($.type==="tool_use"&&$.name)return{...$,name:u1($.name)};return $});return J});return JSON.stringify(Yj(j))}function M1(j){return j.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(J,$,W)=>{if($)return`"name": "${c1(W)??Dj(W)}"`;let V=c1(W);return V?`"name": "${V}"`:J})}function n1(j,J=!1){if(J)return{ready:M1(j),pending:""};let $=j.length,W='"name"',V=Math.max(0,j.length-W.length+1);for(let M=V;M<j.length;M++)if(W.startsWith(j.slice(M))){$=Math.min($,M);break}let z=j.lastIndexOf(W);if(z!==-1){let M=j.slice(z);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(M))$=Math.min($,z)}if($<j.length)return{ready:M1(j.slice(0,$)),pending:j.slice($)};return{ready:M1(j),pending:""}}function U1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function Ij(j){let J=j?.trim();if(!J)return null;try{let $=new URL(J);if($.protocol!=="http:"&&$.protocol!=="https:"||$.username||$.password)return null;return $}catch{return null}}function _J(){return Ij(process.env.ANTHROPIC_BASE_URL)}function B1(j,J={}){let $=null;try{if(typeof j==="string"||j instanceof URL)$=new URL(j.toString());else if(j instanceof Request)$=new URL(j.url)}catch{$=null}if(!$)return{input:j,url:null};let W=$.href,V=J.baseURL?Ij(J.baseURL):_J();if(V){if($.protocol=V.protocol,$.host=V.host,J.baseURL)$.pathname=`${V.pathname.replace(/\/$/,"")}${$.pathname}`}if($.pathname.endsWith("/v1/messages")&&!$.searchParams.has("beta"))$.searchParams.set("beta","true");if($.href===W)return{input:j,url:$};return{input:j instanceof Request?new Request($.toString(),j):$,url:$}}function LJ(j){let W=j.split(/\n\n+/).filter((V)=>{if(V.includes(Jj))return!1;for(let z of Vj)if(V.includes(z))return!1;return!0}).join(`
2
2
 
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(`
3
+ `);for(let V of Wj)W=W.replace(V.match,V.replacement);return W.trim()}var QJ=8388608;function MJ(){return process.env.OPENCODE_ANTHROPIC_AUTH_MEMO!=="0"}var wJ=i1(LJ,{maxBytes:QJ,enabled:MJ});function o0(j){return wJ.call(j)}function g(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function UJ(j){let J={type:"text",text:E0};if(j==null)return[J];if(typeof j==="string"){let W=o0(j);if(W===E0)return[J];return[J,{type:"text",text:W}]}if(g(j)){let W=typeof j.type==="string"?j.type:"text",V=typeof j.text==="string"?j.text:"";return[J,{...j,type:W,text:o0(V)}]}if(!Array.isArray(j))return[J];let $=j.map((W)=>{if(typeof W==="string")return{type:"text",text:o0(W)};if(g(W)&&W.type==="text"&&typeof W.text==="string")return{...W,type:"text",text:o0(W.text)};return{type:"text",text:String(W)}});if($[0]?.text===E0)return $;return[J,...$]}var Nj={type:"ephemeral",ttl:"1h"},BJ=20;function FJ(j){if(g(j.cache_control))return j.cache_control;if(g(j.cacheControl))return j.cacheControl;return null}function R0(j,J){if(!g(j))return!1;return delete j.cacheControl,j.cache_control=J?{...Nj}:{type:"ephemeral"},!0}function o1(j){if(!g(j))return;delete j.cache_control,delete j.cacheControl}function CJ(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function r0(j,J){if(!g(j))return;let $=FJ(j);if($?.type!=="ephemeral")return;if(J)$.ttl="1h";else delete $.ttl}function r1(j,J){if(Array.isArray(j.system))for(let $ of j.system)r0($,J);else r0(j.system,J);if(!Array.isArray(j.messages))return;for(let $ of j.messages)if(r0($,J),g($)&&Array.isArray($.content))for(let W of $.content)r0(W,J)}function HJ(j,J){if(Array.isArray(j.system))for(let $ of j.system)J($);else J(j.system);if(!Array.isArray(j.messages))return;for(let $ of j.messages)if(J($),g($)&&Array.isArray($.content))for(let W of $.content)J(W)}function _j(j){o1(j),HJ(j,o1)}function xJ(j){_j(j),j.cache_control={...Nj}}function TJ(j){return g(j)&&j.type!=="thinking"&&j.type!=="redacted_thinking"}function e0(j){let J=CJ(j.content);if(!J?.length)return;let $=J.filter(TJ);if(!$.length)return;return{content:J,cacheableBlocks:$}}function qJ(j){if(!g(j))return!1;let J=e0(j);if(!J)return!1;return j.content=J.content,R0(J.cacheableBlocks[0],!0)}function EJ(j){if(!g(j))return!1;let J=e0(j);if(!J||J.cacheableBlocks.length<2)return!1;return j.content=J.content,R0(J.cacheableBlocks[1],!0)}function s0(j){if(!g(j))return!1;let J=e0(j);if(!J)return!1;let $=J.cacheableBlocks[J.cacheableBlocks.length-1];return j.content=J.content,R0($,!0)}function RJ(j){if(!g(j))return!1;return(e0(j)?.cacheableBlocks.length??0)>1}function vJ(j){if(!g(j))return 0;let J=j.content;if(Array.isArray(J))return J.length;if(J==null)return 0;return 1}function SJ(j){let J=[],$=0;return j.forEach((W,V)=>{let z=vJ(W);if(g(W)&&W.role==="user"&&z>0)J.push({index:V,blockPosition:$+z-1});$+=z}),J}function AJ(j){let J=SJ(j),$=[...J].reverse().find((M)=>M.index>1);if(!$)return{latest:void 0,bridge:void 0};let W=[...J].reverse().find((M)=>M.index<$.index),V=W?$.blockPosition-W.blockPosition+1:0,z=W&&W.index>1&&V>BJ?W:void 0;return{latest:$,bridge:z}}function s1(j){if(Array.isArray(j.system)){let J=j.system.findIndex((V)=>g(V)&&V.text===E0),$=j.system.slice(J>=0?J+1:0).filter(g),W=$[$.length-1];R0(W,!0)}else R0(j.system,!0)}function fJ(j){if(_j(j),!Array.isArray(j.messages)){s1(j);return}let{latest:J,bridge:$}=AJ(j.messages);if(!$)s1(j);if(RJ(j.messages[0]))qJ(j.messages[0]),EJ(j.messages[0]);else s0(j.messages[0]),s0(j.messages[1]);if($)s0(j.messages[$.index]);if(J)s0(j.messages[J.index])}function kJ(j){if(!Array.isArray(j.messages))return 0;let J=0;return j.messages=j.messages.filter(($)=>{if(!g($)||!Array.isArray($.content))return!0;if($.role!=="assistant")return!0;let W=$.content.filter((V)=>{if(!g(V)||V.type!=="thinking")return!0;if(!zj(V.signature))return!0;return J+=1,!1});if(W.length===$.content.length)return!0;return $.content=W,W.length>0}),J}function yJ(j){if(!Oj(j.model))return null;let J=Object.hasOwn(j,"thinking");return j.thinking={...Pj},{replacedExisting:J}}function bJ(j,J){if(!J.enabled){r1(j,!1),delete j.cache_control,delete j.cacheControl;return}if(J.mode==="automatic"){xJ(j);return}if(J.mode==="hybrid"){fJ(j);return}r1(j,!0),delete j.cacheControl}function hJ(j){if(!Array.isArray(j.messages))return;while(j.messages.length){let J=j.messages[j.messages.length-1];if(!g(J)||J.role!=="assistant")break;j.messages.pop()}}function v(){return performance.now()}function J0(j){return Math.round(j*10)/10}function a1(j){let J=0,$=0,W=0,V=Array.isArray(j.messages)?j.messages:[];J=V.length;for(let z of V){if(!z||typeof z!=="object")continue;let M=z.content;if(!Array.isArray(M))continue;$+=M.length;for(let S of M)if(S&&typeof S==="object"&&S.type==="tool_use")W++}return{messageCount:J,contentBlockCount:$,toolDefinitionCount:Array.isArray(j.tools)?j.tools.length:0,toolUseCount:W,systemBlockCount:Array.isArray(j.system)?j.system.length:0}}async function F1(j,J={}){try{let $=v(),W=JSON.parse(j);J.perf?.("parse",{ms:J0(v()-$),inputBytes:j.length,...a1(W)});let V=v(),z=Array.isArray(W.messages)?W.messages.length:void 0;hJ(W);let M=Array.isArray(W.messages)?W.messages.length:void 0;J.perf?.("strip_trailing_assistant",{ms:J0(v()-V),removedMessages:typeof z==="number"&&typeof M==="number"?z-M:void 0});let S=v(),r=kJ(W),u=yJ(W);J.perf?.("model_normalize",{ms:J0(v()-S),model:typeof W.model==="string"?W.model:void 0,fableMythosThinkingDisplay:u?"summarized":void 0,replacedFableMythosThinking:u?.replacedExisting??!1,removedNonAnthropicThinking:r,hasOutputConfig:Object.hasOwn(W,"output_config")});let j0=v(),y=Array.isArray(W.messages)&&W.messages.some((H0)=>H0.role==="user")?Gj(W.messages,void 0,$j):null;J.perf?.("billing_header",{ms:J0(v()-j0),hasBillingHeader:Boolean(y)});let f=v();if(W.system=UJ(W.system),J.perf?.("system_identity",{ms:J0(v()-f),systemBlockCount:Array.isArray(W.system)?W.system.length:0}),y&&Array.isArray(W.system))W.system.unshift({type:"text",text:y});let n=v();if(bJ(W,{enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.perf?.("cache_strategy",{ms:J0(v()-n),enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.fastModeEnabled&&S0(W.model))W.speed="fast";else if(W.speed==="fast")delete W.speed;let a=v();if(J.identity)Zj(W,J.identity);J.perf?.("metadata",{ms:J0(v()-a),hasAccountUuid:Boolean(J.identity?.accountUuid)});let d=v(),W0=NJ(W);J.perf?.("prefix_tools_stringify",{ms:J0(v()-d),outputBytesBeforeSign:W0.length,...a1(W)});let C0=v(),$0=await Xj(W0);return J.perf?.("cch_sign",{ms:J0(v()-C0),outputBytes:$0.length}),$0}catch{return j}}var gJ=new TextEncoder;function mJ(){return{pending:"",events:0,parseErrors:0,eventCounts:{},typeCounts:{},deltaTypeCounts:{},contentBlockTypeCounts:{},textDeltaBytes:0,thinkingDeltaBytes:0,inputJsonDeltaBytes:0,signatureDeltaBytes:0,redactedThinkingBytes:0}}function a0(j,J){if(!J)return;j[J]=(j[J]??0)+1}function z0(j){return gJ.encode(j).byteLength}function w0(j){return j&&typeof j==="object"&&!Array.isArray(j)?j:void 0}function G0(j,J){let $=j?.[J];return typeof $==="string"?$:void 0}function pJ(j,J){let $=j?.[J];return typeof $==="number"?$:void 0}function lJ(j){if(!j.trim())return null;let J,$=[];for(let y of j.split(/\r?\n/)){if(y.startsWith("event:")){J=y.slice(6).trim();continue}if(y.startsWith("data:")){let f=y.slice(5);$.push(f.startsWith(" ")?f.slice(1):f)}}let W=$.join(`
4
+ `),V={event:J,rawBytes:z0(j),dataBytes:z0(W)};if(!W||W==="[DONE]")return V.type=W==="[DONE]"?"done":void 0,V.event??=V.type,V;let z;try{z=JSON.parse(W)}catch{return V}let M=w0(z),S=w0(M?.delta),r=w0(M?.content_block),u=w0(M?.message),j0=w0(M?.usage)??w0(u?.usage);if(V.type=G0(M,"type"),V.event??=V.type,V.index=pJ(M,"index"),V.contentBlockType=G0(r,"type"),V.deltaType=G0(S,"type"),V.stopReason=G0(M,"stop_reason"),V.deltaType==="text_delta")V.textDeltaBytes=z0(G0(S,"text")??"");if(V.deltaType==="thinking_delta")V.thinkingDeltaBytes=z0(G0(S,"thinking")??"");if(V.deltaType==="input_json_delta")V.inputJsonDeltaBytes=z0(G0(S,"partial_json")??"");if(V.deltaType==="signature_delta")V.signatureDeltaBytes=z0(G0(S,"signature")??"");if(V.contentBlockType==="redacted_thinking")V.redactedThinkingBytes=z0(G0(r,"data")??"");if(j0)V.stopReason??=G0(u,"stop_reason");return V}function dJ(j){let J=j.indexOf(`
5
5
 
6
- `),J=j.indexOf(`\r
6
+ `),$=j.indexOf(`\r
7
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
+ `);if(J===-1)return $===-1?null:{index:$,length:4};if($===-1||J<$)return{index:J,length:2};return{index:$,length:4}}function t1(j,J){if(!J)return;j.pending+=J;while(!0){let $=dJ(j.pending);if(!$)break;let W=j.pending.slice(0,$.index);j.pending=j.pending.slice($.index+$.length);let V=lJ(W);if(!V)continue;if(j.events++,a0(j.eventCounts,V.event??"unknown"),a0(j.typeCounts,V.type),a0(j.deltaTypeCounts,V.deltaType),a0(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 iJ(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 f0(j,J={}){if(!j.body)return j;let $=j.body.getReader(),W=new TextDecoder,V=new TextEncoder,z="",M=0,S=0,r=0,u=0,j0=0,y=!1,f=!1,n=v(),a=v(),d=J.perf?mJ():void 0,W0=()=>{if(f)return;f=!0,$.releaseLock()},C0=(s={})=>({chunks:M,pulls:S,inputBytes:r,outputBytes:u,pendingChars:z.length,rewriteMs:J0(j0),totalMs:J0(v()-a),...d?iJ(d):{},...s}),$0=(s,x0={})=>{J.perf?.(s,C0(x0))};J.perf?.("stream_tool_prefix_wrapper_created",{status:j.status,hasBody:!0});let H0=new ReadableStream({async pull(s){if(S++,!y)y=!0,$0("stream_tool_prefix_first_pull");let x0=v();try{let{done:K0,value:T0}=await $.read(),l0=J0(v()-x0);if(K0){let G=W.decode();if(d)t1(d,G);let D=v(),w=n1(`${z}${G}`,!0);if(j0+=v()-D,w.ready){let P=V.encode(w.ready);u+=P.byteLength,s.enqueue(P)}$0("stream_tool_prefix_rewrite",{readMs:l0}),W0(),s.close();return}M++,r+=T0.byteLength;let d0=W.decode(T0,{stream:!0});if(d)t1(d,d0);let N0=z+d0,i0=v(),q0=n1(N0);if(j0+=v()-i0,z=q0.pending,q0.ready){let G=V.encode(q0.ready);u+=G.byteLength,s.enqueue(G)}let X=v();if(M===1||M%25===0||X-n>5000)n=X,$0("stream_tool_prefix_progress",{readMs:l0,lastChunkBytes:T0.byteLength})}catch(K0){throw $0("stream_tool_prefix_error",{error:K0 instanceof Error?K0.message:String(K0)}),W0(),K0}},async cancel(s){$0("stream_tool_prefix_cancel",{reason:s instanceof Error?s.message:String(s)});try{await $.cancel(s)}finally{W0()}}});return new Response(H0,{status:j.status,statusText:j.statusText,headers:j.headers})}var cJ="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",nJ=60000,oJ=60000,rJ=5000,Lj=200,ZJ=240,sJ=ZJ,aJ=1,Qj=!1;function L1(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function F(){return performance.now()}function A(j){return Math.round(j*10)/10}function Mj(j){return Math.floor(Math.random()*Math.max(0,j))}function j1(j){if(typeof j==="string")return j;if(j instanceof URL)return j.toString();return j.url}function J1(j,J){return J?.method??(j instanceof Request?j.method:void 0)}function wj(j){return j instanceof Error?j.message:String(j)}function tJ(){if(Qj||!1||!L1())return;Qj=!0;let j=100,J=250,$=F()+j;setInterval(()=>{let W=F(),V=W-$;if($=W+j,V<J)return;q("[perf] opencode event_loop_lag",{lagMs:A(V),thresholdMs:J})},j).unref?.()}function eJ(j){let J=F(),$={requestId:String(aJ++),start:J,last:J,mark(W,V){let z=F();if(L1())q("[perf] opencode request stage",{requestId:$.requestId,stage:W,deltaMs:A(z-$.last),totalMs:A(z-$.start),...V});$.last=z},done(W,V){let z=F();if(L1())q("[perf] opencode request done",{requestId:$.requestId,stage:W,deltaMs:A(z-$.last),totalMs:A(z-$.start),...V});$.last=z}};if(L1())q("[perf] opencode request start",{requestId:$.requestId,...j});return $}async function D0(j,J,$){let W=j.client.session,V=await d1(j.client,J),z={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:$,ignored:!0}]}};if(V?.agent)z.body.agent=V.agent;if(V?.model)z.body.model=V.model;if(V?.variant)z.body.variant=V.variant;if(typeof W?.promptAsync==="function"){await W.promptAsync(z);return}if(typeof W?.prompt==="function"){await Promise.resolve(W.prompt(z));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function I0(){throw Error(cJ)}function j3(j){if(j.sessionID==null)return!1;let J=j.model;return J?.providerID==="anthropic"||J?.api?.npm==="@ai-sdk/anthropic"||J?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function J3(j){if(j.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return j.push(Uj),!0}var $3={input:0,output:0,cache:{read:0,write:0}};function V3(j){let J=j["claude-opus-4-8"]??j["claude-opus-4-5"]??Object.values(j)[0];if(!J)return j;return{...j,...Object.fromEntries(Object.values(ej).map(($)=>[$.id,{...J,id:$.id,name:$.name,api:J.api?{...J.api,id:$.id}:void 0,cost:{input:p0.input,output:p0.output,cache:{read:p0.cacheRead,write:p0.cacheWrite5m}},limit:{...J.limit??{},context:sj,output:aj},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:tj}]))}}function W3(j){return Object.fromEntries(Object.entries(j).map(([J,$])=>[J,{...$,cost:$3}]))}var _3=async(j)=>{tJ();let{client:J}=j,$=Cj(),W=await h($),V=new jJ({storage:W,onMainQuotaFetched:async(X,G,D,w)=>{try{let P=await h($)??{version:1,accounts:[]},E=fj(P);if(E&&E.checkedAt>=w&&hj(E.quota,P,E.checkedAt)>Date.now()){V.seedMainFromStorage(P);return}P.quota=P.quota??{},P.quota.mainQuota=X,P.quota.mainQuotaCheckedAt=G,P.quota.mainQuotaToken=D,P.quota.mainLastQuotaApiError=void 0,await y0(P,$,{mainQuota:!0})}catch(P){q("[quota] failed to persist main quota",{error:P instanceof Error?P.message:String(P)})}},onApiError:async(X)=>{try{let G=await h($)??{version:1,accounts:[]};G.quota=G.quota??{},G.quota.mainLastQuotaApiError=X,await y0(G,$,{mainQuota:!0})}catch(G){q("[quota] failed to persist backoff state",{error:G instanceof Error?G.message:String(G)})}}}),z=new gj({quotaManager:V,onFallbackStorageChanged:()=>{j0()}});z.startBackgroundRefresh();let M=null,S=new cj({loadStorage:()=>h($),prepareHeaders:async(X,G)=>{if(!f)return X;let D=await f();if(D.type!=="oauth")return X;if(!D.access||D.expires&&D.expires<Date.now()){if(!M)return X;D.access=await M()}if(!D.access)return X;try{let w=JSON.parse(G.bodyText),P=await S1(D.access,typeof w.model==="string"?w.model:void 0);if(X.delete("anthropic-beta"),A0(X,D.access,{body:w,identity:P}),X.set("anthropic-beta",v0(X.get("anthropic-beta"),[pj])),w.speed==="fast")t0(X)}catch{A0(X,D.access)}return X},log:q});g0({enabled:$1(W),mode:V1(W)}),P1(q1(W)),D1(E1(W));let r={activeId:"main",route:"main"};function u(X,G){r={activeId:G.activeId,route:G.route},V.updateStorage(X),V.seedMainFromStorage(X,G.mainAccessToken),V.seedFallbacksFromAccounts((X?.accounts??[]).filter(e));let D=V.getMain(G.mainAccessToken),w=V.getLastApiError(),P=X?.refresh?.mainLastRefreshError,E={main:{quota:D?.quota??null,quotaBackedOff:V.isBackedOff(),quotaBackoffUntil:w?.nextRetryAt,refreshBackedOff:P?U0(P,G.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:P?.nextRetryAt},fallbacks:(X?.accounts??[]).filter((R)=>R.enabled!==!1&&e(R)).map((R)=>({id:R.id,label:R.label,quota:R.access?V.getFallback(R.id,R.access)?.quota??null:null,enabled:R.enabled!==!1})),activeId:G.activeId,route:G.route,relay:(()=>{let R=y1(X);return R?{enabled:!0,transport:R.transport??"http"}:null})(),fastMode:z1(),cacheKeep:{enabled:A1(X),window:X?.cacheKeep?.startHour!=null&&X?.cacheKeep?.endHour!=null?`${X.cacheKeep.startHour}-${X.cacheKeep.endHour}`:void 0,trackedSessions:S.trackedCount()},lastUpdated:Date.now()};GJ(E).catch((R)=>q("[sidebar] state write failed",{error:R instanceof Error?R.message:String(R)}))}async function j0(){let X=await h($),G,D;if(f)try{let w=await f();G=w.access,D=w.refresh}catch{}u(X,{activeId:r.activeId,route:r.route,mainAccessToken:G,mainRefreshToken:D})}function y(X,G){if(!G)return;if(X?.quota?.enabled!==!0)return;if(V.getMain(G))return;if(n)return;n=!0,V.refreshMain(G).then(()=>j0()).catch(()=>{}).finally(()=>{n=!1})}let f=null,n=!1,a=null,d=0;function W0(X){let G=X?.refresh?.refreshBeforeExpiryMinutes??sJ;return Math.max(ZJ,G)*60000}function C0(X){return X?.refresh?.enabled!==!1}async function $0(X){if(!X)return;let G=await h($),D=G?.refresh?.mainLastRefreshError;if(!G?.refresh||!D?.tokenHash)return;let w=W1(X);if(D.tokenHash===w)return;if(D.nextRetryAt&&D.nextRetryAt>Date.now()){q("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:D.nextRetryAt,retryCount:D.retryCount,remainingMs:D.nextRetryAt-Date.now()});return}G.refresh.mainLastRefreshError=void 0,await y0(G,$,{mainRefresh:!0}),q("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:D.checkedAt,previousNextRetryAt:D.nextRetryAt,previousRetryCount:D.retryCount})}async function H0(){let X=[];if(f)try{let P=await f();if(P.type==="oauth"&&P.access){let E=await V.refreshMain(P.access);X.push({name:"OpenCode anthropic",role:"main",quota:E})}else if(P.type==="oauth")X.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(P){let E=P instanceof Error?P.message:String(P);X.push({name:"OpenCode anthropic",role:"main",error:E.includes("429")?"Usage API rate limited — try again in a moment":E})}let{storage:G,errors:D}=await z.refreshQuotaForAllAccounts({force:!0}),w=new Map(D.map((P)=>[P.accountId,P.message]));if(X.push(...JJ(G,w)),!f)X.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return $J({accounts:X,refreshedAt:Date.now()})}async function s(X){let G=mj(X);if(G.type==="enable"||G.type==="disable"){let E=G.type==="enable",R=await xj(E),o=V1(R);return g0({enabled:E,mode:o}),Z1({argumentsText:X,enabled:E,mode:o})}if(G.type==="mode"){let E=await Tj(G.mode),R=$1(E);return g0({enabled:R,mode:G.mode}),Z1({argumentsText:X,enabled:R,mode:G.mode})}let D=await h($),w=$1(D),P=V1(D);return g0({enabled:w,mode:P}),Z1({argumentsText:X,enabled:w,mode:P})}async function x0(X){let G=lj(X),D=await h($);if(G.type==="window")D=await Rj(G.startHour,G.endHour);else if(G.type==="disable")D=await vj(!1);let w=dj(D),P=S.stats(w);return uj({argumentsText:X,enabled:ij(D),window:w,hybridActive:A1(D),trackedSessions:P.trackedSessions,nextPrewarmAt:P.nextPrewarmAt})}async function K0(X){let G=nj(X);if(G.type==="enable"||G.type==="disable"){let P=G.type==="enable";return await qj(P),P1(P),f1({argumentsText:X,enabled:P})}let D=await h($),w=q1(D);return P1(w),f1({argumentsText:X,enabled:w})}async function T0(X){let G=oj(X);if(G.type==="enable"||G.type==="disable"){let P=G.type==="enable";return await Ej(P),D1(P),k1({argumentsText:X,enabled:P})}let D=await h($),w=E1(D);return D1(w),k1({argumentsText:X,enabled:w})}async function l0(X){let G=XJ(X);if(G.type==="mode")return await WJ(G.mode),h1({argumentsText:X,mode:G.mode});let D=await h();return h1({argumentsText:X,mode:b1(D)})}function d0(X,G=10){let D=Math.max(0,Math.min(Math.round(X/100*G),G));return"█".repeat(D)+"░".repeat(G-D)}function N0(X,G){return`${X} ${d0(G)} ${String(Math.round(G)).padStart(3)}%`}function i0(X){if(!X)return"";let G=new Date(X).getTime();if(Number.isNaN(G))return"";let D=G-Date.now();if(D<=0)return"resets now";let w=Math.floor(D/60000);if(w<1)return"resets <1m";if(w<60)return`resets ${w}m`;let P=Math.floor(w/60),E=w%60;return E>0?`resets ${P}h${E}m`:`resets ${P}h`}function q0(X,G,D){let w=[],P=0;if(X){let{five_hour:o,seven_day:V0}=X;if(o||V0){let Z0=D==="main"?"active":"idle",P0=i0(o?.resetsAt),_0=[`main · ${Z0}${P0?` (${P0})`:""}`];if(o)_0.push(N0("5h",o.usedPercent)),P=Math.max(P,o.usedPercent);if(V0)_0.push(N0("7d",V0.usedPercent)),P=Math.max(P,V0.usedPercent);w.push(_0.join(`
9
+ `))}}if(G?.length)for(let o of G){let V0=o.quota;if(!V0)continue;let{five_hour:Y0,seven_day:Z0}=V0;if(!Y0&&!Z0)continue;let P0=o.label||"alt",u0=D===o.id?"active":"idle",L0=i0(Y0?.resetsAt),O0=[`${P0} · ${u0}${L0?` (${L0})`:""}`];if(Y0)O0.push(N0("5h",Y0.usedPercent)),P=Math.max(P,Y0.usedPercent);if(Z0)O0.push(N0("7d",Z0.usedPercent)),P=Math.max(P,Z0.usedPercent);w.push(O0.join(`
10
+ `))}if(!w.length)return;let E=w.join(`
11
11
 
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(`
12
+ `),R=P>=90?"error":P>=70?"warning":"info";J.tui?.showToast?.({body:{title:"Claude Quota",message:E,variant:R,duration:R==="error"?8000:5000}})?.catch?.(()=>{})}return{config:async(X)=>{X.command={...X.command??{},[G1]:{template:G1,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[K1]:{template:K1,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[N1]:{template:N1,description:"Show current Claude OAuth quota usage for all accounts."},[Y1]:{template:Y1,description:"Show or toggle Anthropic request dump capture for debugging."},[O1]:{template:O1,description:"Show or toggle Anthropic fast mode for supported Opus models."},[_1]:{template:_1,description:"Show or change Claude account routing between main-first and fallback-first."},[I1]:{template:I1,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."}}},"experimental.chat.system.transform":async(X,G)=>{if(!j3(X))return;J3(G.system)},provider:{id:"anthropic",async models(X,G){let D=V3(X.models);if(G.auth?.type!=="oauth"||!Fj(W??{}))return D;return W3(D)}},"command.execute.before":async(X)=>{if(X.command===G1)await D0(j,X.sessionID,await s(X.arguments)),I0();if(X.command===K1)await D0(j,X.sessionID,await x0(X.arguments)),I0();if(X.command===N1){await D0(j,X.sessionID,await H0());let G=await h(),D=f?await f().catch(()=>{return}):void 0;u(G,{activeId:"main",route:"main",mainAccessToken:D?.access,mainRefreshToken:D?.refresh}),I0()}if(X.command===Y1)await D0(j,X.sessionID,await K0(X.arguments)),I0();if(X.command===O1)await D0(j,X.sessionID,await T0(X.arguments)),I0();if(X.command===_1)await D0(j,X.sessionID,await l0(X.arguments)),I0();if(X.command===I1){let G=await h(),D=yj(G),w=(G?.accounts??[]).filter((E)=>E.enabled!==!1).map((E)=>E.id),P=rj({argumentsText:X.arguments,config:D,accountIds:w});if(P.updatedConfig)await bj(P.updatedConfig);await D0(j,X.sessionID,P.text),I0()}},auth:{provider:"anthropic",async loader(X,G){f=X;let D=await X();if(D.type==="oauth"){let E=function(){if(a)clearInterval(a),a=null;let Y=async()=>{try{let I=await h($);if(!C0(I))return;let x=await X();if(x.type!=="oauth")return;if(await $0(x.refresh),!x.expires)return;let N=x.expires-Date.now(),H=W0(I);if(N>H)return;if(q("[refresh] opencode main oauth background due",{expiresInMs:N,refreshBeforeMs:H}),x.refresh&&U0(I?.refresh?.mainLastRefreshError,x.refresh,Date.now())){q("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:I?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:I?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:N});return}if(x.refresh&&I?.refresh?.mainRefreshLeaseUntil&&I.refresh.mainRefreshLeaseUntil>Date.now()&&I.refresh.mainRefreshLeaseTokenHash===W1(x.refresh))return;await P();let K=await X();q("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:K.expires?K.expires-Date.now():void 0})}catch(I){q("[refresh] opencode main oauth refresh failed",{message:I instanceof Error?I.message:String(I)})}};if(a=setInterval(()=>{Y()},nJ+Mj(oJ)),"unref"in a)a.unref()},R=function(Y,I){if(Y instanceof Request&&Y.body)return!1;return I==null||typeof I==="string"},o=function(Y){return Y.has("x-parent-session-id")},V0=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},P0=function(Y,I){if(Y.delete("authorization"),Y.delete("x-api-key"),I.authHeader==="x-api-key")Y.set("x-api-key",I.apiKey??"");else Y.set("Authorization",`Bearer ${I.apiKey??""}`);Y.set("Content-Type","application/json")},L0=function(Y){return V.getFallback(Y.id,Y.access)?.quota??Y.quota},O0=function(Y){return Object.values(Y??{}).some((I)=>I&&I.remainingPercent<=0)},g1=function(Y,I){return Y.status===429||I},Q1=function(Y){if(!Y)return!1;let I=V.getMain(Y);return Boolean(I&&I.refreshAfter>Date.now()&&O0(I.quota))},w=null;async function P(){if(!w)w=(async()=>{let x=null,N=null,H=null;async function K(O){let T=await h($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};T.refresh=T.refresh??{},O(T),await y0(T,$,{mainRefresh:!0})}async function b(O){let T=Date.now()+rJ;while(Date.now()<T){await new Promise((B)=>setTimeout(B,Lj+Mj(Lj)));let Z=await X();if(Z.type!=="oauth"||!Z.access)continue;if((Z.access!==O.access||Z.refresh!==O.refresh||(Z.expires??0)>(O.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 O=0;O<=2;O++){let T=null;try{if(O>0){let C=500*2**(O-1);await new Promise((L)=>setTimeout(L,C))}if(T=await X(),!T.refresh)throw Error("Token refresh failed: missing refresh token");let Z=await h($),_=W1(T.refresh),B=Z?.refresh?.mainLastRefreshError;if(q("[refresh] opencode main oauth refresh check",{attempt:O,expiresInMs:T.expires?T.expires-Date.now():void 0,hasBackoff:Boolean(B),backoffActive:B?U0(B,T.refresh,Date.now()):!1,retryCount:B?.retryCount,nextRetryAt:B?.nextRetryAt}),B&&U0(B,T.refresh,Date.now()))throw q("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:B.nextRetryAt,retryCount:B.retryCount}),Error(v1(B,Date.now()));if(Z?.refresh?.mainRefreshLeaseUntil&&Z.refresh.mainRefreshLeaseUntil>Date.now()&&Z.refresh.mainRefreshLeaseTokenHash===_){q("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:Z.refresh.mainRefreshLeaseUntil});let C=await b(T);if(C)return C;throw Error("Claude OAuth refresh is already in progress")}let Q=await Hj({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!Q){q("[refresh] opencode main oauth refresh skipped file lock");let C=await b(T);if(C)return C;throw Error("Claude OAuth refresh is already in progress")}H=Q.release,x=uJ(),N=_,await K((C)=>{C.refresh=C.refresh??{},C.refresh.mainRefreshLeaseId=x??void 0,C.refresh.mainRefreshLeaseUntil=Date.now()+120000,C.refresh.mainRefreshLeaseTokenHash=_});let l=await h($);if(q("[refresh] opencode main oauth refresh lease acquired",{attempt:O,leaseUntil:Date.now()+120000}),l?.refresh?.mainRefreshLeaseId!==x||l.refresh.mainRefreshLeaseTokenHash!==_)throw Error("Claude OAuth refresh is already in progress");q("[refresh] opencode main oauth refresh request start",{attempt:O});let m=await Bj({refreshToken:T.refresh,maxRetries:0});return await J.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:m.refresh,access:m.access,expires:m.expires}}),await K((C)=>{if(!C?.refresh)return;if(C.refresh.mainLastRefreshError=void 0,C.refresh.mainRefreshLeaseId===x)C.refresh.mainRefreshLeaseId=void 0,C.refresh.mainRefreshLeaseUntil=void 0,C.refresh.mainRefreshLeaseTokenHash=void 0}),q("[refresh] opencode main oauth refresh succeeded",{attempt:O,expiresInMs:m.expires-Date.now()}),m.access}catch(Z){let _=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(O<2&&(_||Z instanceof C1&&Z.status>=500))continue;q("[refresh] opencode main oauth refresh attempt failed",{attempt:O,error:Z instanceof Error?Z.message:String(Z),transient:_});let B=T?.refresh;if(B&&Z instanceof C1)await K((Q)=>{Q.refresh=Q.refresh??{},Q.refresh.mainLastRefreshError=Sj({error:Z,now:Date.now(),refreshToken:B,previous:Q.refresh.mainLastRefreshError})});throw Z}finally{if(x)await K((Z)=>{if(!Z?.refresh)return;if(Z.refresh.mainRefreshLeaseId===x&&Z.refresh.mainRefreshLeaseTokenHash===N)Z.refresh.mainRefreshLeaseId=void 0,Z.refresh.mainRefreshLeaseUntil=void 0,Z.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await H?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{w=null});return w}M=P,E(),V.seedFallbacksFromAccounts((W?.accounts??[]).filter(e)),u(W,{activeId:"main",route:"main",mainAccessToken:D.access,mainRefreshToken:D.refresh});async function Z0(Y,I){if(!Y.body||Y.status!==200)return I?.mark("inspect_stream_skip",{status:Y.status}),{response:Y,rateLimited:!1};if(Y.headers.get("x-cortexkit-relay-optimistic")==="true")return I?.mark("inspect_stream_skip",{status:Y.status,reason:"optimistic_relay"}),{response:Y,rateLimited:!1};let x=F(),N=Y.body.getReader(),H=[],K=new TextDecoder,b="",O=0;while(!b.includes(`
13
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};
14
+ `)&&b.length<65536){let{done:Z,value:_}=await N.read();if(Z)break;if(H.push(_),O+=_.byteLength,b+=K.decode(_,{stream:!0}),V0(b))break}if(V0(b))return await N.cancel().catch(()=>{}),I?.mark("inspect_stream_first_event",{ms:A(F()-x),bytes:O,rateLimited:!0}),{response:Y,rateLimited:!0};let T=new ReadableStream({start(Z){for(let _ of H)Z.enqueue(_)},async pull(Z){let{done:_,value:B}=await N.read();if(_){Z.close();return}Z.enqueue(B)},cancel(Z){return N.cancel(Z)}});return I?.mark("inspect_stream_first_event",{ms:A(F()-x),bytes:O,rateLimited:!1}),{response:new Response(T,{status:Y.status,statusText:Y.statusText,headers:Y.headers}),rateLimited:!1}}async function _0(Y,I,x,N,H="api_fallback",K){let b=F(),O=w1(Y,I),T=O.get("x-session-affinity")||O.get("x-opencode-session"),Z=o(O);O.delete("x-parent-session-id"),O.delete("x-session-affinity"),O.delete("x-opencode-session");let _=I?.body,B=typeof _==="string"?_.length:void 0;if(_&&typeof _==="string"){let C=F(),L=(()=>{if(!z1())return!1;try{return S0(JSON.parse(_).model)}catch{return!1}})();if(_=await F1(_,{cache1hEnabled:!Z&&B0(),cache1hMode:F0(),fastModeEnabled:L,perf:(U,k)=>N?.mark(`rewrite_body_${U}`,{route:H,...k})}),P0(O,x),O.set("anthropic-beta",v0(O.get("anthropic-beta"),[])),L)t0(O);N?.mark("rewrite_body",{route:H,ms:A(F()-C),originalBytes:B,rewrittenBytes:_.length,cacheEnabled:!Z&&B0(),cacheMode:F0(),fastModeEnabled:L,subagent:Z})}else P0(O,x);let Q=B1(Y,{baseURL:x.baseURL}),l=F(),m;try{m=await fetch(Q.input,{...I,body:_,headers:O,...U1()&&{tls:{rejectUnauthorized:!1}}})}catch(C){if(typeof _==="string")await m0({affinity:T,route:H,error:wj(C),bodyText:_,url:Q.url?.toString()??j1(Q.input),method:J1(Y,I),headers:O});throw C}if(typeof _==="string")await m0({affinity:T,route:H,status:m.status,bodyText:_,url:Q.url?.toString()??j1(Q.input),method:J1(Y,I),headers:O});return N?.mark("send_headers_received",{route:H,ms:A(F()-l),status:m.status,relayConfigured:!1,totalSendWithAccessMs:A(F()-b),baseURL:x.baseURL}),m}async function u0(Y,I,x,N,H="unknown",K){let b=F(),O=K,T=async()=>{return O??=await h($),O},Z=w1(Y,I),_=Z.get("x-session-affinity")||Z.get("x-opencode-session"),B=o(Z);Z.delete("x-parent-session-id"),Z.delete("x-session-affinity"),Z.delete("x-opencode-session");let Q=I?.body,l;if(Q&&typeof Q==="string"){let i=F();try{let X0=JSON.parse(Q);if(typeof X0.model==="string")l=X0.model}catch{}N?.mark("model_parse_for_identity",{route:H,ms:A(F()-i),bodyBytes:Q.length})}let m=F(),C=await S1(x,l);N?.mark("resolve_claude_code_identity",{route:H,ms:A(F()-m),hasAccountUuid:Boolean(C.accountUuid)});let L=typeof Q==="string"?Q.length:void 0;if(Q&&typeof Q==="string"){let i=F(),X0=(()=>{if(!z1())return!1;try{return S0(JSON.parse(Q).model)}catch{return!1}})();Q=await F1(Q,{cache1hEnabled:!B&&B0(),cache1hMode:F0(),fastModeEnabled:X0,identity:C,perf:(PJ,OJ)=>N?.mark(`rewrite_body_${PJ}`,{route:H,...OJ})});let Q0=F();try{A0(Z,x,{body:JSON.parse(Q),identity:C}),N?.mark("set_oauth_headers_body_parse",{route:H,ms:A(F()-Q0),bodyBytes:Q.length,parsed:!0})}catch{A0(Z,x,{identity:C}),N?.mark("set_oauth_headers_body_parse",{route:H,ms:A(F()-Q0),bodyBytes:Q.length,parsed:!1})}if(X0)t0(Z);N?.mark("rewrite_body",{route:H,ms:A(F()-i),originalBytes:L,rewrittenBytes:Q.length,cacheEnabled:!B&&B0(),cacheMode:F0(),fastModeEnabled:X0,subagent:B})}let U=B1(Y);if(H==="main"&&typeof Q==="string"&&!B&&B0()&&F0()==="hybrid"){let i=await T(),X0=F(),Q0=S.track({sessionId:_,url:U.url?.toString()??U.input.toString(),headers:Z,bodyText:Q,storage:i,cacheMode:"hybrid"});N?.mark("cachekeep_track",{session:_,ms:A(F()-X0),tracked:Q0.tracked,reason:Q0.tracked?void 0:Q0.reason,bodyBytes:Q.length})}let k=async()=>{try{let i=await fetch(U.input,{...I,body:Q,headers:Z,...U1()&&{tls:{rejectUnauthorized:!1}}});if(typeof Q==="string")await m0({affinity:_,route:H,status:i.status,bodyText:Q,url:U.url?.toString()??j1(U.input),method:J1(Y,I),headers:Z});return i}catch(i){if(typeof Q==="string")await m0({affinity:_,route:H,error:wj(i),bodyText:Q,url:U.url?.toString()??j1(U.input),method:J1(Y,I),headers:Z});throw i}},t=y1(await T()),p=F(),c=await VJ({config:t,input:U.input,init:I,headers:Z,body:Q,fallback:k,affinity:_,optimisticResponse:t?.transport==="websocket"});return N?.mark("send_headers_received",{route:H,ms:A(F()-p),status:c.status,relayConfigured:t!=null,totalSendWithAccessMs:A(F()-b)}),c}async function KJ(Y){if(!Y)return!1;try{return await V.refreshMain(Y),Q1(Y)}catch{return!1}}async function c0(Y,I={}){let x=await z.getUsableFallbackAccounts(Y),N=new Map(x.map((K)=>[K.id,K])),H=[];for(let K of Y?.accounts??[]){if(e(K)){let b=N.get(K.id);if(b)H.push(b);continue}if(I.includeApiRoutes===!0&&k0(K)&&K.enabled!==!1&&K.apiKey&&T1(K.baseURL))H.push(K)}if(!h0(Y))return H;return H.filter((K)=>e(K)?X1(L0(K),Y,K.id):!0)}async function n0(Y,I,x,N,H,K,b){if(!x.length)return H??null;let O=b?.returnLastOnExhausted??!0;await H?.body?.cancel().catch(()=>{});let T=H??null;for(let[Z,_]of x.entries()){let B;if(k0(_)){if(!_.apiKey)continue;B=await _0(Y,I,_,K,`api_fallback_${Z}`,N)}else{let l=_.access;if(!l)continue;B=await u0(Y,I,l,K,`fallback_${Z}`,N)}T=B;let Q=R1(B.status,N);if(!Q){let l=await Z0(B,K);B=l.response,T=B,Q=l.rateLimited}if(!Q){if(await z.markUsed(_),b?.onSuccess?.(_),e(_)&&_.access&&V.shouldRefreshOnRequestCount(d))V.refreshFallback(_.id,_.access).then(()=>b?.onSuccess?.(_)).catch(()=>{});return B}if(Z<x.length-1||!O)await B.body?.cancel().catch(()=>{})}return O?T:null}async function YJ(Y,I,x,N,H,K,b,O){if(!R(Y,I?.body))return x;let T=F(),Z=K??await h($);if(H?.mark("fallback_load_storage",{ms:A(F()-T),cached:!!K}),!(Z?.accounts??[]).some((L)=>L.enabled!==!1&&(e(L)||k0(L)&&Boolean(L.apiKey)&&T1(L.baseURL))))return x;let B=x,Q=R1(B.status,Z),l=g1(B,!1);if(!Q){let L=await Z0(B,H);B=L.response,Q=L.rateLimited,l=g1(B,L.rateLimited)}if(!Q)return B;let m=!1;if(N)m=N.some(k0);else if(l)m=await KJ(b);let C=N;if(!C){let L=F();C=await c0(Z,{includeApiRoutes:m}),H?.mark("fallback_get_accounts",{ms:A(F()-L),accounts:C.length})}if(h0(Z)){let L=C.length;if(C=C.filter((U)=>e(U)?X1(L0(U),Z,U.id):!0),C.length<L)q("[killswitch] filtered fallbacks",{before:L,after:C.length})}return await n0(Y,I,C,Z,B,H,{onSuccess:O})??B}return{apiKey:"",async fetch(Y,I){let x=I?.body,N=eJ({bodyBytes:typeof x==="string"?x.length:void 0}),H=F(),K=await X();if(N.mark("get_auth",{ms:A(F()-H),authType:K.type,hasAccess:Boolean(K.access)}),K.type!=="oauth"){let L=await fetch(Y,I);return N.done("non_oauth_passthrough",{status:L.status}),L}await $0(K.refresh);let b=F(),O=await h();N.mark("load_storage",{ms:A(F()-b)}),V.updateStorage(O),V.seedMainFromStorage(O,K.access),V.seedFallbacksFromAccounts((O?.accounts??[]).filter(e));let T=R(Y,I?.body);if(T)d++;if(T&&K.access&&(!K.expires||K.expires>Date.now()))y(O,K.access);let Z=(L,U)=>u(O,{activeId:L,route:U,mainAccessToken:K.access,mainRefreshToken:K.refresh}),_;if(T&&b1(O)==="fallback-first")try{let L=F();_=await c0(O,{includeApiRoutes:Q1(K.access)}),N.mark("fallback_first_get_accounts",{ms:A(F()-L),accounts:_.length});let U=await n0(Y,I,_,O,void 0,N,{returnLastOnExhausted:!1,onSuccess:(k)=>Z(k.id,"fallback-first")});if(U)return N.done("return_fallback_first",{status:U.status}),f0(U,{perf:(k,t)=>N.mark(k,t)});_=void 0}catch(L){N.mark("fallback_first_error",{error:L instanceof Error?L.message:String(L)})}if(!K.access||!K.expires||K.expires<Date.now()){let U=(await h())?.refresh?.mainLastRefreshError;if(K.refresh&&U&&U0(U,K.refresh,Date.now()))throw q("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:U.nextRetryAt,retryCount:U.retryCount,expiresInMs:K.expires?K.expires-Date.now():void 0}),Error(v1(U,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 k=F();K.access=await P(),N.mark("refresh_main_access",{ms:A(F()-k)})}if(!K.access)throw N.done("missing_access_error"),Error("OAuth access token is missing after refresh");function B(){if(O?.quota?.showToasts!==!0)return;let L=V.getMain();if(!L)return;let U=(O?.accounts??[]).filter((p)=>p.enabled!==!1&&e(p)).map((p)=>({...p,quota:V.getFallback(p.id,p.access)?.quota??p.quota})),k=b0(L.quota,O),t;if(k)t="main";else t=U.find((p)=>b0(p.quota,O))?.id??"main";q0(L.quota,U,t)}if(T&&Y0(O))try{let L=F(),U=V.getMain(K.access),k=U?.quota;if(!k)k=await V.refreshMain(K.access),U=V.getMain(K.access),B();else if(V.needsRefresh(d))if(O0(k))k=await V.refreshMain(K.access),U=V.getMain(K.access);else V.refreshMain(K.access).then(()=>{j0(),B()}).catch(()=>{});if(u(O,{activeId:"main",route:"main",mainAccessToken:K.access,mainRefreshToken:K.refresh}),N.mark("main_quota_for_routing",{ms:A(F()-L),passes:b0(k,O)}),!b0(k,O)){let t=F();_=await c0(O,{includeApiRoutes:Boolean(U&&U.refreshAfter>Date.now()&&O0(U.quota))}),N.mark("preselect_fallback_accounts",{ms:A(F()-t),accounts:_.length});let p=await n0(Y,I,_,O,void 0,N,{onSuccess:(c)=>Z(c.id,"fallback")});if(p)return N.done("return_preselected_fallback",{status:p.status}),f0(p,{perf:(c,i)=>N.mark(c,i)})}}catch(L){N.mark("main_quota_for_routing_error",{error:L instanceof Error?L.message:String(L)})}let Q=V.getMain(K.access)?.quota;if(O?.quota?.failClosedOnUnknownQuota&&!Q&&V.isBackedOff()){let L=V.getLastApiError(),U=L?Aj(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:U}}),{status:429,headers:{"content-type":"application/json","retry-after":String(L?.nextRetryAt?Math.max(1,Math.ceil((L.nextRetryAt-Date.now())/1000)):60)}})}if(h0(O)){if(V.needsRefresh(d))try{let U=(O?.accounts??[]).filter((k)=>k.enabled!==!1&&e(k)&&Boolean(k.access));await Promise.all([V.refreshMain(K.access),V.refreshAllFallbacks(U)])}catch(U){q("[quota] killswitch refresh failed",{error:U instanceof Error?U.message:String(U),backedOff:V.isBackedOff()})}Q=V.getMain(K.access)?.quota}if(h0(O)&&!X1(Q,O)){let U=R(Y,I?.body)?await c0(O,{includeApiRoutes:Q1(K.access)}):[];if(U.length>0){q("[route] skipping main (killswitch), trying fallbacks");let c=await n0(Y,I,U,O,void 0,N,{onSuccess:(i)=>Z(i.id,"fallback")});if(c)return N.done("return_killswitch_fallback",{status:c.status}),f0(c,{perf:(i,X0)=>N.mark(i,X0)})}let k=Date.now(),t=(O?.accounts??[]).filter((c)=>c.enabled!==!1&&e(c)).map((c)=>({...c,quota:L0(c)})),p=kj(Q,t,k);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:`Killswitch: no routable accounts. Retry in ${Math.floor(p/60)}m ${p%60}s.`}}),{status:429,headers:{"content-type":"application/json","retry-after":String(p)}})}let l=await u0(Y,I,K.access,N,"main",O),m=!1,C=await YJ(Y,I,l,_,N,O,K.access,(L)=>{m=!0,Z(L.id,"fallback")});if(!m)Z("main","main");return N.done("return_response",{status:C.status}),f0(C,{perf:(L,U)=>N.mark(L,U)})}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let X=await H1("max");return{url:X.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{return x1(G,X.verifier,X.redirectUri,X.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let X=await H1("console");return{url:X.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{let D=await x1(G,X.verifier,X.redirectUri,X.state);if(D.type==="failed")return D;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 ${D.access}`}}).then((P)=>P.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{_3 as AnthropicAuthPlugin};
@@ -50,3 +50,12 @@ export declare function getCollapsedQuotaSummary(quota: AccountQuota | null): {
50
50
  sevenDayUsedPercent: number | null;
51
51
  text: string | null;
52
52
  };
53
+ export declare const FIVE_HOUR_MS: number;
54
+ export declare const SEVEN_DAY_MS: number;
55
+ export interface QuotaPacing {
56
+ pacePercent: number;
57
+ deltaPercent: number;
58
+ state: 'deficit' | 'reserve' | 'on-pace';
59
+ runsOutAt: string | null;
60
+ }
61
+ export declare function computeQuotaPacing(window: QuotaWindow, windowMs: number, now: number): QuotaPacing | null;
@@ -1 +1 @@
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};
1
+ import{$a as f,Wa as a,Xa as b,Ya as c,Za as d,_a as e,ab as g,bb as h,cb as i}from"./index-9yjbmhf1.js";import"./index-agh52sak.js";export{d as setSidebarState,e as resolveActiveAccount,a as getSidebarStateFile,c as getSidebarState,f as getCollapsedQuotaSummary,i as computeQuotaPacing,h as SEVEN_DAY_MS,g as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
@@ -0,0 +1,41 @@
1
+ export declare const TUI_PREFS_FILE_ENV = "OPENCODE_TUI_PREFERENCES_FILE";
2
+ export declare function getTuiPreferencesFile(): string;
3
+ export declare function readTuiPreferencesFile(): Promise<Record<string, unknown>>;
4
+ export declare const PLUGIN_KEY = "anthropic-auth";
5
+ export declare const DEFAULT_SLOT_ORDER = 160;
6
+ export interface AnthropicAuthTuiPrefs {
7
+ forceToTop: boolean;
8
+ order: number;
9
+ startCollapsed: boolean;
10
+ rememberCollapsed: boolean;
11
+ collapsed: boolean | null;
12
+ pollMs: number;
13
+ refreshDebounceMs: number;
14
+ header: {
15
+ label: string;
16
+ showVersion: boolean;
17
+ };
18
+ sections: {
19
+ quota: boolean;
20
+ fallbackAccounts: boolean;
21
+ routing: boolean;
22
+ cache: boolean;
23
+ health: boolean;
24
+ pacing: boolean;
25
+ };
26
+ appearance: {
27
+ barWidth: number;
28
+ barFilledChar: string;
29
+ barEmptyChar: string;
30
+ warnThreshold: number;
31
+ errorThreshold: number;
32
+ };
33
+ }
34
+ export type AppearancePrefs = AnthropicAuthTuiPrefs['appearance'];
35
+ export declare const DEFAULT_PREFS: AnthropicAuthTuiPrefs;
36
+ export declare function resolveAnthropicAuthPrefs(root: Record<string, unknown>): AnthropicAuthTuiPrefs;
37
+ export declare function computeEffectiveOrder(root: Record<string, unknown>, pluginKey: string, defaultOrder: number): number;
38
+ type JsonValue = string | number | boolean | null;
39
+ export declare function queueTuiPreferenceUpdate(pluginKey: string, path: string[], value: JsonValue): Promise<void>;
40
+ export declare function watchTuiPreferences(onChange: () => void): () => void;
41
+ export {};
@@ -0,0 +1,6 @@
1
+ import{db as P,eb as C,fb as _}from"./index-agh52sak.js";var g=C((T,L)=>{(function(Q){if(typeof L==="object"&&typeof L.exports==="object"){var J=Q(_,T);if(J!==void 0)L.exports=J}else if(typeof define==="function"&&define.amd)define(["require","exports","./impl/format","./impl/edit","./impl/scanner","./impl/parser"],Q)})(function(Q,J){Object.defineProperty(J,"__esModule",{value:!0}),J.applyEdits=J.modify=J.format=J.printParseErrorCode=J.ParseErrorCode=J.stripComments=J.visit=J.getNodeValue=J.getNodePath=J.findNodeAtOffset=J.findNodeAtLocation=J.parseTree=J.parse=J.getLocation=J.SyntaxKind=J.ScanError=J.createScanner=void 0;let X=Q("./impl/format"),Z=Q("./impl/edit"),G=Q("./impl/scanner"),$=Q("./impl/parser");J.createScanner=G.createScanner;var W;(function(z){z[z.None=0]="None",z[z.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=2]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",z[z.InvalidUnicode=4]="InvalidUnicode",z[z.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",z[z.InvalidCharacter=6]="InvalidCharacter"})(W||(J.ScanError=W={}));var H;(function(z){z[z.OpenBraceToken=1]="OpenBraceToken",z[z.CloseBraceToken=2]="CloseBraceToken",z[z.OpenBracketToken=3]="OpenBracketToken",z[z.CloseBracketToken=4]="CloseBracketToken",z[z.CommaToken=5]="CommaToken",z[z.ColonToken=6]="ColonToken",z[z.NullKeyword=7]="NullKeyword",z[z.TrueKeyword=8]="TrueKeyword",z[z.FalseKeyword=9]="FalseKeyword",z[z.StringLiteral=10]="StringLiteral",z[z.NumericLiteral=11]="NumericLiteral",z[z.LineCommentTrivia=12]="LineCommentTrivia",z[z.BlockCommentTrivia=13]="BlockCommentTrivia",z[z.LineBreakTrivia=14]="LineBreakTrivia",z[z.Trivia=15]="Trivia",z[z.Unknown=16]="Unknown",z[z.EOF=17]="EOF"})(H||(J.SyntaxKind=H={})),J.getLocation=$.getLocation,J.parse=$.parse,J.parseTree=$.parseTree,J.findNodeAtLocation=$.findNodeAtLocation,J.findNodeAtOffset=$.findNodeAtOffset,J.getNodePath=$.getNodePath,J.getNodeValue=$.getNodeValue,J.visit=$.visit,J.stripComments=$.stripComments;var q;(function(z){z[z.InvalidSymbol=1]="InvalidSymbol",z[z.InvalidNumberFormat=2]="InvalidNumberFormat",z[z.PropertyNameExpected=3]="PropertyNameExpected",z[z.ValueExpected=4]="ValueExpected",z[z.ColonExpected=5]="ColonExpected",z[z.CommaExpected=6]="CommaExpected",z[z.CloseBraceExpected=7]="CloseBraceExpected",z[z.CloseBracketExpected=8]="CloseBracketExpected",z[z.EndOfFileExpected=9]="EndOfFileExpected",z[z.InvalidCommentToken=10]="InvalidCommentToken",z[z.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=12]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",z[z.InvalidUnicode=14]="InvalidUnicode",z[z.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",z[z.InvalidCharacter=16]="InvalidCharacter"})(q||(J.ParseErrorCode=q={}));function D(z){switch(z){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}J.printParseErrorCode=D;function m(z,U,j){return X.format(z,U,j)}J.format=m;function f(z,U,j,A){return Z.setProperty(z,U,j,A)}J.modify=f;function u(z,U){let j=U.slice(0).sort((I,Y)=>{let F=I.offset-Y.offset;if(F===0)return I.length-Y.length;return F}),A=z.length;for(let I=j.length-1;I>=0;I--){let Y=j[I];if(Y.offset+Y.length<=A)z=Z.applyEdit(z,Y);else throw Error("Overlapping edit");A=Y.offset}return z}J.applyEdits=u})});var M=P(g(),1);import{watch as K}from"node:fs";import{mkdir as c,readFile as O,rename as y,writeFile as S}from"node:fs/promises";import{homedir as E}from"node:os";import{basename as l,dirname as v,join as k}from"node:path";var p="OPENCODE_TUI_PREFERENCES_FILE",x="tui-preferences.jsonc";function w(){let Q=process.env[p];if(Q)return Q;let J=process.env.OPENCODE_CONFIG_DIR||k(process.env.XDG_CONFIG_HOME||k(E(),".config"),"opencode");return k(J,x)}function N(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}async function Xz(){try{let Q=await O(w(),"utf8"),J=[],X=M.parse(Q,J,{allowTrailingComma:!0});if(J.length>0)return{};return N(X)?X:{}}catch{return{}}}var i="anthropic-auth",s=160,b={forceToTop:!1,order:s,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"CLAUDE",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,cache:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function V(Q,J){return typeof Q==="boolean"?Q:J}function B(Q,J,X,Z){if(typeof Q!=="number"||!Number.isFinite(Q))return J;return Math.min(Math.max(Math.round(Q),X),Z)}function d(Q,J,X){if(typeof Q!=="string"||Q.length===0)return J;return Q.slice(0,X)}function h(Q,J){if(typeof Q!=="string")return J;return[...Q][0]??J}function Zz(Q){let J=Q[i];if(!N(J))return structuredClone(b);let X=b,Z=N(J.header)?J.header:{},G=N(J.sections)?J.sections:{},$=N(J.appearance)?J.appearance:{},W=B($.warnThreshold,X.appearance.warnThreshold,0,99),H=Math.max(B($.errorThreshold,X.appearance.errorThreshold,0,100),Math.min(W+1,100));return{forceToTop:V(J.forceToTop,X.forceToTop),order:B(J.order,X.order,-1e4,1e4),startCollapsed:V(J.startCollapsed,X.startCollapsed),rememberCollapsed:V(J.rememberCollapsed,X.rememberCollapsed),collapsed:typeof J.collapsed==="boolean"?J.collapsed:null,pollMs:B(J.pollMs,X.pollMs,500,30000),refreshDebounceMs:B(J.refreshDebounceMs,X.refreshDebounceMs,50,5000),header:{label:d(Z.label,X.header.label,20),showVersion:V(Z.showVersion,X.header.showVersion)},sections:{quota:V(G.quota,X.sections.quota),fallbackAccounts:V(G.fallbackAccounts,X.sections.fallbackAccounts),routing:V(G.routing,X.sections.routing),cache:V(G.cache,X.sections.cache),health:V(G.health,X.sections.health),pacing:V(G.pacing,X.sections.pacing)},appearance:{barWidth:B($.barWidth,X.appearance.barWidth,4,40),barFilledChar:h($.barFilledChar,X.appearance.barFilledChar),barEmptyChar:h($.barEmptyChar,X.appearance.barEmptyChar),warnThreshold:W,errorThreshold:H}}}var n=-1e5;function $z(Q,J,X){let Z=Q[J];if(!N(Z))return X;if(Z.forceToTop===!0)return n+Object.keys(Q).indexOf(J);return B(Z.order,X,-1e4,1e4)}var t=`// Shared preferences for opencode TUI plugins.
2
+ // One top-level key per plugin (short name). See each plugin's README for
3
+ // its supported settings. This file is safe to hand-edit; plugins update
4
+ // individual keys in place and preserve comments.
5
+ {}
6
+ `;async function a(Q,J,X){let Z=w();await c(v(Z),{recursive:!0});let G;try{G=await O(Z,"utf8")}catch{G=""}if(G.trim()==="")G=t;let $=M.modify(G,[Q,...J],X,{formattingOptions:{insertSpaces:!0,tabSize:2}}),W=M.applyEdits(G,$),H=`${Z}.${process.pid}.tmp`;await S(H,W,"utf8"),await y(H,Z)}var R=Promise.resolve();function Gz(Q,J,X){return R=R.then(()=>a(Q,J,X)).catch(()=>{}),R}var o=150;function Hz(Q){let J=w(),X=l(J),Z=null,G=null;O(J,"utf8").then(($)=>{if(G===null)G=$}).catch(()=>{});try{let $=K(v(J),(W,H)=>{let q=H===X||H?.startsWith(`${X}.`)&&H.endsWith(".tmp");if(H!=null&&!q)return;if(Z)clearTimeout(Z);Z=setTimeout(()=>{Z=null,O(J,"utf8").catch(()=>null).then((D)=>{if(D===null)return;if(D===G)return;G=D,Q()})},o)});return()=>{if(Z)clearTimeout(Z);$.close()}}catch{return()=>{}}}export{Hz as watchTuiPreferences,Zz as resolveAnthropicAuthPrefs,Xz as readTuiPreferencesFile,Gz as queueTuiPreferenceUpdate,w as getTuiPreferencesFile,$z as computeEffectiveOrder,p as TUI_PREFS_FILE_ENV,i as PLUGIN_KEY,s as DEFAULT_SLOT_ORDER,b as DEFAULT_PREFS};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-anthropic-auth",
3
- "version": "1.9.1",
3
+ "version": "1.9.3",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,6 +17,10 @@
17
17
  "./tui": {
18
18
  "types": "./dist/tui.d.ts",
19
19
  "import": "./src/tui.tsx"
20
+ },
21
+ "./tui-prefs": {
22
+ "types": "./dist/tui-preferences.d.ts",
23
+ "import": "./dist/tui-preferences.js"
20
24
  }
21
25
  },
22
26
  "oc-plugin": [
@@ -33,11 +37,12 @@
33
37
  "dist",
34
38
  "src/tui.tsx",
35
39
  "src/sidebar-state.ts",
40
+ "src/tui-preferences.ts",
36
41
  "README.md",
37
42
  "LICENSE"
38
43
  ],
39
44
  "scripts": {
40
- "build": "rm -rf dist && bun build src/index.ts src/cli.ts src/sidebar-state.ts --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --minify && tsc -p tsconfig.build.json --emitDeclarationOnly",
45
+ "build": "rm -rf dist && bun build src/index.ts src/cli.ts src/sidebar-state.ts src/tui-preferences.ts --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --minify && tsc -p tsconfig.build.json --emitDeclarationOnly",
41
46
  "build:dev": "rm -rf dist && tsc -p tsconfig.build.json",
42
47
  "dev": "bun ../../scripts/dev.ts",
43
48
  "dev:clean": "bun ../../scripts/dev-clean.ts",
@@ -51,9 +56,10 @@
51
56
  "@opencode-ai/plugin": "*"
52
57
  },
53
58
  "dependencies": {
54
- "@cortexkit/anthropic-auth-core": "1.9.1",
55
- "@opentui/core": ">=0.3.1",
56
- "@opentui/solid": ">=0.3.1",
59
+ "@cortexkit/anthropic-auth-core": "1.9.3",
60
+ "@opentui/core": ">=0.4.0",
61
+ "@opentui/solid": ">=0.4.0",
62
+ "jsonc-parser": "^3.3.1",
57
63
  "solid-js": "^1.9.10"
58
64
  }
59
65
  }
@@ -123,3 +123,57 @@ export function getCollapsedQuotaSummary(quota: AccountQuota | null): {
123
123
  text: `5h: ${fiveHourUsedPercent == null ? '—' : `${Math.round(fiveHourUsedPercent)}%`} 7d: ${sevenDayUsedPercent == null ? '—' : `${Math.round(sevenDayUsedPercent)}%`}`,
124
124
  }
125
125
  }
126
+
127
+ export const FIVE_HOUR_MS = 5 * 60 * 60 * 1000
128
+ export const SEVEN_DAY_MS = 7 * 24 * 60 * 60 * 1000
129
+
130
+ const PACING_MIN_ELAPSED_MS = 5 * 60 * 1000
131
+ const PACING_MIN_ELAPSED_FRACTION = 0.01
132
+ const ON_PACE_DELTA = 1
133
+
134
+ export interface QuotaPacing {
135
+ pacePercent: number
136
+ deltaPercent: number
137
+ state: 'deficit' | 'reserve' | 'on-pace'
138
+ runsOutAt: string | null
139
+ }
140
+
141
+ // Even-burn pacing for a quota window. The window start is inferred from the
142
+ // reset timestamp minus the window length. Two metrics: deltaPercent compares
143
+ // usage against a uniform burn-down (positive = deficit), and runsOutAt
144
+ // projects the current average burn rate forward — null means the window
145
+ // lasts until reset at that rate. Returns null when there is no reset
146
+ // timestamp or the elapsed time is too small to give a meaningful rate.
147
+ export function computeQuotaPacing(
148
+ window: QuotaWindow,
149
+ windowMs: number,
150
+ now: number,
151
+ ): QuotaPacing | null {
152
+ if (!window.resetsAt) return null
153
+ const resetsAt = new Date(window.resetsAt).getTime()
154
+ if (!Number.isFinite(resetsAt)) return null
155
+ const start = resetsAt - windowMs
156
+ const elapsed = now - start
157
+ if (elapsed < PACING_MIN_ELAPSED_MS) return null
158
+ if (elapsed < windowMs * PACING_MIN_ELAPSED_FRACTION) return null
159
+ if (elapsed >= windowMs) return null
160
+
161
+ const used = window.usedPercent
162
+ const pacePercent = Math.min(Math.max((elapsed / windowMs) * 100, 0), 100)
163
+ const deltaPercent = used - pacePercent
164
+ const state =
165
+ Math.abs(deltaPercent) < ON_PACE_DELTA
166
+ ? 'on-pace'
167
+ : deltaPercent > 0
168
+ ? 'deficit'
169
+ : 'reserve'
170
+
171
+ let runsOutAt: string | null = null
172
+ if (used > 0) {
173
+ const msToFull = (elapsed * 100) / used
174
+ const runOut = start + msToFull
175
+ if (runOut < resetsAt) runsOutAt = new Date(runOut).toISOString()
176
+ }
177
+
178
+ return { pacePercent, deltaPercent, state, runsOutAt }
179
+ }