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