@cortexkit/opencode-anthropic-auth 1.10.1 → 1.10.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Oa as I,Qa as $,m as w,n as k,p as A,r as R,t as d,u as l,v as p}from"./index-
|
|
2
|
+
import{Oa as I,Qa as $,m as w,n as k,p as A,r as R,t as d,u as l,v as p}from"./index-tes31apx.js";import"./index-p8j7mmfc.js";import{stdin as E,stdout as U}from"node:process";import{createInterface as _}from"node:readline/promises";function g(){return{version:1,main:{type:"opencode",provider:"anthropic"},fallbackOn:[401,403,429],refresh:{enabled:!0,intervalMinutes:10,refreshBeforeExpiryMinutes:240},quota:{enabled:!0,checkIntervalMinutes:5,minimumRemaining:{five_hour:10,seven_day:20},failClosedOnUnknownQuota:!0},accounts:[]}}function y(){console.log(`Usage:
|
|
3
3
|
opencode-anthropic-auth login [label]
|
|
4
4
|
opencode-anthropic-auth api add [label]
|
|
5
5
|
opencode-anthropic-auth list
|
|
@@ -4,7 +4,7 @@ ${f.stack}`:""}`;return` ${JSON.stringify(f)}`}function Q(f,_){if(J_)return;try{
|
|
|
4
4
|
`),o.length>=l0)qf();else i0()}catch{}}function B(f,_){Q(`[relay] ${f}`,_)}if(!J_)process.on("exit",qf);import{createHash as q_,randomUUID as lf}from"node:crypto";import{mkdir as p0,readFile as Rf,rename as d0,rm as W_,stat as v0,writeFile as Tf}from"node:fs/promises";import{homedir as u0}from"node:os";import{dirname as x_,join as a}from"node:path";var r0=globalThis.setTimeout.bind(globalThis),n0=globalThis.clearTimeout.bind(globalThis),P_="anthropic-auth.json",g0="anthropic-auth-state.json",s0="https://api.anthropic.com/api/oauth/usage";function X(f){return f.type==="oauth"}function nE(f){return f.type==="api"}function c0(f){let _=f?.trim();if(!_)return!1;try{let D=new URL(_);return(D.protocol==="http:"||D.protocol==="https:")&&!D.username&&!D.password}catch{return!1}}function gE(f){return f.costZeroing?.enabled!==!1}var t0=[401,403,429],R_=240,o0=R_;var e0=300000,a0=3600000,fD=86400000,_D=60000,DD=900000,ED=300000,$D=5,Y_={five_hour:0,seven_day:0},mD=!0,MD=60000,CD=60000,LD=600000,OD=1e4,UD=100;function HD(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return a(process.env.XDG_CONFIG_HOME||a(u0(),".config"),"opencode")}function G(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||a(HD(),P_)}function kf(f=G()){let _=process.env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim();if(_)return _;return f.endsWith(P_)?a(x_(f),g0):`${f}.state.json`}function N(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function X_(f){return{id:typeof f.id==="string"&&f.id.trim()?f.id.trim():lf(),label:typeof f.label==="string"?f.label:void 0,enabled:typeof f.enabled==="boolean"?f.enabled:void 0,addedAt:typeof f.addedAt==="number"?f.addedAt:void 0,lastUsed:typeof f.lastUsed==="number"?f.lastUsed:void 0}}function bD(f){if(!N(f))return null;if(f.type==="api"){let _=typeof f.baseURL==="string"?f.baseURL.trim():"",D=typeof f.apiKey==="string"?f.apiKey.trim():"";if(!c0(_))return null;let E=f.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...X_(f),type:"api",apiKey:D||void 0,baseURL:_,authHeader:E}}if(f.type!=="oauth")return null;if(typeof f.refresh!=="string"||!f.refresh.trim())return null;return{...X_(f),type:"oauth",access:typeof f.access==="string"?f.access:void 0,refresh:f.refresh,expires:typeof f.expires==="number"?f.expires:void 0,lastRefreshedAt:typeof f.lastRefreshedAt==="number"?f.lastRefreshedAt:void 0,lastRefreshError:Z_(f.lastRefreshError),lastQuotaRefreshError:Z_(f.lastQuotaRefreshError),quota:ND(f.quota)}}function Z_(f){if(!N(f))return;if(typeof f.message!=="string")return;let _=Number(f.checkedAt);if(!Number.isFinite(_))return;let D=Number(f.nextRetryAt),E=Number(f.retryCount);return{message:f.message,checkedAt:_,nextRetryAt:Number.isFinite(D)?D:void 0,retryCount:Number.isFinite(E)?E:void 0,tokenHash:typeof f.tokenHash==="string"?f.tokenHash:void 0}}function ND(f){if(!N(f))return;let _={};for(let D of["five_hour","seven_day"]){let E=f[D];if(!N(E))continue;let $=Number(E.usedPercent),m=Number(E.remainingPercent),M=Number(E.checkedAt);if(!Number.isFinite($)||!Number.isFinite(m)||!Number.isFinite(M))continue;_[D]={usedPercent:$,remainingPercent:m,checkedAt:M,resetsAt:typeof E.resetsAt==="string"?E.resetsAt:void 0}}return Object.keys(_).length?_:void 0}function SD(f){if(!N(f)||!Array.isArray(f.accounts))return null;return{version:1,main:{type:"opencode",provider:"anthropic"},routing:N(f.routing)?f.routing:void 0,fallbackOn:Array.isArray(f.fallbackOn)?f.fallbackOn.filter((_)=>Number.isInteger(_)):void 0,refresh:N(f.refresh)?f.refresh:void 0,quota:N(f.quota)?f.quota:void 0,claudeCache:N(f.claudeCache)?f.claudeCache:void 0,dump:N(f.dump)?f.dump:void 0,claudeFast:N(f.claudeFast)?f.claudeFast:void 0,costZeroing:N(f.costZeroing)?f.costZeroing:void 0,cacheKeep:N(f.cacheKeep)?f.cacheKeep:void 0,relay:N(f.relay)?f.relay:void 0,killswitch:N(f.killswitch)?f.killswitch:void 0,accounts:f.accounts.map(bD).filter((_)=>_!=null)}}async function Uf(f){try{return{exists:!0,value:JSON.parse(await Rf(f,"utf8"))}}catch(_){if(_.code==="ENOENT")return{exists:!1,value:null};return{exists:!1,value:null}}}function T(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function BD(f,_){if(!N(f))return f;let D=N(_)?_:{},E=N(D.main)?D.main:void 0,$=N(D.accounts)?D.accounts:{},m=N(f.quota)?f.quota:{},M=N(f.refresh)?f.refresh:{},C=E??m,L=E??M,O=Array.isArray(f.accounts)?f.accounts.map((U)=>{if(!N(U))return U;let S=typeof U.id==="string"&&N($[U.id])?$[U.id]:{};return{...U,...S}}):[];return{...f,refresh:T({...M,mainLastRefreshError:L.lastRefreshError,mainRefreshLeaseId:L.refreshLeaseId,mainRefreshLeaseUntil:L.refreshLeaseUntil,mainRefreshLeaseTokenHash:L.refreshLeaseTokenHash}),quota:T({...m,mainQuota:C.quota,mainQuotaCheckedAt:C.quotaCheckedAt,mainQuotaToken:C.quotaToken,mainLastQuotaApiError:C.lastQuotaApiError}),accounts:O}}async function V(f=G()){let _=await Uf(f);if(!_.exists)return null;let D=await Uf(kf(f));return SD(BD(_.value,D.value))}async function AD(f){let _=await Uf(f);return N(_.value)?_.value:{}}function KD(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function FD(f){return T({id:f.id,label:f.label,type:f.type,enabled:f.enabled,addedAt:f.addedAt,baseURL:f.type==="api"?f.baseURL:void 0,authHeader:f.type==="api"?f.authHeader:void 0})}function T_(f){if(f.type==="api")return T({apiKey:f.apiKey,lastUsed:f.lastUsed});return T({access:f.access,refresh:f.refresh,expires:f.expires,lastUsed:f.lastUsed,lastRefreshedAt:f.lastRefreshedAt,lastRefreshError:f.lastRefreshError,lastQuotaRefreshError:f.lastQuotaRefreshError,quota:f.quota})}function ff(f){return Math.max(f?.five_hour?.checkedAt??0,f?.seven_day?.checkedAt??0)}function jD(f,_){if(!N(f))return _;let D=f,E=ff(D.quota),$=ff(_.quota);if(E>$){let M=Boolean(D.access&&_.access&&D.access!==_.access),C=D.lastRefreshedAt??0,L=_.lastRefreshedAt??0;if(M&&L<=C){let O={...D};if(typeof _.lastUsed==="number"&&(typeof D.lastUsed!=="number"||_.lastUsed>D.lastUsed))O.lastUsed=_.lastUsed;return O}return{...D,..._,quota:D.quota,lastQuotaRefreshError:D.lastQuotaRefreshError}}let m={...D,..._};if(!("lastQuotaRefreshError"in _))delete m.lastQuotaRefreshError;if(!("lastRefreshError"in _))delete m.lastRefreshError;return m}function zD(f){let _=f.refresh?T({enabled:f.refresh.enabled,intervalMinutes:f.refresh.intervalMinutes,refreshBeforeExpiryMinutes:f.refresh.refreshBeforeExpiryMinutes}):void 0,D=f.quota?T({enabled:f.quota.enabled,checkIntervalMinutes:f.quota.checkIntervalMinutes,refreshEveryNRequests:f.quota.refreshEveryNRequests,minimumRemaining:f.quota.minimumRemaining,failClosedOnUnknownQuota:f.quota.failClosedOnUnknownQuota,showToasts:f.quota.showToasts}):void 0;return KD({version:1,main:f.main,routing:f.routing,fallbackOn:f.fallbackOn,refresh:_,quota:D,claudeCache:f.claudeCache,dump:f.dump,claudeFast:f.claudeFast,costZeroing:f.costZeroing,cacheKeep:f.cacheKeep,relay:f.relay,killswitch:f.killswitch,accounts:f.accounts.map(FD)})}function GD(f){let _=Object.fromEntries(f.accounts.map((D)=>[D.id,T_(D)]));return{version:1,main:T({quota:f.quota?.mainQuota,quotaCheckedAt:f.quota?.mainQuotaCheckedAt,quotaToken:f.quota?.mainQuotaToken,lastQuotaApiError:f.quota?.mainLastQuotaApiError,lastRefreshError:f.refresh?.mainLastRefreshError,refreshLeaseId:f.refresh?.mainRefreshLeaseId,refreshLeaseUntil:f.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:f.refresh?.mainRefreshLeaseTokenHash}),accounts:_}}async function wf(f,_){await p0(x_(f),{recursive:!0});let D=`${f}.${lf()}.tmp`;await Tf(D,`${JSON.stringify(_,null,2)}
|
|
5
5
|
`,{encoding:"utf8",mode:384}),await d0(D,f)}async function q(f,_=G()){let E={...await AD(_),...zD(f)};await wf(_,E),await wf(kf(_),GD(f))}function JD(f,_){f.main=f.main??{};let D=typeof f.main.quotaCheckedAt==="number"?f.main.quotaCheckedAt:ff(f.main.quota),E=typeof _.quota?.mainQuotaCheckedAt==="number"?_.quota.mainQuotaCheckedAt:ff(_.quota?.mainQuota);if(D>E)return;f.main.quota=_.quota?.mainQuota,f.main.quotaCheckedAt=_.quota?.mainQuotaCheckedAt,f.main.quotaToken=_.quota?.mainQuotaToken,f.main.lastQuotaApiError=_.quota?.mainLastQuotaApiError}function WD(f,_){f.main=f.main??{},f.main.lastRefreshError=_.refresh?.mainLastRefreshError,f.main.refreshLeaseId=_.refresh?.mainRefreshLeaseId,f.main.refreshLeaseUntil=_.refresh?.mainRefreshLeaseUntil,f.main.refreshLeaseTokenHash=_.refresh?.mainRefreshLeaseTokenHash}function yf(f){if(Array.isArray(f))return f.map(yf);if(!N(f))return f;return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0).map(([_,D])=>[_,yf(D)]))}async function YD(f,_=G(),D={mainQuota:!0,mainRefresh:!0,accounts:!0}){let E=kf(_),$=(await Uf(E)).value,m=N($)?{...$,version:1}:{version:1};if(D.mainQuota)JD(m,f);if(D.mainRefresh)WD(m,f);if(D.accounts){let M=D.accounts===!0?null:new Set(D.accounts);m.accounts={...N(m.accounts)?m.accounts:{}};for(let C of f.accounts){if(M&&!M.has(C.id))continue;m.accounts[C.id]=jD(m.accounts[C.id],T_(C))}if(M){for(let C of M)if(!f.accounts.some((L)=>L.id===C))delete m.accounts[C]}}await wf(E,yf(m))}async function Hf(f){let D=`${f.path??G()}.${f.name}.lock`,E=a(D,"owner.json"),$=lf(),m=f.now??Date.now,M=null,C=!1;async function L(){try{return JSON.parse(await Rf(D,"utf8"))}catch(F){if(F.code!=="EISDIR")throw F;return JSON.parse(await Rf(E,"utf8"))}}async function O(){await Tf(D,`${JSON.stringify({ownerId:$,expiresAt:m()+f.ttlMs})}
|
|
6
6
|
`,{encoding:"utf8",mode:384})}async function U(){try{return await Tf(D,`${JSON.stringify({ownerId:$,expiresAt:m()+f.ttlMs})}
|
|
7
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(F){let j=F.code;if(j==="EEXIST"||j==="EISDIR")return!1;throw F}}function S(){if(!f.renew||C)return;let F=f.renewIntervalMs??Math.max(1000,Math.floor(f.ttlMs/3));if(M=r0(()=>{(async()=>{try{let j=await L(),P=m();if(C||j?.ownerId!==$||Number(j?.expiresAt)<=P)return;await O(),S()}catch{}})()},F),"unref"in M)M.unref()}if(!await U()){try{let F=await L();if(Number(F?.expiresAt)>m())return null}catch{try{if((await v0(D)).mtimeMs+f.ttlMs>Date.now())return null}catch{return null}}if(await W_(D,{recursive:!0,force:!0}).catch(()=>{}),!await U())return null}return S(),{release:async()=>{if(C=!0,M)n0(M),M=null;try{if((await L())?.ownerId!==$)return}catch{return}await W_(D,{recursive:!0,force:!0}).catch(()=>{})}}}function sE(f){return f?.claudeCache?.enabled===!0}function XD(f){return typeof f==="string"&&B_.includes(f)?f:Of}function ZD(f){return XD(f?.claudeCache?.mode)}async function cE(f,_,D=G()){let E=await V(D)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.claudeCache={...E.claudeCache??{},enabled:f,mode:_??ZD(E)},await q(E,D),E}async function tE(f,_=G()){let D=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.claudeCache={...D.claudeCache??{},enabled:D.claudeCache?.enabled===!0,mode:f},await q(D,_),D}function oE(f){return f?.dump?.enabled===!0}async function eE(f,_=G()){let D=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.dump={...D.dump??{},enabled:f},await q(D,_),D}function aE(f){return f?.claudeFast?.enabled===!0}async function f$(f,_=G()){let D=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.claudeFast={...D.claudeFast??{},enabled:f},await q(D,_),D}async function _$(f,_,D=G()){let E=await V(D)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.cacheKeep={enabled:!0,startHour:f,endHour:_},await q(E,D),E}async function D$(f,_=G()){let D=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.cacheKeep={...D.cacheKeep??{},enabled:f},await q(D,_),D}function hD(f){return f?.fallbackOn?.length?f.fallbackOn:t0}function E$(f,_){return hD(_).includes(f)}function w_(f){let _=f?.quota?.minimumRemaining||{};return{five_hour:_.five_hour??_["5h"]??Y_.five_hour,seven_day:_.seven_day??_["1w"]??Y_.seven_day}}function _f(f){return f?.quota?.enabled!==!1}function VD(f){return f?.refresh?.enabled!==!1}function ID(f){return Math.floor(Math.random()*Math.max(0,f))}function QD(f){let _=f?.refresh?.refreshBeforeExpiryMinutes??o0;return Math.max(R_,_)*60000}function y_(f){return q_("sha256").update(f).digest("hex")}function qD(f){if(f instanceof y)return f.status===429||f.status>=500;if(!(f instanceof Error))return!1;return f.message.includes("fetch failed")||"code"in f&&(f.code==="ECONNRESET"||f.code==="ECONNREFUSED"||f.code==="ETIMEDOUT"||f.code==="UND_ERR_CONNECT_TIMEOUT")}function xD(f){let _=y_(f.refreshToken),E=(f.previous?.tokenHash===_?f.previous.retryCount??0:0)+1,$;if(f.error instanceof y&&f.error.retryAfter)$=f.error.retryAfter*1000;else if(qD(f.error))$=Math.min(a0,e0*2**Math.min(E-1,6));else $=fD;return{message:Df(f.error),checkedAt:f.now,nextRetryAt:f.now+$,retryCount:E,tokenHash:_}}function e(f,_,D){if(!f?.nextRetryAt||f.nextRetryAt<=D)return!1;if(!_)return!0;return f.tokenHash===y_(_)}function xf(f,_){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function bf(f){let D=(f.previous?.retryCount??0)+1,E=d_(f.error)?Math.min(DD,_D*2**Math.min(D-1,6)):ED;return{message:Df(f.error),checkedAt:f.now,nextRetryAt:f.now+E,retryCount:D}}function g(f,_){if(!f?.nextRetryAt||f.nextRetryAt<=_)return!1;return!0}function $$(f,_){return`Quota API backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function Z(f){let _=f?.quota?.checkIntervalMinutes??$D;return Math.max(1,_)*60000}function l_(f){if(!f?.quota?.mainQuota||!f.quota.mainQuotaCheckedAt)return null;return{quota:f.quota.mainQuota,checkedAt:f.quota.mainQuotaCheckedAt,tokenFingerprint:f.quota.mainQuotaToken}}function i_(f){let _=f?.quota?.refreshEveryNRequests;return typeof _==="number"&&Number.isFinite(_)&&_>0?Math.floor(_):0}function pf(f){return f?.quota?.failClosedOnUnknownQuota??mD}function k_(f,_){if(!_f(_))return!0;let D=w_(_);for(let E of["five_hour","seven_day"]){let $=f?.[E];if(!$)return!pf(_);if($.remainingPercent<D[E])return!1}return!0}var h={five_hour:5,seven_day:10};function h_(f){return{five_hour:f?.five_hour??f?.["5h"]??h.five_hour,seven_day:f?.seven_day??f?.["1w"]??h.seven_day}}function PD(f){return f?.killswitch?.enabled===!0}function RD(f,_){if(!f?.killswitch)return h;if(_&&f.killswitch.accounts?.[_])return h_(f.killswitch.accounts[_]);return h_(f.killswitch.main)}function m$(f,_,D){if(!PD(_))return!0;let E=RD(_,D),$=!1;for(let m of["five_hour","seven_day"]){let M=f?.[m];if(!M){$=!0;continue}if(M.remainingPercent<E[m])return!1}if($)return!pf(_);return!0}function M$(f,_,D){let E=[],$=[f,..._.map((m)=>m.quota)];for(let m of $)for(let M of["five_hour","seven_day"]){let C=m?.[M]?.resetsAt;if(!C)continue;let L=Date.parse(C);if(Number.isFinite(L)&&L>D)E.push(L)}if(!E.length)return 300;return Math.max(1,Math.ceil((Math.min(...E)-D)/1000))+60}function C$(f){return f?.killswitch??{enabled:!1}}async function L$(f,_=G()){let D=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.killswitch=f,await q(D,_),D}function df(f,_,D){if(!_f(_))return D+Z(_);let E=w_(_),$=[];for(let m of["five_hour","seven_day"]){let M=f?.[m];if(!M)return D+Z(_);if(M.remainingPercent>=E[m])continue;let C=M.resetsAt?Date.parse(M.resetsAt):Number.NaN;if(!Number.isFinite(C)||C<=D)return D+Z(_);$.push(C)}if(!$.length)return D+Z(_);return Math.min(...$)+60000}function l(f,_,D){return!f.access||!f.expires||f.expires-D<=QD(_)}function p_(f,_,D){if(!_f(_))return!0;let E=Z(_);return["five_hour","seven_day"].every(($)=>{let m=f?.[$];return Boolean(m&&D-m.checkedAt<E)})}function Pf(f,_,D){return!p_(f.quota,_,D)}function TD(f,_){if(!f)return!1;if(!f.resetsAt)return!0;let D=Date.parse(f.resetsAt);return!Number.isFinite(D)||D>_}function wD(f,_){return["five_hour","seven_day"].every((D)=>TD(f?.[D],_))}function d_(f){let _=Df(f);if(/Claude quota check failed: (429|5\d\d)\b/.test(_))return!0;if(!(f instanceof Error))return!1;let D=f.code;return _.includes("fetch failed")||D==="ECONNRESET"||D==="ECONNREFUSED"||D==="ETIMEDOUT"||D==="UND_ERR_CONNECT_TIMEOUT"}function yD(f,_,D,E){return d_(D)&&k_(f.quota,_)&&wD(f.quota,E)}function V_(f){if(!Number.isFinite(f))return 0;if(f<0)return 0;if(f>100)return 100;return f}function I_(f,_){if(typeof f?.utilization!=="number")return;let D=V_(f.utilization);return{usedPercent:D,remainingPercent:V_(100-D),resetsAt:f.resets_at,checkedAt:_}}async function Nf(f){let D=await(f.fetchImpl??fetch)(s0,{method:"GET",headers:{Authorization:`Bearer ${f.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${R}`}});if(!D.ok){let m=await D.text().catch(()=>"");throw Error(`Claude quota check failed: ${D.status} — ${m}`)}let E=f.now?.()??Date.now(),$=await D.json();return{five_hour:I_($.five_hour,E),seven_day:I_($.seven_day,E)}}function W(f,_){let D=f.accounts.findIndex((E)=>E.id===_.id);if(D>=0)f.accounts[D]=_}function Df(f){return f instanceof Error?f.message:String(f)}function v_(f,_,D){f.lastRefreshError=xD({error:_,now:D,refreshToken:f.refresh,previous:f.lastRefreshError})}function Q_(f,_,D){if(f.lastQuotaRefreshError=bf({error:_,now:D,previous:f.lastQuotaRefreshError}),_ instanceof y)v_(f,_,D)}function lD(f){return`fallback-oauth-refresh-${q_("sha256").update(f).digest("hex").slice(0,16)}`}class iD{now;fetchImpl;configPath;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;constructor(f={}){this.now=f.now??Date.now,this.fetchImpl=f.fetchImpl??fetch,this.configPath=f.configPath??G(),this.quotaManager=f.quotaManager??null,this.onFallbackStorageChanged=f.onFallbackStorageChanged}seedFallbackQuota(f,_){if(!this.quotaManager)return;if(!f.quota)return;let D=Math.max(f.quota.five_hour?.checkedAt??0,f.quota.seven_day?.checkedAt??0);if(D<=0)return;let E=this.quotaManager.getFallback(f.id,f.access);if(E&&E.checkedAt>=D)return;let $=Z(_);this.quotaManager.setFallback(f.id,{quota:f.quota,refreshAfter:D+$,checkedAt:D},f.access)}async load(){return V(this.configPath)}async save(f,_){await YD(f,this.configPath,{accounts:_??!0})}startBackgroundRefresh(){let f=async()=>{await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()};if(f().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{f().catch(()=>{})},MD+ID(CD)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts(f){let _=f!==void 0?f:await this.load();if(!_)return[];let D=[],E=!1;for(let $ of _.accounts){if($.enabled===!1||!X($))continue;try{let m=$;if(l(m,_,this.now())){let C=m.lastRefreshError;if(C&&e(C,m.refresh,this.now()))throw Error(xf(C,this.now()));m=await this.refreshAccount(m,_),E=!0}if(this.seedFallbackQuota(m,_),(this.quotaManager?this.quotaManager.isFallbackStale(m.id,m.access):Pf(m,_,this.now()))&&!g(m.lastQuotaRefreshError,this.now()))m=await this.refreshAccountQuota(m,_),E=!0;if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount(m),_))D.push(m)}catch(m){if(yD($,_,m,this.now()))Q("[refresh] fallback quota using cached quota after refresh error",{accountId:$.id,error:Df(m)}),D.push($);else if(!pf(_))D.push($)}}if(E)await this.save(_);return D}async markUsed(f){let _=await this.load();if(!_)return;let D=_.accounts.find((E)=>E.id===f.id);if(!D)return;D.lastUsed=this.now(),await this.save(_)}accountPassesQuotaPolicy(f,_){return k_(f.quota,_)}quotaPolicyAccount(f){if(!this.quotaManager)return f;let _=this.quotaManager.getFallback(f.id,f.access)?.quota;return _?{...f,quota:_}:f}async refreshDueAccounts(){let f=await this.load();if(!f||!VD(f))return;let _=!1;for(let D of f.accounts){if(D.enabled===!1||!X(D))continue;if(!l(D,f,this.now()))continue;if(e(D.lastRefreshError,D.refresh,this.now()))continue;try{Q("[refresh] fallback oauth background due",{accountId:D.id,expiresInMs:D.expires?D.expires-this.now():void 0}),await this.refreshAccount(D,f),_=!0}catch(E){Q("[refresh] fallback oauth background failed",{accountId:D.id,error:E instanceof Error?E.message:String(E)}),v_(D,E,this.now()),W(f,D),_=!0}}if(_)await this.save(f)}async refreshQuotaForDueAccounts(){let f=await this.load();if(!f||!_f(f))return;let _=!1;for(let D of f.accounts){if(D.enabled===!1||!X(D))continue;let E=D;try{if(l(E,f,this.now())){if(e(E.lastRefreshError,E.refresh,this.now()))continue;E=await this.refreshAccount(E,f),_=!0}if(g(E.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(E,f),!(this.quotaManager?this.quotaManager.isFallbackStale(E.id,E.access):Pf(E,f,this.now())))continue;await this.refreshAccountQuota(E,f),_=!0}catch($){Q_(D,$,this.now()),W(f,D),_=!0}}if(_)await this.save(f),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(f={}){let _=await this.load(),D=[];if(!_||!_f(_))return{storage:_,errors:D};let E=f.force??!1,$=!1;for(let m of _.accounts){if(m.enabled===!1||!X(m))continue;let M=m;try{if(l(M,_,this.now())){let C=M.lastRefreshError;if(C&&e(C,M.refresh,this.now()))throw Error(xf(C,this.now()));M=await this.refreshAccount(M,_),$=!0}if(!E&&!Pf(M,_,this.now())){if(M.lastQuotaRefreshError)M.lastQuotaRefreshError=void 0,W(_,M),$=!0;continue}await this.refreshAccountQuota(M,_),$=!0}catch(C){Q_(m,C,this.now()),W(_,m),$=!0,D.push({accountId:m.id,message:Df(C)})}}if($)await this.save(_);return{storage:_,errors:D}}async refreshAccount(f,_,D={}){let E=this.refreshPromises.get(f.id);if(E){let M=await E;return W(_,M),M}let $=this.refreshAccountNow(f,_,D).finally(()=>{this.refreshPromises.delete(f.id)});this.refreshPromises.set(f.id,$);let m=await $;return W(_,m),m}async waitForConcurrentFallbackRefresh(f,_,D,E){let $=Date.now()+OD;while(Date.now()<$){await new Promise((O)=>setTimeout(O,UD));let m=await this.load(),M=m?.accounts.find((O)=>O.id===f.id&&X(O));if(!M)continue;if((M.access!==D.access||M.refresh!==D.refresh||(M.expires??0)>(D.expires??0)+60000)&&(E.force||!l(M,m,this.now())))return W(_,M),Q("[refresh] fallback oauth joined concurrent refresh",{accountId:M.id,expiresInMs:M.expires?M.expires-this.now():void 0}),M;let L=M.lastRefreshError;if(L&&e(L,M.refresh,this.now()))throw W(_,M),Error(xf(L,this.now()))}return null}async refreshAccountNow(f,_,D){let E=await this.load(),$=E?.accounts.find((C)=>C.id===f.id&&X(C));if($&&!D.force&&!l($,E,this.now()))return W(_,$),$;let m=$??f,M=await Hf({name:lD(m.id),ttlMs:LD,path:this.configPath,now:this.now,renew:!0});if(!M){Q("[refresh] fallback oauth refresh skipped file lock",{accountId:m.id});let C=await this.waitForConcurrentFallbackRefresh(f,_,m,D);if(C)return C;throw Error("Fallback OAuth refresh is already in progress")}try{if(E=await this.load(),$=E?.accounts.find((O)=>O.id===f.id&&X(O)),$&&!D.force&&!l($,E,this.now()))return W(_,$),$;m=$??m;let C=m.refresh;Q("[refresh] fallback oauth refresh request start",{accountId:m.id,force:D.force===!0,expiresInMs:m.expires?m.expires-this.now():void 0});let L=await F_({refreshToken:C,fetchImpl:this.fetchImpl,now:this.now});return m.access=L.access,m.refresh=L.refresh,m.expires=L.expires,m.lastRefreshedAt=L.expires-L.expiresIn*1000,m.lastRefreshError=void 0,W(_,m),await this.save(_),Q("[refresh] fallback oauth refresh succeeded",{accountId:m.id,expiresInMs:m.expires?m.expires-this.now():void 0}),m}finally{await M.release()}}async refreshAccountQuota(f,_){let D=f;if(!D.access)throw Error(`Fallback account ${f.id} has no access token`);let E=(C)=>this.quotaManager?this.quotaManager.refreshFallback(D.id,C):Nf({accessToken:C,fetchImpl:this.fetchImpl,now:this.now}),$=this.now();try{D.quota=await E(D.access)}catch(C){if(!(C instanceof Error?C.message:String(C)).includes("Claude quota check failed: 401"))throw C;if(D=await this.refreshAccount(f,_,{force:!0}),!D.access)throw C;D.quota=await E(D.access)}let m=await this.load(),M=m?.accounts.find((C)=>C.id===D.id&&X(C));if(m&&M&&M.access!==D.access)return this.seedFallbackQuota(M,m),W(_,M),M;if(m&&M?.access===D.access&&M.quota&&ff(M.quota)>=$&&p_(M.quota,m,this.now()))return this.seedFallbackQuota(M,m),W(_,M),M;if(D.lastQuotaRefreshError=void 0,W(_,D),this.quotaManager&&D.quota){let C=this.now();this.quotaManager.setFallback(D.id,{quota:D.quota,refreshAfter:C+Z(_),checkedAt:C},D.access)}return D}}var H$="claude-cache",u_="## Claude Cache Status",kD="## Claude Cache Enabled",pD="## Claude Cache Disabled",dD="## Claude Cache Usage",vD="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",Sf=!1,Bf=Of;function b$(){return Sf}function N$(){return Bf}function S$(f){Sf=f.enabled,Bf=f.mode}function uD(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&_[0]==="on")return{type:"enable"};if(_.length===1&&_[0]==="off")return{type:"disable"};if(_.length===2&&_[0]==="mode"&&(_[1]==="explicit"||_[1]==="automatic"||_[1]==="hybrid"))return{type:"mode",mode:_[1]};return{type:"usage"}}function Ef(f){let _=f?.enabled??Sf,D=f?.mode??Bf;return[u_,"",`- Enabled: ${_?"enabled":"disabled"}`,`- Mode: ${D}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Scope: main sessions only; subagent sessions keep default ephemeral cache behavior","- Modes: explicit = existing OpenCode breakpoints; automatic = top-level cache_control only; hybrid = system + messages[0] + top-level cache_control","- TTL: 1h when enabled for main sessions; default ephemeral cache behavior otherwise"].join(`
|
|
7
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(F){let j=F.code;if(j==="EEXIST"||j==="EISDIR")return!1;throw F}}function S(){if(!f.renew||C)return;let F=f.renewIntervalMs??Math.max(1000,Math.floor(f.ttlMs/3));if(M=r0(()=>{(async()=>{try{let j=await L(),P=m();if(C||j?.ownerId!==$||Number(j?.expiresAt)<=P)return;await O(),S()}catch{}})()},F),"unref"in M)M.unref()}if(!await U()){try{let F=await L();if(Number(F?.expiresAt)>m())return null}catch{try{if((await v0(D)).mtimeMs+f.ttlMs>Date.now())return null}catch{return null}}if(await W_(D,{recursive:!0,force:!0}).catch(()=>{}),!await U())return null}return S(),{release:async()=>{if(C=!0,M)n0(M),M=null;try{if((await L())?.ownerId!==$)return}catch{return}await W_(D,{recursive:!0,force:!0}).catch(()=>{})}}}function sE(f){return f?.claudeCache?.enabled===!0}function XD(f){return typeof f==="string"&&B_.includes(f)?f:Of}function ZD(f){return XD(f?.claudeCache?.mode)}async function cE(f,_,D=G()){let E=await V(D)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.claudeCache={...E.claudeCache??{},enabled:f,mode:_??ZD(E)},await q(E,D),E}async function tE(f,_=G()){let D=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.claudeCache={...D.claudeCache??{},enabled:D.claudeCache?.enabled===!0,mode:f},await q(D,_),D}function oE(f){return f?.dump?.enabled===!0}async function eE(f,_=G()){let D=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.dump={...D.dump??{},enabled:f},await q(D,_),D}function aE(f){return f?.claudeFast?.enabled===!0}async function f$(f,_=G()){let D=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.claudeFast={...D.claudeFast??{},enabled:f},await q(D,_),D}async function _$(f,_,D=G()){let E=await V(D)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return E.cacheKeep={enabled:!0,startHour:f,endHour:_},await q(E,D),E}async function D$(f,_=G()){let D=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.cacheKeep={...D.cacheKeep??{},enabled:f},await q(D,_),D}function hD(f){return f?.fallbackOn?.length?f.fallbackOn:t0}function E$(f,_){return hD(_).includes(f)}function w_(f){let _=f?.quota?.minimumRemaining||{};return{five_hour:_.five_hour??_["5h"]??Y_.five_hour,seven_day:_.seven_day??_["1w"]??Y_.seven_day}}function _f(f){return f?.quota?.enabled!==!1}function VD(f){return f?.refresh?.enabled!==!1}function ID(f){return Math.floor(Math.random()*Math.max(0,f))}function QD(f){let _=f?.refresh?.refreshBeforeExpiryMinutes??o0;return Math.max(R_,_)*60000}function y_(f){return q_("sha256").update(f).digest("hex")}function qD(f){if(f instanceof y)return f.status===429||f.status>=500;if(!(f instanceof Error))return!1;return f.message.includes("fetch failed")||"code"in f&&(f.code==="ECONNRESET"||f.code==="ECONNREFUSED"||f.code==="ETIMEDOUT"||f.code==="UND_ERR_CONNECT_TIMEOUT")}function xD(f){let _=y_(f.refreshToken),E=(f.previous?.tokenHash===_?f.previous.retryCount??0:0)+1,$;if(f.error instanceof y&&f.error.retryAfter)$=f.error.retryAfter*1000;else if(qD(f.error))$=Math.min(a0,e0*2**Math.min(E-1,6));else $=fD;return{message:Df(f.error),checkedAt:f.now,nextRetryAt:f.now+$,retryCount:E,tokenHash:_}}function e(f,_,D){if(!f?.nextRetryAt||f.nextRetryAt<=D)return!1;if(!_)return!0;return f.tokenHash===y_(_)}function xf(f,_){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function bf(f){let D=(f.previous?.retryCount??0)+1,E=d_(f.error)?Math.min(DD,_D*2**Math.min(D-1,6)):ED;return{message:Df(f.error),checkedAt:f.now,nextRetryAt:f.now+E,retryCount:D}}function g(f,_){if(!f?.nextRetryAt||f.nextRetryAt<=_)return!1;return!0}function $$(f,_){return`Quota API backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function Z(f){let _=f?.quota?.checkIntervalMinutes??$D;return Math.max(1,_)*60000}function l_(f){if(!f?.quota?.mainQuota||!f.quota.mainQuotaCheckedAt)return null;return{quota:f.quota.mainQuota,checkedAt:f.quota.mainQuotaCheckedAt,tokenFingerprint:f.quota.mainQuotaToken}}function i_(f){let _=f?.quota?.refreshEveryNRequests;return typeof _==="number"&&Number.isFinite(_)&&_>0?Math.floor(_):0}function pf(f){return f?.quota?.failClosedOnUnknownQuota??mD}function k_(f,_){if(!_f(_))return!0;let D=w_(_);for(let E of["five_hour","seven_day"]){let $=f?.[E];if(!$)return!pf(_);if($.remainingPercent<D[E])return!1}return!0}var h={five_hour:5,seven_day:10};function h_(f){return{five_hour:f?.five_hour??f?.["5h"]??h.five_hour,seven_day:f?.seven_day??f?.["1w"]??h.seven_day}}function PD(f){return f?.killswitch?.enabled===!0}function RD(f,_){if(!f?.killswitch)return h;if(_&&f.killswitch.accounts?.[_])return h_(f.killswitch.accounts[_]);return h_(f.killswitch.main)}function m$(f,_,D){if(!PD(_))return!0;let E=RD(_,D),$=!1;for(let m of["five_hour","seven_day"]){let M=f?.[m];if(!M){$=!0;continue}if(M.remainingPercent<E[m])return!1}if($)return!pf(_);return!0}function M$(f,_,D){let E=[],$=[f,..._.map((m)=>m.quota)];for(let m of $)for(let M of["five_hour","seven_day"]){let C=m?.[M]?.resetsAt;if(!C)continue;let L=Date.parse(C);if(Number.isFinite(L)&&L>D)E.push(L)}if(!E.length)return 300;return Math.max(1,Math.ceil((Math.min(...E)-D)/1000))+60}function C$(f){return f?.killswitch??{enabled:!1}}async function L$(f,_=G()){let D=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return D.killswitch=f,await q(D,_),D}function df(f,_,D){if(!_f(_))return D+Z(_);let E=w_(_),$=[];for(let m of["five_hour","seven_day"]){let M=f?.[m];if(!M)return D+Z(_);if(M.remainingPercent>=E[m])continue;let C=M.resetsAt?Date.parse(M.resetsAt):Number.NaN;if(!Number.isFinite(C)||C<=D)return D+Z(_);$.push(C)}if(!$.length)return D+Z(_);return Math.min(...$)+60000}function l(f,_,D){return!f.access||!f.expires||f.expires-D<=QD(_)}function p_(f,_,D){if(!_f(_))return!0;let E=Z(_);return["five_hour","seven_day"].every(($)=>{let m=f?.[$];return Boolean(m&&D-m.checkedAt<E)})}function Pf(f,_,D){return!p_(f.quota,_,D)}function TD(f,_){if(!f)return!1;if(!f.resetsAt)return!0;let D=Date.parse(f.resetsAt);return!Number.isFinite(D)||D>_}function wD(f,_){return["five_hour","seven_day"].every((D)=>TD(f?.[D],_))}function d_(f){let _=Df(f);if(/Claude quota check failed: (429|5\d\d)\b/.test(_))return!0;if(_.includes("Quota refresh is already in progress"))return!0;if(!(f instanceof Error))return!1;let D=f.code;return _.includes("fetch failed")||D==="ECONNRESET"||D==="ECONNREFUSED"||D==="ETIMEDOUT"||D==="UND_ERR_CONNECT_TIMEOUT"}function yD(f,_,D,E){return d_(D)&&k_(f.quota,_)&&wD(f.quota,E)}function V_(f){if(!Number.isFinite(f))return 0;if(f<0)return 0;if(f>100)return 100;return f}function I_(f,_){if(typeof f?.utilization!=="number")return;let D=V_(f.utilization);return{usedPercent:D,remainingPercent:V_(100-D),resetsAt:f.resets_at,checkedAt:_}}async function Nf(f){let D=await(f.fetchImpl??fetch)(s0,{method:"GET",headers:{Authorization:`Bearer ${f.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${R}`}});if(!D.ok){let m=await D.text().catch(()=>"");throw Error(`Claude quota check failed: ${D.status} — ${m}`)}let E=f.now?.()??Date.now(),$=await D.json();return{five_hour:I_($.five_hour,E),seven_day:I_($.seven_day,E)}}function W(f,_){let D=f.accounts.findIndex((E)=>E.id===_.id);if(D>=0)f.accounts[D]=_}function Df(f){return f instanceof Error?f.message:String(f)}function v_(f,_,D){f.lastRefreshError=xD({error:_,now:D,refreshToken:f.refresh,previous:f.lastRefreshError})}function Q_(f,_,D){if(f.lastQuotaRefreshError=bf({error:_,now:D,previous:f.lastQuotaRefreshError}),_ instanceof y)v_(f,_,D)}function lD(f){return`fallback-oauth-refresh-${q_("sha256").update(f).digest("hex").slice(0,16)}`}class iD{now;fetchImpl;configPath;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;constructor(f={}){this.now=f.now??Date.now,this.fetchImpl=f.fetchImpl??fetch,this.configPath=f.configPath??G(),this.quotaManager=f.quotaManager??null,this.onFallbackStorageChanged=f.onFallbackStorageChanged}seedFallbackQuota(f,_){if(!this.quotaManager)return;if(!f.quota)return;let D=Math.max(f.quota.five_hour?.checkedAt??0,f.quota.seven_day?.checkedAt??0);if(D<=0)return;let E=this.quotaManager.getFallback(f.id,f.access);if(E&&E.checkedAt>=D)return;let $=Z(_);this.quotaManager.setFallback(f.id,{quota:f.quota,refreshAfter:D+$,checkedAt:D},f.access)}async load(){return V(this.configPath)}async save(f,_){await YD(f,this.configPath,{accounts:_??!0})}startBackgroundRefresh(){let f=async()=>{await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()};if(f().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{f().catch(()=>{})},MD+ID(CD)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts(f){let _=f!==void 0?f:await this.load();if(!_)return[];let D=[],E=!1;for(let $ of _.accounts){if($.enabled===!1||!X($))continue;try{let m=$;if(l(m,_,this.now())){let C=m.lastRefreshError;if(C&&e(C,m.refresh,this.now()))throw Error(xf(C,this.now()));m=await this.refreshAccount(m,_),E=!0}if(this.seedFallbackQuota(m,_),(this.quotaManager?this.quotaManager.isFallbackStale(m.id,m.access):Pf(m,_,this.now()))&&!g(m.lastQuotaRefreshError,this.now()))m=await this.refreshAccountQuota(m,_),E=!0;if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount(m),_))D.push(m)}catch(m){if(yD($,_,m,this.now()))Q("[refresh] fallback quota using cached quota after refresh error",{accountId:$.id,error:Df(m)}),D.push($);else if(!pf(_))D.push($)}}if(E)await this.save(_);return D}async markUsed(f){let _=await this.load();if(!_)return;let D=_.accounts.find((E)=>E.id===f.id);if(!D)return;D.lastUsed=this.now(),await this.save(_)}accountPassesQuotaPolicy(f,_){return k_(f.quota,_)}quotaPolicyAccount(f){if(!this.quotaManager)return f;let _=this.quotaManager.getFallback(f.id,f.access)?.quota;return _?{...f,quota:_}:f}async refreshDueAccounts(){let f=await this.load();if(!f||!VD(f))return;let _=!1;for(let D of f.accounts){if(D.enabled===!1||!X(D))continue;if(!l(D,f,this.now()))continue;if(e(D.lastRefreshError,D.refresh,this.now()))continue;try{Q("[refresh] fallback oauth background due",{accountId:D.id,expiresInMs:D.expires?D.expires-this.now():void 0}),await this.refreshAccount(D,f),_=!0}catch(E){Q("[refresh] fallback oauth background failed",{accountId:D.id,error:E instanceof Error?E.message:String(E)}),v_(D,E,this.now()),W(f,D),_=!0}}if(_)await this.save(f)}async refreshQuotaForDueAccounts(){let f=await this.load();if(!f||!_f(f))return;let _=!1;for(let D of f.accounts){if(D.enabled===!1||!X(D))continue;let E=D;try{if(l(E,f,this.now())){if(e(E.lastRefreshError,E.refresh,this.now()))continue;E=await this.refreshAccount(E,f),_=!0}if(g(E.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(E,f),!(this.quotaManager?this.quotaManager.isFallbackStale(E.id,E.access):Pf(E,f,this.now())))continue;await this.refreshAccountQuota(E,f),_=!0}catch($){Q_(D,$,this.now()),W(f,D),_=!0}}if(_)await this.save(f),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(f={}){let _=await this.load(),D=[];if(!_||!_f(_))return{storage:_,errors:D};let E=f.force??!1,$=!1;for(let m of _.accounts){if(m.enabled===!1||!X(m))continue;let M=m;try{if(l(M,_,this.now())){let C=M.lastRefreshError;if(C&&e(C,M.refresh,this.now()))throw Error(xf(C,this.now()));M=await this.refreshAccount(M,_),$=!0}if(!E&&!Pf(M,_,this.now())){if(M.lastQuotaRefreshError)M.lastQuotaRefreshError=void 0,W(_,M),$=!0;continue}await this.refreshAccountQuota(M,_),$=!0}catch(C){Q_(m,C,this.now()),W(_,m),$=!0,D.push({accountId:m.id,message:Df(C)})}}if($)await this.save(_);return{storage:_,errors:D}}async refreshAccount(f,_,D={}){let E=this.refreshPromises.get(f.id);if(E){let M=await E;return W(_,M),M}let $=this.refreshAccountNow(f,_,D).finally(()=>{this.refreshPromises.delete(f.id)});this.refreshPromises.set(f.id,$);let m=await $;return W(_,m),m}async waitForConcurrentFallbackRefresh(f,_,D,E){let $=Date.now()+OD;while(Date.now()<$){await new Promise((O)=>setTimeout(O,UD));let m=await this.load(),M=m?.accounts.find((O)=>O.id===f.id&&X(O));if(!M)continue;if((M.access!==D.access||M.refresh!==D.refresh||(M.expires??0)>(D.expires??0)+60000)&&(E.force||!l(M,m,this.now())))return W(_,M),Q("[refresh] fallback oauth joined concurrent refresh",{accountId:M.id,expiresInMs:M.expires?M.expires-this.now():void 0}),M;let L=M.lastRefreshError;if(L&&e(L,M.refresh,this.now()))throw W(_,M),Error(xf(L,this.now()))}return null}async refreshAccountNow(f,_,D){let E=await this.load(),$=E?.accounts.find((C)=>C.id===f.id&&X(C));if($&&!D.force&&!l($,E,this.now()))return W(_,$),$;let m=$??f,M=await Hf({name:lD(m.id),ttlMs:LD,path:this.configPath,now:this.now,renew:!0});if(!M){Q("[refresh] fallback oauth refresh skipped file lock",{accountId:m.id});let C=await this.waitForConcurrentFallbackRefresh(f,_,m,D);if(C)return C;throw Error("Fallback OAuth refresh is already in progress")}try{if(E=await this.load(),$=E?.accounts.find((O)=>O.id===f.id&&X(O)),$&&!D.force&&!l($,E,this.now()))return W(_,$),$;m=$??m;let C=m.refresh;Q("[refresh] fallback oauth refresh request start",{accountId:m.id,force:D.force===!0,expiresInMs:m.expires?m.expires-this.now():void 0});let L=await F_({refreshToken:C,fetchImpl:this.fetchImpl,now:this.now});return m.access=L.access,m.refresh=L.refresh,m.expires=L.expires,m.lastRefreshedAt=L.expires-L.expiresIn*1000,m.lastRefreshError=void 0,W(_,m),await this.save(_),Q("[refresh] fallback oauth refresh succeeded",{accountId:m.id,expiresInMs:m.expires?m.expires-this.now():void 0}),m}finally{await M.release()}}async refreshAccountQuota(f,_){let D=f;if(!D.access)throw Error(`Fallback account ${f.id} has no access token`);let E=(C)=>this.quotaManager?this.quotaManager.refreshFallback(D.id,C):Nf({accessToken:C,fetchImpl:this.fetchImpl,now:this.now}),$=this.now();try{D.quota=await E(D.access)}catch(C){if(!(C instanceof Error?C.message:String(C)).includes("Claude quota check failed: 401"))throw C;if(D=await this.refreshAccount(f,_,{force:!0}),!D.access)throw C;D.quota=await E(D.access)}let m=await this.load(),M=m?.accounts.find((C)=>C.id===D.id&&X(C));if(m&&M&&M.access!==D.access)return this.seedFallbackQuota(M,m),W(_,M),M;if(m&&M?.access===D.access&&M.quota&&ff(M.quota)>=$&&p_(M.quota,m,this.now()))return this.seedFallbackQuota(M,m),W(_,M),M;if(D.lastQuotaRefreshError=void 0,W(_,D),this.quotaManager&&D.quota){let C=this.now();this.quotaManager.setFallback(D.id,{quota:D.quota,refreshAfter:C+Z(_),checkedAt:C},D.access)}return D}}var H$="claude-cache",u_="## Claude Cache Status",kD="## Claude Cache Enabled",pD="## Claude Cache Disabled",dD="## Claude Cache Usage",vD="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",Sf=!1,Bf=Of;function b$(){return Sf}function N$(){return Bf}function S$(f){Sf=f.enabled,Bf=f.mode}function uD(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&_[0]==="on")return{type:"enable"};if(_.length===1&&_[0]==="off")return{type:"disable"};if(_.length===2&&_[0]==="mode"&&(_[1]==="explicit"||_[1]==="automatic"||_[1]==="hybrid"))return{type:"mode",mode:_[1]};return{type:"usage"}}function Ef(f){let _=f?.enabled??Sf,D=f?.mode??Bf;return[u_,"",`- Enabled: ${_?"enabled":"disabled"}`,`- Mode: ${D}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Scope: main sessions only; subagent sessions keep default ephemeral cache behavior","- Modes: explicit = existing OpenCode breakpoints; automatic = top-level cache_control only; hybrid = system + messages[0] + top-level cache_control","- TTL: 1h when enabled for main sessions; default ephemeral cache behavior otherwise"].join(`
|
|
8
8
|
`)}function B$(f){let _=uD(f.argumentsText),D=f.enabled??Sf,E=f.mode??Bf;if(_.type==="status")return Ef({enabled:D,mode:E});if(_.type==="enable")return[kD,"",Ef({enabled:!0,mode:E})].join(`
|
|
9
9
|
`);if(_.type==="disable")return[pD,"",Ef({enabled:!1,mode:E})].join(`
|
|
10
10
|
`);if(_.type==="mode")return[u_,"",`Mode updated to \`${_.mode}\`.`,"",Ef({enabled:D,mode:_.mode})].join(`
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import{$ as eW,A as mW,Aa as N4,B as pW,Ba as FW,C as $1,Ca as
|
|
1
|
+
import{$ as eW,A as mW,Aa as N4,B as pW,Ba as FW,C as $1,Ca as u0,D as iW,Da as V4,E as O1,Ea as X4,F as dW,Fa as Z4,G as lW,Ga as K4,H as uW,Ha as CW,I as q1,Ia as HW,J as G1,Ja as Y4,K as nW,Ka as p1,L as x0,La as _4,M as R1,Ma as D4,N as cW,Na as i1,O as oW,P as p0,Pa as I4,Q as i0,R as N1,Ra as d1,S as rW,Sa as Y1,T as T1,Ta as z4,U as tW,Ua as w4,V as sW,Va as l1,W as aW,X as E1,Y as q0,Z as R0,_ as d0,a as YW,aa as V1,b as _W,ba as QW,c as v0,ca as LW,d as A0,da as S1,e as DW,ea as MW,f as f0,fa as UW,g as kW,ga as BW,h as IW,ha as v1,i as zW,ia as W4,j as wW,ja as j4,k as C1,ka as A1,l as yW,la as J4,m as H1,ma as k1,n as f1,na as P4,o as E,oa as $4,p as W0,pa as y1,q as h0,qa as X1,r as x1,ra as O4,s as hW,sa as h1,t as bW,ta as l0,u as A,ua as b1,va as Z1,w as b0,wa as K1,x as gW,xa as G4,y as g0,ya as g1,z as m0,za as m1}from"./index-tes31apx.js";import{Za as L4}from"./index-9yjbmhf1.js";import{db as WW}from"./index-jb14nj5c.js";import{gb as Q4}from"./index-3ynbghx3.js";import"./index-p8j7mmfc.js";import{randomUUID as zj}from"node:crypto";function H0(W){return typeof W==="object"&&W!==null}function H4(W){if(Array.isArray(W))return W;if(H0(W)&&Array.isArray(W.data))return W.data;return[]}function f4(W){if(!H0(W)||!H0(W.info))return;return typeof W.info.role==="string"?W.info.role:void 0}function n1(W){if(!H0(W)||!H0(W.info))return null;let J=W.info,j=H0(J.model)?J.model:void 0,$=typeof J.agent==="string"?J.agent:void 0,P=typeof j?.providerID==="string"?j.providerID:typeof J.providerID==="string"?J.providerID:void 0,N=typeof j?.modelID==="string"?j.modelID:typeof J.modelID==="string"?J.modelID:void 0,I=typeof j?.variant==="string"?j.variant:typeof J.variant==="string"?J.variant:void 0;if(!$&&(!P||!N)&&!I)return null;let H={};if($)H.agent=$;if(P&&N)H.model={providerID:P,modelID:N};if(I)H.variant=I;return H}function c1(W,J){return{agent:W.agent??J.agent,model:W.model??J.model,variant:W.variant??J.variant}}function o1(W){return Boolean(W.agent&&W.model&&W.variant)}async function r1(W,J){if(!W||!J)return null;let j=W;if(typeof j.session?.messages!=="function")return null;let $=[];try{$=H4(await Promise.resolve(j.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if($.length===0)return null;let P={};for(let N=$.length-1;N>=0;N--){if(f4($[N])!=="assistant")continue;let I=n1($[N]);if(!I)continue;if(P=c1(P,I),o1(P))return P}for(let N=$.length-1;N>=0;N--){let I=n1($[N]);if(!I)continue;if(P=c1(P,I),o1(P))return P}if(!P.agent&&!P.model&&!P.variant)return null;return P}var K0=[],x4=1,w1=0,t1=new Map;function s1(W,J){if(K0.push({id:x4++,type:"open-dialog",payload:W,sessionId:J}),K0.length>100)K0=K0.slice(K0.length-100)}function a1(W=0,J){let j=Date.now();if(w1=j,J!==void 0)t1.set(J,j);let $=(P)=>J===void 0||P.sessionId===void 0||P.sessionId===J;if(W>0)K0=K0.filter((P)=>{if(P.id>W)return!0;if(J===void 0)return!1;return P.sessionId!==J});return K0.filter((P)=>P.id>W&&$(P))}function e1(W){let J=Date.now();if(W!==void 0){let j=t1.get(W)??0;return j>0&&J-j<3000}return w1>0&&J-w1<3000}import{randomBytes as q4,timingSafeEqual as R4}from"node:crypto";import{unlink as T4}from"node:fs/promises";import{createServer as E4}from"node:http";import{join as S4}from"node:path";function v4(W){return new Promise((J,j)=>{let $=[],P=0;W.on("data",(N)=>{if(P+=N.length,P>1e6){W.destroy(),j(Error("body too large"));return}$.push(N)}),W.on("end",()=>J(Buffer.concat($).toString("utf8"))),W.on("error",j)})}function A4(W,J){if(!W?.startsWith("Bearer "))return!1;let j=Buffer.from(W.slice(7)),$=Buffer.from(J);return j.length===$.length&&R4(j,$)}async function jW(W){let J=q4(32).toString("hex"),j=E4((N,I)=>{$(N,I)});async function $(N,I){let H=(k,b)=>{I.writeHead(k,{"content-type":"application/json"}),I.end(JSON.stringify(b))};try{let k=N.url??"";if(N.method==="GET"&&k==="/health")return H(200,{ok:!0});if(N.method!=="POST"||!k.startsWith("/rpc/"))return H(404,{error:"not found"});if(!A4(N.headers.authorization,J))return H(401,{error:"unauthorized"});let b=k.slice(5),m=JSON.parse(await v4(N)||"{}");if(b==="pending-notifications"){let S=W.drain(Number(m.lastReceivedId??0),typeof m.sessionId==="string"?m.sessionId:void 0);return H(200,{messages:S})}if(b==="apply"){let S=await W.apply(m);return H(200,S)}return H(404,{error:"unknown method"})}catch(k){H(500,{error:k instanceof Error?k.message:String(k)})}}let P=await new Promise((N,I)=>{j.on("error",I),j.listen(0,"127.0.0.1",()=>{let H=j.address();if(H&&typeof H==="object")N(H.port);else I(Error("no port"))})});j.unref();try{await WW(W.dir,{port:P,token:J,pid:process.pid})}catch(N){throw await new Promise((I)=>j.close(()=>I())),N}return{port:P,token:J,async stop(){await new Promise((N)=>j.close(()=>N())),await T4(S4(W.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function JW(W,J){let j=new Map,$=0,P=0,N=0,I=0,H=0,k=(S)=>{let r=performance.now(),d=W(S);return H+=performance.now()-r,N++,d};return{call:(S)=>{if(!J.enabled())return k(S);let r=j.get(S);if(r!==void 0)return P++,j.delete(S),j.set(S,r),r;let d=k(S),O0=S.length+d.length;if(O0>J.maxBytes)return d;j.set(S,d),$+=O0;while($>J.maxBytes&&j.size>1){let l=j.keys().next().value,j0=j.get(l)??"";j.delete(l),$-=l.length+j0.length,I++}return d},stats:()=>({hits:P,misses:N,evictions:I,entries:j.size,cacheBytes:$,computeMsTotal:H})}}function PW(W){return`${YW}${W.charAt(0).toUpperCase()}${W.slice(1)}`}function fW(W){if(W==="StructuredOutput")return W;return`${W.charAt(0).toLowerCase()}${W.slice(1)}`}var k4=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function $W(W){let J=fW(W);if(J.startsWith("aft_"))return J;if(k4.has(J))return`aft_${J}`;return null}function M1(W,J){let j=new Headers;if(W instanceof Request)W.headers.forEach((P,N)=>{j.set(N,P)});let $=J?.headers;if($){if($ instanceof Headers)$.forEach((P,N)=>{j.set(N,P)});else if(Array.isArray($))for(let P of $){let[N,I]=P;if(typeof I<"u")j.set(N,String(I))}else for(let[P,N]of Object.entries($))if(typeof N<"u")j.set(P,String(N))}return j}function W1(W){return W.set("anthropic-beta",v0(W.get("anthropic-beta"),[_W])),W}function k0(W,J,j={}){return UW(W,J,j)}function y4(W){if(W.tools&&Array.isArray(W.tools))W.tools=W.tools.map((J)=>({...J,name:J.name?PW(J.name):J.name}));if(W.messages&&Array.isArray(W.messages))W.messages=W.messages.map((J)=>{if(J.content&&Array.isArray(J.content))J.content=J.content.map((j)=>{if(j.type==="tool_use"&&j.name)return{...j,name:PW(j.name)};return j});return J});return JSON.stringify(BW(W))}function Q1(W){return W.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(J,j,$)=>{if(j)return`"name": "${$W($)??fW($)}"`;let P=$W($);return P?`"name": "${P}"`:J})}function OW(W,J=!1){if(J)return{ready:Q1(W),pending:""};let j=W.length,$='"name"',P=Math.max(0,W.length-$.length+1);for(let I=P;I<W.length;I++)if($.startsWith(W.slice(I))){j=Math.min(j,I);break}let N=W.lastIndexOf($);if(N!==-1){let I=W.slice(N);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(I))j=Math.min(j,N)}if(j<W.length)return{ready:Q1(W.slice(0,j)),pending:W.slice(j)};return{ready:Q1(W),pending:""}}function U1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let W=process.env.ANTHROPIC_INSECURE?.trim();return W==="1"||W==="true"}function xW(W){let J=W?.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 h4(){return xW(process.env.ANTHROPIC_BASE_URL)}function B1(W,J={}){let j=null;try{if(typeof W==="string"||W instanceof URL)j=new URL(W.toString());else if(W instanceof Request)j=new URL(W.url)}catch{j=null}if(!j)return{input:W,url:null};let $=j.href,P=J.baseURL?xW(J.baseURL):h4();if(P){if(j.protocol=P.protocol,j.host=P.host,J.baseURL)j.pathname=`${P.pathname.replace(/\/$/,"")}${j.pathname}`}if(j.pathname.endsWith("/v1/messages")&&!j.searchParams.has("beta"))j.searchParams.set("beta","true");if(j.href===$)return{input:W,url:j};return{input:W instanceof Request?new Request(j.toString(),W):j,url:j}}function b4(W){let $=W.split(/\n\n+/).filter((P)=>{if(P.includes(DW))return!1;for(let N of zW)if(P.includes(N))return!1;return!0}).join(`
|
|
2
2
|
|
|
3
|
-
`);for(let P of wW)$=$.replace(P.match,P.replacement);return $.trim()}var g4=8388608;function m4(){return process.env.OPENCODE_ANTHROPIC_AUTH_MEMO!=="0"}var p4=JW(b4,{maxBytes:g4,enabled:m4});function t0(W){return p4.call(W)}function i(W){return W!=null&&typeof W==="object"&&!Array.isArray(W)}function i4(W){let J={type:"text",text:f0};if(W==null)return[J];if(typeof W==="string"){let $=t0(W);if($===f0)return[J];return[J,{type:"text",text:$}]}if(i(W)){let $=typeof W.type==="string"?W.type:"text",P=typeof W.text==="string"?W.text:"";return[J,{...W,type:$,text:t0(P)}]}if(!Array.isArray(W))return[J];let j=W.map(($)=>{if(typeof $==="string")return{type:"text",text:t0($)};if(i($)&&$.type==="text"&&typeof $.text==="string")return{...$,type:"text",text:t0($.text)};return{type:"text",text:String($)}});if(j[0]?.text===f0)return j;return[J,...j]}var qW={type:"ephemeral",ttl:"1h"},
|
|
4
|
-
`);J.splice($,J.length-$,{...P,type:"text",text:N})}function VW(W){if(Array.isArray(W.system)){let J=W.system.findIndex((P)=>i(P)&&P.text===f0),j=W.system.slice(J>=0?J+1:0).filter(i),$=j[j.length-1];S0($,!0)}else S0(W.system,!0)}function Jj(W){if(RW(W),jj(W),!Array.isArray(W.messages)){VW(W);return}let{latest:J,bridge:j}=Wj(W.messages);if(!j)VW(W);if(s4(W.messages[0]))r4(W.messages[0]),t4(W.messages[0]);else a0(W.messages[0]),a0(W.messages[1]);if(j)a0(W.messages[j.index]);if(J)a0(W.messages[J.index])}function Pj(W){if(!Array.isArray(W.messages))return 0;let J=0;return W.messages=W.messages.filter((j)=>{if(!i(j)||!Array.isArray(j.content))return!0;if(j.role!=="assistant")return!0;let $=j.content.filter((P)=>{if(!i(P)||P.type!=="thinking")return!0;if(!HW(P.signature))return!0;return J+=1,!1});if($.length===j.content.length)return!0;return j.content=$,$.length>0}),J}function $j(W){if(!CW(W.model))return null;let J=Object.hasOwn(W,"thinking");return W.thinking={...FW},{replacedExisting:J}}function Oj(W,J){if(!J.enabled){NW(W,!1),delete W.cache_control,delete W.cacheControl;return}if(J.mode==="automatic"){c4(W);return}if(J.mode==="hybrid"){Jj(W);return}NW(W,!0),delete W.cacheControl}function Gj(W){if(!Array.isArray(W.messages))return;while(W.messages.length){let J=W.messages[W.messages.length-1];if(!i(J)||J.role!=="assistant")break;W.messages.pop()}}function v(){return performance.now()}function P0(W){return Math.round(W*10)/10}function XW(W){let J=0,j=0,$=0,P=Array.isArray(W.messages)?W.messages:[];J=P.length;for(let N of P){if(!N||typeof N!=="object")continue;let I=N.content;if(!Array.isArray(I))continue;j+=I.length;for(let H of I)if(H&&typeof H==="object"&&H.type==="tool_use")$++}return{messageCount:J,contentBlockCount:j,toolDefinitionCount:Array.isArray(W.tools)?W.tools.length:0,toolUseCount:$,systemBlockCount:Array.isArray(W.system)?W.system.length:0}}async function F1(W,J={}){try{let j=v(),$=JSON.parse(W);J.perf?.("parse",{ms:P0(v()-j),inputBytes:W.length,...XW($)});let P=v(),N=Array.isArray($.messages)?$.messages.length:void 0;Gj($);let I=Array.isArray($.messages)?$.messages.length:void 0;J.perf?.("strip_trailing_assistant",{ms:P0(v()-P),removedMessages:typeof N==="number"&&typeof I==="number"?N-I:void 0});let H=v(),k=Pj($),b=$j($);J.perf?.("model_normalize",{ms:P0(v()-H),model:typeof $.model==="string"?$.model:void 0,fableMythosThinkingDisplay:b?"summarized":void 0,replacedFableMythosThinking:b?.replacedExisting??!1,removedNonAnthropicThinking:k,hasOutputConfig:Object.hasOwn($,"output_config")});let m=v(),S=Array.isArray($.messages)&&$.messages.some((J0)=>J0.role==="user")?LW($.messages,void 0,IW):null;J.perf?.("billing_header",{ms:P0(v()-m),hasBillingHeader:Boolean(S)});let r=v();if($.system=i4($.system),J.perf?.("system_identity",{ms:P0(v()-r),systemBlockCount:Array.isArray($.system)?$.system.length:0}),S&&Array.isArray($.system))$.system.unshift({type:"text",text:S});let
|
|
3
|
+
`);for(let P of wW)$=$.replace(P.match,P.replacement);return $.trim()}var g4=8388608;function m4(){return process.env.OPENCODE_ANTHROPIC_AUTH_MEMO!=="0"}var p4=JW(b4,{maxBytes:g4,enabled:m4});function t0(W){return p4.call(W)}function i(W){return W!=null&&typeof W==="object"&&!Array.isArray(W)}function i4(W){let J={type:"text",text:f0};if(W==null)return[J];if(typeof W==="string"){let $=t0(W);if($===f0)return[J];return[J,{type:"text",text:$}]}if(i(W)){let $=typeof W.type==="string"?W.type:"text",P=typeof W.text==="string"?W.text:"";return[J,{...W,type:$,text:t0(P)}]}if(!Array.isArray(W))return[J];let j=W.map(($)=>{if(typeof $==="string")return{type:"text",text:t0($)};if(i($)&&$.type==="text"&&typeof $.text==="string")return{...$,type:"text",text:t0($.text)};return{type:"text",text:String($)}});if(j[0]?.text===f0)return j;return[J,...j]}var qW={type:"ephemeral",ttl:"1h"},d4=20;function l4(W){if(i(W.cache_control))return W.cache_control;if(i(W.cacheControl))return W.cacheControl;return null}function S0(W,J){if(!i(W))return!1;return delete W.cacheControl,W.cache_control=J?{...qW}:{type:"ephemeral"},!0}function GW(W){if(!i(W))return;delete W.cache_control,delete W.cacheControl}function u4(W){if(Array.isArray(W))return W;if(typeof W==="string")return[{type:"text",text:W}];return null}function s0(W,J){if(!i(W))return;let j=l4(W);if(j?.type!=="ephemeral")return;if(J)j.ttl="1h";else delete j.ttl}function NW(W,J){if(Array.isArray(W.system))for(let j of W.system)s0(j,J);else s0(W.system,J);if(!Array.isArray(W.messages))return;for(let j of W.messages)if(s0(j,J),i(j)&&Array.isArray(j.content))for(let $ of j.content)s0($,J)}function n4(W,J){if(Array.isArray(W.system))for(let j of W.system)J(j);else J(W.system);if(!Array.isArray(W.messages))return;for(let j of W.messages)if(J(j),i(j)&&Array.isArray(j.content))for(let $ of j.content)J($)}function RW(W){GW(W),n4(W,GW)}function c4(W){RW(W),W.cache_control={...qW}}function o4(W){return i(W)&&W.type!=="thinking"&&W.type!=="redacted_thinking"}function j1(W){let J=u4(W.content);if(!J?.length)return;let j=J.filter(o4);if(!j.length)return;return{content:J,cacheableBlocks:j}}function r4(W){if(!i(W))return!1;let J=j1(W);if(!J)return!1;return W.content=J.content,S0(J.cacheableBlocks[0],!0)}function t4(W){if(!i(W))return!1;let J=j1(W);if(!J||J.cacheableBlocks.length<2)return!1;return W.content=J.content,S0(J.cacheableBlocks[1],!0)}function a0(W){if(!i(W))return!1;let J=j1(W);if(!J)return!1;let j=J.cacheableBlocks[J.cacheableBlocks.length-1];return W.content=J.content,S0(j,!0)}function s4(W){if(!i(W))return!1;return(j1(W)?.cacheableBlocks.length??0)>1}function a4(W){if(!i(W))return 0;let J=W.content;if(Array.isArray(J))return J.length;if(J==null)return 0;return 1}function e4(W){let J=[],j=0;return W.forEach(($,P)=>{let N=a4($);if(i($)&&$.role==="user"&&N>0)J.push({index:P,blockPosition:j+N-1});j+=N}),J}function Wj(W){let J=e4(W),j=[...J].reverse().find((I)=>I.index>1);if(!j)return{latest:void 0,bridge:void 0};let $=[...J].reverse().find((I)=>I.index<j.index),P=$?j.blockPosition-$.blockPosition+1:0,N=$&&$.index>1&&P>d4?$:void 0;return{latest:j,bridge:N}}function L1(W){return i(W)&&typeof W.text==="string"?W.text:""}function jj(W){if(!Array.isArray(W.system))return;let J=W.system,j=0;if(L1(J[j]).startsWith("x-anthropic-billing-header:"))j++;if(L1(J[j])===f0)j++;let $=j+1;if($>=J.length-1)return;let P=J[$];if(!i(P))return;let N=J.slice($).map(L1).join(`
|
|
4
|
+
`);J.splice($,J.length-$,{...P,type:"text",text:N})}function VW(W){if(Array.isArray(W.system)){let J=W.system.findIndex((P)=>i(P)&&P.text===f0),j=W.system.slice(J>=0?J+1:0).filter(i),$=j[j.length-1];S0($,!0)}else S0(W.system,!0)}function Jj(W){if(RW(W),jj(W),!Array.isArray(W.messages)){VW(W);return}let{latest:J,bridge:j}=Wj(W.messages);if(!j)VW(W);if(s4(W.messages[0]))r4(W.messages[0]),t4(W.messages[0]);else a0(W.messages[0]),a0(W.messages[1]);if(j)a0(W.messages[j.index]);if(J)a0(W.messages[J.index])}function Pj(W){if(!Array.isArray(W.messages))return 0;let J=0;return W.messages=W.messages.filter((j)=>{if(!i(j)||!Array.isArray(j.content))return!0;if(j.role!=="assistant")return!0;let $=j.content.filter((P)=>{if(!i(P)||P.type!=="thinking")return!0;if(!HW(P.signature))return!0;return J+=1,!1});if($.length===j.content.length)return!0;return j.content=$,$.length>0}),J}function $j(W){if(!CW(W.model))return null;let J=Object.hasOwn(W,"thinking");return W.thinking={...FW},{replacedExisting:J}}function Oj(W,J){if(!J.enabled){NW(W,!1),delete W.cache_control,delete W.cacheControl;return}if(J.mode==="automatic"){c4(W);return}if(J.mode==="hybrid"){Jj(W);return}NW(W,!0),delete W.cacheControl}function Gj(W){if(!Array.isArray(W.messages))return;while(W.messages.length){let J=W.messages[W.messages.length-1];if(!i(J)||J.role!=="assistant")break;W.messages.pop()}}function v(){return performance.now()}function P0(W){return Math.round(W*10)/10}function XW(W){let J=0,j=0,$=0,P=Array.isArray(W.messages)?W.messages:[];J=P.length;for(let N of P){if(!N||typeof N!=="object")continue;let I=N.content;if(!Array.isArray(I))continue;j+=I.length;for(let H of I)if(H&&typeof H==="object"&&H.type==="tool_use")$++}return{messageCount:J,contentBlockCount:j,toolDefinitionCount:Array.isArray(W.tools)?W.tools.length:0,toolUseCount:$,systemBlockCount:Array.isArray(W.system)?W.system.length:0}}async function F1(W,J={}){try{let j=v(),$=JSON.parse(W);J.perf?.("parse",{ms:P0(v()-j),inputBytes:W.length,...XW($)});let P=v(),N=Array.isArray($.messages)?$.messages.length:void 0;Gj($);let I=Array.isArray($.messages)?$.messages.length:void 0;J.perf?.("strip_trailing_assistant",{ms:P0(v()-P),removedMessages:typeof N==="number"&&typeof I==="number"?N-I:void 0});let H=v(),k=Pj($),b=$j($);J.perf?.("model_normalize",{ms:P0(v()-H),model:typeof $.model==="string"?$.model:void 0,fableMythosThinkingDisplay:b?"summarized":void 0,replacedFableMythosThinking:b?.replacedExisting??!1,removedNonAnthropicThinking:k,hasOutputConfig:Object.hasOwn($,"output_config")});let m=v(),S=Array.isArray($.messages)&&$.messages.some((J0)=>J0.role==="user")?LW($.messages,void 0,IW):null;J.perf?.("billing_header",{ms:P0(v()-m),hasBillingHeader:Boolean(S)});let r=v();if($.system=i4($.system),J.perf?.("system_identity",{ms:P0(v()-r),systemBlockCount:Array.isArray($.system)?$.system.length:0}),S&&Array.isArray($.system))$.system.unshift({type:"text",text:S});let d=v();if(Oj($,{enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.perf?.("cache_strategy",{ms:P0(v()-d),enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.fastModeEnabled&&A0($.model))$.speed="fast";else if($.speed==="fast")delete $.speed;let O0=v();if(J.identity)MW($,J.identity);J.perf?.("metadata",{ms:P0(v()-O0),hasAccountUuid:Boolean(J.identity?.accountUuid)});let l=v(),j0=y4($);J.perf?.("prefix_tools_stringify",{ms:P0(v()-l),outputBytesBeforeSign:j0.length,...XW($)});let N0=v(),z0=await QW(j0);return J.perf?.("cch_sign",{ms:P0(v()-N0),outputBytes:z0.length}),z0}catch{return W}}var Nj=new TextEncoder;function Vj(){return{pending:"",events:0,parseErrors:0,eventCounts:{},typeCounts:{},deltaTypeCounts:{},contentBlockTypeCounts:{},textDeltaBytes:0,thinkingDeltaBytes:0,inputJsonDeltaBytes:0,signatureDeltaBytes:0,redactedThinkingBytes:0}}function e0(W,J){if(!J)return;W[J]=(W[J]??0)+1}function I0(W){return Nj.encode(W).byteLength}function Y0(W){return W&&typeof W==="object"&&!Array.isArray(W)?W:void 0}function s(W,J){let j=W?.[J];return typeof j==="string"?j:void 0}function Xj(W,J){let j=W?.[J];return typeof j==="number"?j:void 0}function Zj(W){if(!W.trim())return null;let J,j=[];for(let S of W.split(/\r?\n/)){if(S.startsWith("event:")){J=S.slice(6).trim();continue}if(S.startsWith("data:")){let r=S.slice(5);j.push(r.startsWith(" ")?r.slice(1):r)}}let $=j.join(`
|
|
5
5
|
`),P={event:J,rawBytes:I0(W),dataBytes:I0($)};if(!$||$==="[DONE]")return P.type=$==="[DONE]"?"done":void 0,P.event??=P.type,P;let N;try{N=JSON.parse($)}catch{return P}let I=Y0(N),H=Y0(I?.delta),k=Y0(I?.content_block),b=Y0(I?.message),m=Y0(I?.usage)??Y0(b?.usage);if(P.type=s(I,"type"),P.event??=P.type,P.index=Xj(I,"index"),P.contentBlockType=s(k,"type"),P.deltaType=s(H,"type"),P.stopReason=s(I,"stop_reason"),P.deltaType==="text_delta")P.textDeltaBytes=I0(s(H,"text")??"");if(P.deltaType==="thinking_delta")P.thinkingDeltaBytes=I0(s(H,"thinking")??"");if(P.deltaType==="input_json_delta")P.inputJsonDeltaBytes=I0(s(H,"partial_json")??"");if(P.deltaType==="signature_delta")P.signatureDeltaBytes=I0(s(H,"signature")??"");if(P.contentBlockType==="redacted_thinking")P.redactedThinkingBytes=I0(s(k,"data")??"");if(m)P.stopReason??=s(b,"stop_reason");return P}function TW(W){let J=W.indexOf(`
|
|
6
6
|
|
|
7
7
|
`),j=W.indexOf(`\r
|
|
8
8
|
\r
|
|
9
9
|
`);if(J===-1)return j===-1?null:{index:j,length:4};if(j===-1||J<j)return{index:J,length:2};return{index:j,length:4}}function ZW(W,J){if(!J)return;W.pending+=J;while(!0){let j=TW(W.pending);if(!j)break;let $=W.pending.slice(0,j.index);W.pending=W.pending.slice(j.index+j.length);let P=Zj($);if(!P)continue;if(W.events++,e0(W.eventCounts,P.event??"unknown"),e0(W.typeCounts,P.type),e0(W.deltaTypeCounts,P.deltaType),e0(W.contentBlockTypeCounts,P.contentBlockType),W.textDeltaBytes+=P.textDeltaBytes??0,W.thinkingDeltaBytes+=P.thinkingDeltaBytes??0,W.inputJsonDeltaBytes+=P.inputJsonDeltaBytes??0,W.signatureDeltaBytes+=P.signatureDeltaBytes??0,W.redactedThinkingBytes+=P.redactedThinkingBytes??0,W.last=P,P.dataBytes>0&&!P.type&&!P.event)W.parseErrors++}}function Kj(){return{pending:""}}function Yj(W,J){let j=W?.toLowerCase(),$=J.toLowerCase();return j==="api_error"||j==="overloaded_error"||j==="server_error"||j==="internal_server_error"||$.includes("internal server error")||$.includes("server overloaded")}function _j(W,J){let j=W?`${W}: ${J}`:J,$=Error(`Anthropic stream error: ${j}`);if($.code="ECONNRESET",$.syscall="anthropic-sse",W)$.providerErrorType=W;return $}function Dj(W){if(!W.includes("error"))return null;let J,j=[];for(let b of W.split(/\r?\n/)){if(b.startsWith("event:")){J=b.slice(6).trim();continue}if(b.startsWith("data:")){let m=b.slice(5);j.push(m.startsWith(" ")?m.slice(1):m)}}let $=j.join(`
|
|
10
|
-
`);if(!$||$==="[DONE]")return null;let P;try{P=JSON.parse($)}catch{return null}let N=Y0(P);if(J!=="error"&&s(N,"type")!=="error")return null;let I=Y0(N?.error),H=s(I,"type")??s(I,"code")??void 0,k=s(I,"message")??s(N,"message")??H??"Anthropic stream error";if(!Yj(H,k))return null;return _j(H,k)}function KW(W,J){if(!J)return null;W.pending+=J;while(!0){let j=TW(W.pending);if(!j)break;let $=W.pending.slice(0,j.index);W.pending=W.pending.slice(j.index+j.length);let P=Dj($);if(P)return P}return null}function Ij(W){return{sseEvents:W.events,ssePendingChars:W.pending.length,sseParseErrors:W.parseErrors,sseEventCounts:{...W.eventCounts},sseTypeCounts:{...W.typeCounts},sseDeltaTypeCounts:{...W.deltaTypeCounts},sseContentBlockTypeCounts:{...W.contentBlockTypeCounts},sseTextDeltaBytes:W.textDeltaBytes,sseThinkingDeltaBytes:W.thinkingDeltaBytes,sseInputJsonDeltaBytes:W.inputJsonDeltaBytes,sseSignatureDeltaBytes:W.signatureDeltaBytes,sseRedactedThinkingBytes:W.redactedThinkingBytes,sseLastEvent:W.last?{...W.last}:void 0}}function y0(W,J={}){if(!W.body)return W;let j=W.body.getReader(),$=new TextDecoder,P=new TextEncoder,N="",I=0,H=0,k=0,b=0,m=0,S=!1,r=!1,l=v(),O0=v(),d=J.perf?Vj():void 0,j0=Kj(),N0=()=>{if(r)return;r=!0,j.releaseLock()},z0=(a={})=>({chunks:I,pulls:H,inputBytes:k,outputBytes:b,pendingChars:N.length,rewriteMs:P0(m),totalMs:P0(v()-O0),...d?Ij(d):{},...a}),J0=(a,T0={})=>{J.perf?.(a,z0(T0))};J.perf?.("stream_tool_prefix_wrapper_created",{status:W.status,hasBody:!0});let D1=new ReadableStream({async pull(a){if(H++,!S)S=!0,J0("stream_tool_prefix_first_pull");let T0=v();try{let{done:X0,value:w0}=await j.read(),E0=P0(v()-T0);if(X0){let O=$.decode();if(d)ZW(d,O);let G=KW(j0,O);if(G)throw J0("stream_tool_prefix_retryable_error",{error:G.message,providerErrorType:G.providerErrorType}),N0(),G;let Y=v(),L=OW(`${N}${O}`,!0);if(m+=v()-Y,L.ready){let K=P.encode(L.ready);b+=K.byteLength,a.enqueue(K)}J0("stream_tool_prefix_rewrite",{readMs:E0}),N0(),a.close();return}I++,k+=w0.byteLength;let Q0=$.decode(w0,{stream:!0});if(d)ZW(d,Q0);let L0=KW(j0,Q0);if(L0)throw J0("stream_tool_prefix_retryable_error",{error:L0.message,providerErrorType:L0.providerErrorType,readMs:E0,lastChunkBytes:w0.byteLength}),N0(),L0;let I1=N+Q0,M0=v(),U0=OW(I1);if(m+=v()-M0,N=U0.pending,U0.ready){let O=P.encode(U0.ready);b+=O.byteLength,a.enqueue(O)}let u0=v();if(I===1||I%25===0||u0-l>5000)l=u0,J0("stream_tool_prefix_progress",{readMs:E0,lastChunkBytes:w0.byteLength})}catch(X0){throw J0("stream_tool_prefix_error",{error:X0 instanceof Error?X0.message:String(X0)}),N0(),X0}},async cancel(a){J0("stream_tool_prefix_cancel",{reason:a instanceof Error?a.message:String(a)});try{await j.cancel(a)}finally{N0()}}});return new Response(D1,{status:W.status,statusText:W.statusText,headers:W.headers})}var wj="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",Qj=60000,Lj=60000,Mj=5000,EW=200,M4=240,Uj=M4,Bj=1,SW=!1;function _1(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function F(){return performance.now()}function h(W){return Math.round(W*10)/10}function vW(W){return Math.floor(Math.random()*Math.max(0,W))}function J1(W){if(typeof W==="string")return W;if(W instanceof URL)return W.toString();return W.url}function P1(W,J){return J?.method??(W instanceof Request?W.method:void 0)}function AW(W){return W instanceof Error?W.message:String(W)}function Fj(){if(SW||!1||!_1())return;SW=!0;let W=100,J=250,j=F()+W;setInterval(()=>{let $=F(),P=$-j;if(j=$+W,P<J)return;E("[perf] opencode event_loop_lag",{lagMs:h(P),thresholdMs:J})},W).unref?.()}function Cj(W){let J=F(),j={requestId:String(Bj++),start:J,last:J,mark($,P){let N=F();if(_1())E("[perf] opencode request stage",{requestId:j.requestId,stage:$,deltaMs:h(N-j.last),totalMs:h(N-j.start),...P});j.last=N},done($,P){let N=F();if(_1())E("[perf] opencode request done",{requestId:j.requestId,stage:$,deltaMs:h(N-j.last),totalMs:h(N-j.start),...P});j.last=N}};if(_1())E("[perf] opencode request start",{requestId:j.requestId,...W});return j}async function Hj(W,J,j){let $=W.client.session,P=await r1(W.client,J),N={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:j,ignored:!0}]}};if(P?.agent)N.body.agent=P.agent;if(P?.model)N.body.model=P.model;if(P?.variant)N.body.variant=P.variant;if(typeof $?.promptAsync==="function"){await $.promptAsync(N);return}if(typeof $?.prompt==="function"){await Promise.resolve($.prompt(N));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function fj(){throw Error(wj)}function xj(W){if(W.sessionID==null)return!1;let J=W.model;return J?.providerID==="anthropic"||J?.api?.npm==="@ai-sdk/anthropic"||J?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function qj(W){if(W.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return W.push(kW),!0}var Rj={input:0,output:0,cache:{read:0,write:0}};function Tj(W){let J=W["claude-opus-4-8"]??W["claude-opus-4-5"]??Object.values(W)[0];if(!J)return W;return{...W,...Object.fromEntries(Object.values(K4).map((j)=>[j.id,{...J,id:j.id,name:j.name,api:J.api?{...J.api,id:j.id}:void 0,cost:{input:n0.input,output:n0.output,cache:{read:n0.cacheRead,write:n0.cacheWrite5m}},limit:{...J.limit??{},context:V4,output:X4},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:Z4}]))}}function Ej(W){return Object.fromEntries(Object.entries(W).map(([J,j])=>[J,{...j,cost:Rj}]))}var ej=async(W)=>{Fj();let{client:J}=W,j=bW(),$=await A(j),P=new Y4({storage:$,onMainQuotaFetched:async(O,G,Y,L)=>{try{let K=await A(j)??{version:1,accounts:[]},T=oW(K);if(T&&T.checkedAt>=L&&sW(T.quota,K,T.checkedAt)>Date.now()){P.seedMainFromStorage(K);return}K.quota=K.quota??{},K.quota.mainQuota=O,K.quota.mainQuotaCheckedAt=G,K.quota.mainQuotaToken=Y,K.quota.mainLastQuotaApiError=void 0,await b0(K,j,{mainQuota:!0})}catch(K){E("[quota] failed to persist main quota",{error:K instanceof Error?K.message:String(K)})}},onApiError:async(O)=>{try{let G=await A(j)??{version:1,accounts:[]};G.quota=G.quota??{},G.quota.mainLastQuotaApiError=O,await b0(G,j,{mainQuota:!0})}catch(G){E("[quota] failed to persist backoff state",{error:G instanceof Error?G.message:String(G)})}}}),N=new aW({quotaManager:P,onFallbackStorageChanged:()=>{S()}});N.startBackgroundRefresh();let I=null,H=new $4({loadStorage:()=>A(j),prepareHeaders:async(O,G)=>{if(!l)return O;let Y=await l();if(Y.type!=="oauth")return O;if(!Y.access||Y.expires&&Y.expires<Date.now()){if(!I)return O;Y.access=await I()}if(!Y.access)return O;try{let L=JSON.parse(G.bodyText),K=await S1(Y.access,typeof L.model==="string"?L.model:void 0);if(O.delete("anthropic-beta"),k0(O,Y.access,{body:L,identity:K}),O.set("anthropic-beta",v0(O.get("anthropic-beta"),[W4])),L.speed==="fast")W1(O)}catch{k0(O,Y.access)}return O},log:E});l0({enabled:g0($),mode:m0($)}),X1($1($)),K1(O1($));let k=null;if(W.directory){let O=globalThis;if(O.__anthropicAuthRpcServer)await O.__anthropicAuthRpcServer.stop().catch(()=>{}),O.__anthropicAuthRpcServer=void 0;try{k=await jW({dir:Q4(W.directory),drain:a1,apply:L0}),O.__anthropicAuthRpcServer=k}catch(G){E("[rpc] failed to start",{error:G instanceof Error?G.message:String(G)})}}let b={activeId:"main",route:"main"};function m(O,G){b={activeId:G.activeId,route:G.route},P.updateStorage(O),P.seedMainFromStorage(O,G.mainAccessToken),P.seedFallbacksFromAccounts((O?.accounts??[]).filter(W0));let Y=P.getMain(G.mainAccessToken),L=P.getLastApiError(),K=O?.refresh?.mainLastRefreshError,T={main:{quota:Y?.quota??null,quotaBackedOff:P.isBackedOff(),quotaBackoffUntil:L?.nextRetryAt,refreshBackedOff:K?x0(K,G.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:K?.nextRetryAt},fallbacks:(O?.accounts??[]).filter((f)=>f.enabled!==!1&&W0(f)).map((f)=>({id:f.id,label:f.label,quota:f.access?P.getFallback(f.id,f.access)?.quota??null:null,enabled:f.enabled!==!1})),activeId:G.activeId,route:G.route,relay:(()=>{let f=i1(O);return f?{enabled:!0,transport:f.transport??"http"}:null})(),fastMode:Z1(),cacheKeep:{enabled:k1(O),window:O?.cacheKeep?.startHour!=null&&O?.cacheKeep?.endHour!=null?`${O.cacheKeep.startHour}-${O.cacheKeep.endHour}`:void 0,trackedSessions:H.trackedCount()},lastUpdated:Date.now()};L4(T).catch((f)=>E("[sidebar] state write failed",{error:f instanceof Error?f.message:String(f)}))}async function S(){let O=await A(j),G,Y;if(l)try{let L=await l();G=L.access,Y=L.refresh}catch{}m(O,{activeId:b.activeId,route:b.route,mainAccessToken:G,mainRefreshToken:Y})}function r(O,G){if(!G)return;if(O?.quota?.enabled!==!0)return;if(P.getMain(G))return;if(O0)return;O0=!0,P.refreshMain(G).then(()=>S()).catch(()=>{}).finally(()=>{O0=!1})}let l=null,O0=!1,d=null,j0=0;function N0(O){let G=O?.refresh?.refreshBeforeExpiryMinutes??Uj;return Math.max(M4,G)*60000}function z0(O){return O?.refresh?.enabled!==!1}async function J0(O){if(!O)return;let G=await A(j),Y=G?.refresh?.mainLastRefreshError;if(!G?.refresh||!Y?.tokenHash)return;let L=G1(O);if(Y.tokenHash===L)return;if(Y.nextRetryAt&&Y.nextRetryAt>Date.now()){E("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:Y.nextRetryAt,retryCount:Y.retryCount,remainingMs:Y.nextRetryAt-Date.now()});return}G.refresh.mainLastRefreshError=void 0,await b0(G,j,{mainRefresh:!0}),E("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:Y.checkedAt,previousNextRetryAt:Y.nextRetryAt,previousRetryCount:Y.retryCount})}async function D1(){let O=[];if(l)try{let K=await l();if(K.type==="oauth"&&K.access){let T=await P.refreshMain(K.access);O.push({name:"OpenCode anthropic",role:"main",quota:T})}else if(K.type==="oauth")O.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(K){let T=K instanceof Error?K.message:String(K);O.push({name:"OpenCode anthropic",role:"main",error:T.includes("429")?"Usage API rate limited — try again in a moment":T})}let{storage:G,errors:Y}=await N.refreshQuotaForAllAccounts({force:!0}),L=new Map(Y.map((K)=>[K.accountId,K.message]));if(O.push(..._4(G,L)),!l)O.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return D4({accounts:O,refreshedAt:Date.now()})}async function a(O){let G=eW(O);if(G.type==="enable"||G.type==="disable"){let T=G.type==="enable",f=await mW(T),y=m0(f);return l0({enabled:T,mode:y}),V1({argumentsText:O,enabled:T,mode:y})}if(G.type==="mode"){let T=await pW(G.mode),f=g0(T);return l0({enabled:f,mode:G.mode}),V1({argumentsText:O,enabled:f,mode:G.mode})}let Y=await A(j),L=g0(Y),K=m0(Y);return l0({enabled:L,mode:K}),V1({argumentsText:O,enabled:L,mode:K})}async function T0(O){let G=j4(O),Y=await A(j);if(G.type==="window")Y=await dW(G.startHour,G.endHour);else if(G.type==="disable")Y=await nW(!1);let L=A1(Y),K=H.stats(L);return P4({argumentsText:O,enabled:J4(Y),window:L,hybridActive:k1(Y),trackedSessions:K.trackedSessions,nextPrewarmAt:K.nextPrewarmAt})}async function X0(O){let G=O4(O);if(G.type==="enable"||G.type==="disable"){let K=G.type==="enable";return await iW(K),X1(K),h1({argumentsText:O,enabled:K})}let Y=await A(j),L=$1(Y);return X1(L),h1({argumentsText:O,enabled:L})}async function w0(O){let G=G4(O);if(G.type==="enable"||G.type==="disable"){let K=G.type==="enable";return await lW(K),K1(K),g1({argumentsText:O,enabled:K})}let Y=await A(j),L=O1(Y);return K1(L),g1({argumentsText:O,enabled:L})}async function E0(O){let G=w4(O);if(G.type==="mode")return await z4(G.mode),d1({argumentsText:O,mode:G.mode});let Y=await A();return d1({argumentsText:O,mode:Y1(Y)})}async function Q0(O,G){if(O==="claude-quota")return{command:O,text:await D1(),knobs:{}};if(O==="claude-routing"){let f=await E0(G),y=await A(j);return{command:O,text:f,knobs:{mode:Y1(y)}}}if(O==="claude-fast"){let f=await w0(G),y=await A(j);return{command:O,text:f,knobs:{enabled:O1(y)}}}if(O==="claude-dump"){let f=await X0(G),y=await A(j);return{command:O,text:f,knobs:{enabled:$1(y)}}}if(O==="claude-cache"){let f=await a(G),y=await A(j);return{command:O,text:f,knobs:{enabled:g0(y),mode:m0(y)}}}if(O==="claude-cachekeep"){let f=await T0(G),y=await A(j);return{command:O,text:f,knobs:{window:A1(y)}}}let Y=await A(),L=T1(Y),K=(Y?.accounts??[]).filter((f)=>f.enabled!==!1).map((f)=>f.id),T=N4({argumentsText:G,config:L,accountIds:K});if(T.updatedConfig)await tW(T.updatedConfig);return{command:O,text:T.text,knobs:{config:T1(await A()),accountIds:K}}}async function L0(O){let G=await Q0(O.command,O.arguments);return{text:G.text,knobs:G.knobs}}function I1(O,G=10){let Y=Math.max(0,Math.min(Math.round(O/100*G),G));return"█".repeat(Y)+"░".repeat(G-Y)}function M0(O,G){return`${O} ${I1(G)} ${String(Math.round(G)).padStart(3)}%`}function U0(O){if(!O)return"";let G=new Date(O).getTime();if(Number.isNaN(G))return"";let Y=G-Date.now();if(Y<=0)return"resets now";let L=Math.floor(Y/60000);if(L<1)return"resets <1m";if(L<60)return`resets ${L}m`;let K=Math.floor(L/60),T=L%60;return T>0?`resets ${K}h${T}m`:`resets ${K}h`}function u0(O,G,Y){let L=[],K=0;if(O){let{five_hour:y,seven_day:$0}=O;if(y||$0){let V0=Y==="main"?"active":"idle",_0=U0(y?.resetsAt),B0=[`main · ${V0}${_0?` (${_0})`:""}`];if(y)B0.push(M0("5h",y.usedPercent)),K=Math.max(K,y.usedPercent);if($0)B0.push(M0("7d",$0.usedPercent)),K=Math.max(K,$0.usedPercent);L.push(B0.join(`
|
|
10
|
+
`);if(!$||$==="[DONE]")return null;let P;try{P=JSON.parse($)}catch{return null}let N=Y0(P);if(J!=="error"&&s(N,"type")!=="error")return null;let I=Y0(N?.error),H=s(I,"type")??s(I,"code")??void 0,k=s(I,"message")??s(N,"message")??H??"Anthropic stream error";if(!Yj(H,k))return null;return _j(H,k)}function KW(W,J){if(!J)return null;W.pending+=J;while(!0){let j=TW(W.pending);if(!j)break;let $=W.pending.slice(0,j.index);W.pending=W.pending.slice(j.index+j.length);let P=Dj($);if(P)return P}return null}function Ij(W){return{sseEvents:W.events,ssePendingChars:W.pending.length,sseParseErrors:W.parseErrors,sseEventCounts:{...W.eventCounts},sseTypeCounts:{...W.typeCounts},sseDeltaTypeCounts:{...W.deltaTypeCounts},sseContentBlockTypeCounts:{...W.contentBlockTypeCounts},sseTextDeltaBytes:W.textDeltaBytes,sseThinkingDeltaBytes:W.thinkingDeltaBytes,sseInputJsonDeltaBytes:W.inputJsonDeltaBytes,sseSignatureDeltaBytes:W.signatureDeltaBytes,sseRedactedThinkingBytes:W.redactedThinkingBytes,sseLastEvent:W.last?{...W.last}:void 0}}function y0(W,J={}){if(!W.body)return W;let j=W.body.getReader(),$=new TextDecoder,P=new TextEncoder,N="",I=0,H=0,k=0,b=0,m=0,S=!1,r=!1,d=v(),O0=v(),l=J.perf?Vj():void 0,j0=Kj(),N0=()=>{if(r)return;r=!0,j.releaseLock()},z0=(a={})=>({chunks:I,pulls:H,inputBytes:k,outputBytes:b,pendingChars:N.length,rewriteMs:P0(m),totalMs:P0(v()-O0),...l?Ij(l):{},...a}),J0=(a,T0={})=>{J.perf?.(a,z0(T0))};J.perf?.("stream_tool_prefix_wrapper_created",{status:W.status,hasBody:!0});let D1=new ReadableStream({async pull(a){if(H++,!S)S=!0,J0("stream_tool_prefix_first_pull");let T0=v();try{let{done:X0,value:w0}=await j.read(),E0=P0(v()-T0);if(X0){let O=$.decode();if(l)ZW(l,O);let G=KW(j0,O);if(G)throw J0("stream_tool_prefix_retryable_error",{error:G.message,providerErrorType:G.providerErrorType}),N0(),G;let Y=v(),L=OW(`${N}${O}`,!0);if(m+=v()-Y,L.ready){let K=P.encode(L.ready);b+=K.byteLength,a.enqueue(K)}J0("stream_tool_prefix_rewrite",{readMs:E0}),N0(),a.close();return}I++,k+=w0.byteLength;let Q0=$.decode(w0,{stream:!0});if(l)ZW(l,Q0);let L0=KW(j0,Q0);if(L0)throw J0("stream_tool_prefix_retryable_error",{error:L0.message,providerErrorType:L0.providerErrorType,readMs:E0,lastChunkBytes:w0.byteLength}),N0(),L0;let I1=N+Q0,M0=v(),U0=OW(I1);if(m+=v()-M0,N=U0.pending,U0.ready){let O=P.encode(U0.ready);b+=O.byteLength,a.enqueue(O)}let n0=v();if(I===1||I%25===0||n0-d>5000)d=n0,J0("stream_tool_prefix_progress",{readMs:E0,lastChunkBytes:w0.byteLength})}catch(X0){throw J0("stream_tool_prefix_error",{error:X0 instanceof Error?X0.message:String(X0)}),N0(),X0}},async cancel(a){J0("stream_tool_prefix_cancel",{reason:a instanceof Error?a.message:String(a)});try{await j.cancel(a)}finally{N0()}}});return new Response(D1,{status:W.status,statusText:W.statusText,headers:W.headers})}var wj="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",Qj=60000,Lj=60000,Mj=5000,EW=200,M4=240,Uj=M4,Bj=1,SW=!1;function _1(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function F(){return performance.now()}function h(W){return Math.round(W*10)/10}function vW(W){return Math.floor(Math.random()*Math.max(0,W))}function J1(W){if(typeof W==="string")return W;if(W instanceof URL)return W.toString();return W.url}function P1(W,J){return J?.method??(W instanceof Request?W.method:void 0)}function AW(W){return W instanceof Error?W.message:String(W)}function Fj(){if(SW||!1||!_1())return;SW=!0;let W=100,J=250,j=F()+W;setInterval(()=>{let $=F(),P=$-j;if(j=$+W,P<J)return;E("[perf] opencode event_loop_lag",{lagMs:h(P),thresholdMs:J})},W).unref?.()}function Cj(W){let J=F(),j={requestId:String(Bj++),start:J,last:J,mark($,P){let N=F();if(_1())E("[perf] opencode request stage",{requestId:j.requestId,stage:$,deltaMs:h(N-j.last),totalMs:h(N-j.start),...P});j.last=N},done($,P){let N=F();if(_1())E("[perf] opencode request done",{requestId:j.requestId,stage:$,deltaMs:h(N-j.last),totalMs:h(N-j.start),...P});j.last=N}};if(_1())E("[perf] opencode request start",{requestId:j.requestId,...W});return j}async function Hj(W,J,j){let $=W.client.session,P=await r1(W.client,J),N={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:j,ignored:!0}]}};if(P?.agent)N.body.agent=P.agent;if(P?.model)N.body.model=P.model;if(P?.variant)N.body.variant=P.variant;if(typeof $?.promptAsync==="function"){await $.promptAsync(N);return}if(typeof $?.prompt==="function"){await Promise.resolve($.prompt(N));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function fj(){throw Error(wj)}function xj(W){if(W.sessionID==null)return!1;let J=W.model;return J?.providerID==="anthropic"||J?.api?.npm==="@ai-sdk/anthropic"||J?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function qj(W){if(W.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return W.push(kW),!0}var Rj={input:0,output:0,cache:{read:0,write:0}};function Tj(W){let J=W["claude-opus-4-8"]??W["claude-opus-4-5"]??Object.values(W)[0];if(!J)return W;return{...W,...Object.fromEntries(Object.values(K4).map((j)=>[j.id,{...J,id:j.id,name:j.name,api:J.api?{...J.api,id:j.id}:void 0,cost:{input:u0.input,output:u0.output,cache:{read:u0.cacheRead,write:u0.cacheWrite5m}},limit:{...J.limit??{},context:V4,output:X4},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:Z4}]))}}function Ej(W){return Object.fromEntries(Object.entries(W).map(([J,j])=>[J,{...j,cost:Rj}]))}var ej=async(W)=>{Fj();let{client:J}=W,j=bW(),$=await A(j),P=new Y4({storage:$,onMainQuotaFetched:async(O,G,Y,L)=>{try{let K=await A(j)??{version:1,accounts:[]},T=oW(K);if(T&&T.checkedAt>=L&&sW(T.quota,K,T.checkedAt)>Date.now()){P.seedMainFromStorage(K);return}K.quota=K.quota??{},K.quota.mainQuota=O,K.quota.mainQuotaCheckedAt=G,K.quota.mainQuotaToken=Y,K.quota.mainLastQuotaApiError=void 0,await b0(K,j,{mainQuota:!0})}catch(K){E("[quota] failed to persist main quota",{error:K instanceof Error?K.message:String(K)})}},onApiError:async(O)=>{try{let G=await A(j)??{version:1,accounts:[]};G.quota=G.quota??{},G.quota.mainLastQuotaApiError=O,await b0(G,j,{mainQuota:!0})}catch(G){E("[quota] failed to persist backoff state",{error:G instanceof Error?G.message:String(G)})}}}),N=new aW({quotaManager:P,onFallbackStorageChanged:()=>{S()}});N.startBackgroundRefresh();let I=null,H=new $4({loadStorage:()=>A(j),prepareHeaders:async(O,G)=>{if(!d)return O;let Y=await d();if(Y.type!=="oauth")return O;if(!Y.access||Y.expires&&Y.expires<Date.now()){if(!I)return O;Y.access=await I()}if(!Y.access)return O;try{let L=JSON.parse(G.bodyText),K=await S1(Y.access,typeof L.model==="string"?L.model:void 0);if(O.delete("anthropic-beta"),k0(O,Y.access,{body:L,identity:K}),O.set("anthropic-beta",v0(O.get("anthropic-beta"),[W4])),L.speed==="fast")W1(O)}catch{k0(O,Y.access)}return O},log:E});d0({enabled:g0($),mode:m0($)}),X1($1($)),K1(O1($));let k=null;if(W.directory){let O=globalThis;if(O.__anthropicAuthRpcServer)await O.__anthropicAuthRpcServer.stop().catch(()=>{}),O.__anthropicAuthRpcServer=void 0;try{k=await jW({dir:Q4(W.directory),drain:a1,apply:L0}),O.__anthropicAuthRpcServer=k}catch(G){E("[rpc] failed to start",{error:G instanceof Error?G.message:String(G)})}}let b={activeId:"main",route:"main"};function m(O,G){b={activeId:G.activeId,route:G.route},P.updateStorage(O),P.seedMainFromStorage(O,G.mainAccessToken),P.seedFallbacksFromAccounts((O?.accounts??[]).filter(W0));let Y=P.getMain(G.mainAccessToken),L=P.getLastApiError(),K=O?.refresh?.mainLastRefreshError,T={main:{quota:Y?.quota??null,quotaBackedOff:P.isBackedOff(),quotaBackoffUntil:L?.nextRetryAt,refreshBackedOff:K?x0(K,G.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:K?.nextRetryAt},fallbacks:(O?.accounts??[]).filter((f)=>f.enabled!==!1&&W0(f)).map((f)=>({id:f.id,label:f.label,quota:f.access?P.getFallback(f.id,f.access)?.quota??null:null,enabled:f.enabled!==!1})),activeId:G.activeId,route:G.route,relay:(()=>{let f=i1(O);return f?{enabled:!0,transport:f.transport??"http"}:null})(),fastMode:Z1(),cacheKeep:{enabled:k1(O),window:O?.cacheKeep?.startHour!=null&&O?.cacheKeep?.endHour!=null?`${O.cacheKeep.startHour}-${O.cacheKeep.endHour}`:void 0,trackedSessions:H.trackedCount()},lastUpdated:Date.now()};return L4(T).catch((f)=>E("[sidebar] state write failed",{error:f instanceof Error?f.message:String(f)}))}async function S(){let O=await A(j),G,Y;if(d)try{let L=await d();G=L.access,Y=L.refresh}catch{}m(O,{activeId:b.activeId,route:b.route,mainAccessToken:G,mainRefreshToken:Y})}function r(O,G){if(!G)return;if(O?.quota?.enabled!==!0)return;if(P.getMain(G))return;if(O0)return;O0=!0,P.refreshMain(G).then(()=>S()).catch(()=>{}).finally(()=>{O0=!1})}let d=null,O0=!1,l=null,j0=0;function N0(O){let G=O?.refresh?.refreshBeforeExpiryMinutes??Uj;return Math.max(M4,G)*60000}function z0(O){return O?.refresh?.enabled!==!1}async function J0(O){if(!O)return;let G=await A(j),Y=G?.refresh?.mainLastRefreshError;if(!G?.refresh||!Y?.tokenHash)return;let L=G1(O);if(Y.tokenHash===L)return;if(Y.nextRetryAt&&Y.nextRetryAt>Date.now()){E("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:Y.nextRetryAt,retryCount:Y.retryCount,remainingMs:Y.nextRetryAt-Date.now()});return}G.refresh.mainLastRefreshError=void 0,await b0(G,j,{mainRefresh:!0}),E("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:Y.checkedAt,previousNextRetryAt:Y.nextRetryAt,previousRetryCount:Y.retryCount})}async function D1(){let O=[];if(d)try{let K=await d();if(K.type==="oauth"&&K.access){let T=await P.refreshMain(K.access);O.push({name:"OpenCode anthropic",role:"main",quota:T})}else if(K.type==="oauth")O.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(K){let T=K instanceof Error?K.message:String(K);O.push({name:"OpenCode anthropic",role:"main",error:T.includes("429")?"Usage API rate limited — try again in a moment":T})}let{storage:G,errors:Y}=await N.refreshQuotaForAllAccounts({force:!0}),L=new Map(Y.map((K)=>[K.accountId,K.message]));if(O.push(..._4(G,L)),!d)O.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return D4({accounts:O,refreshedAt:Date.now()})}async function a(O){let G=eW(O);if(G.type==="enable"||G.type==="disable"){let T=G.type==="enable",f=await mW(T),y=m0(f);return d0({enabled:T,mode:y}),V1({argumentsText:O,enabled:T,mode:y})}if(G.type==="mode"){let T=await pW(G.mode),f=g0(T);return d0({enabled:f,mode:G.mode}),V1({argumentsText:O,enabled:f,mode:G.mode})}let Y=await A(j),L=g0(Y),K=m0(Y);return d0({enabled:L,mode:K}),V1({argumentsText:O,enabled:L,mode:K})}async function T0(O){let G=j4(O),Y=await A(j);if(G.type==="window")Y=await lW(G.startHour,G.endHour);else if(G.type==="disable")Y=await uW(!1);let L=A1(Y),K=H.stats(L);return P4({argumentsText:O,enabled:J4(Y),window:L,hybridActive:k1(Y),trackedSessions:K.trackedSessions,nextPrewarmAt:K.nextPrewarmAt})}async function X0(O){let G=O4(O);if(G.type==="enable"||G.type==="disable"){let K=G.type==="enable";return await iW(K),X1(K),h1({argumentsText:O,enabled:K})}let Y=await A(j),L=$1(Y);return X1(L),h1({argumentsText:O,enabled:L})}async function w0(O){let G=G4(O);if(G.type==="enable"||G.type==="disable"){let K=G.type==="enable";return await dW(K),K1(K),g1({argumentsText:O,enabled:K})}let Y=await A(j),L=O1(Y);return K1(L),g1({argumentsText:O,enabled:L})}async function E0(O){let G=w4(O);if(G.type==="mode")return await z4(G.mode),l1({argumentsText:O,mode:G.mode});let Y=await A();return l1({argumentsText:O,mode:Y1(Y)})}async function Q0(O,G){if(O==="claude-quota")return{command:O,text:await D1(),knobs:{}};if(O==="claude-routing"){let f=await E0(G),y=await A(j);return{command:O,text:f,knobs:{mode:Y1(y)}}}if(O==="claude-fast"){let f=await w0(G),y=await A(j);return{command:O,text:f,knobs:{enabled:O1(y)}}}if(O==="claude-dump"){let f=await X0(G),y=await A(j);return{command:O,text:f,knobs:{enabled:$1(y)}}}if(O==="claude-cache"){let f=await a(G),y=await A(j);return{command:O,text:f,knobs:{enabled:g0(y),mode:m0(y)}}}if(O==="claude-cachekeep"){let f=await T0(G),y=await A(j);return{command:O,text:f,knobs:{window:A1(y)}}}let Y=await A(),L=T1(Y),K=(Y?.accounts??[]).filter((f)=>f.enabled!==!1).map((f)=>f.id),T=N4({argumentsText:G,config:L,accountIds:K});if(T.updatedConfig)await tW(T.updatedConfig);return{command:O,text:T.text,knobs:{config:T1(await A()),accountIds:K}}}async function L0(O){let G=await Q0(O.command,O.arguments);return{text:G.text,knobs:G.knobs}}function I1(O,G=10){let Y=Math.max(0,Math.min(Math.round(O/100*G),G));return"█".repeat(Y)+"░".repeat(G-Y)}function M0(O,G){return`${O} ${I1(G)} ${String(Math.round(G)).padStart(3)}%`}function U0(O){if(!O)return"";let G=new Date(O).getTime();if(Number.isNaN(G))return"";let Y=G-Date.now();if(Y<=0)return"resets now";let L=Math.floor(Y/60000);if(L<1)return"resets <1m";if(L<60)return`resets ${L}m`;let K=Math.floor(L/60),T=L%60;return T>0?`resets ${K}h${T}m`:`resets ${K}h`}function n0(O,G,Y){let L=[],K=0;if(O){let{five_hour:y,seven_day:$0}=O;if(y||$0){let V0=Y==="main"?"active":"idle",_0=U0(y?.resetsAt),B0=[`main · ${V0}${_0?` (${_0})`:""}`];if(y)B0.push(M0("5h",y.usedPercent)),K=Math.max(K,y.usedPercent);if($0)B0.push(M0("7d",$0.usedPercent)),K=Math.max(K,$0.usedPercent);L.push(B0.join(`
|
|
11
11
|
`))}}if(G?.length)for(let y of G){let $0=y.quota;if(!$0)continue;let{five_hour:Z0,seven_day:V0}=$0;if(!Z0&&!V0)continue;let _0=y.label||"alt",c0=Y===y.id?"active":"idle",F0=U0(Z0?.resetsAt),D0=[`${_0} · ${c0}${F0?` (${F0})`:""}`];if(Z0)D0.push(M0("5h",Z0.usedPercent)),K=Math.max(K,Z0.usedPercent);if(V0)D0.push(M0("7d",V0.usedPercent)),K=Math.max(K,V0.usedPercent);L.push(D0.join(`
|
|
12
12
|
`))}if(!L.length)return;let T=L.join(`
|
|
13
13
|
|
|
14
|
-
`),f=K>=90?"error":K>=70?"warning":"info";J.tui?.showToast?.({body:{title:"Claude Quota",message:T,variant:f,duration:f==="error"?8000:5000}})?.catch?.(()=>{})}return{config:async(O)=>{O.command={...O.command??{},[E1]:{template:E1,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[v1]:{template:v1,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[p1]:{template:p1,description:"Show current Claude OAuth quota usage for all accounts."},[y1]:{template:y1,description:"Show or toggle Anthropic request dump capture for debugging."},[b1]:{template:b1,description:"Show or toggle Anthropic fast mode for supported Opus models."},[
|
|
14
|
+
`),f=K>=90?"error":K>=70?"warning":"info";J.tui?.showToast?.({body:{title:"Claude Quota",message:T,variant:f,duration:f==="error"?8000:5000}})?.catch?.(()=>{})}return{config:async(O)=>{O.command={...O.command??{},[E1]:{template:E1,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[v1]:{template:v1,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[p1]:{template:p1,description:"Show current Claude OAuth quota usage for all accounts."},[y1]:{template:y1,description:"Show or toggle Anthropic request dump capture for debugging."},[b1]:{template:b1,description:"Show or toggle Anthropic fast mode for supported Opus models."},[d1]:{template:d1,description:"Show or change Claude account routing between main-first and fallback-first."},[m1]:{template:m1,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."}}},"experimental.chat.system.transform":async(O,G)=>{if(!xj(O))return;qj(G.system)},provider:{id:"anthropic",async models(O,G){let Y=Tj(O.models);if(G.auth?.type!=="oauth"||!hW($??{}))return Y;return Ej(Y)}},"command.execute.before":async(O)=>{if(!["claude-cache","claude-cachekeep","claude-quota","claude-dump","claude-fast","claude-routing","claude-killswitch"].includes(O.command))return;let Y=O.command,L=await Q0(Y,O.arguments);if(Y==="claude-quota"){let K=await A(),T=d?await d().catch(()=>{return}):void 0;m(K,{activeId:"main",route:"main",mainAccessToken:T?.access,mainRefreshToken:T?.refresh})}if(e1(O.sessionID))s1(L,O.sessionID);else await Hj(W,O.sessionID,L.text);fj()},auth:{provider:"anthropic",async loader(O,G){d=O;let Y=await O();if(Y.type==="oauth"){let T=function(){if(l)clearInterval(l),l=null;let X=async()=>{try{let D=await A(j);if(!z0(D))return;let q=await O();if(q.type!=="oauth")return;if(await J0(q.refresh),!q.expires)return;let w=q.expires-Date.now(),x=N0(D);if(w>x)return;if(E("[refresh] opencode main oauth background due",{expiresInMs:w,refreshBeforeMs:x}),q.refresh&&x0(D?.refresh?.mainLastRefreshError,q.refresh,Date.now())){E("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:D?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:D?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:w});return}if(q.refresh&&D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===G1(q.refresh))return;await K();let Z=await O();E("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:Z.expires?Z.expires-Date.now():void 0})}catch(D){E("[refresh] opencode main oauth refresh failed",{message:D instanceof Error?D.message:String(D)})}};if(l=setInterval(()=>{X()},Qj+vW(Lj)),"unref"in l)l.unref()},f=function(X,D){if(X instanceof Request&&X.body)return!1;return D==null||typeof D==="string"},y=function(X){return X.has("x-parent-session-id")},$0=function(X){return X.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(X)},Z0=function(X){return X?.quota?.enabled===!0},_0=function(X,D){if(X.delete("authorization"),X.delete("x-api-key"),D.authHeader==="x-api-key")X.set("x-api-key",D.apiKey??"");else X.set("Authorization",`Bearer ${D.apiKey??""}`);X.set("Content-Type","application/json")},F0=function(X){return P.getFallback(X.id,X.access)?.quota??X.quota},D0=function(X){return Object.values(X??{}).some((D)=>D&&D.remainingPercent<=0)},u1=function(X,D){return X.status===429||D},z1=function(X){if(!X)return!1;let D=P.getMain(X);return Boolean(D&&D.refreshAfter>Date.now()&&D0(D.quota))},L=null;async function K(){if(!L)L=(async()=>{let q=null,w=null,x=null;async function Z(_){let R=await A(j)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};R.refresh=R.refresh??{},_(R),await b0(R,j,{mainRefresh:!0})}async function p(_){let R=Date.now()+Mj;while(Date.now()<R){await new Promise((B)=>setTimeout(B,EW+vW(EW)));let V=await O();if(V.type!=="oauth"||!V.access)continue;if((V.access!==_.access||V.refresh!==_.refresh||(V.expires??0)>(_.expires??0)+60000)&&(!V.expires||V.expires>Date.now()))return E("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:V.expires?V.expires-Date.now():void 0}),V.access}return null}for(let _=0;_<=2;_++){let R=null;try{if(_>0){let C=500*2**(_-1);await new Promise((Q)=>setTimeout(Q,C))}if(R=await O(),!R.refresh)throw Error("Token refresh failed: missing refresh token");let V=await A(j),z=G1(R.refresh),B=V?.refresh?.mainLastRefreshError;if(E("[refresh] opencode main oauth refresh check",{attempt:_,expiresInMs:R.expires?R.expires-Date.now():void 0,hasBackoff:Boolean(B),backoffActive:B?x0(B,R.refresh,Date.now()):!1,retryCount:B?.retryCount,nextRetryAt:B?.nextRetryAt}),B&&x0(B,R.refresh,Date.now()))throw E("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:B.nextRetryAt,retryCount:B.retryCount}),Error(R1(B,Date.now()));if(V?.refresh?.mainRefreshLeaseUntil&&V.refresh.mainRefreshLeaseUntil>Date.now()&&V.refresh.mainRefreshLeaseTokenHash===z){E("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:V.refresh.mainRefreshLeaseUntil});let C=await p(R);if(C)return C;throw Error("Claude OAuth refresh is already in progress")}let M=await gW({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!M){E("[refresh] opencode main oauth refresh skipped file lock");let C=await p(R);if(C)return C;throw Error("Claude OAuth refresh is already in progress")}x=M.release,q=zj(),w=z,await Z((C)=>{C.refresh=C.refresh??{},C.refresh.mainRefreshLeaseId=q??void 0,C.refresh.mainRefreshLeaseUntil=Date.now()+120000,C.refresh.mainRefreshLeaseTokenHash=z});let c=await A(j);if(E("[refresh] opencode main oauth refresh lease acquired",{attempt:_,leaseUntil:Date.now()+120000}),c?.refresh?.mainRefreshLeaseId!==q||c.refresh.mainRefreshLeaseTokenHash!==z)throw Error("Claude OAuth refresh is already in progress");E("[refresh] opencode main oauth refresh request start",{attempt:_});let u=await yW({refreshToken:R.refresh,maxRetries:0});return await J.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:u.refresh,access:u.access,expires:u.expires}}),await Z((C)=>{if(!C?.refresh)return;if(C.refresh.mainLastRefreshError=void 0,C.refresh.mainRefreshLeaseId===q)C.refresh.mainRefreshLeaseId=void 0,C.refresh.mainRefreshLeaseUntil=void 0,C.refresh.mainRefreshLeaseTokenHash=void 0}),E("[refresh] opencode main oauth refresh succeeded",{attempt:_,expiresInMs:u.expires-Date.now()}),u.access}catch(V){let z=V instanceof Error&&(V.message.includes("fetch failed")||("code"in V)&&(V.code==="ECONNRESET"||V.code==="ECONNREFUSED"||V.code==="ETIMEDOUT"||V.code==="UND_ERR_CONNECT_TIMEOUT"));if(_<2&&(z||V instanceof C1&&V.status>=500))continue;E("[refresh] opencode main oauth refresh attempt failed",{attempt:_,error:V instanceof Error?V.message:String(V),transient:z});let B=R?.refresh;if(B&&V instanceof C1)await Z((M)=>{M.refresh=M.refresh??{},M.refresh.mainLastRefreshError=nW({error:V,now:Date.now(),refreshToken:B,previous:M.refresh.mainLastRefreshError})});throw V}finally{if(q)await Z((V)=>{if(!V?.refresh)return;if(V.refresh.mainRefreshLeaseId===q&&V.refresh.mainRefreshLeaseTokenHash===w)V.refresh.mainRefreshLeaseId=void 0,V.refresh.mainRefreshLeaseUntil=void 0,V.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await x?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{L=null});return L}I=K,T(),P.seedFallbacksFromAccounts(($?.accounts??[]).filter(W0)),m($,{activeId:"main",route:"main",mainAccessToken:Y.access,mainRefreshToken:Y.refresh});async function V0(X,D){if(!X.body||X.status!==200)return D?.mark("inspect_stream_skip",{status:X.status}),{response:X,rateLimited:!1};if(X.headers.get("x-cortexkit-relay-optimistic")==="true")return D?.mark("inspect_stream_skip",{status:X.status,reason:"optimistic_relay"}),{response:X,rateLimited:!1};let q=F(),w=X.body.getReader(),x=[],Z=new TextDecoder,p="",_=0;while(!p.includes(`
|
|
15
15
|
|
|
16
|
-
`)&&p.length<65536){let{done:V,value:w}=await z.read();if(V)break;if(x.push(w),_+=w.byteLength,p+=X.decode(w,{stream:!0}),$0(p))break}if($0(p))return await z.cancel().catch(()=>{}),D?.mark("inspect_stream_first_event",{ms:h(F()-q),bytes:_,rateLimited:!0}),{response:Z,rateLimited:!0};let R=new ReadableStream({start(V){for(let w of x)V.enqueue(w)},async pull(V){let{done:w,value:B}=await z.read();if(w){V.close();return}V.enqueue(B)},cancel(V){return z.cancel(V)}});return D?.mark("inspect_stream_first_event",{ms:h(F()-q),bytes:_,rateLimited:!1}),{response:new Response(R,{status:Z.status,statusText:Z.statusText,headers:Z.headers}),rateLimited:!1}}async function B0(Z,D,q,z,x="api_fallback",X){let p=F(),_=M1(Z,D),R=_.get("x-session-affinity")||_.get("x-opencode-session"),V=y(_);_.delete("x-parent-session-id"),_.delete("x-session-affinity"),_.delete("x-opencode-session");let w=D?.body,B=typeof w==="string"?w.length:void 0;if(w&&typeof w==="string"){let C=F(),Q=(()=>{if(!Z1())return!1;try{return A0(JSON.parse(w).model)}catch{return!1}})();if(w=await F1(w,{cache1hEnabled:!V&&q0(),cache1hMode:R0(),fastModeEnabled:Q,perf:(U,g)=>z?.mark(`rewrite_body_${U}`,{route:x,...g})}),_0(_,q),_.set("anthropic-beta",v0(_.get("anthropic-beta"),[])),Q)W1(_);z?.mark("rewrite_body",{route:x,ms:h(F()-C),originalBytes:B,rewrittenBytes:w.length,cacheEnabled:!V&&q0(),cacheMode:R0(),fastModeEnabled:Q,subagent:V})}else _0(_,q);let M=B1(Z,{baseURL:q.baseURL}),c=F(),n;try{n=await fetch(M.input,{...D,body:w,headers:_,...U1()&&{tls:{rejectUnauthorized:!1}}})}catch(C){if(typeof w==="string")await d0({affinity:R,route:x,error:AW(C),bodyText:w,url:M.url?.toString()??J1(M.input),method:P1(Z,D),headers:_});throw C}if(typeof w==="string")await d0({affinity:R,route:x,status:n.status,bodyText:w,url:M.url?.toString()??J1(M.input),method:P1(Z,D),headers:_});return z?.mark("send_headers_received",{route:x,ms:h(F()-c),status:n.status,relayConfigured:!1,totalSendWithAccessMs:h(F()-p),baseURL:q.baseURL}),n}async function c0(Z,D,q,z,x="unknown",X){let p=F(),_=X,R=async()=>{return _??=await A(j),_},V=M1(Z,D),w=V.get("x-session-affinity")||V.get("x-opencode-session"),B=y(V);V.delete("x-parent-session-id"),V.delete("x-session-affinity"),V.delete("x-opencode-session");let M=D?.body,c;if(M&&typeof M==="string"){let o=F();try{let G0=JSON.parse(M);if(typeof G0.model==="string")c=G0.model}catch{}z?.mark("model_parse_for_identity",{route:x,ms:h(F()-o),bodyBytes:M.length})}let n=F(),C=await S1(q,c);z?.mark("resolve_claude_code_identity",{route:x,ms:h(F()-n),hasAccountUuid:Boolean(C.accountUuid)});let Q=typeof M==="string"?M.length:void 0;if(M&&typeof M==="string"){let o=F(),G0=(()=>{if(!Z1())return!1;try{return A0(JSON.parse(M).model)}catch{return!1}})();M=await F1(M,{cache1hEnabled:!B&&q0(),cache1hMode:R0(),fastModeEnabled:G0,identity:C,perf:(F4,C4)=>z?.mark(`rewrite_body_${F4}`,{route:x,...C4})});let C0=F();try{k0(V,q,{body:JSON.parse(M),identity:C}),z?.mark("set_oauth_headers_body_parse",{route:x,ms:h(F()-C0),bodyBytes:M.length,parsed:!0})}catch{k0(V,q,{identity:C}),z?.mark("set_oauth_headers_body_parse",{route:x,ms:h(F()-C0),bodyBytes:M.length,parsed:!1})}if(G0)W1(V);z?.mark("rewrite_body",{route:x,ms:h(F()-o),originalBytes:Q,rewrittenBytes:M.length,cacheEnabled:!B&&q0(),cacheMode:R0(),fastModeEnabled:G0,subagent:B})}let U=B1(Z);if(x==="main"&&typeof M==="string"&&!B&&q0()&&R0()==="hybrid"){let o=await R(),G0=F(),C0=H.track({sessionId:w,url:U.url?.toString()??U.input.toString(),headers:V,bodyText:M,storage:o,cacheMode:"hybrid"});z?.mark("cachekeep_track",{session:w,ms:h(F()-G0),tracked:C0.tracked,reason:C0.tracked?void 0:C0.reason,bodyBytes:M.length})}let g=async()=>{try{let o=await fetch(U.input,{...D,body:M,headers:V,...U1()&&{tls:{rejectUnauthorized:!1}}});if(typeof M==="string")await d0({affinity:w,route:x,status:o.status,bodyText:M,url:U.url?.toString()??J1(U.input),method:P1(Z,D),headers:V});return o}catch(o){if(typeof M==="string")await d0({affinity:w,route:x,error:AW(o),bodyText:M,url:U.url?.toString()??J1(U.input),method:P1(Z,D),headers:V});throw o}},e=i1(await R()),u=F(),t=await I4({config:e,input:U.input,init:D,headers:V,body:M,fallback:g,affinity:w,optimisticResponse:e?.transport==="websocket"});return z?.mark("send_headers_received",{route:x,ms:h(F()-u),status:t.status,relayConfigured:e!=null,totalSendWithAccessMs:h(F()-p)}),t}async function U4(Z){if(!Z)return!1;try{return await P.refreshMain(Z),z1(Z)}catch{return!1}}async function o0(Z,D={}){let q=await N.getUsableFallbackAccounts(Z),z=new Map(q.map((X)=>[X.id,X])),x=[];for(let X of Z?.accounts??[]){if(W0(X)){let p=z.get(X.id);if(p)x.push(p);continue}if(D.includeApiRoutes===!0&&h0(X)&&X.enabled!==!1&&X.apiKey&&x1(X.baseURL))x.push(X)}if(!i0(Z))return x;return x.filter((X)=>W0(X)?N1(F0(X),Z,X.id):!0)}async function r0(Z,D,q,z,x,X,p){if(!q.length)return x??null;let _=p?.returnLastOnExhausted??!0;await x?.body?.cancel().catch(()=>{});let R=x??null;for(let[V,w]of q.entries()){let B;if(h0(w)){if(!w.apiKey)continue;B=await B0(Z,D,w,X,`api_fallback_${V}`,z)}else{let c=w.access;if(!c)continue;B=await c0(Z,D,c,X,`fallback_${V}`,z)}R=B;let M=q1(B.status,z);if(!M){let c=await V0(B,X);B=c.response,R=B,M=c.rateLimited}if(!M){if(await N.markUsed(w),p?.onSuccess?.(w),W0(w)&&w.access&&P.shouldRefreshOnRequestCount(j0))P.refreshFallback(w.id,w.access).then(()=>p?.onSuccess?.(w)).catch(()=>{});return B}if(V<q.length-1||!_)await B.body?.cancel().catch(()=>{})}return _?R:null}async function B4(Z,D,q,z,x,X,p,_){if(!f(Z,D?.body))return q;let R=F(),V=X??await A(j);if(x?.mark("fallback_load_storage",{ms:h(F()-R),cached:!!X}),!(V?.accounts??[]).some((Q)=>Q.enabled!==!1&&(W0(Q)||h0(Q)&&Boolean(Q.apiKey)&&x1(Q.baseURL))))return q;let B=q,M=q1(B.status,V),c=n1(B,!1);if(!M){let Q=await V0(B,x);B=Q.response,M=Q.rateLimited,c=n1(B,Q.rateLimited)}if(!M)return B;let n=!1;if(z)n=z.some(h0);else if(c)n=await U4(p);let C=z;if(!C){let Q=F();C=await o0(V,{includeApiRoutes:n}),x?.mark("fallback_get_accounts",{ms:h(F()-Q),accounts:C.length})}if(i0(V)){let Q=C.length;if(C=C.filter((U)=>W0(U)?N1(F0(U),V,U.id):!0),C.length<Q)E("[killswitch] filtered fallbacks",{before:Q,after:C.length})}return await r0(Z,D,C,V,B,x,{onSuccess:_})??B}return{apiKey:"",async fetch(Z,D){let q=D?.body,z=Cj({bodyBytes:typeof q==="string"?q.length:void 0}),x=F(),X=await O();if(z.mark("get_auth",{ms:h(F()-x),authType:X.type,hasAccess:Boolean(X.access)}),X.type!=="oauth"){let Q=await fetch(Z,D);return z.done("non_oauth_passthrough",{status:Q.status}),Q}await J0(X.refresh);let p=F(),_=await A();z.mark("load_storage",{ms:h(F()-p)}),P.updateStorage(_),P.seedMainFromStorage(_,X.access),P.seedFallbacksFromAccounts((_?.accounts??[]).filter(W0));let R=f(Z,D?.body);if(R)j0++;if(R&&X.access&&(!X.expires||X.expires>Date.now()))r(_,X.access);let V=(Q,U)=>m(_,{activeId:Q,route:U,mainAccessToken:X.access,mainRefreshToken:X.refresh}),w;if(R&&Y1(_)==="fallback-first")try{let Q=F();w=await o0(_,{includeApiRoutes:z1(X.access)}),z.mark("fallback_first_get_accounts",{ms:h(F()-Q),accounts:w.length});let U=await r0(Z,D,w,_,void 0,z,{returnLastOnExhausted:!1,onSuccess:(g)=>V(g.id,"fallback-first")});if(U)return z.done("return_fallback_first",{status:U.status}),y0(U,{perf:(g,e)=>z.mark(g,e)});w=void 0}catch(Q){z.mark("fallback_first_error",{error:Q instanceof Error?Q.message:String(Q)})}if(!X.access||!X.expires||X.expires<Date.now()){let U=(await A())?.refresh?.mainLastRefreshError;if(X.refresh&&U&&x0(U,X.refresh,Date.now()))throw E("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:U.nextRetryAt,retryCount:U.retryCount,expiresInMs:X.expires?X.expires-Date.now():void 0}),Error(R1(U,Date.now()));E("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(X.access),expiresInMs:X.expires?X.expires-Date.now():void 0,expiredAgoMs:X.expires&&X.expires<Date.now()?Date.now()-X.expires:void 0});let g=F();X.access=await K(),z.mark("refresh_main_access",{ms:h(F()-g)})}if(!X.access)throw z.done("missing_access_error"),Error("OAuth access token is missing after refresh");function B(){if(_?.quota?.showToasts!==!0)return;let Q=P.getMain();if(!Q)return;let U=(_?.accounts??[]).filter((u)=>u.enabled!==!1&&W0(u)).map((u)=>({...u,quota:P.getFallback(u.id,u.access)?.quota??u.quota})),g=p0(Q.quota,_),e;if(g)e="main";else e=U.find((u)=>p0(u.quota,_))?.id??"main";u0(Q.quota,U,e)}if(R&&Z0(_))try{let Q=F(),U=P.getMain(X.access),g=U?.quota;if(!g)g=await P.refreshMain(X.access),U=P.getMain(X.access),B();else if(P.needsRefresh(j0))if(D0(g))g=await P.refreshMain(X.access),U=P.getMain(X.access);else P.refreshMain(X.access).then(()=>{S(),B()}).catch(()=>{});if(m(_,{activeId:"main",route:"main",mainAccessToken:X.access,mainRefreshToken:X.refresh}),z.mark("main_quota_for_routing",{ms:h(F()-Q),passes:p0(g,_)}),!p0(g,_)){let e=F();w=await o0(_,{includeApiRoutes:Boolean(U&&U.refreshAfter>Date.now()&&D0(U.quota))}),z.mark("preselect_fallback_accounts",{ms:h(F()-e),accounts:w.length});let u=await r0(Z,D,w,_,void 0,z,{onSuccess:(t)=>V(t.id,"fallback")});if(u)return z.done("return_preselected_fallback",{status:u.status}),y0(u,{perf:(t,o)=>z.mark(t,o)})}}catch(Q){z.mark("main_quota_for_routing_error",{error:Q instanceof Error?Q.message:String(Q)})}let M=P.getMain(X.access)?.quota;if(_?.quota?.failClosedOnUnknownQuota&&!M&&P.isBackedOff()){let Q=P.getLastApiError(),U=Q?cW(Q,Date.now()):"Quota API unavailable";return E("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:Q?.nextRetryAt,retryCount:Q?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:U}}),{status:429,headers:{"content-type":"application/json","retry-after":String(Q?.nextRetryAt?Math.max(1,Math.ceil((Q.nextRetryAt-Date.now())/1000)):60)}})}if(i0(_)){if(P.needsRefresh(j0))try{let U=(_?.accounts??[]).filter((g)=>g.enabled!==!1&&W0(g)&&Boolean(g.access));await Promise.all([P.refreshMain(X.access),P.refreshAllFallbacks(U)])}catch(U){E("[quota] killswitch refresh failed",{error:U instanceof Error?U.message:String(U),backedOff:P.isBackedOff()})}M=P.getMain(X.access)?.quota}if(i0(_)&&!N1(M,_)){let U=f(Z,D?.body)?await o0(_,{includeApiRoutes:z1(X.access)}):[];if(U.length>0){E("[route] skipping main (killswitch), trying fallbacks");let t=await r0(Z,D,U,_,void 0,z,{onSuccess:(o)=>V(o.id,"fallback")});if(t)return z.done("return_killswitch_fallback",{status:t.status}),y0(t,{perf:(o,G0)=>z.mark(o,G0)})}let g=Date.now(),e=(_?.accounts??[]).filter((t)=>t.enabled!==!1&&W0(t)).map((t)=>({...t,quota:F0(t)})),u=rW(M,e,g);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:`Killswitch: no routable accounts. Retry in ${Math.floor(u/60)}m ${u%60}s.`}}),{status:429,headers:{"content-type":"application/json","retry-after":String(u)}})}let c=await c0(Z,D,X.access,z,"main",_),n=!1,C=await B4(Z,D,c,w,z,_,X.access,(Q)=>{n=!0,V(Q.id,"fallback")});if(!n)V("main","main");return z.done("return_response",{status:C.status}),y0(C,{perf:(Q,U)=>z.mark(Q,U)})}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let O=await H1("max");return{url:O.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{return f1(G,O.verifier,O.redirectUri,O.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let O=await H1("console");return{url:O.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{let Y=await f1(G,O.verifier,O.redirectUri,O.state);if(Y.type==="failed")return Y;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${Y.access}`}}).then((K)=>K.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{ej as AnthropicAuthPlugin};
|
|
16
|
+
`)&&p.length<65536){let{done:V,value:z}=await w.read();if(V)break;if(x.push(z),_+=z.byteLength,p+=Z.decode(z,{stream:!0}),$0(p))break}if($0(p)){await w.cancel().catch(()=>{});try{w.releaseLock()}catch{}let V=new ReadableStream({start(z){for(let B of x)z.enqueue(B);z.close()}});return D?.mark("inspect_stream_first_event",{ms:h(F()-q),bytes:_,rateLimited:!0}),{response:new Response(V,{status:X.status,statusText:X.statusText,headers:X.headers}),rateLimited:!0}}let R=new ReadableStream({start(V){for(let z of x)V.enqueue(z)},async pull(V){let{done:z,value:B}=await w.read();if(z){V.close();return}V.enqueue(B)},cancel(V){return w.cancel(V)}});return D?.mark("inspect_stream_first_event",{ms:h(F()-q),bytes:_,rateLimited:!1}),{response:new Response(R,{status:X.status,statusText:X.statusText,headers:X.headers}),rateLimited:!1}}async function B0(X,D,q,w,x="api_fallback",Z){let p=F(),_=M1(X,D),R=_.get("x-session-affinity")||_.get("x-opencode-session"),V=y(_);_.delete("x-parent-session-id"),_.delete("x-session-affinity"),_.delete("x-opencode-session");let z=D?.body,B=typeof z==="string"?z.length:void 0;if(z&&typeof z==="string"){let C=F(),Q=(()=>{if(!Z1())return!1;try{return A0(JSON.parse(z).model)}catch{return!1}})();if(z=await F1(z,{cache1hEnabled:!V&&q0(),cache1hMode:R0(),fastModeEnabled:Q,perf:(U,g)=>w?.mark(`rewrite_body_${U}`,{route:x,...g})}),_0(_,q),_.set("anthropic-beta",v0(_.get("anthropic-beta"),[])),Q)W1(_);w?.mark("rewrite_body",{route:x,ms:h(F()-C),originalBytes:B,rewrittenBytes:z.length,cacheEnabled:!V&&q0(),cacheMode:R0(),fastModeEnabled:Q,subagent:V})}else _0(_,q);let M=B1(X,{baseURL:q.baseURL}),c=F(),u;try{u=await fetch(M.input,{...D,body:z,headers:_,...U1()&&{tls:{rejectUnauthorized:!1}}})}catch(C){if(typeof z==="string")await l0({affinity:R,route:x,error:AW(C),bodyText:z,url:M.url?.toString()??J1(M.input),method:P1(X,D),headers:_});throw C}if(typeof z==="string")await l0({affinity:R,route:x,status:u.status,bodyText:z,url:M.url?.toString()??J1(M.input),method:P1(X,D),headers:_});return w?.mark("send_headers_received",{route:x,ms:h(F()-c),status:u.status,relayConfigured:!1,totalSendWithAccessMs:h(F()-p),baseURL:q.baseURL}),u}async function c0(X,D,q,w,x="unknown",Z){let p=F(),_=Z,R=async()=>{return _??=await A(j),_},V=M1(X,D),z=V.get("x-session-affinity")||V.get("x-opencode-session"),B=y(V);V.delete("x-parent-session-id"),V.delete("x-session-affinity"),V.delete("x-opencode-session");let M=D?.body,c;if(M&&typeof M==="string"){let o=F();try{let G0=JSON.parse(M);if(typeof G0.model==="string")c=G0.model}catch{}w?.mark("model_parse_for_identity",{route:x,ms:h(F()-o),bodyBytes:M.length})}let u=F(),C=await S1(q,c);w?.mark("resolve_claude_code_identity",{route:x,ms:h(F()-u),hasAccountUuid:Boolean(C.accountUuid)});let Q=typeof M==="string"?M.length:void 0;if(M&&typeof M==="string"){let o=F(),G0=(()=>{if(!Z1())return!1;try{return A0(JSON.parse(M).model)}catch{return!1}})();M=await F1(M,{cache1hEnabled:!B&&q0(),cache1hMode:R0(),fastModeEnabled:G0,identity:C,perf:(F4,C4)=>w?.mark(`rewrite_body_${F4}`,{route:x,...C4})});let C0=F();try{k0(V,q,{body:JSON.parse(M),identity:C}),w?.mark("set_oauth_headers_body_parse",{route:x,ms:h(F()-C0),bodyBytes:M.length,parsed:!0})}catch{k0(V,q,{identity:C}),w?.mark("set_oauth_headers_body_parse",{route:x,ms:h(F()-C0),bodyBytes:M.length,parsed:!1})}if(G0)W1(V);w?.mark("rewrite_body",{route:x,ms:h(F()-o),originalBytes:Q,rewrittenBytes:M.length,cacheEnabled:!B&&q0(),cacheMode:R0(),fastModeEnabled:G0,subagent:B})}let U=B1(X);if(x==="main"&&typeof M==="string"&&!B&&q0()&&R0()==="hybrid"){let o=await R(),G0=F(),C0=H.track({sessionId:z,url:U.url?.toString()??U.input.toString(),headers:V,bodyText:M,storage:o,cacheMode:"hybrid"});w?.mark("cachekeep_track",{session:z,ms:h(F()-G0),tracked:C0.tracked,reason:C0.tracked?void 0:C0.reason,bodyBytes:M.length})}let g=async()=>{try{let o=await fetch(U.input,{...D,body:M,headers:V,...U1()&&{tls:{rejectUnauthorized:!1}}});if(typeof M==="string")await l0({affinity:z,route:x,status:o.status,bodyText:M,url:U.url?.toString()??J1(U.input),method:P1(X,D),headers:V});return o}catch(o){if(typeof M==="string")await l0({affinity:z,route:x,error:AW(o),bodyText:M,url:U.url?.toString()??J1(U.input),method:P1(X,D),headers:V});throw o}},e=i1(await R()),n=F(),t=await I4({config:e,input:U.input,init:D,headers:V,body:M,fallback:g,affinity:z,optimisticResponse:e?.transport==="websocket"});return w?.mark("send_headers_received",{route:x,ms:h(F()-n),status:t.status,relayConfigured:e!=null,totalSendWithAccessMs:h(F()-p)}),t}async function U4(X){if(!X)return!1;try{return await P.refreshMain(X),z1(X)}catch{return!1}}async function o0(X,D={}){let q=await N.getUsableFallbackAccounts(X),w=new Map(q.map((Z)=>[Z.id,Z])),x=[];for(let Z of X?.accounts??[]){if(W0(Z)){let p=w.get(Z.id);if(p)x.push(p);continue}if(D.includeApiRoutes===!0&&h0(Z)&&Z.enabled!==!1&&Z.apiKey&&x1(Z.baseURL))x.push(Z)}if(!i0(X))return x;return x.filter((Z)=>W0(Z)?N1(F0(Z),X,Z.id):!0)}async function r0(X,D,q,w,x,Z,p){if(!q.length)return x??null;let _=p?.returnLastOnExhausted??!0;await x?.body?.cancel().catch(()=>{});let R=x??null;for(let[V,z]of q.entries()){let B;if(h0(z)){if(!z.apiKey)continue;B=await B0(X,D,z,Z,`api_fallback_${V}`,w)}else{let c=z.access;if(!c)continue;B=await c0(X,D,c,Z,`fallback_${V}`,w)}R=B;let M=q1(B.status,w);if(!M){let c=await V0(B,Z);B=c.response,R=B,M=c.rateLimited}if(!M){if(await N.markUsed(z),await p?.onSuccess?.(z),W0(z)&&z.access&&P.shouldRefreshOnRequestCount(j0))P.refreshFallback(z.id,z.access).then(()=>p?.onSuccess?.(z)).catch(()=>{});return B}if(V<q.length-1||!_)await B.body?.cancel().catch(()=>{})}return _?R:null}async function B4(X,D,q,w,x,Z,p,_){if(!f(X,D?.body))return q;let R=F(),V=Z??await A(j);if(x?.mark("fallback_load_storage",{ms:h(F()-R),cached:!!Z}),!(V?.accounts??[]).some((Q)=>Q.enabled!==!1&&(W0(Q)||h0(Q)&&Boolean(Q.apiKey)&&x1(Q.baseURL))))return q;let B=q,M=q1(B.status,V),c=u1(B,!1);if(!M){let Q=await V0(B,x);B=Q.response,M=Q.rateLimited,c=u1(B,Q.rateLimited)}if(!M)return B;let u=!1;if(w)u=w.some(h0);else if(c)u=await U4(p);let C=w;if(!C){let Q=F();C=await o0(V,{includeApiRoutes:u}),x?.mark("fallback_get_accounts",{ms:h(F()-Q),accounts:C.length})}if(i0(V)){let Q=C.length;if(C=C.filter((U)=>W0(U)?N1(F0(U),V,U.id):!0),C.length<Q)E("[killswitch] filtered fallbacks",{before:Q,after:C.length})}return await r0(X,D,C,V,B,x,{onSuccess:_})??B}return{apiKey:"",async fetch(X,D){let q=D?.body,w=Cj({bodyBytes:typeof q==="string"?q.length:void 0}),x=F(),Z=await O();if(w.mark("get_auth",{ms:h(F()-x),authType:Z.type,hasAccess:Boolean(Z.access)}),Z.type!=="oauth"){let Q=await fetch(X,D);return w.done("non_oauth_passthrough",{status:Q.status}),Q}await J0(Z.refresh);let p=F(),_=await A();w.mark("load_storage",{ms:h(F()-p)}),P.updateStorage(_),P.seedMainFromStorage(_,Z.access),P.seedFallbacksFromAccounts((_?.accounts??[]).filter(W0));let R=f(X,D?.body);if(R)j0++;if(R&&Z.access&&(!Z.expires||Z.expires>Date.now()))r(_,Z.access);let V=(Q,U)=>m(_,{activeId:Q,route:U,mainAccessToken:Z.access,mainRefreshToken:Z.refresh}),z;if(R&&Y1(_)==="fallback-first")try{let Q=F();z=await o0(_,{includeApiRoutes:z1(Z.access)}),w.mark("fallback_first_get_accounts",{ms:h(F()-Q),accounts:z.length});let U=await r0(X,D,z,_,void 0,w,{returnLastOnExhausted:!1,onSuccess:(g)=>V(g.id,"fallback-first")});if(U)return w.done("return_fallback_first",{status:U.status}),y0(U,{perf:(g,e)=>w.mark(g,e)});z=void 0}catch(Q){w.mark("fallback_first_error",{error:Q instanceof Error?Q.message:String(Q)})}if(!Z.access||!Z.expires||Z.expires<Date.now()){let U=(await A())?.refresh?.mainLastRefreshError;if(Z.refresh&&U&&x0(U,Z.refresh,Date.now()))throw E("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:U.nextRetryAt,retryCount:U.retryCount,expiresInMs:Z.expires?Z.expires-Date.now():void 0}),Error(R1(U,Date.now()));E("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(Z.access),expiresInMs:Z.expires?Z.expires-Date.now():void 0,expiredAgoMs:Z.expires&&Z.expires<Date.now()?Date.now()-Z.expires:void 0});let g=F();Z.access=await K(),w.mark("refresh_main_access",{ms:h(F()-g)})}if(!Z.access)throw w.done("missing_access_error"),Error("OAuth access token is missing after refresh");function B(){if(_?.quota?.showToasts!==!0)return;let Q=P.getMain();if(!Q)return;let U=(_?.accounts??[]).filter((n)=>n.enabled!==!1&&W0(n)).map((n)=>({...n,quota:P.getFallback(n.id,n.access)?.quota??n.quota})),g=p0(Q.quota,_),e;if(g)e="main";else e=U.find((n)=>p0(n.quota,_))?.id??"main";n0(Q.quota,U,e)}if(R&&Z0(_))try{let Q=F(),U=P.getMain(Z.access),g=U?.quota;if(!g)g=await P.refreshMain(Z.access),U=P.getMain(Z.access),B();else if(P.needsRefresh(j0))if(D0(g))g=await P.refreshMain(Z.access),U=P.getMain(Z.access);else P.refreshMain(Z.access).then(()=>{S(),B()}).catch(()=>{});if(m(_,{activeId:"main",route:"main",mainAccessToken:Z.access,mainRefreshToken:Z.refresh}),w.mark("main_quota_for_routing",{ms:h(F()-Q),passes:p0(g,_)}),!p0(g,_)){let e=F();z=await o0(_,{includeApiRoutes:Boolean(U&&U.refreshAfter>Date.now()&&D0(U.quota))}),w.mark("preselect_fallback_accounts",{ms:h(F()-e),accounts:z.length});let n=await r0(X,D,z,_,void 0,w,{onSuccess:(t)=>V(t.id,"fallback")});if(n)return w.done("return_preselected_fallback",{status:n.status}),y0(n,{perf:(t,o)=>w.mark(t,o)})}}catch(Q){w.mark("main_quota_for_routing_error",{error:Q instanceof Error?Q.message:String(Q)})}let M=P.getMain(Z.access)?.quota;if(_?.quota?.failClosedOnUnknownQuota&&!M&&P.isBackedOff()){let Q=P.getLastApiError(),U=Q?cW(Q,Date.now()):"Quota API unavailable";return E("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:Q?.nextRetryAt,retryCount:Q?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:U}}),{status:429,headers:{"content-type":"application/json","retry-after":String(Q?.nextRetryAt?Math.max(1,Math.ceil((Q.nextRetryAt-Date.now())/1000)):60)}})}if(i0(_)){if(P.needsRefresh(j0))try{let U=(_?.accounts??[]).filter((g)=>g.enabled!==!1&&W0(g)&&Boolean(g.access));await Promise.all([P.refreshMain(Z.access),P.refreshAllFallbacks(U)])}catch(U){E("[quota] killswitch refresh failed",{error:U instanceof Error?U.message:String(U),backedOff:P.isBackedOff()})}M=P.getMain(Z.access)?.quota}if(i0(_)&&!N1(M,_)){let U=f(X,D?.body)?await o0(_,{includeApiRoutes:z1(Z.access)}):[];if(U.length>0){E("[route] skipping main (killswitch), trying fallbacks");let t=await r0(X,D,U,_,void 0,w,{onSuccess:(o)=>V(o.id,"fallback")});if(t)return w.done("return_killswitch_fallback",{status:t.status}),y0(t,{perf:(o,G0)=>w.mark(o,G0)})}let g=Date.now(),e=(_?.accounts??[]).filter((t)=>t.enabled!==!1&&W0(t)).map((t)=>({...t,quota:F0(t)})),n=rW(M,e,g);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:`Killswitch: no routable accounts. Retry in ${Math.floor(n/60)}m ${n%60}s.`}}),{status:429,headers:{"content-type":"application/json","retry-after":String(n)}})}let c=await c0(X,D,Z.access,w,"main",_),u=!1,C=await B4(X,D,c,z,w,_,Z.access,(Q)=>{u=!0,V(Q.id,"fallback")});if(!u)V("main","main");return w.done("return_response",{status:C.status}),y0(C,{perf:(Q,U)=>w.mark(Q,U)})}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let O=await H1("max");return{url:O.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{return f1(G,O.verifier,O.redirectUri,O.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let O=await H1("console");return{url:O.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{let Y=await f1(G,O.verifier,O.redirectUri,O.state);if(Y.type==="failed")return Y;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${Y.access}`}}).then((K)=>K.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{ej as AnthropicAuthPlugin};
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{hb as
|
|
1
|
+
import{hb as K,ib as P,jb as _}from"./index-p8j7mmfc.js";var T=P((g,L)=>{(function(Q){if(typeof L==="object"&&typeof L.exports==="object"){var J=Q(_,g);if(J!==void 0)L.exports=J}else if(typeof define==="function"&&define.amd)define(["require","exports","./impl/format","./impl/edit","./impl/scanner","./impl/parser"],Q)})(function(Q,J){Object.defineProperty(J,"__esModule",{value:!0}),J.applyEdits=J.modify=J.format=J.printParseErrorCode=J.ParseErrorCode=J.stripComments=J.visit=J.getNodeValue=J.getNodePath=J.findNodeAtOffset=J.findNodeAtLocation=J.parseTree=J.parse=J.getLocation=J.SyntaxKind=J.ScanError=J.createScanner=void 0;let X=Q("./impl/format"),Z=Q("./impl/edit"),G=Q("./impl/scanner"),$=Q("./impl/parser");J.createScanner=G.createScanner;var W;(function(z){z[z.None=0]="None",z[z.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=2]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",z[z.InvalidUnicode=4]="InvalidUnicode",z[z.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",z[z.InvalidCharacter=6]="InvalidCharacter"})(W||(J.ScanError=W={}));var H;(function(z){z[z.OpenBraceToken=1]="OpenBraceToken",z[z.CloseBraceToken=2]="CloseBraceToken",z[z.OpenBracketToken=3]="OpenBracketToken",z[z.CloseBracketToken=4]="CloseBracketToken",z[z.CommaToken=5]="CommaToken",z[z.ColonToken=6]="ColonToken",z[z.NullKeyword=7]="NullKeyword",z[z.TrueKeyword=8]="TrueKeyword",z[z.FalseKeyword=9]="FalseKeyword",z[z.StringLiteral=10]="StringLiteral",z[z.NumericLiteral=11]="NumericLiteral",z[z.LineCommentTrivia=12]="LineCommentTrivia",z[z.BlockCommentTrivia=13]="BlockCommentTrivia",z[z.LineBreakTrivia=14]="LineBreakTrivia",z[z.Trivia=15]="Trivia",z[z.Unknown=16]="Unknown",z[z.EOF=17]="EOF"})(H||(J.SyntaxKind=H={})),J.getLocation=$.getLocation,J.parse=$.parse,J.parseTree=$.parseTree,J.findNodeAtLocation=$.findNodeAtLocation,J.findNodeAtOffset=$.findNodeAtOffset,J.getNodePath=$.getNodePath,J.getNodeValue=$.getNodeValue,J.visit=$.visit,J.stripComments=$.stripComments;var q;(function(z){z[z.InvalidSymbol=1]="InvalidSymbol",z[z.InvalidNumberFormat=2]="InvalidNumberFormat",z[z.PropertyNameExpected=3]="PropertyNameExpected",z[z.ValueExpected=4]="ValueExpected",z[z.ColonExpected=5]="ColonExpected",z[z.CommaExpected=6]="CommaExpected",z[z.CloseBraceExpected=7]="CloseBraceExpected",z[z.CloseBracketExpected=8]="CloseBracketExpected",z[z.EndOfFileExpected=9]="EndOfFileExpected",z[z.InvalidCommentToken=10]="InvalidCommentToken",z[z.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=12]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",z[z.InvalidUnicode=14]="InvalidUnicode",z[z.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",z[z.InvalidCharacter=16]="InvalidCharacter"})(q||(J.ParseErrorCode=q={}));function D(z){switch(z){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}J.printParseErrorCode=D;function f(z,U,j){return X.format(z,U,j)}J.format=f;function u(z,U,j,A){return Z.setProperty(z,U,j,A)}J.modify=u;function C(z,U){let j=U.slice(0).sort((I,Y)=>{let F=I.offset-Y.offset;if(F===0)return I.length-Y.length;return F}),A=z.length;for(let I=j.length-1;I>=0;I--){let Y=j[I];if(Y.offset+Y.length<=A)z=Z.applyEdit(z,Y);else throw Error("Overlapping edit");A=Y.offset}return z}J.applyEdits=C})});var M=K(T(),1);import{watch as c}from"node:fs";import{mkdir as y,readFile as O,rename as S,writeFile as E}from"node:fs/promises";import{homedir as l}from"node:os";import{basename as p,dirname as m,join as k}from"node:path";import{clearTimeout as b,setTimeout as x}from"node:timers";var i="OPENCODE_TUI_PREFERENCES_FILE",s="tui-preferences.jsonc";function w(){let Q=process.env[i];if(Q)return Q;let J=process.env.OPENCODE_CONFIG_DIR||k(process.env.XDG_CONFIG_HOME||k(l(),".config"),"opencode");return k(J,s)}function N(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}async function Gz(){try{let Q=await O(w(),"utf8"),J=[],X=M.parse(Q,J,{allowTrailingComma:!0});if(J.length>0)return{};return N(X)?X:{}}catch{return{}}}var d="anthropic-auth",n=160,h={forceToTop:!1,order:n,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"CLAUDE",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,cache:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function V(Q,J){return typeof Q==="boolean"?Q:J}function B(Q,J,X,Z){if(typeof Q!=="number"||!Number.isFinite(Q))return J;return Math.min(Math.max(Math.round(Q),X),Z)}function a(Q,J,X){if(typeof Q!=="string"||Q.length===0)return J;return Q.slice(0,X)}function v(Q,J){if(typeof Q!=="string")return J;return[...Q][0]??J}function Hz(Q){let J=Q[d];if(!N(J))return structuredClone(h);let X=h,Z=N(J.header)?J.header:{},G=N(J.sections)?J.sections:{},$=N(J.appearance)?J.appearance:{},W=B($.warnThreshold,X.appearance.warnThreshold,0,99),H=Math.max(B($.errorThreshold,X.appearance.errorThreshold,0,100),Math.min(W+1,100));return{forceToTop:V(J.forceToTop,X.forceToTop),order:B(J.order,X.order,-1e4,1e4),startCollapsed:V(J.startCollapsed,X.startCollapsed),rememberCollapsed:V(J.rememberCollapsed,X.rememberCollapsed),collapsed:typeof J.collapsed==="boolean"?J.collapsed:null,pollMs:B(J.pollMs,X.pollMs,500,30000),refreshDebounceMs:B(J.refreshDebounceMs,X.refreshDebounceMs,50,5000),header:{label:a(Z.label,X.header.label,20),showVersion:V(Z.showVersion,X.header.showVersion)},sections:{quota:V(G.quota,X.sections.quota),fallbackAccounts:V(G.fallbackAccounts,X.sections.fallbackAccounts),routing:V(G.routing,X.sections.routing),cache:V(G.cache,X.sections.cache),health:V(G.health,X.sections.health),pacing:V(G.pacing,X.sections.pacing)},appearance:{barWidth:B($.barWidth,X.appearance.barWidth,4,40),barFilledChar:v($.barFilledChar,X.appearance.barFilledChar),barEmptyChar:v($.barEmptyChar,X.appearance.barEmptyChar),warnThreshold:W,errorThreshold:H}}}var t=-1e5;function Vz(Q,J,X){let Z=Q[J];if(!N(Z))return X;if(Z.forceToTop===!0)return t+Object.keys(Q).indexOf(J);return B(Z.order,X,-1e4,1e4)}var o=`// Shared preferences for opencode TUI plugins.
|
|
2
2
|
// One top-level key per plugin (short name). See each plugin's README for
|
|
3
3
|
// its supported settings. This file is safe to hand-edit; plugins update
|
|
4
4
|
// individual keys in place and preserve comments.
|
|
5
5
|
{}
|
|
6
|
-
`;async function
|
|
6
|
+
`;async function e(Q,J,X){let Z=w();await y(m(Z),{recursive:!0});let G;try{G=await O(Z,"utf8")}catch{G=""}if(G.trim()==="")G=o;let $=M.modify(G,[Q,...J],X,{formattingOptions:{insertSpaces:!0,tabSize:2}}),W=M.applyEdits(G,$),H=`${Z}.${process.pid}.tmp`;await E(H,W,"utf8"),await S(H,Z)}var R=Promise.resolve();function Wz(Q,J,X){return R=R.then(()=>e(Q,J,X)).catch(()=>{}),R}var r=150;function Yz(Q){let J=w(),X=p(J),Z=null,G=null;O(J,"utf8").then(($)=>{if(G===null)G=$}).catch(()=>{});try{let $=c(m(J),(W,H)=>{let q=H===X||H?.startsWith(`${X}.`)&&H.endsWith(".tmp");if(H!=null&&!q)return;if(Z)b(Z);Z=x(()=>{Z=null,O(J,"utf8").catch(()=>null).then((D)=>{if(D===null)return;if(D===G)return;G=D,Q()})},r)});return()=>{if(Z)b(Z);$.close()}}catch{return()=>{}}}export{Yz as watchTuiPreferences,Hz as resolveAnthropicAuthPrefs,Gz as readTuiPreferencesFile,Wz as queueTuiPreferenceUpdate,w as getTuiPreferencesFile,Vz as computeEffectiveOrder,i as TUI_PREFS_FILE_ENV,d as PLUGIN_KEY,n as DEFAULT_SLOT_ORDER,h as DEFAULT_PREFS};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-anthropic-auth",
|
|
3
|
-
"version": "1.10.
|
|
3
|
+
"version": "1.10.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
"@opencode-ai/plugin": "*"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@cortexkit/anthropic-auth-core": "1.10.
|
|
61
|
+
"@cortexkit/anthropic-auth-core": "1.10.3",
|
|
62
62
|
"@opentui/core": ">=0.4.0",
|
|
63
63
|
"@opentui/solid": ">=0.4.0",
|
|
64
64
|
"jsonc-parser": "^3.3.1",
|
package/src/tui-preferences.ts
CHANGED
|
@@ -2,6 +2,10 @@ import { watch } from 'node:fs'
|
|
|
2
2
|
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
3
3
|
import { homedir } from 'node:os'
|
|
4
4
|
import { basename, dirname, join } from 'node:path'
|
|
5
|
+
import {
|
|
6
|
+
clearTimeout as nativeClearTimeout,
|
|
7
|
+
setTimeout as nativeSetTimeout,
|
|
8
|
+
} from 'node:timers'
|
|
5
9
|
import { applyEdits, modify, type ParseError, parse } from 'jsonc-parser'
|
|
6
10
|
|
|
7
11
|
export const TUI_PREFS_FILE_ENV = 'OPENCODE_TUI_PREFERENCES_FILE'
|
|
@@ -290,7 +294,7 @@ const WATCH_DEBOUNCE_MS = 150
|
|
|
290
294
|
export function watchTuiPreferences(onChange: () => void): () => void {
|
|
291
295
|
const file = getTuiPreferencesFile()
|
|
292
296
|
const name = basename(file)
|
|
293
|
-
let timer: ReturnType<typeof
|
|
297
|
+
let timer: ReturnType<typeof nativeSetTimeout> | null = null
|
|
294
298
|
let lastSeen: string | null = null
|
|
295
299
|
// Seed asynchronously; a real change that fires before the seed resolves
|
|
296
300
|
// still wins because the debounce re-reads the file fresh and compares
|
|
@@ -308,8 +312,8 @@ export function watchTuiPreferences(onChange: () => void): () => void {
|
|
|
308
312
|
filename === name ||
|
|
309
313
|
(filename?.startsWith(`${name}.`) && filename.endsWith('.tmp'))
|
|
310
314
|
if (filename != null && !isOurs) return
|
|
311
|
-
if (timer)
|
|
312
|
-
timer =
|
|
315
|
+
if (timer) nativeClearTimeout(timer)
|
|
316
|
+
timer = nativeSetTimeout(() => {
|
|
313
317
|
timer = null
|
|
314
318
|
void readFile(file, 'utf8')
|
|
315
319
|
.catch(() => null)
|
|
@@ -322,7 +326,7 @@ export function watchTuiPreferences(onChange: () => void): () => void {
|
|
|
322
326
|
}, WATCH_DEBOUNCE_MS)
|
|
323
327
|
})
|
|
324
328
|
return () => {
|
|
325
|
-
if (timer)
|
|
329
|
+
if (timer) nativeClearTimeout(timer)
|
|
326
330
|
watcher.close()
|
|
327
331
|
}
|
|
328
332
|
} catch {
|