@cortexkit/opencode-anthropic-auth 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import{$ as A1,A as v1,B as U1,C as x1,D as S0,E as D0,F as q1,G as n,H as E0,I as H1,J as T0,K as S1,L as R0,M as E1,N as V0,O as K0,P as X0,Q as c,R as T1,S as W0,T as $1,U as G1,V as A0,W as D1,X as V1,Y as K1,Z as Y0,_ as R1,a as r0,aa as C1,b as s0,ba as f1,c as j0,ca as y1,d as J0,da as k1,e as e0,ea as g1,f as l,fa as P0,g as N1,ga as w0,h as j1,ha as m1,i as J1,ia as C0,j as Z1,ja as z0,k as F0,ka as b1,l as L1,la as I0,m as v0,ma as h1,n as U0,na as f0,o as H,oa as Q0,pa as u1,q as T,qa as d1,r as x0,ra as i1,s as _1,t as $0,ta as l1,u as G0,v as M1,va as O0,w as B1,wa as y0,x as q0,xa as p1,y as F1,ya as n1,z as H0,za as k0}from"./index-75s94xp3.js";import{randomUUID as Fj}from"node:crypto";function b(j){return typeof j==="object"&&j!==null}function Vj(j){if(Array.isArray(j))return j;if(b(j)&&Array.isArray(j.data))return j.data;return[]}function Kj(j){if(!b(j)||!b(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function d0(j){if(!b(j)||!b(j.info))return null;let J=j.info,Z=b(J.model)?J.model:void 0,G=typeof J.agent==="string"?J.agent:void 0,V=typeof Z?.providerID==="string"?Z.providerID:typeof J.providerID==="string"?J.providerID:void 0,K=typeof Z?.modelID==="string"?Z.modelID:typeof J.modelID==="string"?J.modelID:void 0,_=typeof Z?.variant==="string"?Z.variant:typeof J.variant==="string"?J.variant:void 0;if(!G&&(!V||!K)&&!_)return null;let C={};if(G)C.agent=G;if(V&&K)C.model={providerID:V,modelID:K};if(_)C.variant=_;return C}function i0(j,J){return{agent:j.agent??J.agent,model:j.model??J.model,variant:j.variant??J.variant}}function l0(j){return Boolean(j.agent&&j.model&&j.variant)}async function p0(j,J){if(!j||!J)return null;let Z=j;if(typeof Z.session?.messages!=="function")return null;let G=[];try{G=Vj(await Promise.resolve(Z.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(G.length===0)return null;let V={};for(let K=G.length-1;K>=0;K--){if(Kj(G[K])!=="assistant")continue;let _=d0(G[K]);if(!_)continue;if(V=i0(V,_),l0(V))return V}for(let K=G.length-1;K>=0;K--){let _=d0(G[K]);if(!_)continue;if(V=i0(V,_),l0(V))return V}if(!V.agent&&!V.model&&!V.variant)return null;return V}function n0(j){return`${r0}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function Xj(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}function X1(j,J){let Z=new Headers;if(j instanceof Request)j.headers.forEach((V,K)=>{Z.set(K,V)});let G=J?.headers;if(G){if(G instanceof Headers)G.forEach((V,K)=>{Z.set(K,V)});else if(Array.isArray(G))for(let V of G){let[K,_]=V;if(typeof _<"u")Z.set(K,String(_))}else for(let[V,K]of Object.entries(G))if(typeof K<"u")Z.set(V,String(K))}return Z}function B0(j){return j.set("anthropic-beta",j0(j.get("anthropic-beta"),[s0])),j}function p(j,J,Z={}){return V1(j,J,Z)}function Wj(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((J)=>({...J,name:J.name?n0(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((Z)=>{if(Z.type==="tool_use"&&Z.name)return{...Z,name:n0(Z.name)};return Z});return J});return JSON.stringify(K1(j))}function M0(j){return j.replace(/"name"\s*:\s*"mcp_([^"]+)"/g,(J,Z)=>`"name": "${Xj(Z)}"`)}function c0(j,J=!1){if(J)return{ready:M0(j),pending:""};let Z=j.length,G='"name"',V=Math.max(0,j.length-G.length+1);for(let _=V;_<j.length;_++)if(G.startsWith(j.slice(_))){Z=Math.min(Z,_);break}let K=j.lastIndexOf(G);if(K!==-1){let _=j.slice(K);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(_))Z=Math.min(Z,K)}if(Z<j.length)return{ready:M0(j.slice(0,Z)),pending:j.slice(Z)};return{ready:M0(j),pending:""}}function W1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function Yj(){let j=process.env.ANTHROPIC_BASE_URL?.trim();if(!j)return null;try{let J=new URL(j);if(J.protocol!=="http:"&&J.protocol!=="https:"||J.username||J.password)return null;return J}catch{return null}}function Y1(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 Z=J.href,G=Yj();if(G)J.protocol=G.protocol,J.host=G.host;if(J.pathname==="/v1/messages"&&!J.searchParams.has("beta"))J.searchParams.set("beta","true");if(J.href===Z)return{input:j,url:J};return{input:j instanceof Request?new Request(J.toString(),j):J,url:J}}function a(j){let G=j.split(/\n\n+/).filter((V)=>{if(V.includes(e0))return!1;for(let K of J1)if(V.includes(K))return!1;return!0}).join(`
1
+ import{$ as T0,A as S1,B as R1,C as y1,D as S0,E as Y0,F as f1,G as i,H as R0,I as y0,J as T1,K as K0,L as Q0,M as G0,N as r,O as A1,P as P0,Q as Y1,R as K1,S as f0,T as Q1,U as G1,V as P1,W as I0,X as k1,Y as b1,Z as m1,_ as g1,a as Z1,aa as h1,b as $1,ba as d1,c as $0,ca as z0,d as V0,da as w0,e as V1,ea as l1,f as o,fa as A0,g as F1,ga as O0,h as D1,ha as k0,i as X1,ia as L0,j as W1,ja as p1,k as H0,ka as b0,l as B1,la as u1,m as q0,ma as N0,n as E0,na as i1,o as q,oa as c1,p as H1,pa as m0,q as C,r as a,ra as n1,s as q1,t as X0,ta as _0,u as W0,ua as g0,v as E1,va as o1,w as x1,wa as s1,x as x0,xa as h0,y as C1,z as C0}from"./index-4wz5npbg.js";import{Ba as a1}from"./index-nfgq84t3.js";import{randomUUID as qj}from"node:crypto";function l(j){return typeof j==="object"&&j!==null}function Kj(j){if(Array.isArray(j))return j;if(l(j)&&Array.isArray(j.data))return j.data;return[]}function Qj(j){if(!l(j)||!l(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function c0(j){if(!l(j)||!l(j.info))return null;let J=j.info,Z=l(J.model)?J.model:void 0,V=typeof J.agent==="string"?J.agent:void 0,D=typeof Z?.providerID==="string"?Z.providerID:typeof J.providerID==="string"?J.providerID:void 0,Y=typeof Z?.modelID==="string"?Z.modelID:typeof J.modelID==="string"?J.modelID:void 0,B=typeof Z?.variant==="string"?Z.variant:typeof J.variant==="string"?J.variant:void 0;if(!V&&(!D||!Y)&&!B)return null;let k={};if(V)k.agent=V;if(D&&Y)k.model={providerID:D,modelID:Y};if(B)k.variant=B;return k}function n0(j,J){return{agent:j.agent??J.agent,model:j.model??J.model,variant:j.variant??J.variant}}function o0(j){return Boolean(j.agent&&j.model&&j.variant)}async function s0(j,J){if(!j||!J)return null;let Z=j;if(typeof Z.session?.messages!=="function")return null;let V=[];try{V=Kj(await Promise.resolve(Z.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(V.length===0)return null;let D={};for(let Y=V.length-1;Y>=0;Y--){if(Qj(V[Y])!=="assistant")continue;let B=c0(V[Y]);if(!B)continue;if(D=n0(D,B),o0(D))return D}for(let Y=V.length-1;Y>=0;Y--){let B=c0(V[Y]);if(!B)continue;if(D=n0(D,B),o0(D))return D}if(!D.agent&&!D.model&&!D.variant)return null;return D}function a0(j){return`${Z1}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function I1(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}var Gj=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function r0(j){let J=I1(j);if(J.startsWith("aft_"))return J;if(Gj.has(J))return`aft_${J}`;return null}function z1(j,J){let Z=new Headers;if(j instanceof Request)j.headers.forEach((D,Y)=>{Z.set(Y,D)});let V=J?.headers;if(V){if(V instanceof Headers)V.forEach((D,Y)=>{Z.set(Y,D)});else if(Array.isArray(V))for(let D of V){let[Y,B]=D;if(typeof B<"u")Z.set(Y,String(B))}else for(let[D,Y]of Object.entries(V))if(typeof Y<"u")Z.set(D,String(Y))}return Z}function B0(j){return j.set("anthropic-beta",$0(j.get("anthropic-beta"),[$1])),j}function s(j,J,Z={}){return G1(j,J,Z)}function Pj(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((J)=>({...J,name:J.name?a0(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((Z)=>{if(Z.type==="tool_use"&&Z.name)return{...Z,name:a0(Z.name)};return Z});return J});return JSON.stringify(P1(j))}function v0(j){return j.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(J,Z,V)=>{if(Z)return`"name": "${r0(V)??I1(V)}"`;let D=r0(V);return D?`"name": "${D}"`:J})}function t0(j,J=!1){if(J)return{ready:v0(j),pending:""};let Z=j.length,V='"name"',D=Math.max(0,j.length-V.length+1);for(let B=D;B<j.length;B++)if(V.startsWith(j.slice(B))){Z=Math.min(Z,B);break}let Y=j.lastIndexOf(V);if(Y!==-1){let B=j.slice(Y);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(B))Z=Math.min(Z,Y)}if(Z<j.length)return{ready:v0(j.slice(0,Z)),pending:j.slice(Z)};return{ready:v0(j),pending:""}}function w1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function Ij(){let j=process.env.ANTHROPIC_BASE_URL?.trim();if(!j)return null;try{let J=new URL(j);if(J.protocol!=="http:"&&J.protocol!=="https:"||J.username||J.password)return null;return J}catch{return null}}function O1(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 Z=J.href,V=Ij();if(V)J.protocol=V.protocol,J.host=V.host;if(J.pathname==="/v1/messages"&&!J.searchParams.has("beta"))J.searchParams.set("beta","true");if(J.href===Z)return{input:j,url:J};return{input:j instanceof Request?new Request(J.toString(),j):J,url:J}}function j0(j){let V=j.split(/\n\n+/).filter((D)=>{if(D.includes(V1))return!1;for(let Y of X1)if(D.includes(Y))return!1;return!0}).join(`
2
2
 
3
- `);for(let V of Z1)G=G.replace(V.match,V.replacement);return G.trim()}function R(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function Pj(j){let J={type:"text",text:l};if(j==null)return[J];if(typeof j==="string"){let G=a(j);if(G===l)return[J];return[J,{type:"text",text:G}]}if(R(j)){let G=typeof j.type==="string"?j.type:"text",V=typeof j.text==="string"?j.text:"";return[J,{...j,type:G,text:a(V)}]}if(!Array.isArray(j))return[J];let Z=j.map((G)=>{if(typeof G==="string")return{type:"text",text:a(G)};if(R(G)&&G.type==="text"&&typeof G.text==="string")return{...G,type:"text",text:a(G.text)};return{type:"text",text:String(G)}});if(Z[0]?.text===l)return Z;return[J,...Z]}var P1={type:"ephemeral",ttl:"1h"},wj=20;function zj(j){if(R(j.cache_control))return j.cache_control;if(R(j.cacheControl))return j.cacheControl;return null}function e(j,J){if(!R(j))return!1;return delete j.cacheControl,j.cache_control=J?{...P1}:{type:"ephemeral"},!0}function o0(j){if(!R(j))return;delete j.cache_control,delete j.cacheControl}function Ij(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function r(j,J){if(!R(j))return;let Z=zj(j);if(Z?.type!=="ephemeral")return;if(J)Z.ttl="1h";else delete Z.ttl}function t0(j,J){if(Array.isArray(j.system))for(let Z of j.system)r(Z,J);else r(j.system,J);if(!Array.isArray(j.messages))return;for(let Z of j.messages)if(r(Z,J),R(Z)&&Array.isArray(Z.content))for(let G of Z.content)r(G,J)}function Qj(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),R(Z)&&Array.isArray(Z.content))for(let G of Z.content)J(G)}function w1(j){o0(j),Qj(j,o0)}function Oj(j){w1(j),j.cache_control={...P1}}function s(j){if(!R(j))return!1;let J=Ij(j.content);if(!J?.length)return e(j,!0);j.content=J;let Z=[...J].reverse().find((G)=>R(G)&&G.type!=="thinking");return e(Z??j,!0)}function Nj(j){if(!R(j))return 0;let J=j.content;if(Array.isArray(J))return J.length;if(J==null)return 0;return 1}function Lj(j){let J=[],Z=0;return j.forEach((G,V)=>{let K=Nj(G);if(R(G)&&G.role==="user"&&K>0)J.push({index:V,blockPosition:Z+K-1});Z+=K}),J}function _j(j){let J=Lj(j),Z=[...J].reverse().find((_)=>_.index>1);if(!Z)return{latest:void 0,bridge:void 0};let G=[...J].reverse().find((_)=>_.index<Z.index),V=G?Z.blockPosition-G.blockPosition+1:0,K=G&&G.index>1&&V>wj?G:void 0;return{latest:Z,bridge:K}}function a0(j){if(Array.isArray(j.system)){let J=j.system.findIndex((V)=>R(V)&&V.text===l),Z=j.system.slice(J>=0?J+1:0).filter(R),G=Z[Z.length-1];e(G,!0)}else e(j.system,!0)}function Mj(j){if(w1(j),!Array.isArray(j.messages)){a0(j);return}let{latest:J,bridge:Z}=_j(j.messages);if(!Z)a0(j);if(s(j.messages[0]),s(j.messages[1]),Z)s(j.messages[Z.index]);if(J)s(j.messages[J.index])}function Bj(j,J){if(!J.enabled){t0(j,!1),delete j.cache_control,delete j.cacheControl;return}if(J.mode==="automatic"){Oj(j);return}if(J.mode==="hybrid"){Mj(j);return}t0(j,!0),delete j.cacheControl}async function z1(j,J={}){try{let Z=JSON.parse(j),G=Array.isArray(Z.messages)&&Z.messages.some((V)=>V.role==="user")?G1(Z.messages,void 0,j1):null;if(Z.system=Pj(Z.system),G&&Array.isArray(Z.system))Z.system.unshift({type:"text",text:G});if(Bj(Z,{enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.fastModeEnabled&&J0(Z.model))Z.speed="fast";else if(Z.speed==="fast")delete Z.speed;if(J.identity)D1(Z,J.identity);return await $1(Wj(Z))}catch{return j}}function Z0(j){if(!j.body)return j;let J=j.body.getReader(),Z=new TextDecoder,G=new TextEncoder,V="",K=new ReadableStream({async pull(_){let{done:C,value:y}=await J.read();if(C){let i=c0(`${V}${Z.decode()}`,!0);if(i.ready)_.enqueue(G.encode(i.ready));_.close();return}let L0=V+Z.decode(y,{stream:!0}),d=c0(L0);if(V=d.pending,d.ready)_.enqueue(G.encode(d.ready))}});return new Response(K,{status:j.status,statusText:j.statusText,headers:j.headers})}var vj="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",Uj=60000,xj=60000,qj=5000,I1=200,c1=240,Hj=c1,Sj=1,Q1=!1;function N0(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function B(){return performance.now()}function E(j){return Math.round(j*10)/10}function O1(j){return Math.floor(Math.random()*Math.max(0,j))}function Ej(){if(Q1||!1||!N0())return;Q1=!0;let j=100,J=250,Z=B()+j;setInterval(()=>{let G=B(),V=G-Z;if(Z=G+j,V<J)return;H("[perf] opencode event_loop_lag",{lagMs:E(V),thresholdMs:J})},j).unref?.()}function Tj(j){let J=B(),Z={requestId:String(Sj++),start:J,last:J,mark(G,V){let K=B();if(N0())H("[perf] opencode request stage",{requestId:Z.requestId,stage:G,deltaMs:E(K-Z.last),totalMs:E(K-Z.start),...V});Z.last=K},done(G,V){let K=B();if(N0())H("[perf] opencode request done",{requestId:Z.requestId,stage:G,deltaMs:E(K-Z.last),totalMs:E(K-Z.start),...V});Z.last=K}};if(N0())H("[perf] opencode request start",{requestId:Z.requestId,...j});return Z}async function h(j,J,Z){let G=j.client.session,V=await p0(j.client,J),K={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:Z,ignored:!0}]}};if(V?.agent)K.body.agent=V.agent;if(V?.model)K.body.model=V.model;if(V?.variant)K.body.variant=V.variant;if(typeof G?.promptAsync==="function"){await G.promptAsync(K);return}if(typeof G?.prompt==="function"){await Promise.resolve(G.prompt(K));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function u(){throw Error(vj)}function Rj(j){if(j.sessionID==null)return!1;let J=j.model;return J?.providerID==="anthropic"||J?.api?.npm==="@ai-sdk/anthropic"||J?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function Aj(j){if(j.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return j.push(N1),!0}var uj=async(j)=>{Ej();let{client:J}=j,Z=new E1;Z.startBackgroundRefresh();let G=null,V=new g1({loadStorage:()=>T(),prepareHeaders:async($,Y)=>{if(!C)return $;let w=await C();if(w.type!=="oauth")return $;if(!w.access||w.expires&&w.expires<Date.now()){if(!G)return $;w.access=await G()}if(!w.access)return $;try{let N=JSON.parse(Y.bodyText),S=await A0(w.access,typeof N.model==="string"?N.model:void 0);if($.delete("anthropic-beta"),p($,w.access,{body:N,identity:S}),$.set("anthropic-beta",j0($.get("anthropic-beta"),[R1])),N.speed==="fast")B0($)}catch{p($,w.access)}return $},log:H}),K=await T(),_=i1(K);c({enabled:$0(K),mode:G0(K)}),w0(q0(K)),I0(H0(K));let C=null,y=null;function L0($){let Y=$?.refresh?.refreshBeforeExpiryMinutes??Hj;return Math.max(c1,Y)*60000}function d($){return $?.refresh?.enabled!==!1}async function i($){if(!$)return;let Y=await T(),w=Y?.refresh?.mainLastRefreshError;if(!Y?.refresh||!w?.tokenHash)return;let N=D0($);if(w.tokenHash===N)return;if(w.nextRetryAt&&w.nextRetryAt>Date.now()){H("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:w.nextRetryAt,retryCount:w.retryCount,remainingMs:w.nextRetryAt-Date.now()});return}Y.refresh.mainLastRefreshError=void 0,await x0(Y),H("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:w.checkedAt,previousNextRetryAt:w.nextRetryAt,previousRetryCount:w.retryCount})}async function o1(){let $=[];if(C)try{let N=await C();if(N.type==="oauth"&&N.access)$.push({name:"OpenCode anthropic",role:"main",quota:await R0({accessToken:N.access})});else if(N.type==="oauth")$.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(N){$.push({name:"OpenCode anthropic",role:"main",error:N instanceof Error?N.message:String(N)})}let{storage:Y,errors:w}=await Z.refreshQuotaForAllAccounts();if($.push(...u1(Y,new Map(w.map((N)=>[N.accountId,N.message])))),!C)$.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return d1({accounts:$,refreshedAt:Date.now()})}async function t1($){let Y=T1($);if(Y.type==="enable"||Y.type==="disable"){let f=Y.type==="enable",k=await M1(f),g=G0(k);return c({enabled:f,mode:g}),W0({argumentsText:$,enabled:f,mode:g})}if(Y.type==="mode"){let f=await B1(Y.mode),k=$0(f);return c({enabled:k,mode:Y.mode}),W0({argumentsText:$,enabled:k,mode:Y.mode})}let w=await T(),N=$0(w),S=G0(w);return c({enabled:N,mode:S}),W0({argumentsText:$,enabled:N,mode:S})}async function a1($){let Y=A1($),w=await T();if(Y.type==="window")w=await U1(Y.startHour,Y.endHour);else if(Y.type==="disable")w=await x1(!1);let N=C1(w),S=V.stats(N);return k1({argumentsText:$,enabled:f1(w),window:N,hybridActive:y1(w),trackedSessions:S.trackedSessions,nextPrewarmAt:S.nextPrewarmAt})}async function r1($){let Y=m1($);if(Y.type==="enable"||Y.type==="disable"){let S=Y.type==="enable";return await F1(S),w0(S),C0({argumentsText:$,enabled:S})}let w=await T(),N=q0(w);return w0(N),C0({argumentsText:$,enabled:N})}async function s1($){let Y=h1($);if(Y.type==="enable"||Y.type==="disable"){let S=Y.type==="enable";return await v1(S),I0(S),f0({argumentsText:$,enabled:S})}let w=await T(),N=H0(w);return I0(N),f0({argumentsText:$,enabled:N})}async function e1($){let Y=n1($);if(Y.type==="mode")return await p1(Y.mode),k0({argumentsText:$,mode:Y.mode});let w=await T();return k0({argumentsText:$,mode:y0(w)})}return{config:async($)=>{$.command={...$.command??{},[V0]:{template:V0,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[Y0]:{template:Y0,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[Q0]:{template:Q0,description:"Show current Claude OAuth quota usage for all accounts."},[P0]:{template:P0,description:"Show or toggle Anthropic request dump capture for debugging."},[z0]:{template:z0,description:"Show or toggle Anthropic fast mode for supported Opus models."},[O0]:{template:O0,description:"Show or change Claude account routing between main-first and fallback-first."}}},"experimental.chat.system.transform":async($,Y)=>{if(!Rj($))return;Aj(Y.system)},"command.execute.before":async($)=>{if($.command===V0)await h(j,$.sessionID,await t1($.arguments)),u();if($.command===Y0)await h(j,$.sessionID,await a1($.arguments)),u();if($.command===Q0)await h(j,$.sessionID,await o1()),u();if($.command===P0)await h(j,$.sessionID,await r1($.arguments)),u();if($.command===z0)await h(j,$.sessionID,await s1($.arguments)),u();if($.command===O0)await h(j,$.sessionID,await e1($.arguments)),u()},auth:{provider:"anthropic",async loader($,Y){if(C=$,(await $()).type==="oauth"){let jj=function(){if(y)clearInterval(y),y=null;let X=async()=>{try{let W=await T();if(!d(W))return;let I=await $();if(I.type!=="oauth")return;if(await i(I.refresh),!I.expires)return;let P=I.expires-Date.now(),q=L0(W);if(P>q)return;if(H("[refresh] opencode main oauth background due",{expiresInMs:P,refreshBeforeMs:q}),I.refresh&&n(W?.refresh?.mainLastRefreshError,I.refresh,Date.now())){H("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:W?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:W?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:P});return}if(I.refresh&&W?.refresh?.mainRefreshLeaseUntil&&W.refresh.mainRefreshLeaseUntil>Date.now()&&W.refresh.mainRefreshLeaseTokenHash===D0(I.refresh))return;await g();let Q=await $();H("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:Q.expires?Q.expires-Date.now():void 0})}catch(W){H("[refresh] opencode main oauth refresh failed",{message:W instanceof Error?W.message:String(W)})}};if(y=setInterval(()=>{X()},Uj+O1(xj)),"unref"in y)y.unref()},g0=function(X,W){if(X instanceof Request&&X.body)return!1;return W==null||typeof W==="string"},Jj=function(X){return X.has("x-parent-session-id")},m0=function(X){return X.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(X)},Zj=function(X){return X?.quota?.enabled===!0},$j=function(X,W){let I=Date.now();if(f||I<k)return;f=u0(X,W).catch((P)=>{throw k=I+H1(W),P}).finally(()=>{f=null}),f.catch(()=>{})};for(let X of Object.values(Y.models))X.cost={input:0,output:0,cache:{read:0,write:0}};let N=null,S=null,f=null,k=0;async function g(){if(!N)N=(async()=>{let I=null,P=null,q=null;async function Q(z){let O=await T()??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};O.refresh=O.refresh??{},z(O),await x0(O)}async function v(z){let O=Date.now()+qj;while(Date.now()<O){await new Promise((M)=>setTimeout(M,I1+O1(I1)));let D=await $();if(D.type!=="oauth"||!D.access)continue;if((D.access!==z.access||D.refresh!==z.refresh||(D.expires??0)>(z.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return H("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:D.expires?D.expires-Date.now():void 0}),D.access}return null}for(let z=0;z<=2;z++){let O=null;try{if(z>0){let U=500*2**(z-1);await new Promise((o)=>setTimeout(o,U))}if(O=await $(),!O.refresh)throw Error("Token refresh failed: missing refresh token");let D=await T(),F=D0(O.refresh),M=D?.refresh?.mainLastRefreshError;if(H("[refresh] opencode main oauth refresh check",{attempt:z,expiresInMs:O.expires?O.expires-Date.now():void 0,hasBackoff:Boolean(M),backoffActive:M?n(M,O.refresh,Date.now()):!1,retryCount:M?.retryCount,nextRetryAt:M?.nextRetryAt}),M&&n(M,O.refresh,Date.now()))throw H("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:M.nextRetryAt,retryCount:M.retryCount}),Error(E0(M,Date.now()));if(D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===F){H("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:D.refresh.mainRefreshLeaseUntil});let U=await v(O);if(U)return U;throw Error("Claude OAuth refresh is already in progress")}let L=await _1({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!L){H("[refresh] opencode main oauth refresh skipped file lock");let U=await v(O);if(U)return U;throw Error("Claude OAuth refresh is already in progress")}q=L.release,I=Fj(),P=F,await Q((U)=>{U.refresh=U.refresh??{},U.refresh.mainRefreshLeaseId=I??void 0,U.refresh.mainRefreshLeaseUntil=Date.now()+120000,U.refresh.mainRefreshLeaseTokenHash=F});let x=await T();if(H("[refresh] opencode main oauth refresh lease acquired",{attempt:z,leaseUntil:Date.now()+120000}),x?.refresh?.mainRefreshLeaseId!==I||x.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Claude OAuth refresh is already in progress");H("[refresh] opencode main oauth refresh request start",{attempt:z});let A=await L1({refreshToken:O.refresh,maxRetries:0});return await J.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:A.refresh,access:A.access,expires:A.expires}}),await Q((U)=>{if(!U?.refresh)return;if(U.refresh.mainLastRefreshError=void 0,U.refresh.mainRefreshLeaseId===I)U.refresh.mainRefreshLeaseId=void 0,U.refresh.mainRefreshLeaseUntil=void 0,U.refresh.mainRefreshLeaseTokenHash=void 0}),H("[refresh] opencode main oauth refresh succeeded",{attempt:z,expiresInMs:A.expires-Date.now()}),A.access}catch(D){let F=D instanceof Error&&(D.message.includes("fetch failed")||("code"in D)&&(D.code==="ECONNRESET"||D.code==="ECONNREFUSED"||D.code==="ETIMEDOUT"||D.code==="UND_ERR_CONNECT_TIMEOUT"));if(z<2&&(F||D instanceof F0&&D.status>=500))continue;H("[refresh] opencode main oauth refresh attempt failed",{attempt:z,error:D instanceof Error?D.message:String(D),transient:F});let M=O?.refresh;if(M&&D instanceof F0)await Q((L)=>{L.refresh=L.refresh??{},L.refresh.mainLastRefreshError=q1({error:D,now:Date.now(),refreshToken:M,previous:L.refresh.mainLastRefreshError})});throw D}finally{if(I)await Q((D)=>{if(!D?.refresh)return;if(D.refresh.mainRefreshLeaseId===I&&D.refresh.mainRefreshLeaseTokenHash===P)D.refresh.mainRefreshLeaseId=void 0,D.refresh.mainRefreshLeaseUntil=void 0,D.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await q?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{N=null});return N}G=g,jj();async function b0(X,W){if(!X.body||X.status!==200)return W?.mark("inspect_stream_skip",{status:X.status}),{response:X,rateLimited:!1};if(X.headers.get("x-cortexkit-relay-optimistic")==="true")return W?.mark("inspect_stream_skip",{status:X.status,reason:"optimistic_relay"}),{response:X,rateLimited:!1};let I=B(),P=X.body.getReader(),q=[],Q=new TextDecoder,v="",z=0;while(!v.includes(`
3
+ `);for(let D of W1)V=V.replace(D.match,D.replacement);return V.trim()}function y(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function zj(j){let J={type:"text",text:o};if(j==null)return[J];if(typeof j==="string"){let V=j0(j);if(V===o)return[J];return[J,{type:"text",text:V}]}if(y(j)){let V=typeof j.type==="string"?j.type:"text",D=typeof j.text==="string"?j.text:"";return[J,{...j,type:V,text:j0(D)}]}if(!Array.isArray(j))return[J];let Z=j.map((V)=>{if(typeof V==="string")return{type:"text",text:j0(V)};if(y(V)&&V.type==="text"&&typeof V.text==="string")return{...V,type:"text",text:j0(V.text)};return{type:"text",text:String(V)}});if(Z[0]?.text===o)return Z;return[J,...Z]}var L1={type:"ephemeral",ttl:"1h"},wj=20;function Oj(j){if(y(j.cache_control))return j.cache_control;if(y(j.cacheControl))return j.cacheControl;return null}function F0(j,J){if(!y(j))return!1;return delete j.cacheControl,j.cache_control=J?{...L1}:{type:"ephemeral"},!0}function e0(j){if(!y(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 J0(j,J){if(!y(j))return;let Z=Oj(j);if(Z?.type!=="ephemeral")return;if(J)Z.ttl="1h";else delete Z.ttl}function j1(j,J){if(Array.isArray(j.system))for(let Z of j.system)J0(Z,J);else J0(j.system,J);if(!Array.isArray(j.messages))return;for(let Z of j.messages)if(J0(Z,J),y(Z)&&Array.isArray(Z.content))for(let V of Z.content)J0(V,J)}function Nj(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),y(Z)&&Array.isArray(Z.content))for(let V of Z.content)J(V)}function N1(j){e0(j),Nj(j,e0)}function _j(j){N1(j),j.cache_control={...L1}}function Z0(j){if(!y(j))return!1;let J=Lj(j.content);if(!J?.length)return!1;let Z=[...J].reverse().find((V)=>y(V)&&V.type!=="thinking"&&V.type!=="redacted_thinking");if(!Z)return!1;return j.content=J,F0(Z,!0)}function Uj(j){if(!y(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((V,D)=>{let Y=Uj(V);if(y(V)&&V.role==="user"&&Y>0)J.push({index:D,blockPosition:Z+Y-1});Z+=Y}),J}function vj(j){let J=Mj(j),Z=[...J].reverse().find((B)=>B.index>1);if(!Z)return{latest:void 0,bridge:void 0};let V=[...J].reverse().find((B)=>B.index<Z.index),D=V?Z.blockPosition-V.blockPosition+1:0,Y=V&&V.index>1&&D>wj?V:void 0;return{latest:Z,bridge:Y}}function J1(j){if(Array.isArray(j.system)){let J=j.system.findIndex((D)=>y(D)&&D.text===o),Z=j.system.slice(J>=0?J+1:0).filter(y),V=Z[Z.length-1];F0(V,!0)}else F0(j.system,!0)}function Fj(j){if(N1(j),!Array.isArray(j.messages)){J1(j);return}let{latest:J,bridge:Z}=vj(j.messages);if(!Z)J1(j);if(Z0(j.messages[0]),Z0(j.messages[1]),Z)Z0(j.messages[Z.index]);if(J)Z0(j.messages[J.index])}function Bj(j,J){if(!J.enabled){j1(j,!1),delete j.cache_control,delete j.cacheControl;return}if(J.mode==="automatic"){_j(j);return}if(J.mode==="hybrid"){Fj(j);return}j1(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(!y(J)||J.role!=="assistant")break;j.messages.pop()}}async function _1(j,J={}){try{let Z=JSON.parse(j);Hj(Z);let V=Array.isArray(Z.messages)&&Z.messages.some((D)=>D.role==="user")?K1(Z.messages,void 0,D1):null;if(Z.system=zj(Z.system),V&&Array.isArray(Z.system))Z.system.unshift({type:"text",text:V});if(Bj(Z,{enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.fastModeEnabled&&V0(Z.model))Z.speed="fast";else if(Z.speed==="fast")delete Z.speed;if(J.identity)Q1(Z,J.identity);return await Y1(Pj(Z))}catch{return j}}function D0(j){if(!j.body)return j;let J=j.body.getReader(),Z=new TextDecoder,V=new TextEncoder,D="",Y=new ReadableStream({async pull(B){let{done:k,value:g}=await J.read();if(k){let h=t0(`${D}${Z.decode()}`,!0);if(h.ready)B.enqueue(V.encode(h.ready));B.close();return}let b=D+Z.decode(g,{stream:!0}),m=t0(b);if(D=m.pending,m.ready)B.enqueue(V.encode(m.ready))}});return new Response(Y,{status:j.status,statusText:j.statusText,headers:j.headers})}var Ej="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",xj=60000,Cj=60000,Sj=5000,U1=200,r1=240,Rj=r1,yj=1,M1=!1;function U0(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function H(){return performance.now()}function R(j){return Math.round(j*10)/10}function v1(j){return Math.floor(Math.random()*Math.max(0,j))}function fj(){if(M1||!1||!U0())return;M1=!0;let j=100,J=250,Z=H()+j;setInterval(()=>{let V=H(),D=V-Z;if(Z=V+j,D<J)return;q("[perf] opencode event_loop_lag",{lagMs:R(D),thresholdMs:J})},j).unref?.()}function Tj(j){let J=H(),Z={requestId:String(yj++),start:J,last:J,mark(V,D){let Y=H();if(U0())q("[perf] opencode request stage",{requestId:Z.requestId,stage:V,deltaMs:R(Y-Z.last),totalMs:R(Y-Z.start),...D});Z.last=Y},done(V,D){let Y=H();if(U0())q("[perf] opencode request done",{requestId:Z.requestId,stage:V,deltaMs:R(Y-Z.last),totalMs:R(Y-Z.start),...D});Z.last=Y}};if(U0())q("[perf] opencode request start",{requestId:Z.requestId,...j});return Z}async function p(j,J,Z){let V=j.client.session,D=await s0(j.client,J),Y={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:Z,ignored:!0}]}};if(D?.agent)Y.body.agent=D.agent;if(D?.model)Y.body.model=D.model;if(D?.variant)Y.body.variant=D.variant;if(typeof V?.promptAsync==="function"){await V.promptAsync(Y);return}if(typeof V?.prompt==="function"){await Promise.resolve(V.prompt(Y));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function u(){throw Error(Ej)}function Aj(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 kj(j){if(j.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return j.push(F1),!0}var cj=async(j)=>{fj();let{client:J}=j,Z=H1(),V=await C(Z),D=new u1({storage:V,onMainQuotaFetched:async($,W,K)=>{try{let I=await C(Z)??{version:1,accounts:[]};I.quota=I.quota??{},I.quota.mainQuota=$,I.quota.mainQuotaCheckedAt=W,I.quota.mainQuotaToken=K,I.quota.mainLastQuotaApiError=void 0,await a(I,Z)}catch(I){q("[quota] failed to persist main quota",{error:I instanceof Error?I.message:String(I)})}},onApiError:async($)=>{try{let W=await C(Z)??{version:1,accounts:[]};W.quota=W.quota??{},W.quota.mainLastQuotaApiError=$,await a(W,Z)}catch(W){q("[quota] failed to persist backoff state",{error:W instanceof Error?W.message:String(W)})}}}),Y=new T1({quotaManager:D});Y.startBackgroundRefresh();let B=null,k=new d1({loadStorage:()=>C(Z),prepareHeaders:async($,W)=>{if(!b)return $;let K=await b();if(K.type!=="oauth")return $;if(!K.access||K.expires&&K.expires<Date.now()){if(!B)return $;K.access=await B()}if(!K.access)return $;try{let I=JSON.parse(W.bodyText),_=await f0(K.access,typeof I.model==="string"?I.model:void 0);if($.delete("anthropic-beta"),s($,K.access,{body:I,identity:_}),$.set("anthropic-beta",$0($.get("anthropic-beta"),[k1])),I.speed==="fast")B0($)}catch{s($,K.access)}return $},log:q});r({enabled:X0(V),mode:W0(V)}),w0(x0(V)),L0(C0(V));function g($,W){let K=D.getMain(W.mainAccessToken),I=D.getLastApiError(),_=$?.refresh?.mainLastRefreshError,f={main:{quota:K?.quota??null,quotaBackedOff:D.isBackedOff(),quotaBackoffUntil:I?.nextRetryAt,refreshBackedOff:_?i(_,W.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:_?.nextRetryAt},fallbacks:($?.accounts??[]).filter((E)=>E.enabled!==!1).map((E)=>({id:E.id,label:E.label,quota:E.access?D.getFallback(E.id,E.access)?.quota??null:null,enabled:E.enabled!==!1})),activeId:W.activeId,route:W.route,relay:(()=>{let E=m0($);return E?{enabled:!0,transport:E.transport??"http"}:null})(),fastMode:k0(),cacheKeep:{enabled:T0($),window:$?.cacheKeep?.startHour!=null&&$?.cacheKeep?.endHour!=null?`${$.cacheKeep.startHour}-${$.cacheKeep.endHour}`:void 0,trackedSessions:k.trackedCount()},lastUpdated:Date.now()};a1(f).catch((E)=>q("[sidebar] state write failed",{error:E instanceof Error?E.message:String(E)}))}let b=null,m=null,h=0;function t1($){let W=$?.refresh?.refreshBeforeExpiryMinutes??Rj;return Math.max(r1,W)*60000}function e1($){return $?.refresh?.enabled!==!1}async function d0($){if(!$)return;let W=await C(Z),K=W?.refresh?.mainLastRefreshError;if(!W?.refresh||!K?.tokenHash)return;let I=Y0($);if(K.tokenHash===I)return;if(K.nextRetryAt&&K.nextRetryAt>Date.now()){q("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:K.nextRetryAt,retryCount:K.retryCount,remainingMs:K.nextRetryAt-Date.now()});return}W.refresh.mainLastRefreshError=void 0,await a(W,Z),q("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:K.checkedAt,previousNextRetryAt:K.nextRetryAt,previousRetryCount:K.retryCount})}async function jj(){let $=[];if(b)try{let _=await b();if(_.type==="oauth"&&_.access){let f=await D.refreshMain(_.access);$.push({name:"OpenCode anthropic",role:"main",quota:f})}else if(_.type==="oauth")$.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(_){let f=_ instanceof Error?_.message:String(_);$.push({name:"OpenCode anthropic",role:"main",error:f.includes("429")?"Usage API rate limited — try again in a moment":f})}let{storage:W,errors:K}=await Y.refreshQuotaForAllAccounts({force:!0}),I=new Map(K.map((_)=>[_.accountId,_.message]));if($.push(...i1(W,I)),!b)$.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return c1({accounts:$,refreshedAt:Date.now()})}async function Jj($){let W=A1($);if(W.type==="enable"||W.type==="disable"){let f=W.type==="enable",E=await E1(f),t=W0(E);return r({enabled:f,mode:t}),P0({argumentsText:$,enabled:f,mode:t})}if(W.type==="mode"){let f=await x1(W.mode),E=X0(f);return r({enabled:E,mode:W.mode}),P0({argumentsText:$,enabled:E,mode:W.mode})}let K=await C(Z),I=X0(K),_=W0(K);return r({enabled:I,mode:_}),P0({argumentsText:$,enabled:I,mode:_})}async function Zj($){let W=b1($),K=await C(Z);if(W.type==="window")K=await R1(W.startHour,W.endHour);else if(W.type==="disable")K=await y1(!1);let I=m1(K),_=k.stats(I);return h1({argumentsText:$,enabled:g1(K),window:I,hybridActive:T0(K),trackedSessions:_.trackedSessions,nextPrewarmAt:_.nextPrewarmAt})}async function $j($){let W=l1($);if(W.type==="enable"||W.type==="disable"){let _=W.type==="enable";return await C1(_),w0(_),A0({argumentsText:$,enabled:_})}let K=await C(Z),I=x0(K);return w0(I),A0({argumentsText:$,enabled:I})}async function Vj($){let W=p1($);if(W.type==="enable"||W.type==="disable"){let _=W.type==="enable";return await S1(_),L0(_),b0({argumentsText:$,enabled:_})}let K=await C(Z),I=C0(K);return L0(I),b0({argumentsText:$,enabled:I})}async function Dj($){let W=s1($);if(W.type==="mode")return await o1(W.mode),h0({argumentsText:$,mode:W.mode});let K=await C();return h0({argumentsText:$,mode:g0(K)})}return{config:async($)=>{$.command={...$.command??{},[K0]:{template:K0,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[I0]:{template:I0,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[N0]:{template:N0,description:"Show current Claude OAuth quota usage for all accounts."},[z0]:{template:z0,description:"Show or toggle Anthropic request dump capture for debugging."},[O0]:{template:O0,description:"Show or toggle Anthropic fast mode for supported Opus models."},[_0]:{template:_0,description:"Show or change Claude account routing between main-first and fallback-first."}}},"experimental.chat.system.transform":async($,W)=>{if(!Aj($))return;kj(W.system)},"command.execute.before":async($)=>{if($.command===K0)await p(j,$.sessionID,await Jj($.arguments)),u();if($.command===I0)await p(j,$.sessionID,await Zj($.arguments)),u();if($.command===N0){await p(j,$.sessionID,await jj());let W=await C(),K=b?await b().catch(()=>{return}):void 0;g(W,{activeId:"main",route:"main",mainAccessToken:K?.access,mainRefreshToken:K?.refresh}),u()}if($.command===z0)await p(j,$.sessionID,await $j($.arguments)),u();if($.command===O0)await p(j,$.sessionID,await Vj($.arguments)),u();if($.command===_0)await p(j,$.sessionID,await Dj($.arguments)),u()},auth:{provider:"anthropic",async loader($,W){b=$;let K=await $();if(K.type==="oauth"){let f=function(){if(m)clearInterval(m),m=null;let P=async()=>{try{let w=await C(Z);if(!e1(w))return;let v=await $();if(v.type!=="oauth")return;if(await d0(v.refresh),!v.expires)return;let N=v.expires-Date.now(),x=t1(w);if(N>x)return;if(q("[refresh] opencode main oauth background due",{expiresInMs:N,refreshBeforeMs:x}),v.refresh&&i(w?.refresh?.mainLastRefreshError,v.refresh,Date.now())){q("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:w?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:w?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:N});return}if(v.refresh&&w?.refresh?.mainRefreshLeaseUntil&&w.refresh.mainRefreshLeaseUntil>Date.now()&&w.refresh.mainRefreshLeaseTokenHash===Y0(v.refresh))return;await _();let Q=await $();q("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:Q.expires?Q.expires-Date.now():void 0})}catch(w){q("[refresh] opencode main oauth refresh failed",{message:w instanceof Error?w.message:String(w)})}};if(m=setInterval(()=>{P()},xj+v1(Cj)),"unref"in m)m.unref()},E=function(P,w){if(P instanceof Request&&P.body)return!1;return w==null||typeof w==="string"},t=function(P){return P.has("x-parent-session-id")},l0=function(P){return P.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(P)},Xj=function(P){return P?.quota?.enabled===!0};for(let P of Object.values(W.models))P.cost={input:0,output:0,cache:{read:0,write:0}};let I=null;async function _(){if(!I)I=(async()=>{let v=null,N=null,x=null;async function Q(G){let U=await C(Z)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};U.refresh=U.refresh??{},G(U),await a(U,Z)}async function S(G){let U=Date.now()+Sj;while(Date.now()<U){await new Promise((M)=>setTimeout(M,U1+v1(U1)));let X=await $();if(X.type!=="oauth"||!X.access)continue;if((X.access!==G.access||X.refresh!==G.refresh||(X.expires??0)>(G.expires??0)+60000)&&(!X.expires||X.expires>Date.now()))return q("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:X.expires?X.expires-Date.now():void 0}),X.access}return null}for(let G=0;G<=2;G++){let U=null;try{if(G>0){let L=500*2**(G-1);await new Promise((A)=>setTimeout(A,L))}if(U=await $(),!U.refresh)throw Error("Token refresh failed: missing refresh token");let X=await C(Z),O=Y0(U.refresh),M=X?.refresh?.mainLastRefreshError;if(q("[refresh] opencode main oauth refresh check",{attempt:G,expiresInMs:U.expires?U.expires-Date.now():void 0,hasBackoff:Boolean(M),backoffActive:M?i(M,U.refresh,Date.now()):!1,retryCount:M?.retryCount,nextRetryAt:M?.nextRetryAt}),M&&i(M,U.refresh,Date.now()))throw q("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:M.nextRetryAt,retryCount:M.retryCount}),Error(R0(M,Date.now()));if(X?.refresh?.mainRefreshLeaseUntil&&X.refresh.mainRefreshLeaseUntil>Date.now()&&X.refresh.mainRefreshLeaseTokenHash===O){q("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:X.refresh.mainRefreshLeaseUntil});let L=await S(U);if(L)return L;throw Error("Claude OAuth refresh is already in progress")}let z=await q1({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!z){q("[refresh] opencode main oauth refresh skipped file lock");let L=await S(U);if(L)return L;throw Error("Claude OAuth refresh is already in progress")}x=z.release,v=qj(),N=O,await Q((L)=>{L.refresh=L.refresh??{},L.refresh.mainRefreshLeaseId=v??void 0,L.refresh.mainRefreshLeaseUntil=Date.now()+120000,L.refresh.mainRefreshLeaseTokenHash=O});let T=await C(Z);if(q("[refresh] opencode main oauth refresh lease acquired",{attempt:G,leaseUntil:Date.now()+120000}),T?.refresh?.mainRefreshLeaseId!==v||T.refresh.mainRefreshLeaseTokenHash!==O)throw Error("Claude OAuth refresh is already in progress");q("[refresh] opencode main oauth refresh request start",{attempt:G});let F=await B1({refreshToken:U.refresh,maxRetries:0});return await J.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:F.refresh,access:F.access,expires:F.expires}}),await Q((L)=>{if(!L?.refresh)return;if(L.refresh.mainLastRefreshError=void 0,L.refresh.mainRefreshLeaseId===v)L.refresh.mainRefreshLeaseId=void 0,L.refresh.mainRefreshLeaseUntil=void 0,L.refresh.mainRefreshLeaseTokenHash=void 0}),q("[refresh] opencode main oauth refresh succeeded",{attempt:G,expiresInMs:F.expires-Date.now()}),F.access}catch(X){let O=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(G<2&&(O||X instanceof H0&&X.status>=500))continue;q("[refresh] opencode main oauth refresh attempt failed",{attempt:G,error:X instanceof Error?X.message:String(X),transient:O});let M=U?.refresh;if(M&&X instanceof H0)await Q((z)=>{z.refresh=z.refresh??{},z.refresh.mainLastRefreshError=f1({error:X,now:Date.now(),refreshToken:M,previous:z.refresh.mainLastRefreshError})});throw X}finally{if(v)await Q((X)=>{if(!X?.refresh)return;if(X.refresh.mainRefreshLeaseId===v&&X.refresh.mainRefreshLeaseTokenHash===N)X.refresh.mainRefreshLeaseId=void 0,X.refresh.mainRefreshLeaseUntil=void 0,X.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await x?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{I=null});return I}B=_,f(),D.seedFallbacksFromAccounts(V?.accounts??[]),g(V,{activeId:"main",route:"main",mainAccessToken:K.access,mainRefreshToken:K.refresh});async function p0(P,w){if(!P.body||P.status!==200)return w?.mark("inspect_stream_skip",{status:P.status}),{response:P,rateLimited:!1};if(P.headers.get("x-cortexkit-relay-optimistic")==="true")return w?.mark("inspect_stream_skip",{status:P.status,reason:"optimistic_relay"}),{response:P,rateLimited:!1};let v=H(),N=P.body.getReader(),x=[],Q=new TextDecoder,S="",G=0;while(!S.includes(`
4
4
 
5
- `)&&v.length<65536){let{done:D,value:F}=await P.read();if(D)break;if(q.push(F),z+=F.byteLength,v+=Q.decode(F,{stream:!0}),m0(v))break}if(m0(v))return await P.cancel().catch(()=>{}),W?.mark("inspect_stream_first_event",{ms:E(B()-I),bytes:z,rateLimited:!0}),{response:X,rateLimited:!0};let O=new ReadableStream({start(D){for(let F of q)D.enqueue(F)},async pull(D){let{done:F,value:M}=await P.read();if(F){D.close();return}D.enqueue(M)},cancel(D){return P.cancel(D)}});return W?.mark("inspect_stream_first_event",{ms:E(B()-I),bytes:z,rateLimited:!1}),{response:new Response(O,{status:X.status,statusText:X.statusText,headers:X.headers}),rateLimited:!1}}async function h0(X,W,I,P,q="unknown"){let Q=B(),v=X1(X,W),z=v.get("x-session-affinity")||v.get("x-opencode-session"),O=Jj(v);v.delete("x-parent-session-id"),v.delete("x-session-affinity"),v.delete("x-opencode-session");let D=W?.body,F;if(D&&typeof D==="string")try{let m=JSON.parse(D);if(typeof m.model==="string")F=m.model}catch{}let M=await A0(I,F),L=typeof D==="string"?D.length:void 0;if(D&&typeof D==="string"){let m=B(),t=(()=>{if(!b1())return!1;try{return J0(JSON.parse(D).model)}catch{return!1}})();D=await z1(D,{cache1hEnabled:!O&&K0(),cache1hMode:X0(),fastModeEnabled:t,identity:M});try{p(v,I,{body:JSON.parse(D),identity:M})}catch{p(v,I,{identity:M})}if(t)B0(v);P?.mark("rewrite_body",{route:q,ms:E(B()-m),originalBytes:L,rewrittenBytes:D.length,cacheEnabled:!O&&K0(),cacheMode:X0(),fastModeEnabled:t,subagent:O})}let x=Y1(X);if(q==="main"&&typeof D==="string"&&!O&&K0()&&X0()==="hybrid"){let m=await T();if((await V.track({sessionId:z,url:x.url?.toString()??x.input.toString(),headers:v,bodyText:D,storage:m,cacheMode:"hybrid"})).tracked)P?.mark("cachekeep_track",{session:z})}let A=()=>fetch(x.input,{...W,body:D,headers:v,...W1()&&{tls:{rejectUnauthorized:!1}}}),U=B(),o=await l1({config:_,input:x.input,init:W,headers:v,body:D,fallback:A,affinity:z,optimisticResponse:_?.transport==="websocket"});return P?.mark("send_headers_received",{route:q,ms:E(B()-U),status:o.status,relayConfigured:_!=null,totalSendWithAccessMs:E(B()-Q)}),o}async function u0(X,W){let I=Date.now(),P=await R0({accessToken:X});return S={accessToken:X,refreshAfter:S1(P,W,I),quota:P},P}async function Gj(X,W){let I=Date.now();if(S?.accessToken!==X)return await u0(X,W);if(I>=S.refreshAfter)$j(X,W);return S.quota}async function _0(X,W,I,P,q,Q,v){if(!I.length)return q??null;let z=v?.returnLastOnExhausted??!0;await q?.body?.cancel().catch(()=>{});let O=q??null;for(let[D,F]of I.entries()){let M=F.access;if(!M)continue;let L=await h0(X,W,M,Q,`fallback_${D}`);O=L;let x=S0(L.status,P);if(!x){let A=await b0(L,Q);L=A.response,O=L,x=A.rateLimited}if(!x)return await Z.markUsed(F),L;if(D<I.length-1||!z)await L.body?.cancel().catch(()=>{})}return z?O:null}async function Dj(X,W,I,P,q,Q){if(!g0(X,W?.body))return I;let v=B(),z=Q??await T();q?.mark("fallback_load_storage",{ms:E(B()-v),cached:!!Q});let O=I,D=S0(O.status,z);if(!D){let M=await b0(O,q);O=M.response,D=M.rateLimited}if(!D)return O;let F=P;if(!F){let M=B();F=await Z.getUsableFallbackAccounts(),q?.mark("fallback_get_accounts",{ms:E(B()-M),accounts:F.length})}return await _0(X,W,F,z,O,q)??O}return{apiKey:"",async fetch(X,W){let I=W?.body,P=Tj({bodyBytes:typeof I==="string"?I.length:void 0,relayConfigured:_!=null}),q=B(),Q=await $();if(P.mark("get_auth",{ms:E(B()-q),authType:Q.type,hasAccess:Boolean(Q.access)}),Q.type!=="oauth"){let L=await fetch(X,W);return P.done("non_oauth_passthrough",{status:L.status}),L}await i(Q.refresh);let v=B(),z=await T();P.mark("load_storage",{ms:E(B()-v)});let O=g0(X,W?.body),D;if(O&&y0(z)==="fallback-first")try{let L=B();D=await Z.getUsableFallbackAccounts(z),P.mark("fallback_first_get_accounts",{ms:E(B()-L),accounts:D.length});let x=await _0(X,W,D,z,void 0,P,{returnLastOnExhausted:!1});if(x)return P.done("return_fallback_first",{status:x.status}),Z0(x);D=[]}catch(L){P.mark("fallback_first_error",{error:L instanceof Error?L.message:String(L)})}if(!Q.access||!Q.expires||Q.expires<Date.now()){let x=(await T())?.refresh?.mainLastRefreshError;if(Q.refresh&&x&&n(x,Q.refresh,Date.now()))throw H("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:x.nextRetryAt,retryCount:x.retryCount,expiresInMs:Q.expires?Q.expires-Date.now():void 0}),Error(E0(x,Date.now()));H("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(Q.access),expiresInMs:Q.expires?Q.expires-Date.now():void 0,expiredAgoMs:Q.expires&&Q.expires<Date.now()?Date.now()-Q.expires:void 0});let A=B();Q.access=await g(),P.mark("refresh_main_access",{ms:E(B()-A)})}if(!Q.access)throw P.done("missing_access_error"),Error("OAuth access token is missing after refresh");if(O&&Zj(z))try{let L=B(),x=await Gj(Q.access,z);if(P.mark("main_quota_for_routing",{ms:E(B()-L),passes:T0(x,z)}),!T0(x,z)){let A=B();D=await Z.getUsableFallbackAccounts(),P.mark("preselect_fallback_accounts",{ms:E(B()-A),accounts:D.length});let U=await _0(X,W,D,z,void 0,P);if(U)return P.done("return_preselected_fallback",{status:U.status}),Z0(U)}}catch(L){P.mark("main_quota_for_routing_error",{error:L instanceof Error?L.message:String(L)})}let F=await h0(X,W,Q.access,P,"main"),M=await Dj(X,W,F,D,P,z);return P.done("return_response",{status:M.status}),Z0(M)}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let $=await v0("max");return{url:$.url,instructions:"Paste the authorization code here:",method:"code",callback:async(Y)=>{return U0(Y,$.verifier,$.redirectUri,$.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let $=await v0("console");return{url:$.url,instructions:"Paste the authorization code here:",method:"code",callback:async(Y)=>{let w=await U0(Y,$.verifier,$.redirectUri,$.state);if(w.type==="failed")return w;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 ${w.access}`}}).then((S)=>S.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{uj as AnthropicAuthPlugin};
5
+ `)&&S.length<65536){let{done:X,value:O}=await N.read();if(X)break;if(x.push(O),G+=O.byteLength,S+=Q.decode(O,{stream:!0}),l0(S))break}if(l0(S))return await N.cancel().catch(()=>{}),w?.mark("inspect_stream_first_event",{ms:R(H()-v),bytes:G,rateLimited:!0}),{response:P,rateLimited:!0};let U=new ReadableStream({start(X){for(let O of x)X.enqueue(O)},async pull(X){let{done:O,value:M}=await N.read();if(O){X.close();return}X.enqueue(M)},cancel(X){return N.cancel(X)}});return w?.mark("inspect_stream_first_event",{ms:R(H()-v),bytes:G,rateLimited:!1}),{response:new Response(U,{status:P.status,statusText:P.statusText,headers:P.headers}),rateLimited:!1}}async function u0(P,w,v,N,x="unknown",Q){let S=H(),G=Q,U=async()=>{return G??=await C(Z),G},X=z1(P,w),O=X.get("x-session-affinity")||X.get("x-opencode-session"),M=t(X);X.delete("x-parent-session-id"),X.delete("x-session-affinity"),X.delete("x-opencode-session");let z=w?.body,T;if(z&&typeof z==="string")try{let d=JSON.parse(z);if(typeof d.model==="string")T=d.model}catch{}let F=await f0(v,T),L=typeof z==="string"?z.length:void 0;if(z&&typeof z==="string"){let d=H(),e=(()=>{if(!k0())return!1;try{return V0(JSON.parse(z).model)}catch{return!1}})();z=await _1(z,{cache1hEnabled:!M&&Q0(),cache1hMode:G0(),fastModeEnabled:e,identity:F});try{s(X,v,{body:JSON.parse(z),identity:F})}catch{s(X,v,{identity:F})}if(e)B0(X);N?.mark("rewrite_body",{route:x,ms:R(H()-d),originalBytes:L,rewrittenBytes:z.length,cacheEnabled:!M&&Q0(),cacheMode:G0(),fastModeEnabled:e,subagent:M})}let A=O1(P);if(x==="main"&&typeof z==="string"&&!M&&Q0()&&G0()==="hybrid"){let d=await U();if(k.track({sessionId:O,url:A.url?.toString()??A.input.toString(),headers:X,bodyText:z,storage:d,cacheMode:"hybrid"}).tracked)N?.mark("cachekeep_track",{session:O})}let c=()=>fetch(A.input,{...w,body:z,headers:X,...w1()&&{tls:{rejectUnauthorized:!1}}}),n=m0(await U()),Yj=H(),i0=await n1({config:n,input:A.input,init:w,headers:X,body:z,fallback:c,affinity:O,optimisticResponse:n?.transport==="websocket"});return N?.mark("send_headers_received",{route:x,ms:R(H()-Yj),status:i0.status,relayConfigured:n!=null,totalSendWithAccessMs:R(H()-S)}),i0}async function M0(P,w,v,N,x,Q,S){if(!v.length)return x??null;let G=S?.returnLastOnExhausted??!0;await x?.body?.cancel().catch(()=>{});let U=x??null;for(let[X,O]of v.entries()){let M=O.access;if(!M)continue;let z=await u0(P,w,M,Q,`fallback_${X}`,N);U=z;let T=S0(z.status,N);if(!T){let F=await p0(z,Q);z=F.response,U=z,T=F.rateLimited}if(!T){if(await Y.markUsed(O),S?.onSuccess?.(O),M&&D.shouldRefreshOnRequestCount(h))D.refreshFallback(O.id,M).then(()=>S?.onSuccess?.(O)).catch(()=>{});return z}if(X<v.length-1||!G)await z.body?.cancel().catch(()=>{})}return G?U:null}async function Wj(P,w,v,N,x,Q,S){if(!E(P,w?.body))return v;let G=H(),U=Q??await C(Z);x?.mark("fallback_load_storage",{ms:R(H()-G),cached:!!Q});let X=v,O=S0(X.status,U);if(!O){let z=await p0(X,x);X=z.response,O=z.rateLimited}if(!O)return X;let M=N;if(!M){let z=H();M=await Y.getUsableFallbackAccounts(),x?.mark("fallback_get_accounts",{ms:R(H()-z),accounts:M.length})}return await M0(P,w,M,U,X,x,{onSuccess:S})??X}return{apiKey:"",async fetch(P,w){let v=w?.body,N=Tj({bodyBytes:typeof v==="string"?v.length:void 0}),x=H(),Q=await $();if(N.mark("get_auth",{ms:R(H()-x),authType:Q.type,hasAccess:Boolean(Q.access)}),Q.type!=="oauth"){let F=await fetch(P,w);return N.done("non_oauth_passthrough",{status:F.status}),F}await d0(Q.refresh);let S=H(),G=await C();N.mark("load_storage",{ms:R(H()-S)}),D.updateStorage(G),D.seedFallbacksFromAccounts(G?.accounts??[]);let U=E(P,w?.body);if(U)h++;let X=(F,L)=>g(G,{activeId:F,route:L,mainAccessToken:Q.access,mainRefreshToken:Q.refresh}),O;if(U&&g0(G)==="fallback-first")try{let F=H();O=await Y.getUsableFallbackAccounts(G),N.mark("fallback_first_get_accounts",{ms:R(H()-F),accounts:O.length});let L=await M0(P,w,O,G,void 0,N,{returnLastOnExhausted:!1,onSuccess:(A)=>X(A.id,"fallback-first")});if(L)return N.done("return_fallback_first",{status:L.status}),D0(L);O=[]}catch(F){N.mark("fallback_first_error",{error:F instanceof Error?F.message:String(F)})}if(!Q.access||!Q.expires||Q.expires<Date.now()){let L=(await C())?.refresh?.mainLastRefreshError;if(Q.refresh&&L&&i(L,Q.refresh,Date.now()))throw q("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:L.nextRetryAt,retryCount:L.retryCount,expiresInMs:Q.expires?Q.expires-Date.now():void 0}),Error(R0(L,Date.now()));q("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(Q.access),expiresInMs:Q.expires?Q.expires-Date.now():void 0,expiredAgoMs:Q.expires&&Q.expires<Date.now()?Date.now()-Q.expires:void 0});let A=H();Q.access=await _(),N.mark("refresh_main_access",{ms:R(H()-A)})}if(!Q.access)throw N.done("missing_access_error"),Error("OAuth access token is missing after refresh");if(U&&Xj(G))try{let F=H(),L=D.getMain(Q.access)?.quota;if(!L)L=await D.refreshMain(Q.access);else if(D.needsRefresh(h))D.refreshMain(Q.access).then(()=>g(G,{activeId:"main",route:"main",mainAccessToken:Q.access,mainRefreshToken:Q.refresh})).catch(()=>{});if(g(G,{activeId:"main",route:"main",mainAccessToken:Q.access,mainRefreshToken:Q.refresh}),N.mark("main_quota_for_routing",{ms:R(H()-F),passes:y0(L,G)}),!y0(L,G)){let A=H();O=await Y.getUsableFallbackAccounts(G),N.mark("preselect_fallback_accounts",{ms:R(H()-A),accounts:O.length});let c=await M0(P,w,O,G,void 0,N,{onSuccess:(n)=>X(n.id,"fallback")});if(c)return N.done("return_preselected_fallback",{status:c.status}),D0(c)}}catch(F){N.mark("main_quota_for_routing_error",{error:F instanceof Error?F.message:String(F)})}let M=await u0(P,w,Q.access,N,"main",G),z=!1,T=await Wj(P,w,M,O,N,G,(F)=>{z=!0,X(F.id,"fallback")});if(!z)X("main","main");return N.done("return_response",{status:T.status}),D0(T)}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let $=await q0("max");return{url:$.url,instructions:"Paste the authorization code here:",method:"code",callback:async(W)=>{return E0(W,$.verifier,$.redirectUri,$.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let $=await q0("console");return{url:$.url,instructions:"Paste the authorization code here:",method:"code",callback:async(W)=>{let K=await E0(W,$.verifier,$.redirectUri,$.state);if(K.type==="failed")return K;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${K.access}`}}).then((_)=>_.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{cj as AnthropicAuthPlugin};
@@ -0,0 +1,42 @@
1
+ export interface QuotaWindow {
2
+ usedPercent: number;
3
+ remainingPercent: number;
4
+ resetsAt?: string;
5
+ }
6
+ export interface AccountQuota {
7
+ five_hour?: QuotaWindow;
8
+ seven_day?: QuotaWindow;
9
+ }
10
+ export interface SidebarAccountState {
11
+ id: string;
12
+ label: string | undefined;
13
+ quota: AccountQuota | null;
14
+ enabled: boolean;
15
+ }
16
+ export interface SidebarState {
17
+ main: {
18
+ quota: AccountQuota | null;
19
+ quotaBackedOff?: boolean;
20
+ quotaBackoffUntil?: number;
21
+ refreshBackedOff?: boolean;
22
+ refreshBackoffUntil?: number;
23
+ };
24
+ fallbacks: SidebarAccountState[];
25
+ activeId: string | undefined;
26
+ route: string;
27
+ relay: {
28
+ enabled: boolean;
29
+ transport: string;
30
+ } | null;
31
+ fastMode: boolean;
32
+ cacheKeep?: {
33
+ enabled: boolean;
34
+ window?: string;
35
+ trackedSessions?: number;
36
+ };
37
+ lastUpdated: number;
38
+ }
39
+ export declare function getSidebarStateFile(): string;
40
+ export declare const DEFAULT_SIDEBAR_STATE: SidebarState;
41
+ export declare function getSidebarState(): Promise<SidebarState>;
42
+ export declare function setSidebarState(state: SidebarState): Promise<void>;
@@ -0,0 +1 @@
1
+ import{Aa as c,Ba as d,ya as a,za as b}from"./index-nfgq84t3.js";export{d as setSidebarState,a as getSidebarStateFile,c as getSidebarState,b as DEFAULT_SIDEBAR_STATE};
package/dist/tui.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+ import type { TuiPluginModule } from '@opencode-ai/plugin/tui';
3
+ declare const plugin: TuiPluginModule & {
4
+ id: string;
5
+ };
6
+ export default plugin;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-anthropic-auth",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -13,8 +13,16 @@
13
13
  ".": {
14
14
  "import": "./dist/index.js",
15
15
  "types": "./dist/index.d.ts"
16
+ },
17
+ "./tui": {
18
+ "types": "./dist/tui.d.ts",
19
+ "import": "./src/tui.tsx"
16
20
  }
17
21
  },
22
+ "oc-plugin": [
23
+ "server",
24
+ "tui"
25
+ ],
18
26
  "bin": {
19
27
  "opencode-anthropic-auth": "dist/cli.js"
20
28
  },
@@ -23,11 +31,13 @@
23
31
  },
24
32
  "files": [
25
33
  "dist",
34
+ "src/tui.tsx",
35
+ "src/sidebar-state.ts",
26
36
  "README.md",
27
37
  "LICENSE"
28
38
  ],
29
39
  "scripts": {
30
- "build": "rm -rf dist && bun build src/index.ts src/cli.ts --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --minify && tsc -p tsconfig.build.json --emitDeclarationOnly",
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",
31
41
  "build:dev": "rm -rf dist && tsc -p tsconfig.build.json",
32
42
  "dev": "bun ../../scripts/dev.ts",
33
43
  "dev:clean": "bun ../../scripts/dev-clean.ts",
@@ -41,6 +51,9 @@
41
51
  "@opencode-ai/plugin": "*"
42
52
  },
43
53
  "dependencies": {
44
- "@cortexkit/anthropic-auth-core": "1.4.0"
54
+ "@cortexkit/anthropic-auth-core": "1.5.0",
55
+ "@opentui/core": ">=0.1.92",
56
+ "@opentui/solid": ">=0.1.92",
57
+ "solid-js": "^1.9.10"
45
58
  }
46
59
  }
@@ -0,0 +1,79 @@
1
+ export interface QuotaWindow {
2
+ usedPercent: number
3
+ remainingPercent: number
4
+ resetsAt?: string
5
+ }
6
+
7
+ export interface AccountQuota {
8
+ five_hour?: QuotaWindow
9
+ seven_day?: QuotaWindow
10
+ }
11
+
12
+ export interface SidebarAccountState {
13
+ id: string
14
+ label: string | undefined
15
+ quota: AccountQuota | null
16
+ enabled: boolean
17
+ }
18
+
19
+ export interface SidebarState {
20
+ main: {
21
+ quota: AccountQuota | null
22
+ quotaBackedOff?: boolean
23
+ quotaBackoffUntil?: number
24
+ refreshBackedOff?: boolean
25
+ refreshBackoffUntil?: number
26
+ }
27
+ fallbacks: SidebarAccountState[]
28
+ activeId: string | undefined
29
+ route: string
30
+ relay: { enabled: boolean; transport: string } | null
31
+ fastMode: boolean
32
+ cacheKeep?: {
33
+ enabled: boolean
34
+ window?: string
35
+ trackedSessions?: number
36
+ }
37
+ lastUpdated: number
38
+ }
39
+
40
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
41
+ import { tmpdir } from 'node:os'
42
+ import { dirname, join } from 'node:path'
43
+
44
+ const STATE_FILE_ENV = 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE'
45
+ const DEFAULT_STATE_DIR = join(tmpdir(), 'opencode-anthropic-auth')
46
+ const DEFAULT_STATE_FILE = join(DEFAULT_STATE_DIR, 'sidebar-state.json')
47
+
48
+ export function getSidebarStateFile(): string {
49
+ return process.env[STATE_FILE_ENV] || DEFAULT_STATE_FILE
50
+ }
51
+
52
+ export const DEFAULT_SIDEBAR_STATE: SidebarState = {
53
+ main: { quota: null },
54
+ fallbacks: [],
55
+ activeId: undefined,
56
+ route: 'main',
57
+ relay: null,
58
+ fastMode: false,
59
+ lastUpdated: 0,
60
+ }
61
+
62
+ export async function getSidebarState(): Promise<SidebarState> {
63
+ try {
64
+ const raw = await readFile(getSidebarStateFile(), 'utf8')
65
+ return JSON.parse(raw) as SidebarState
66
+ } catch {
67
+ return DEFAULT_SIDEBAR_STATE
68
+ }
69
+ }
70
+
71
+ export async function setSidebarState(state: SidebarState): Promise<void> {
72
+ try {
73
+ const stateFile = getSidebarStateFile()
74
+ await mkdir(dirname(stateFile), { recursive: true })
75
+ await writeFile(stateFile, JSON.stringify(state), 'utf8')
76
+ } catch {
77
+ // Best-effort — sidebar is non-critical
78
+ }
79
+ }