@cortexkit/opencode-anthropic-auth 1.4.1 → 1.6.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 +54 -4
- package/dist/cli.js +1 -1
- package/dist/index-q0d64q8d.js +2 -0
- package/dist/index-zx0zb5c8.js +335 -0
- package/dist/index.js +7 -3
- package/dist/sidebar-state.d.ts +47 -0
- package/dist/sidebar-state.js +1 -0
- package/dist/tui.d.ts +6 -0
- package/package.json +16 -3
- package/src/sidebar-state.ts +107 -0
- package/src/tui.tsx +497 -0
- package/dist/index-wc8ekdxb.js +0 -325
package/dist/index.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
-
import{$ as
|
|
1
|
+
import{$ as v1,A as p1,B as l1,Ba as f0,C as u1,Ca as j1,D as c0,Da as Pj,E as M0,Ea as zj,F as i1,Fa as J1,G as $0,H as n0,I as c1,J as P0,K as z0,L as v0,M as n1,N as o1,O as s1,P as r1,Q as F0,R as q0,S as E0,T as Q0,U as t1,V as C0,W as B1,X as H1,Y as o0,Z as U1,_ as M1,a as I1,aa as x0,b as O1,ba as a1,c as _0,ca as e1,d as B0,da as jj,e as L1,ea as Jj,f as K0,fa as s0,g as k1,ga as Zj,h as N1,ha as $j,i as w1,ia as S0,j as _1,ja as R0,k as d0,ka as Gj,l as f1,la as r0,m as p0,ma as T0,n as l0,na as t0,o as F,oa as y0,p as m1,pa as Vj,q as R,qa as a0,r as Y0,ra as A0,s as b1,sa as Dj,t as H0,ta as Kj,u as U0,ua as k0,v as h1,va as Xj,w as g1,wa as Wj,x as u0,xa as e0,y as d1,z as i0,za as Yj}from"./index-zx0zb5c8.js";import{Ja as Qj}from"./index-q0d64q8d.js";import{randomUUID as pj}from"node:crypto";function Z0(j){return typeof j==="object"&&j!==null}function Fj(j){if(Array.isArray(j))return j;if(Z0(j)&&Array.isArray(j.data))return j.data;return[]}function qj(j){if(!Z0(j)||!Z0(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function G1(j){if(!Z0(j)||!Z0(j.info))return null;let J=j.info,Z=Z0(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,Y=typeof Z?.modelID==="string"?Z.modelID:typeof J.modelID==="string"?J.modelID:void 0,v=typeof Z?.variant==="string"?Z.variant:typeof J.variant==="string"?J.variant:void 0;if(!G&&(!V||!Y)&&!v)return null;let u={};if(G)u.agent=G;if(V&&Y)u.model={providerID:V,modelID:Y};if(v)u.variant=v;return u}function V1(j,J){return{agent:j.agent??J.agent,model:j.model??J.model,variant:j.variant??J.variant}}function D1(j){return Boolean(j.agent&&j.model&&j.variant)}async function K1(j,J){if(!j||!J)return null;let Z=j;if(typeof Z.session?.messages!=="function")return null;let G=[];try{G=Fj(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 Y=G.length-1;Y>=0;Y--){if(qj(G[Y])!=="assistant")continue;let v=G1(G[Y]);if(!v)continue;if(V=V1(V,v),D1(V))return V}for(let Y=G.length-1;Y>=0;Y--){let v=G1(G[Y]);if(!v)continue;if(V=V1(V,v),D1(V))return V}if(!V.agent&&!V.model&&!V.variant)return null;return V}function X1(j){return`${I1}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function F1(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 W1(j){let J=F1(j);if(J.startsWith("aft_"))return J;if(Ej.has(J))return`aft_${J}`;return null}function q1(j,J){let Z=new Headers;if(j instanceof Request)j.headers.forEach((V,Y)=>{Z.set(Y,V)});let G=J?.headers;if(G){if(G instanceof Headers)G.forEach((V,Y)=>{Z.set(Y,V)});else if(Array.isArray(G))for(let V of G){let[Y,v]=V;if(typeof v<"u")Z.set(Y,String(v))}else for(let[V,Y]of Object.entries(G))if(typeof Y<"u")Z.set(V,String(Y))}return Z}function g0(j){return j.set("anthropic-beta",_0(j.get("anthropic-beta"),[O1])),j}function X0(j,J,Z={}){return M1(j,J,Z)}function Cj(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((J)=>({...J,name:J.name?X1(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:X1(Z.name)};return Z});return J});return JSON.stringify(v1(j))}function b0(j){return j.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(J,Z,G)=>{if(Z)return`"name": "${W1(G)??F1(G)}"`;let V=W1(G);return V?`"name": "${V}"`:J})}function Y1(j,J=!1){if(J)return{ready:b0(j),pending:""};let Z=j.length,G='"name"',V=Math.max(0,j.length-G.length+1);for(let v=V;v<j.length;v++)if(G.startsWith(j.slice(v))){Z=Math.min(Z,v);break}let Y=j.lastIndexOf(G);if(Y!==-1){let v=j.slice(Y);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(v))Z=Math.min(Z,Y)}if(Z<j.length)return{ready:b0(j.slice(0,Z)),pending:j.slice(Z)};return{ready:b0(j),pending:""}}function E1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function xj(){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 C1(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=xj();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 L0(j){let G=j.split(/\n\n+/).filter((V)=>{if(V.includes(L1))return!1;for(let Y of w1)if(V.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 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(D?.length)for(let h of D){let p=h.quota;if(!p)continue;let{five_hour:c,seven_day:i}=p;if(!c&&!i)continue;let s=h.label||"alt",V0=X===h.id?"active":"idle",r=$1(c?.resetsAt),D0=[`${s} · ${V0}${r?` (${r})`:""}`];if(c)D0.push(O0("5h",c.usedPercent)),P=Math.max(P,c.usedPercent);if(i)D0.push(O0("7d",i.usedPercent)),P=Math.max(P,i.usedPercent);W.push(D0.join(`
|
|
5
|
+
`))}if(!W.length)return;let x=W.join(`
|
|
4
6
|
|
|
5
|
-
`)
|
|
7
|
+
`),E=P>=90?"error":P>=70?"warning":"info";J.tui?.showToast?.({body:{title:"Claude Quota",message:x,variant:E,duration:E==="error"?8000:5000}})?.catch?.(()=>{})}return{config:async($)=>{$.command={...$.command??{},[F0]:{template:F0,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[x0]:{template:x0,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[k0]:{template:k0,description:"Show current Claude OAuth quota usage for all accounts."},[S0]:{template:S0,description:"Show or toggle Anthropic request dump capture for debugging."},[T0]:{template:T0,description:"Show or toggle Anthropic fast mode for supported Opus models."},[f0]:{template:f0,description:"Show or change Claude account routing between main-first and fallback-first."},[A0]:{template:A0,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."}}},"experimental.chat.system.transform":async($,D)=>{if(!tj($))return;aj(D.system)},"command.execute.before":async($)=>{if($.command===F0)await t(j,$.sessionID,await wj($.arguments)),a();if($.command===x0)await t(j,$.sessionID,await _j($.arguments)),a();if($.command===k0){await t(j,$.sessionID,await Nj());let D=await R(),X=d?await d().catch(()=>{return}):void 0;o(D,{activeId:"main",route:"main",mainAccessToken:X?.access,mainRefreshToken:X?.refresh}),a()}if($.command===S0)await t(j,$.sessionID,await Bj($.arguments)),a();if($.command===T0)await t(j,$.sessionID,await Hj($.arguments)),a();if($.command===f0)await t(j,$.sessionID,await Uj($.arguments)),a();if($.command===A0){let D=await R(),X=o1(D),W=(D?.accounts??[]).filter((x)=>x.enabled!==!1).map((x)=>x.id),P=Dj({argumentsText:$.arguments,config:X,accountIds:W});if(P.updatedConfig)await s1(P.updatedConfig);await t(j,$.sessionID,P.text),a()}},auth:{provider:"anthropic",async loader($,D){d=$;let X=await $();if(X.type==="oauth"){let x=function(){if(j0)clearInterval(j0),j0=null;let Q=async()=>{try{let L=await R(Z);if(!Lj(L))return;let U=await $();if(U.type!=="oauth")return;if(await Z1(U.refresh),!U.expires)return;let N=U.expires-Date.now(),S=Oj(L);if(N>S)return;if(F("[refresh] opencode main oauth background due",{expiresInMs:N,refreshBeforeMs:S}),U.refresh&&$0(L?.refresh?.mainLastRefreshError,U.refresh,Date.now())){F("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:L?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:L?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:N});return}if(U.refresh&&L?.refresh?.mainRefreshLeaseUntil&&L.refresh.mainRefreshLeaseUntil>Date.now()&&L.refresh.mainRefreshLeaseTokenHash===M0(U.refresh))return;await P();let I=await $();F("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:I.expires?I.expires-Date.now():void 0})}catch(L){F("[refresh] opencode main oauth refresh failed",{message:L instanceof Error?L.message:String(L)})}};if(j0=setInterval(()=>{Q()},uj+A1(ij)),"unref"in j0)j0.unref()},E=function(Q,L){if(Q instanceof Request&&Q.body)return!1;return L==null||typeof L==="string"},h=function(Q){return Q.has("x-parent-session-id")},p=function(Q){return Q.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(Q)},c=function(Q){return Q?.quota?.enabled===!0},n=function(Q){return V.getFallback(Q.id,Q.access)?.quota??Q.quota};for(let Q of Object.values(D.models))Q.cost={input:0,output:0,cache:{read:0,write:0}};let W=null;async function P(){if(!W)W=(async()=>{let U=null,N=null,S=null;async function I(z){let H=await R(Z)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};H.refresh=H.refresh??{},z(H),await Y0(H,Z)}async function T(z){let H=Date.now()+cj;while(Date.now()<H){await new Promise((w)=>setTimeout(w,T1+A1(T1)));let K=await $();if(K.type!=="oauth"||!K.access)continue;if((K.access!==z.access||K.refresh!==z.refresh||(K.expires??0)>(z.expires??0)+60000)&&(!K.expires||K.expires>Date.now()))return F("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:K.expires?K.expires-Date.now():void 0}),K.access}return null}for(let z=0;z<=2;z++){let H=null;try{if(z>0){let C=500*2**(z-1);await new Promise((B)=>setTimeout(B,C))}if(H=await $(),!H.refresh)throw Error("Token refresh failed: missing refresh token");let K=await R(Z),_=M0(H.refresh),w=K?.refresh?.mainLastRefreshError;if(F("[refresh] opencode main oauth refresh check",{attempt:z,expiresInMs:H.expires?H.expires-Date.now():void 0,hasBackoff:Boolean(w),backoffActive:w?$0(w,H.refresh,Date.now()):!1,retryCount:w?.retryCount,nextRetryAt:w?.nextRetryAt}),w&&$0(w,H.refresh,Date.now()))throw F("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:w.nextRetryAt,retryCount:w.retryCount}),Error(n0(w,Date.now()));if(K?.refresh?.mainRefreshLeaseUntil&&K.refresh.mainRefreshLeaseUntil>Date.now()&&K.refresh.mainRefreshLeaseTokenHash===_){F("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:K.refresh.mainRefreshLeaseUntil});let C=await T(H);if(C)return C;throw Error("Claude OAuth refresh is already in progress")}let O=await b1({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!O){F("[refresh] opencode main oauth refresh skipped file lock");let C=await T(H);if(C)return C;throw Error("Claude OAuth refresh is already in progress")}S=O.release,U=pj(),N=_,await I((C)=>{C.refresh=C.refresh??{},C.refresh.mainRefreshLeaseId=U??void 0,C.refresh.mainRefreshLeaseUntil=Date.now()+120000,C.refresh.mainRefreshLeaseTokenHash=_});let g=await R(Z);if(F("[refresh] opencode main oauth refresh lease acquired",{attempt:z,leaseUntil:Date.now()+120000}),g?.refresh?.mainRefreshLeaseId!==U||g.refresh.mainRefreshLeaseTokenHash!==_)throw Error("Claude OAuth refresh is already in progress");F("[refresh] opencode main oauth refresh request start",{attempt:z});let m=await f1({refreshToken:H.refresh,maxRetries:0});return await J.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:m.refresh,access:m.access,expires:m.expires}}),await I((C)=>{if(!C?.refresh)return;if(C.refresh.mainLastRefreshError=void 0,C.refresh.mainRefreshLeaseId===U)C.refresh.mainRefreshLeaseId=void 0,C.refresh.mainRefreshLeaseUntil=void 0,C.refresh.mainRefreshLeaseTokenHash=void 0}),F("[refresh] opencode main oauth refresh succeeded",{attempt:z,expiresInMs:m.expires-Date.now()}),m.access}catch(K){let _=K instanceof Error&&(K.message.includes("fetch failed")||("code"in K)&&(K.code==="ECONNRESET"||K.code==="ECONNREFUSED"||K.code==="ETIMEDOUT"||K.code==="UND_ERR_CONNECT_TIMEOUT"));if(z<2&&(_||K instanceof d0&&K.status>=500))continue;F("[refresh] opencode main oauth refresh attempt failed",{attempt:z,error:K instanceof Error?K.message:String(K),transient:_});let w=H?.refresh;if(w&&K instanceof d0)await I((O)=>{O.refresh=O.refresh??{},O.refresh.mainLastRefreshError=i1({error:K,now:Date.now(),refreshToken:w,previous:O.refresh.mainLastRefreshError})});throw K}finally{if(U)await I((K)=>{if(!K?.refresh)return;if(K.refresh.mainRefreshLeaseId===U&&K.refresh.mainRefreshLeaseTokenHash===N)K.refresh.mainRefreshLeaseId=void 0,K.refresh.mainRefreshLeaseUntil=void 0,K.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await S?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{W=null});return W}v=P,x(),V.seedFallbacksFromAccounts(G?.accounts??[]),o(G,{activeId:"main",route:"main",mainAccessToken:X.access,mainRefreshToken:X.refresh});async function i(Q,L){if(!Q.body||Q.status!==200)return L?.mark("inspect_stream_skip",{status:Q.status}),{response:Q,rateLimited:!1};if(Q.headers.get("x-cortexkit-relay-optimistic")==="true")return L?.mark("inspect_stream_skip",{status:Q.status,reason:"optimistic_relay"}),{response:Q,rateLimited:!1};let U=q(),N=Q.body.getReader(),S=[],I=new TextDecoder,T="",z=0;while(!T.includes(`
|
|
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};
|
|
@@ -0,0 +1,47 @@
|
|
|
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>;
|
|
43
|
+
export declare function resolveActiveAccount(state: SidebarState): {
|
|
44
|
+
id: string;
|
|
45
|
+
name: string;
|
|
46
|
+
quota: AccountQuota | null;
|
|
47
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ga as a,Ha as b,Ia as c,Ja as d,Ka as e}from"./index-q0d64q8d.js";export{d as setSidebarState,e as resolveActiveAccount,a as getSidebarStateFile,c as getSidebarState,b as DEFAULT_SIDEBAR_STATE};
|
package/dist/tui.d.ts
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-anthropic-auth",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.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.
|
|
54
|
+
"@cortexkit/anthropic-auth-core": "1.6.0",
|
|
55
|
+
"@opentui/core": ">=0.3.1",
|
|
56
|
+
"@opentui/solid": ">=0.3.1",
|
|
57
|
+
"solid-js": "^1.9.10"
|
|
45
58
|
}
|
|
46
59
|
}
|
|
@@ -0,0 +1,107 @@
|
|
|
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
|
+
}
|
|
80
|
+
|
|
81
|
+
// Resolve the currently-active account from activeId for the collapsed sidebar
|
|
82
|
+
// view. activeId === 'main' (or undefined/unmatched/disabled) → the main
|
|
83
|
+
// account; otherwise the enabled fallback whose id matches.
|
|
84
|
+
export function resolveActiveAccount(state: SidebarState): {
|
|
85
|
+
id: string
|
|
86
|
+
name: string
|
|
87
|
+
quota: AccountQuota | null
|
|
88
|
+
} {
|
|
89
|
+
const activeId = state.activeId
|
|
90
|
+
if (activeId && activeId !== 'main') {
|
|
91
|
+
// `account.enabled` is defensive: writeSidebarState already filters disabled
|
|
92
|
+
// accounts out of state.fallbacks, so in normal operation every entry is
|
|
93
|
+
// enabled. Kept so this pure helper stays correct for any caller and is
|
|
94
|
+
// exercised directly by the unit tests.
|
|
95
|
+
const fallback = state.fallbacks.find(
|
|
96
|
+
(account) => account.enabled && account.id === activeId,
|
|
97
|
+
)
|
|
98
|
+
if (fallback) {
|
|
99
|
+
return {
|
|
100
|
+
id: fallback.id,
|
|
101
|
+
name: fallback.label ?? fallback.id,
|
|
102
|
+
quota: fallback.quota,
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return { id: 'main', name: 'main', quota: state.main.quota }
|
|
107
|
+
}
|