@cortexkit/opencode-anthropic-auth 1.13.0 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{ga as O,ib as S,kb as x,l as N,m as L,n as T,p as q,r as D,t as C,u as H}from"./index-
|
|
2
|
+
import{ga as O,ib as S,kb as x,l as N,m as L,n as T,p as q,r as D,t as C,u as H}from"./index-fwjqfkj2.js";import"./index-se4sd5kz.js";import{Vb as z}from"./index-1gc9eney.js";import{stdin as y,stdout as v}from"node:process";import{createInterface as R}from"node:readline/promises";function P(){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 w(){console.log(`Usage:
|
|
3
3
|
opencode-anthropic-auth login [label]
|
|
4
4
|
opencode-anthropic-auth api add [label]
|
|
5
5
|
opencode-anthropic-auth list
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{mkdir as q,readFile as M,writeFile as b}from"node:fs/promises";import{tmpdir as L}from"node:os";import{dirname as k,join as g}from"node:path";var R="OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE",f=g(L(),"opencode-anthropic-auth"),I=g(f,"sidebar-state.json");function h(){return process.env[R]||I}var K={main:{quota:null},fallbacks:[],activeId:void 0,route:"main",relay:null,fastMode:!1,lastUpdated:0};function G(J){return J!==null&&typeof J==="object"&&!Array.isArray(J)}function z(J){if(!G(J))return;let X=Number(J.usedPercent),Y=Number(J.remainingPercent);if(!Number.isFinite(X)||!Number.isFinite(Y))return;return{usedPercent:X,remainingPercent:Y,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0}}function N(J){if(!G(J))return null;let X={},Y=z(J.five_hour),Z=z(J.seven_day);if(Y)X.five_hour=Y;if(Z)X.seven_day=Z;if(Array.isArray(J.scoped)){let $=J.scoped.map((x)=>{if(!G(x))return;let j=z(x);if(!j)return;if(typeof x.id!=="string"||!x.id.trim())return;if(typeof x.title!=="string"||!x.title.trim())return;if(typeof x.modelName!=="string"||!x.modelName.trim())return;let V=typeof x.modelId==="string"&&x.modelId.trim()?x.modelId.trim():void 0;return{...j,id:x.id.trim(),title:x.title.trim(),...V&&{modelId:V},modelName:x.modelName.trim()}}).filter((x)=>x!=null);X.scoped=$}return Object.keys(X).length?X:null}function F(J){if(!G(J))return{...K};let X={quota:null};if(G(J.main)){let x=J.main;if(X.quota=N(x.quota),typeof x.quotaBackedOff==="boolean")X.quotaBackedOff=x.quotaBackedOff;if(typeof x.quotaBackoffUntil==="number")X.quotaBackoffUntil=x.quotaBackoffUntil;if(typeof x.refreshBackedOff==="boolean")X.refreshBackedOff=x.refreshBackedOff;if(typeof x.refreshBackoffUntil==="number")X.refreshBackoffUntil=x.refreshBackoffUntil}let Y=Array.isArray(J.fallbacks)?J.fallbacks.filter(G).filter((x)=>typeof x.id==="string").map((x)=>({id:x.id,label:typeof x.label==="string"?x.label:void 0,quota:N(x.quota),enabled:typeof x.enabled==="boolean"?x.enabled:!1,needsReauth:typeof x.needsReauth==="boolean"?x.needsReauth:!1})):[],Z=null;if(G(J.relay)){let x=J.relay;if(typeof x.enabled==="boolean"&&typeof x.transport==="string")Z={enabled:x.enabled,transport:x.transport}}let $;if(G(J.cacheKeep)){let x=J.cacheKeep;if(typeof x.enabled==="boolean")$={enabled:x.enabled,window:typeof x.window==="string"?x.window:void 0,trackedSessions:typeof x.trackedSessions==="number"?x.trackedSessions:void 0}}return{main:X,fallbacks:Y,activeId:typeof J.activeId==="string"?J.activeId:void 0,route:typeof J.route==="string"?J.route:K.route,relay:Z,fastMode:typeof J.fastMode==="boolean"?J.fastMode:K.fastMode,cacheKeep:$,lastUpdated:typeof J.lastUpdated==="number"?J.lastUpdated:0}}var W=Promise.resolve();async function P(){try{let J=await M(h(),"utf8");return F(JSON.parse(J))}catch{return K}}async function A(J,X=h()){return W=W.then(async()=>{await q(k(X),{recursive:!0}),await b(X,JSON.stringify(J),"utf8")}).catch(()=>{}),W}async function m(){return W}function v(J){let X=J.activeId;if(X&&X!=="main"){let Y=J.fallbacks?.find((Z)=>Z.enabled&&Z.id===X);if(Y)return{id:Y.id,name:Y.label??Y.id,quota:Y.quota}}return{id:"main",name:"main",quota:J.main?.quota??null}}function U(J){let X=J.replace(/\s+only$/i,"").trim();return/^fable$/i.test(X)?"Fa":X}function y(J){let X=J?.five_hour?.usedPercent??null,Y=J?.seven_day?.usedPercent??null,Z=J?.scoped??[],$=Z.map((V)=>V.usedPercent);if(X==null&&Y==null&&Z.length===0)return{fiveHourUsedPercent:X,sevenDayUsedPercent:Y,scopedUsedPercents:$,text:null};let x=Z.map((V)=>`${U(V.title)}: ${Math.round(V.usedPercent)}%`),j=X==null&&Y==null?[]:[`5h: ${X==null?"—":`${Math.round(X)}%`}`,`7d: ${Y==null?"—":`${Math.round(Y)}%`}`];return{fiveHourUsedPercent:X,sevenDayUsedPercent:Y,scopedUsedPercents:$,text:[...j,...x].join(" ")}}var u=18000000,l=604800000,D=300000,_=0.01,p=1;function c(J,X,Y){if(!J.resetsAt)return null;let Z=new Date(J.resetsAt).getTime();if(!Number.isFinite(Z))return null;let $=Z-X,x=Y-$;if(x<D)return null;if(x<X*_)return null;if(x>=X)return null;let j=J.usedPercent,V=Math.min(Math.max(x/X*100,0),100),B=j-V,C=Math.abs(B)<p?"on-pace":B>0?"deficit":"reserve",O=null;if(j>0){let H=x*100/j,Q=$+H;if(Q<Z)O=new Date(Q).toISOString()}return{pacePercent:V,deltaPercent:B,state:C,runsOutAt:O}}
|
|
2
|
+
export{h as Db,K as Eb,F as Fb,P as Gb,A as Hb,m as Ib,v as Jb,U as Kb,y as Lb,u as Mb,l as Nb,c as Ob};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import{Ab as I,Bb as u,Cb as O,wb as Z1}from"./index-se4sd5kz.js";import{Vb as t1}from"./index-1gc9eney.js";var Mf="9d1c250a-e61b-44d9-88ed-5944d1962f5e",S0={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.com/cai/oauth/authorize"},kf="https://platform.claude.com/oauth/code/callback",lf="https://platform.claude.com/v1/oauth/token",pf="axios/1.15.2",W0=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],Y0="user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload",uD="mcp_";var Z0="fast-mode-2026-02-01";function gD(f,_){let $=(f??"").split(",").map((D)=>D.trim()).filter(Boolean);return[...new Set([...$,..._])].join(",")}function sD(f){return typeof f==="string"&&(f.startsWith("claude-opus-4-6")||f.startsWith("claude-opus-4-7")||f.startsWith("claude-opus-4-8"))}var rD="You are OpenCode",nD="You are Claude Code, Anthropic's official CLI for Claude.",cD=["<use_parallel_tool_calls>","For maximum efficiency, whenever you perform multiple independent operations, invoke all relevant tools simultaneously rather than sequentially. Prioritize calling independent tools in parallel whenever possible. For example, when reading 3 known files, run 3 tool calls in parallel to read all 3 files into context at the same time. When running multiple independent read-only commands like `ls` or `list_dir`, run all of those commands in parallel. Err on the side of maximizing parallel tool calls for independent work rather than running too many tools sequentially.","","Do not parallelize tool calls when one call depends on the output of another call. If a tool call needs an ID, filename, search result, or any other value returned by a previous tool call, run the first call, wait for its result, then run the dependent call using the real returned value. Never invent placeholder IDs, guessed task IDs, or other guessed values for dependent tool calls just to place them in the same parallel block.","</use_parallel_tool_calls>"].join(`
|
|
2
|
-
`);var p="2.1.177",vf="3bf",X0="cli",F0="0.94.0",V0="v24.3.0",m0="claude-cli/2.1.177 (external, cli)",Q0=["explicit","automatic","hybrid"],Lf="explicit",tD=["github.com/anomalyco/opencode","opencode.ai/docs"],oD=[{match:"if OpenCode honestly",replacement:"if the assistant honestly"},{match:"Here is some useful information about the environment you are running in:",replacement:"Environment context you are running in:"}];function A0(f){let _="";for(let $ of f)_+=String.fromCharCode($);return btoa(_).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function R0(){let f=new Uint8Array(64);crypto.getRandomValues(f);let _=A0(f),$=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(_));return{verifier:_,challenge:A0(new Uint8Array($)),method:"S256"}}function uf(f){if(!f)return;let _=Number(f);if(Number.isFinite(_)&&_>0)return Math.ceil(_);let $=Date.parse(f);if(Number.isFinite($)){let D=Math.ceil(($-Date.now())/1000);return D>0?D:void 0}return}class df extends Error{status;body;retryAfter;isRefreshError=!0;constructor(f,_,$){super(`Claude OAuth refresh failed: ${f} — ${_}`);this.status=f,this.body=_,this.name="ClaudeOAuthRefreshError",this.retryAfter=uf($??void 0)}}function s1(f){if(!(f instanceof Error))return!1;let _=f.code;return f.message.includes("fetch failed")||_==="ECONNRESET"||_==="ECONNREFUSED"||_==="ETIMEDOUT"||_==="UND_ERR_CONNECT_TIMEOUT"}async function P0(f){let _=f.fetchImpl??fetch,$=f.maxRetries??2,D=f.baseDelayMs??500;for(let C=0;C<=$;C++)try{if(C>0){let K=D*2**(C-1);await new Promise((G)=>setTimeout(G,K))}let N=await _(lf,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":pf},body:JSON.stringify({grant_type:"refresh_token",refresh_token:f.refreshToken,client_id:Mf,scope:Y0})});if(!N.ok){if(N.status>=500&&C<$){await N.body?.cancel().catch(()=>{});continue}let K=await N.text().catch(()=>"");throw new df(N.status,K,N.headers.get("retry-after"))}let b=await N.json(),E=f.now?.()??Date.now();return{access:b.access_token,refresh:b.refresh_token??f.refreshToken,expires:E+b.expires_in*1000,expiresIn:b.expires_in}}catch(N){if(N instanceof df)throw N;if(C<$&&s1(N))continue;throw N}throw Error("Token refresh exhausted all retries")}function r1(){return crypto.randomUUID().replace(/-/g,"")}function n1(f){let _=f.trim();try{let b=new URL(_),E=b.searchParams.get("code"),K=b.searchParams.get("state");if(E&&K)return{code:E,state:K}}catch{}let $=_.split("#");if($.length===2&&$[0]&&$[1])return{code:$[0],state:$[1]};let D=new URLSearchParams(_),C=D.get("code"),N=D.get("state");if(C&&N)return{code:C,state:N};return null}async function c1(f,_,$){let D=await fetch(lf,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":pf},body:JSON.stringify({code:f.code,state:f.state,grant_type:"authorization_code",client_id:Mf,redirect_uri:$,code_verifier:_})});if(!D.ok)return{type:"failed"};let C=await D.json();return{type:"success",refresh:C.refresh_token,access:C.access_token,expires:Date.now()+C.expires_in*1000}}async function $C(f){let _=await R0(),$=r1(),D=new URL(S0[f],import.meta.url);return D.searchParams.set("code","true"),D.searchParams.set("client_id",Mf),D.searchParams.set("response_type","code"),D.searchParams.set("redirect_uri",kf),D.searchParams.set("scope",W0.join(" ")),D.searchParams.set("code_challenge",_.challenge),D.searchParams.set("code_challenge_method","S256"),D.searchParams.set("state",$),{url:D.toString(),redirectUri:kf,state:$,verifier:_.verifier}}async function DC(f,_,$,D){let C=n1(f);if(!C)return{type:"failed"};if(D&&C.state!==D)return{type:"failed"};return c1(C,_,$)}import{createHash as p0,randomUUID as Cf}from"node:crypto";import{mkdir as v0,readFile as Of,rename as d0,rm as t,stat as q0,writeFile as zf}from"node:fs/promises";import{homedir as o1}from"node:os";import{dirname as i0,join as o}from"node:path";var a1=globalThis.setTimeout.bind(globalThis),e1=globalThis.clearTimeout.bind(globalThis),u0="anthropic-auth.json",f_="anthropic-auth-state.json",__="https://api.anthropic.com/api/oauth/usage";function h(f){return f.type==="oauth"}function BC(f){return f.type==="api"}function $_(f){let _=f?.trim();if(!_)return!1;try{let $=new URL(_);return($.protocol==="http:"||$.protocol==="https:")&&!$.username&&!$.password}catch{return!1}}function HC(f){return f.costZeroing?.enabled!==!1}var D_=[401,403,429],g0=240,C_=g0;var N_=300000,b_=3600000,s0=86400000,E_=60000,K_=900000,G_=300000,U_=5,I0={five_hour:0,seven_day:0},j_=!0,B_=60000,H_=60000,M_=600000,L_=1e4,O_=100;function z_(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return o(process.env.XDG_CONFIG_HOME||o(o1(),".config"),"opencode")}function z(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||o(z_(),u0)}function r0(f=z()){let _=process.env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim();if(_)return _;return f.endsWith(u0)?o(i0(f),f_):`${f}.state.json`}function H(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function x0(f){return{id:typeof f.id==="string"&&f.id.trim()?f.id.trim():Cf(),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 J_(f){if(!H(f))return null;if(f.type==="api"){let _=typeof f.baseURL==="string"?f.baseURL.trim():"",$=typeof f.apiKey==="string"?f.apiKey.trim():"";if(!$_(_))return null;let D=f.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...x0(f),type:"api",apiKey:$||void 0,baseURL:_,authHeader:D}}if(f.type!=="oauth")return null;if(typeof f.refresh!=="string"||!f.refresh.trim())return null;return{...x0(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:T0(f.lastRefreshError),lastQuotaRefreshError:T0(f.lastQuotaRefreshError),quota:S_(f.quota)}}function T0(f){if(!H(f))return;if(typeof f.message!=="string")return;let _=Number(f.checkedAt);if(!Number.isFinite(_))return;let $=Number(f.nextRetryAt),D=Number(f.retryCount),C=Number(f.status);return{message:f.message,checkedAt:_,nextRetryAt:Number.isFinite($)?$:void 0,retryCount:Number.isFinite(D)?D:void 0,tokenHash:typeof f.tokenHash==="string"?f.tokenHash:void 0,status:Number.isFinite(C)?C:void 0,permanent:typeof f.permanent==="boolean"?f.permanent:void 0}}function h0(f){if(!H(f))return;let _=Number(f.usedPercent),$=Number(f.remainingPercent),D=Number(f.checkedAt);if(!Number.isFinite(_)||!Number.isFinite($)||!Number.isFinite(D))return;return{usedPercent:_,remainingPercent:$,checkedAt:D,resetsAt:typeof f.resetsAt==="string"?f.resetsAt:void 0}}function S_(f){if(!H(f))return;let _={};for(let $ of["five_hour","seven_day"]){let D=h0(f[$]);if(D)_[$]=D}if(Array.isArray(f.scoped)){let $=f.scoped.map((D)=>{if(!H(D))return;let C=h0(D);if(!C)return;if(typeof D.id!=="string"||!D.id.trim())return;if(typeof D.title!=="string"||!D.title.trim())return;if(typeof D.modelName!=="string"||!D.modelName.trim())return;let N=typeof D.modelId==="string"&&D.modelId.trim()?D.modelId.trim():void 0;return{...C,id:D.id.trim(),title:D.title.trim(),...N&&{modelId:N},modelName:D.modelName.trim()}}).filter((D)=>D!=null);if($.length)_.scoped=$}return Object.keys(_).length?_:void 0}function A(){return{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]}}function W_(f){if(!H(f)||!Array.isArray(f.accounts))return null;return{version:1,main:{type:"opencode",provider:"anthropic"},routing:H(f.routing)?f.routing:void 0,fallbackOn:Array.isArray(f.fallbackOn)?f.fallbackOn.filter((_)=>Number.isInteger(_)):void 0,refresh:H(f.refresh)?f.refresh:void 0,quota:H(f.quota)?f.quota:void 0,claudeCache:H(f.claudeCache)?f.claudeCache:void 0,dump:H(f.dump)?f.dump:void 0,claudeFast:H(f.claudeFast)?f.claudeFast:void 0,costZeroing:H(f.costZeroing)?f.costZeroing:void 0,cacheKeep:H(f.cacheKeep)?f.cacheKeep:void 0,relay:H(f.relay)?f.relay:void 0,logging:H(f.logging)?f.logging:void 0,killswitch:H(f.killswitch)?f.killswitch:void 0,accounts:f.accounts.map(J_).filter((_)=>_!=null)}}async function Sf(f){try{return{exists:!0,value:JSON.parse(await Of(f,"utf8"))}}catch(_){if(_.code==="ENOENT")return{exists:!1,value:null};let $=_ instanceof Error?_.message:String(_);throw Error(`account store at ${f} is corrupt or unreadable (${$}) — fix or remove it`)}}function s(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function Jf(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function nf(f){return Math.max(Jf(f.lastRefreshedAt),Jf(f.lastUsed),Jf(f.addedAt))}function Y_(f,_){if(f.type!=="oauth")return!1;if(typeof f.refresh!=="string"||!f.refresh.trim())return!1;if(!Boolean(typeof f.access==="string"&&typeof _.access==="string"&&f.access!==_.access||typeof f.refresh==="string"&&typeof _.refresh==="string"&&f.refresh!==_.refresh))return!1;return nf(f)>nf(_)}function Z_(f,_){if(Y_(f,_)){let $={..._,...f},D=nf(f);if(D>Jf($.lastRefreshedAt))$.lastRefreshedAt=D;return delete $.quota,delete $.lastRefreshError,delete $.lastQuotaRefreshError,$}return{...f,..._}}function X_(f,_){if(!H(f))return f;let $=H(_)?_:{},D=H($.main)?$.main:void 0,C=H($.accounts)?$.accounts:{},N=H(f.quota)?f.quota:{},b=H(f.refresh)?f.refresh:{},E=D??N,K=D??b,G=Array.isArray(f.accounts)?f.accounts.map((U)=>{if(!H(U))return U;let L=typeof U.id==="string"&&H(C[U.id])?C[U.id]:{};return Z_(U,L)}):[];return{...f,refresh:s({...b,mainLastRefreshError:K.lastRefreshError,mainRefreshLeaseId:K.refreshLeaseId,mainRefreshLeaseUntil:K.refreshLeaseUntil,mainRefreshLeaseTokenHash:K.refreshLeaseTokenHash}),quota:s({...N,mainQuota:E.quota,mainQuotaCheckedAt:E.quotaCheckedAt,mainQuotaToken:E.quotaToken,mainLastQuotaApiError:E.lastQuotaApiError}),accounts:G}}async function F(f=z()){let _=await Sf(f),$=await Sf(r0(f));if(!_.exists&&!$.exists)return null;let D=_.exists?_.value:A();return W_(X_(D,$.value))}async function F_(f){let _=await Sf(f);return H(_.value)?_.value:{}}function V_(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function m_(f){return s({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 Q_(f){if(f.type==="api")return s({apiKey:f.apiKey,lastUsed:f.lastUsed});return s({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 Nf(f){return Math.max(f?.five_hour?.checkedAt??0,f?.seven_day?.checkedAt??0,...f?.scoped?.map((_)=>_.checkedAt)??[])}function A_(f,_){if(!H(f))return _;let $=f,D=Nf($.quota),C=Nf(_.quota),N=Boolean($.access&&_.access&&$.access!==_.access||$.refresh&&_.refresh&&$.refresh!==_.refresh);if(D>C){let E=$.lastRefreshedAt??0,K=_.lastRefreshedAt??0;if(N&&K<=E){let U={...$};if(typeof _.lastUsed==="number"&&(typeof $.lastUsed!=="number"||_.lastUsed>$.lastUsed))U.lastUsed=_.lastUsed;return U}let G={...$,..._};if(N){if("quota"in _)if(G.quota=$.quota,"lastQuotaRefreshError"in $)G.lastQuotaRefreshError=$.lastQuotaRefreshError;else delete G.lastQuotaRefreshError;else delete G.quota,delete G.lastQuotaRefreshError;if(!("lastRefreshError"in _))delete G.lastRefreshError;return G}return{...G,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}}let b={...$,..._};if(!("lastQuotaRefreshError"in _))delete b.lastQuotaRefreshError;if(!("lastRefreshError"in _))delete b.lastRefreshError;return b}function R_(f){let _=f.refresh?s({enabled:f.refresh.enabled,intervalMinutes:f.refresh.intervalMinutes,refreshBeforeExpiryMinutes:f.refresh.refreshBeforeExpiryMinutes}):void 0,$=f.quota?s({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 V_({version:1,main:f.main,routing:f.routing,fallbackOn:f.fallbackOn,refresh:_,quota:$,claudeCache:f.claudeCache,dump:f.dump,logging:f.logging,claudeFast:f.claudeFast,costZeroing:f.costZeroing,cacheKeep:f.cacheKeep,relay:f.relay,killswitch:f.killswitch,accounts:f.accounts.map(m_)})}var w0=Promise.resolve();function n0(f){return new Promise((_,$)=>{w0=w0.then(()=>f().then(_,$),()=>f().then(_,$))})}async function c0(f,_){await v0(i0(f),{recursive:!0});let $=`${f}.${Cf()}.tmp`;await zf($,`${JSON.stringify(_,null,2)}
|
|
2
|
+
`);var p="2.1.177",vf="3bf",X0="cli",F0="0.94.0",V0="v24.3.0",m0="claude-cli/2.1.177 (external, cli)",Q0=["explicit","automatic","hybrid"],Lf="explicit",tD=["github.com/anomalyco/opencode","opencode.ai/docs"],oD=[{match:"if OpenCode honestly",replacement:"if the assistant honestly"},{match:"Here is some useful information about the environment you are running in:",replacement:"Environment context you are running in:"}];function A0(f){let _="";for(let $ of f)_+=String.fromCharCode($);return btoa(_).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function R0(){let f=new Uint8Array(64);crypto.getRandomValues(f);let _=A0(f),$=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(_));return{verifier:_,challenge:A0(new Uint8Array($)),method:"S256"}}function uf(f){if(!f)return;let _=Number(f);if(Number.isFinite(_)&&_>0)return Math.ceil(_);let $=Date.parse(f);if(Number.isFinite($)){let D=Math.ceil(($-Date.now())/1000);return D>0?D:void 0}return}class df extends Error{status;body;retryAfter;isRefreshError=!0;constructor(f,_,$){super(`Claude OAuth refresh failed: ${f} — ${_}`);this.status=f,this.body=_,this.name="ClaudeOAuthRefreshError",this.retryAfter=uf($??void 0)}}function s1(f){if(!(f instanceof Error))return!1;let _=f.code;return f.message.includes("fetch failed")||_==="ECONNRESET"||_==="ECONNREFUSED"||_==="ETIMEDOUT"||_==="UND_ERR_CONNECT_TIMEOUT"}async function P0(f){let _=f.fetchImpl??fetch,$=f.maxRetries??2,D=f.baseDelayMs??500;for(let C=0;C<=$;C++)try{if(C>0){let K=D*2**(C-1);await new Promise((G)=>setTimeout(G,K))}let N=await _(lf,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":pf},body:JSON.stringify({grant_type:"refresh_token",refresh_token:f.refreshToken,client_id:Mf,scope:Y0})});if(!N.ok){if(N.status>=500&&C<$){await N.body?.cancel().catch(()=>{});continue}let K=await N.text().catch(()=>"");throw new df(N.status,K,N.headers.get("retry-after"))}let b=await N.json(),E=f.now?.()??Date.now();return{access:b.access_token,refresh:b.refresh_token??f.refreshToken,expires:E+b.expires_in*1000,expiresIn:b.expires_in}}catch(N){if(N instanceof df)throw N;if(C<$&&s1(N))continue;throw N}throw Error("Token refresh exhausted all retries")}function r1(){return crypto.randomUUID().replace(/-/g,"")}function n1(f){let _=f.trim();try{let b=new URL(_),E=b.searchParams.get("code"),K=b.searchParams.get("state");if(E&&K)return{code:E,state:K}}catch{}let $=_.split("#");if($.length===2&&$[0]&&$[1])return{code:$[0],state:$[1]};let D=new URLSearchParams(_),C=D.get("code"),N=D.get("state");if(C&&N)return{code:C,state:N};return null}async function c1(f,_,$){let D=await fetch(lf,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":pf},body:JSON.stringify({code:f.code,state:f.state,grant_type:"authorization_code",client_id:Mf,redirect_uri:$,code_verifier:_})});if(!D.ok)return{type:"failed"};let C=await D.json();return{type:"success",refresh:C.refresh_token,access:C.access_token,expires:Date.now()+C.expires_in*1000}}async function $C(f){let _=await R0(),$=r1(),D=new URL(S0[f],import.meta.url);return D.searchParams.set("code","true"),D.searchParams.set("client_id",Mf),D.searchParams.set("response_type","code"),D.searchParams.set("redirect_uri",kf),D.searchParams.set("scope",W0.join(" ")),D.searchParams.set("code_challenge",_.challenge),D.searchParams.set("code_challenge_method","S256"),D.searchParams.set("state",$),{url:D.toString(),redirectUri:kf,state:$,verifier:_.verifier}}async function DC(f,_,$,D){let C=n1(f);if(!C)return{type:"failed"};if(D&&C.state!==D)return{type:"failed"};return c1(C,_,$)}import{createHash as p0,randomUUID as Cf}from"node:crypto";import{mkdir as v0,readFile as Of,rename as d0,rm as t,stat as q0,writeFile as zf}from"node:fs/promises";import{homedir as o1}from"node:os";import{dirname as i0,join as o}from"node:path";var a1=globalThis.setTimeout.bind(globalThis),e1=globalThis.clearTimeout.bind(globalThis),u0="anthropic-auth.json",f_="anthropic-auth-state.json",__="https://api.anthropic.com/api/oauth/usage";function h(f){return f.type==="oauth"}function BC(f){return f.type==="api"}function $_(f){let _=f?.trim();if(!_)return!1;try{let $=new URL(_);return($.protocol==="http:"||$.protocol==="https:")&&!$.username&&!$.password}catch{return!1}}function HC(f){return f.costZeroing?.enabled!==!1}var D_=[401,403,429],g0=240,C_=g0;var N_=300000,b_=3600000,s0=86400000,E_=60000,K_=900000,G_=300000,U_=5,I0={five_hour:0,seven_day:0},j_=!0,B_=60000,H_=60000,M_=600000,L_=1e4,O_=100;function z_(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return o(process.env.XDG_CONFIG_HOME||o(o1(),".config"),"opencode")}function z(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||o(z_(),u0)}function r0(f=z()){let _=process.env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim();if(_)return _;return f.endsWith(u0)?o(i0(f),f_):`${f}.state.json`}function H(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function x0(f){return{id:typeof f.id==="string"&&f.id.trim()?f.id.trim():Cf(),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 J_(f){if(!H(f))return null;if(f.type==="api"){let _=typeof f.baseURL==="string"?f.baseURL.trim():"",$=typeof f.apiKey==="string"?f.apiKey.trim():"";if(!$_(_))return null;let D=f.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...x0(f),type:"api",apiKey:$||void 0,baseURL:_,authHeader:D}}if(f.type!=="oauth")return null;if(typeof f.refresh!=="string"||!f.refresh.trim())return null;return{...x0(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:T0(f.lastRefreshError),lastQuotaRefreshError:T0(f.lastQuotaRefreshError),quota:S_(f.quota)}}function T0(f){if(!H(f))return;if(typeof f.message!=="string")return;let _=Number(f.checkedAt);if(!Number.isFinite(_))return;let $=Number(f.nextRetryAt),D=Number(f.retryCount),C=Number(f.status);return{message:f.message,checkedAt:_,nextRetryAt:Number.isFinite($)?$:void 0,retryCount:Number.isFinite(D)?D:void 0,tokenHash:typeof f.tokenHash==="string"?f.tokenHash:void 0,status:Number.isFinite(C)?C:void 0,permanent:typeof f.permanent==="boolean"?f.permanent:void 0}}function h0(f){if(!H(f))return;let _=Number(f.usedPercent),$=Number(f.remainingPercent),D=Number(f.checkedAt);if(!Number.isFinite(_)||!Number.isFinite($)||!Number.isFinite(D))return;return{usedPercent:_,remainingPercent:$,checkedAt:D,resetsAt:typeof f.resetsAt==="string"?f.resetsAt:void 0}}function S_(f){if(!H(f))return;let _={};for(let $ of["five_hour","seven_day"]){let D=h0(f[$]);if(D)_[$]=D}if(typeof f.checkedAt==="number"&&Number.isFinite(f.checkedAt))_.checkedAt=f.checkedAt;if(Array.isArray(f.scoped)){let $=f.scoped.map((D)=>{if(!H(D))return;let C=h0(D);if(!C)return;if(typeof D.id!=="string"||!D.id.trim())return;if(typeof D.title!=="string"||!D.title.trim())return;if(typeof D.modelName!=="string"||!D.modelName.trim())return;let N=typeof D.modelId==="string"&&D.modelId.trim()?D.modelId.trim():void 0;return{...C,id:D.id.trim(),title:D.title.trim(),...N&&{modelId:N},modelName:D.modelName.trim()}}).filter((D)=>D!=null);_.scoped=$}return Object.keys(_).length?_:void 0}function A(){return{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]}}function W_(f){if(!H(f)||!Array.isArray(f.accounts))return null;return{version:1,main:{type:"opencode",provider:"anthropic"},routing:H(f.routing)?f.routing:void 0,fallbackOn:Array.isArray(f.fallbackOn)?f.fallbackOn.filter((_)=>Number.isInteger(_)):void 0,refresh:H(f.refresh)?f.refresh:void 0,quota:H(f.quota)?f.quota:void 0,claudeCache:H(f.claudeCache)?f.claudeCache:void 0,dump:H(f.dump)?f.dump:void 0,claudeFast:H(f.claudeFast)?f.claudeFast:void 0,costZeroing:H(f.costZeroing)?f.costZeroing:void 0,cacheKeep:H(f.cacheKeep)?f.cacheKeep:void 0,relay:H(f.relay)?f.relay:void 0,logging:H(f.logging)?f.logging:void 0,killswitch:H(f.killswitch)?f.killswitch:void 0,accounts:f.accounts.map(J_).filter((_)=>_!=null)}}async function Sf(f){try{return{exists:!0,value:JSON.parse(await Of(f,"utf8"))}}catch(_){if(_.code==="ENOENT")return{exists:!1,value:null};let $=_ instanceof Error?_.message:String(_);throw Error(`account store at ${f} is corrupt or unreadable (${$}) — fix or remove it`)}}function s(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function Jf(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function nf(f){return Math.max(Jf(f.lastRefreshedAt),Jf(f.lastUsed),Jf(f.addedAt))}function Y_(f,_){if(f.type!=="oauth")return!1;if(typeof f.refresh!=="string"||!f.refresh.trim())return!1;if(!Boolean(typeof f.access==="string"&&typeof _.access==="string"&&f.access!==_.access||typeof f.refresh==="string"&&typeof _.refresh==="string"&&f.refresh!==_.refresh))return!1;return nf(f)>nf(_)}function Z_(f,_){if(Y_(f,_)){let $={..._,...f},D=nf(f);if(D>Jf($.lastRefreshedAt))$.lastRefreshedAt=D;return delete $.quota,delete $.lastRefreshError,delete $.lastQuotaRefreshError,$}return{...f,..._}}function X_(f,_){if(!H(f))return f;let $=H(_)?_:{},D=H($.main)?$.main:void 0,C=H($.accounts)?$.accounts:{},N=H(f.quota)?f.quota:{},b=H(f.refresh)?f.refresh:{},E=D??N,K=D??b,G=Array.isArray(f.accounts)?f.accounts.map((U)=>{if(!H(U))return U;let L=typeof U.id==="string"&&H(C[U.id])?C[U.id]:{};return Z_(U,L)}):[];return{...f,refresh:s({...b,mainLastRefreshError:K.lastRefreshError,mainRefreshLeaseId:K.refreshLeaseId,mainRefreshLeaseUntil:K.refreshLeaseUntil,mainRefreshLeaseTokenHash:K.refreshLeaseTokenHash}),quota:s({...N,mainQuota:E.quota,mainQuotaCheckedAt:E.quotaCheckedAt,mainQuotaToken:E.quotaToken,mainLastQuotaApiError:E.lastQuotaApiError}),accounts:G}}async function F(f=z()){let _=await Sf(f),$=await Sf(r0(f));if(!_.exists&&!$.exists)return null;let D=_.exists?_.value:A();return W_(X_(D,$.value))}async function F_(f){let _=await Sf(f);return H(_.value)?_.value:{}}function V_(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function m_(f){return s({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 Q_(f){if(f.type==="api")return s({apiKey:f.apiKey,lastUsed:f.lastUsed});return s({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 Nf(f){return Math.max(f?.five_hour?.checkedAt??0,f?.seven_day?.checkedAt??0,...f?.scoped?.map((_)=>_.checkedAt)??[],f?.checkedAt??0)}function A_(f,_){if(!H(f))return _;let $=f,D=Nf($.quota),C=Nf(_.quota),N=Boolean($.access&&_.access&&$.access!==_.access||$.refresh&&_.refresh&&$.refresh!==_.refresh);if(D>C){let E=$.lastRefreshedAt??0,K=_.lastRefreshedAt??0;if(N&&K<=E){let U={...$};if(typeof _.lastUsed==="number"&&(typeof $.lastUsed!=="number"||_.lastUsed>$.lastUsed))U.lastUsed=_.lastUsed;return U}let G={...$,..._};if(N){if("quota"in _)if(G.quota=$.quota,"lastQuotaRefreshError"in $)G.lastQuotaRefreshError=$.lastQuotaRefreshError;else delete G.lastQuotaRefreshError;else delete G.quota,delete G.lastQuotaRefreshError;if(!("lastRefreshError"in _))delete G.lastRefreshError;return G}return{...G,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}}let b={...$,..._};if(!("lastQuotaRefreshError"in _))delete b.lastQuotaRefreshError;if(!("lastRefreshError"in _))delete b.lastRefreshError;return b}function R_(f){let _=f.refresh?s({enabled:f.refresh.enabled,intervalMinutes:f.refresh.intervalMinutes,refreshBeforeExpiryMinutes:f.refresh.refreshBeforeExpiryMinutes}):void 0,$=f.quota?s({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 V_({version:1,main:f.main,routing:f.routing,fallbackOn:f.fallbackOn,refresh:_,quota:$,claudeCache:f.claudeCache,dump:f.dump,logging:f.logging,claudeFast:f.claudeFast,costZeroing:f.costZeroing,cacheKeep:f.cacheKeep,relay:f.relay,killswitch:f.killswitch,accounts:f.accounts.map(m_)})}var w0=Promise.resolve();function n0(f){return new Promise((_,$)=>{w0=w0.then(()=>f().then(_,$),()=>f().then(_,$))})}async function c0(f,_){await v0(i0(f),{recursive:!0});let $=`${f}.${Cf()}.tmp`;await zf($,`${JSON.stringify(_,null,2)}
|
|
3
3
|
`,{encoding:"utf8",mode:384});try{await d0($,f)}catch(D){throw await t($,{force:!0}).catch(()=>{}),D}}function m(f,_=z()){let $=_;return n0(()=>P_(f,$))}async function P_(f,_){let D={...await F_(_),...R_(f)};await c0(_,D),await t0(f,_,{mainQuota:!0,mainRefresh:!0,accounts:!0})}function q_(f,_){f.main=f.main??{};let $=typeof f.main.quotaCheckedAt==="number"?f.main.quotaCheckedAt:Nf(f.main.quota),D=typeof _.quota?.mainQuotaCheckedAt==="number"?_.quota.mainQuotaCheckedAt:Nf(_.quota?.mainQuota);if($>D)return;f.main.quota=_.quota?.mainQuota,f.main.quotaCheckedAt=_.quota?.mainQuotaCheckedAt,f.main.quotaToken=_.quota?.mainQuotaToken,f.main.lastQuotaApiError=_.quota?.mainLastQuotaApiError}function I_(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 cf(f){if(Array.isArray(f))return f.map(cf);if(!H(f))return f;return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0).map(([_,$])=>[_,cf($)]))}function x_(f,_=z(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let D=_;return n0(()=>t0(f,D,$))}async function t0(f,_,$){let D=r0(_),C=(await Sf(D)).value,N=H(C)?{...C,version:1}:{version:1};if($.mainQuota)q_(N,f);if($.mainRefresh)I_(N,f);if($.accounts){let b=$.accounts===!0?null:new Set($.accounts);N.accounts={...H(N.accounts)?N.accounts:{}};for(let E of f.accounts){if(b&&!b.has(E.id))continue;N.accounts[E.id]=A_(N.accounts[E.id],Q_(E))}if(b){for(let E of b)if(!f.accounts.some((K)=>K.id===E))delete N.accounts[E]}else{let E=new Set(f.accounts.map((K)=>K.id));for(let K of Object.keys(N.accounts))if(!E.has(K))delete N.accounts[K]}}await c0(D,cf(N))}async function Zf(f){let $=`${f.path??z()}.${f.name}.lock`,D=o($,"owner.json"),C=Cf(),N=f.now??Date.now,b=null,E=!1;async function K(){try{return JSON.parse(await Of($,"utf8"))}catch(M){if(M.code!=="EISDIR")throw M;return JSON.parse(await Of(D,"utf8"))}}async function G(){await zf($,`${JSON.stringify({ownerId:C,expiresAt:N()+f.ttlMs})}
|
|
4
4
|
`,{encoding:"utf8",mode:384})}async function U(){try{return await zf($,`${JSON.stringify({ownerId:C,expiresAt:N()+f.ttlMs})}
|
|
5
5
|
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(M){let X=M.code;if(X==="EEXIST"||X==="EISDIR")return!1;throw M}}function L(){if(!f.renew||E)return;let M=f.renewIntervalMs??Math.max(1000,Math.floor(f.ttlMs/3));if(b=a1(()=>{(async()=>{try{let X=await K(),W=N();if(E||X?.ownerId!==C||Number(X?.expiresAt)<=W)return;await G(),L()}catch{}})()},M),"unref"in b)b.unref()}let Z=await U();if(!Z){let M=`${$}.evicting`,X=o(M,"owner.json"),W=Cf(),B=5000,d=8;async function q(){await new Promise((V)=>setTimeout(V,Math.floor(Math.random()*4)))}async function y(){try{let V=await K();return Number(V?.expiresAt)>N()}catch{try{return(await q0($)).mtimeMs+f.ttlMs>N()}catch{return!1}}}async function T(){try{return JSON.parse(await Of(X,"utf8"))?.ownerId===W}catch{return!1}}async function j(){await v0(M);try{await zf(X,`${JSON.stringify({ownerId:W,createdAt:N()})}
|
|
6
|
-
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(V){if(V.code==="ENOENT")return!1;throw await Y(),V}return await f.onStep?.("eviction-marker-acquired"),!0}async function Y(){if(await T())await t(M,{recursive:!0,force:!0}).catch(()=>{})}for(let V=0;V<8;V++){if(Z=await U(),Z)break;if(await y())return null;try{if(!await j()){await q();continue}}catch(Bf){if(Bf.code!=="EEXIST")throw Bf;let Hf;try{Hf=await q0(M)}catch(P){if(P.code==="ENOENT"){await q();continue}throw P}if(Hf.mtimeMs+5000>N())return null;await f.onStep?.("stale-marker-stat");let l=`${M}.${Cf()}`;try{await d0(M,l)}catch(P){if(P.code==="ENOENT"){await q();continue}throw P}await f.onStep?.("stale-marker-claimed"),await t(l,{recursive:!0,force:!0}).catch(()=>{}),await q();continue}try{if(await y())return null;if(!await T())return null;if(await f.onStep?.("stale-lock-confirmed"),!await T())return null;if(await t($,{recursive:!0,force:!0}).catch(()=>{}),!await T())return null;if(Z=await U(),!Z)return null;if(!await T())return await t($,{recursive:!0,force:!0}).catch(()=>{}),Z=!1,null;break}finally{await Y()}}}if(!Z)return null;return L(),{release:async()=>{if(E=!0,b)e1(b),b=null;try{if((await K())?.ownerId!==C)return}catch{return}await t($,{recursive:!0,force:!0}).catch(()=>{})}}}function MC(f){return f?.claudeCache?.enabled===!0}function T_(f){return typeof f==="string"&&Q0.includes(f)?f:Lf}function h_(f){return T_(f?.claudeCache?.mode)}async function LC(f,_,$=z()){let D=await F($)??A();return D.claudeCache={...D.claudeCache??{},enabled:f,mode:_??h_(D)},await m(D,$),D}async function OC(f,_=z()){let $=await F(_)??A();return $.claudeCache={...$.claudeCache??{},enabled:$.claudeCache?.enabled===!0,mode:f},await m($,_),$}function zC(f){return f?.dump?.enabled===!0}async function JC(f,_=z()){let $=await F(_)??A();return $.dump={...$.dump??{},enabled:f},await m($,_),$}function SC(f){return f?.claudeFast?.enabled===!0}async function WC(f,_=z()){let $=await F(_)??A();return $.claudeFast={...$.claudeFast??{},enabled:f},await m($,_),$}async function YC(f,_,$=z()){let D=await F($)??A();return D.cacheKeep={enabled:!0,startHour:f,endHour:_},await m(D,$),D}async function ZC(f,_=z()){let $=await F(_)??A();return $.cacheKeep={...$.cacheKeep??{},enabled:f},await m($,_),$}function XC(f){return f?.cacheKeep?.subagents===!0}async function FC(f,_=z()){let $=await F(_)??A();return $.cacheKeep={...$.cacheKeep??{},subagents:f},await m($,_),$}function w_(f){return f?.fallbackOn?.length?f.fallbackOn:D_}function VC(f,_){return w_(_).includes(f)}function o0(f){let _=f?.quota?.minimumRemaining||{};return{five_hour:_.five_hour??_["5h"]??I0.five_hour,seven_day:_.seven_day??_["1w"]??I0.seven_day}}function bf(f){return f?.quota?.enabled!==!1}function y_(f){return f?.refresh?.enabled!==!1}function k_(f){return Math.floor(Math.random()*Math.max(0,f))}function l_(f){let _=f?.refresh?.refreshBeforeExpiryMinutes??C_;return Math.max(g0,_)*60000}function a0(f){return p0("sha256").update(f).digest("hex")}function p_(f){let _=f.status;if(typeof _==="number"&&Number.isFinite(_))return _===429||_>=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 v_(f){let _=a0(f.refreshToken),D=(f.previous?.tokenHash===_?f.previous.retryCount??0:0)+1,C=f.error.retryAfter,N;if(typeof C==="number"&&C>0)N=C*1000;else if(p_(f.error))N=Math.min(b_,N_*2**Math.min(D-1,6));else N=s0;let b=f.error.status,E=typeof b==="number"&&Number.isFinite(b)?b:void 0,K=e(f.error),U=(typeof f.error.body==="string"?f.error.body:"").includes("invalid_grant")||K.includes("invalid_grant");return{message:K,checkedAt:f.now,nextRetryAt:f.now+N,retryCount:D,tokenHash:_,status:E,permanent:E===400&&U}}function mC(f){if(!f)return!1;if(typeof f.permanent==="boolean")return f.permanent;if(typeof f.status==="number")return f.status===400;if(typeof f.nextRetryAt==="number")return f.nextRetryAt-f.checkedAt>=s0;return!1}function Df(f,_,$){if(!f?.nextRetryAt||f.nextRetryAt<=$)return!1;if(!_)return!0;return f.tokenHash===a0(_)}function gf(f,_){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function tf(f){if(f.status===403)return!0;return/Claude quota check failed: 403\b/.test(e(f))}function Xf(f){let $=(f.previous?.retryCount??0)+1,D=D1(f.error)?Math.min(K_,E_*2**Math.min($-1,6)):G_;return{message:e(f.error),checkedAt:f.now,nextRetryAt:f.now+D,retryCount:$}}function a(f,_){if(!f?.nextRetryAt||f.nextRetryAt<=_)return!1;return!0}function QC(f,_){return`Quota API backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function w(f){let _=f?.quota?.checkIntervalMinutes??U_;return Math.max(1,_)*60000}function AC(f){return f?.logging?.level}async function RC(f,_=z()){let{setLogLevel:$}=await import("./logger-sg9wxpvj.js"),D=await F(_)??A();D.logging={...D.logging??{},level:f},await m(D,_),$(f)}function e0(f){if(!f?.quota?.mainQuota||!f.quota.mainQuotaCheckedAt)return null;return{quota:f.quota.mainQuota,checkedAt:f.quota.mainQuotaCheckedAt,tokenFingerprint:f.quota.mainQuotaToken}}function f1(f){let _=f?.quota?.refreshEveryNRequests;return typeof _==="number"&&Number.isFinite(_)&&_>0?Math.floor(_):0}function Wf(f){return f?.quota?.failClosedOnUnknownQuota??j_}function d_(f){if(typeof f!=="string")return null;let _=f.toLowerCase();if(_.includes("fable"))return"fable";if(_.includes("mythos"))return"mythos";return null}function of(f,_){let $=d_(_);if(!$)return;return f?.scoped?.find((D)=>{return[D.modelId,D.modelName,D.title].filter((N)=>typeof N==="string").join(" ").toLowerCase().includes($)})}function i_(f,_){let $=of(f,_);return Boolean($&&Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)}function y0(f,_){return!i_(f,_)}function _1(f,_){if(!bf(_))return!0;let $=o0(_);for(let D of["five_hour","seven_day"]){let C=f?.[D];if(!C)return!Wf(_);if(!Number.isFinite(C.remainingPercent))return!Wf(_);if(C.remainingPercent<$[D])return!1}return!0}var g={five_hour:5,seven_day:10,scoped:0};function Ef(f){let _=f?.five_hour??f?.["5h"],$=f?.seven_day??f?.["1w"],D=f?.scoped;return{five_hour:typeof _==="number"&&Number.isFinite(_)?_:g.five_hour,seven_day:typeof $==="number"&&Number.isFinite($)?$:g.seven_day,scoped:typeof D==="number"&&Number.isFinite(D)?D:g.scoped}}function u_(f){return f?.killswitch?.enabled===!0}function g_(f,_){if(!f?.killswitch)return g;if(_&&f.killswitch.accounts?.[_])return Ef(f.killswitch.accounts[_]);return Ef(f.killswitch.main)}function PC(f,_,$,D){if(!u_(_))return!0;let C=g_(_,$),N=!1;for(let b of["five_hour","seven_day"]){let E=f?.[b];if(!E){N=!0;continue}if(!Number.isFinite(E.remainingPercent)){N=!0;continue}if(E.remainingPercent<C[b])return!1}if(D){let b=of(f,D);if(b&&Number.isFinite(b.remainingPercent)&&b.remainingPercent<=C.scoped)return!1}if(N)return!Wf(_);return!0}function qC(f,_,$,D){let C=[],N=[f,..._.map((b)=>b.quota)];for(let b of N)if(D){let K=of(b,D)?.resetsAt;if(!K)continue;let G=Date.parse(K);if(Number.isFinite(G)&&G>$)C.push(G)}else for(let E of["five_hour","seven_day"]){let K=b?.[E]?.resetsAt;if(!K)continue;let G=Date.parse(K);if(Number.isFinite(G)&&G>$)C.push(G)}if(!C.length)return 300;return Math.max(1,Math.ceil((Math.min(...C)-$)/1000))+60}function IC(f){return f?.killswitch??{enabled:!1}}async function xC(f,_=z()){let $=await F(_)??A();return $.killswitch=f,await m($,_),$}async function TC(f,_=z()){let $=await F(_);if(!$)return!1;let D=a_($,f);if(D)await m($,_);return D}async function hC(f,_=z()){let $=await F(_);if(!$)return;e_($,f),await m($,_)}async function wC(f,_,$=z()){let D=await F($);if(!D)return!1;let C=f$(D,f,_);if(C)await m(D,$);return C}async function yC(f,_=z()){let $=await F(_)??A();o_($,f),await m($,_)}function af(f,_,$){if(!bf(_))return $+w(_);let D=o0(_),C=[];for(let N of["five_hour","seven_day"]){let b=f?.[N];if(!b)return $+w(_);if(b.remainingPercent>=D[N])continue;let E=b.resetsAt?Date.parse(b.resetsAt):Number.NaN;if(!Number.isFinite(E)||E<=$)return $+w(_);C.push(E)}if(!C.length)return $+w(_);return Math.min(...C)+60000}function i(f,_,$){return!f.access||!f.expires||f.expires-$<=l_(_)}function $1(f,_,$){if(!bf(_))return!0;let D=w(_);return["five_hour","seven_day"].every((C)=>{let N=f?.[C];return Boolean(N&&$-N.checkedAt<D)})}function sf(f,_,$){return!$1(f.quota,_,$)}function s_(f,_){if(!f)return!1;if(!f.resetsAt)return!0;let $=Date.parse(f.resetsAt);return!Number.isFinite($)||$>_}function r_(f,_){return["five_hour","seven_day"].every(($)=>s_(f?.[$],_))}function D1(f){let _=f.status;if(typeof _==="number"&&Number.isFinite(_)){if(_===429||_>=500)return!0}let $=e(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{message:D,code:C}=f;return D.includes("fetch failed")||C==="ECONNRESET"||C==="ECONNREFUSED"||C==="ETIMEDOUT"||C==="UND_ERR_CONNECT_TIMEOUT"}function n_(f,_,$,D){return D1($)&&_1(f.quota,_)&&r_(f.quota,D)}function Yf(f){if(!Number.isFinite(f))return 0;if(f<0)return 0;if(f>100)return 100;return f}function rf(f){return typeof f==="string"&&f.trim()?f.trim():void 0}function c_(f){return f.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function t_(f,_){if(!Array.isArray(f))return;let $=new Set,D=[];for(let C of f){if(C?.kind!=="weekly_scoped"||C.group!=="weekly")continue;if(typeof C.percent!=="number"||!Number.isFinite(C.percent))continue;let N=rf(C.scope?.model?.display_name);if(!N)continue;let b=rf(C.scope?.model?.id)??N,E=c_(b);if(!E)continue;let K=`claude-weekly-scoped-${E}`;if($.has(K))continue;$.add(K);let G=Yf(C.percent),U=rf(C.scope?.model?.id);D.push({id:K,title:`${N} only`,...U&&{modelId:U},modelName:N,usedPercent:G,remainingPercent:Yf(100-G),resetsAt:C.resets_at,checkedAt:_})}return D.length?D:void 0}function k0(f,_){if(typeof f?.utilization!=="number")return;if(!Number.isFinite(f.utilization))return;let $=Yf(f.utilization);return{usedPercent:$,remainingPercent:Yf(100-$),resetsAt:f.resets_at,checkedAt:_}}async function Ff(f){let $=await(f.fetchImpl??fetch)(__,{method:"GET",headers:{Authorization:`Bearer ${f.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${p}`}});if(!$.ok){let N=await $.text().catch(()=>"");throw Object.assign(Error(`Claude quota check failed: ${$.status} — ${N}`),{status:$.status,retryAfter:uf($.headers.get("Retry-After"))})}let D=f.now?.()??Date.now(),C=await $.json();return{five_hour:k0(C.five_hour,D),seven_day:k0(C.seven_day,D),scoped:t_(C.limits,D)}}function Q(f,_){let $=f.accounts.findIndex((D)=>D.id===_.id);if($>=0)f.accounts[$]=_}function o_(f,_){let $=f.accounts.findIndex((D)=>D.id===_.id||_.label&&D.label===_.label);if($>=0){f.accounts[$]={...f.accounts[$],..._,addedAt:f.accounts[$]?.addedAt??_.addedAt,..._.type==="oauth"&&{quota:_.quota,lastRefreshedAt:_.lastRefreshedAt,lastRefreshError:_.lastRefreshError,lastQuotaRefreshError:_.lastQuotaRefreshError}};return}f.accounts.push(_)}function a_(f,_){let $=f.accounts.findIndex((D)=>D.id===_);if($<0)return!1;return f.accounts.splice($,1),!0}function e_(f,_){let $=new Map(_.map((N,b)=>[N,b])),D=f.accounts.filter((N)=>$.has(N.id)),C=f.accounts.filter((N)=>!$.has(N.id));D.sort((N,b)=>($.get(N.id)??0)-($.get(b.id)??0)),f.accounts=[...D,...C]}function f$(f,_,$){let D=f.accounts.find((C)=>C.id===_);if(!D)return!1;return D.enabled=$,!0}function e(f){return f instanceof Error?f.message:String(f)}function C1(f,_,$){f.lastRefreshError=v_({error:_,now:$,refreshToken:f.refresh,previous:f.lastRefreshError})}function l0(f,_,$){if(tf(_))return;if(f.lastQuotaRefreshError=Xf({error:_,now:$,previous:f.lastQuotaRefreshError}),_.isRefreshError)C1(f,_,$)}function _$(f){return`fallback-oauth-refresh-${p0("sha256").update(f).digest("hex").slice(0,16)}`}class $${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??z(),this.quotaManager=f.quotaManager??null,this.onFallbackStorageChanged=f.onFallbackStorageChanged}seedFallbackQuota(f,_){if(!this.quotaManager)return;if(!f.quota)return;let $=Math.max(f.quota.five_hour?.checkedAt??0,f.quota.seven_day?.checkedAt??0);if($<=0)return;let D=this.quotaManager.getFallback(f.id,f.access);if(D&&D.checkedAt>=$)return;let C=w(_);this.quotaManager.setFallback(f.id,{quota:f.quota,refreshAfter:$+C,checkedAt:$},f.access)}async load(){return F(this.configPath)}async save(f,_){await x_(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(()=>{})},B_+k_(H_)),"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=[],C=!1;for(let N of $.accounts){if(N.enabled===!1||!h(N))continue;try{let b=N;if(i(b,$,this.now())){let K=b.lastRefreshError;if(K&&Df(K,b.refresh,this.now()))throw Error(gf(K,this.now()));b=await this.refreshAccount(b,$),C=!0}if(this.seedFallbackQuota(b,$),(this.quotaManager?this.quotaManager.isFallbackStale(b.id,b.access):sf(b,$,this.now()))&&!a(b.lastQuotaRefreshError,this.now()))b=await this.refreshAccountQuota(b,$),C=!0;if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount(b),$,{modelId:_.modelId}))D.push(b)}catch(b){if(n_(N,$,b,this.now())){if(u("[refresh] fallback quota using cached quota after refresh error",{accountId:N.id,error:e(b)}),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(N),$,{modelId:_.modelId}))D.push(N)}else if(!Wf($)&&y0(N.quota,_.modelId))D.push(N)}}if(C)await this.save($);return D}async markUsed(f){let _=await this.load();if(!_)return;let $=_.accounts.find((D)=>D.id===f.id);if(!$)return;$.lastUsed=this.now(),await this.save(_)}accountPassesQuotaPolicy(f,_,$={}){return _1(f.quota,_)&&y0(f.quota,$.modelId)}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||!y_(f))return;let _=!1;for(let $ of f.accounts){if($.enabled===!1||!h($))continue;if(!i($,f,this.now()))continue;if(Df($.lastRefreshError,$.refresh,this.now()))continue;try{u("[refresh] fallback oauth background due",{accountId:$.id,expiresInMs:$.expires?$.expires-this.now():void 0}),await this.refreshAccount($,f),_=!0}catch(D){I.warn("refresh","fallback oauth background failed",{accountId:$.id,error:D instanceof Error?D.message:String(D)}),C1($,D,this.now()),Q(f,$),_=!0}}if(_)await this.save(f)}async refreshQuotaForDueAccounts(){let f=await this.load();if(!f||!bf(f))return;let _=!1;for(let $ of f.accounts){if($.enabled===!1||!h($))continue;let D=$;try{if(i(D,f,this.now())){if(Df(D.lastRefreshError,D.refresh,this.now()))continue;D=await this.refreshAccount(D,f),_=!0}if(a(D.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(D,f),!(this.quotaManager?this.quotaManager.isFallbackStale(D.id,D.access):sf(D,f,this.now())))continue;await this.refreshAccountQuota(D,f),_=!0}catch(C){l0($,C,this.now()),Q(f,$),_=!0}}if(_)await this.save(f),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(f={}){let _=await this.load(),$=[];if(!_||!bf(_))return{storage:_,errors:$};let D=f.force??!1,C=!1;for(let N of _.accounts){if(N.enabled===!1||!h(N))continue;let b=N;try{if(i(b,_,this.now())){let E=b.lastRefreshError;if(E&&Df(E,b.refresh,this.now()))throw Error(gf(E,this.now()));b=await this.refreshAccount(b,_),C=!0}if(!D&&!sf(b,_,this.now())){if(b.lastQuotaRefreshError)b.lastQuotaRefreshError=void 0,Q(_,b),C=!0;continue}await this.refreshAccountQuota(b,_),C=!0}catch(E){l0(N,E,this.now()),Q(_,N),C=!0,$.push({accountId:N.id,message:e(E)})}}if(C)await this.save(_);return{storage:_,errors:$}}async refreshAccount(f,_,$={}){let D=this.refreshPromises.get(f.id);if(D){let b=await D;return Q(_,b),b}let C=this.refreshAccountNow(f,_,$).finally(()=>{this.refreshPromises.delete(f.id)});this.refreshPromises.set(f.id,C);let N=await C;return Q(_,N),N}async waitForConcurrentFallbackRefresh(f,_,$,D){let C=Date.now()+L_;while(Date.now()<C){await new Promise((G)=>setTimeout(G,O_));let N=await this.load(),b=N?.accounts.find((G)=>G.id===f.id&&h(G));if(!b)continue;if((b.access!==$.access||b.refresh!==$.refresh||(b.expires??0)>($.expires??0)+60000)&&(D.force||!i(b,N,this.now())))return Q(_,b),u("[refresh] fallback oauth joined concurrent refresh",{accountId:b.id,expiresInMs:b.expires?b.expires-this.now():void 0}),b;let K=b.lastRefreshError;if(K&&Df(K,b.refresh,this.now()))throw Q(_,b),Error(gf(K,this.now()))}return null}async refreshAccountNow(f,_,$){let D=await this.load(),C=D?.accounts.find((E)=>E.id===f.id&&h(E));if(C&&!$.force&&!i(C,D,this.now()))return Q(_,C),C;let N=C??f,b=await Zf({name:_$(N.id),ttlMs:M_,path:this.configPath,now:this.now,renew:!0});if(!b){u("[refresh] fallback oauth refresh skipped file lock",{accountId:N.id});let E=await this.waitForConcurrentFallbackRefresh(f,_,N,$);if(E)return E;throw Error("Fallback OAuth refresh is already in progress")}try{if(D=await this.load(),C=D?.accounts.find((G)=>G.id===f.id&&h(G)),C&&!$.force&&!i(C,D,this.now()))return Q(_,C),C;N=C??N;let E=N.refresh;u("[refresh] fallback oauth refresh request start",{accountId:N.id,force:$.force===!0,expiresInMs:N.expires?N.expires-this.now():void 0});let K=await P0({refreshToken:E,fetchImpl:this.fetchImpl,now:this.now});return N.access=K.access,N.refresh=K.refresh,N.expires=K.expires,N.lastRefreshedAt=K.expires-K.expiresIn*1000,N.lastRefreshError=void 0,Q(_,N),await this.save(_),u("[refresh] fallback oauth refresh succeeded",{accountId:N.id,expiresInMs:N.expires?N.expires-this.now():void 0}),N}finally{await b.release()}}async refreshAccountQuota(f,_){let $=f;if(!$.access)throw Error(`Fallback account ${f.id} has no access token`);let D=(E)=>this.quotaManager?this.quotaManager.refreshFallback($.id,E):Ff({accessToken:E,fetchImpl:this.fetchImpl,now:this.now}),C=this.now();try{$.quota=await D($.access)}catch(E){if(!(E instanceof Error?E.message:String(E)).includes("Claude quota check failed: 401"))throw E;if($=await this.refreshAccount(f,_,{force:!0}),!$.access)throw E;$.quota=await D($.access)}let N=await this.load(),b=N?.accounts.find((E)=>E.id===$.id&&h(E));if(N&&b&&b.access!==$.access)return this.seedFallbackQuota(b,N),Q(_,b),b;if(N&&b?.access===$.access&&b.quota&&Nf(b.quota)>=C&&$1(b.quota,N,this.now()))return this.seedFallbackQuota(b,N),Q(_,b),b;if($.lastQuotaRefreshError=void 0,Q(_,$),this.quotaManager&&$.quota){let E=this.now();this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:E+w(_),checkedAt:E},$.access)}return $}}var pC="claude-cache",N1="## Claude Cache Status",D$="## Claude Cache Enabled",C$="## Claude Cache Disabled",N$="## Claude Cache Usage",b$="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",Vf=!1,mf=Lf;function vC(){return Vf}function dC(){return mf}function iC(f){Vf=f.enabled,mf=f.mode}function E$(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 Kf(f){let _=f?.enabled??Vf,$=f?.mode??mf;return[N1,"",`- Enabled: ${_?"enabled":"disabled"}`,`- Mode: ${$}`,"- 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(`
|
|
6
|
+
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(V){if(V.code==="ENOENT")return!1;throw await Y(),V}return await f.onStep?.("eviction-marker-acquired"),!0}async function Y(){if(await T())await t(M,{recursive:!0,force:!0}).catch(()=>{})}for(let V=0;V<8;V++){if(Z=await U(),Z)break;if(await y())return null;try{if(!await j()){await q();continue}}catch(Bf){if(Bf.code!=="EEXIST")throw Bf;let Hf;try{Hf=await q0(M)}catch(P){if(P.code==="ENOENT"){await q();continue}throw P}if(Hf.mtimeMs+5000>N())return null;await f.onStep?.("stale-marker-stat");let l=`${M}.${Cf()}`;try{await d0(M,l)}catch(P){if(P.code==="ENOENT"){await q();continue}throw P}await f.onStep?.("stale-marker-claimed"),await t(l,{recursive:!0,force:!0}).catch(()=>{}),await q();continue}try{if(await y())return null;if(!await T())return null;if(await f.onStep?.("stale-lock-confirmed"),!await T())return null;if(await t($,{recursive:!0,force:!0}).catch(()=>{}),!await T())return null;if(Z=await U(),!Z)return null;if(!await T())return await t($,{recursive:!0,force:!0}).catch(()=>{}),Z=!1,null;break}finally{await Y()}}}if(!Z)return null;return L(),{release:async()=>{if(E=!0,b)e1(b),b=null;try{if((await K())?.ownerId!==C)return}catch{return}await t($,{recursive:!0,force:!0}).catch(()=>{})}}}function MC(f){return f?.claudeCache?.enabled===!0}function T_(f){return typeof f==="string"&&Q0.includes(f)?f:Lf}function h_(f){return T_(f?.claudeCache?.mode)}async function LC(f,_,$=z()){let D=await F($)??A();return D.claudeCache={...D.claudeCache??{},enabled:f,mode:_??h_(D)},await m(D,$),D}async function OC(f,_=z()){let $=await F(_)??A();return $.claudeCache={...$.claudeCache??{},enabled:$.claudeCache?.enabled===!0,mode:f},await m($,_),$}function zC(f){return f?.dump?.enabled===!0}async function JC(f,_=z()){let $=await F(_)??A();return $.dump={...$.dump??{},enabled:f},await m($,_),$}function SC(f){return f?.claudeFast?.enabled===!0}async function WC(f,_=z()){let $=await F(_)??A();return $.claudeFast={...$.claudeFast??{},enabled:f},await m($,_),$}async function YC(f,_,$=z()){let D=await F($)??A();return D.cacheKeep={enabled:!0,startHour:f,endHour:_},await m(D,$),D}async function ZC(f,_=z()){let $=await F(_)??A();return $.cacheKeep={...$.cacheKeep??{},enabled:f},await m($,_),$}function XC(f){return f?.cacheKeep?.subagents===!0}async function FC(f,_=z()){let $=await F(_)??A();return $.cacheKeep={...$.cacheKeep??{},subagents:f},await m($,_),$}function w_(f){return f?.fallbackOn?.length?f.fallbackOn:D_}function VC(f,_){return w_(_).includes(f)}function o0(f){let _=f?.quota?.minimumRemaining||{};return{five_hour:_.five_hour??_["5h"]??I0.five_hour,seven_day:_.seven_day??_["1w"]??I0.seven_day}}function bf(f){return f?.quota?.enabled!==!1}function y_(f){return f?.refresh?.enabled!==!1}function k_(f){return Math.floor(Math.random()*Math.max(0,f))}function l_(f){let _=f?.refresh?.refreshBeforeExpiryMinutes??C_;return Math.max(g0,_)*60000}function a0(f){return p0("sha256").update(f).digest("hex")}function p_(f){let _=f.status;if(typeof _==="number"&&Number.isFinite(_))return _===429||_>=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 v_(f){let _=a0(f.refreshToken),D=(f.previous?.tokenHash===_?f.previous.retryCount??0:0)+1,C=f.error.retryAfter,N;if(typeof C==="number"&&C>0)N=C*1000;else if(p_(f.error))N=Math.min(b_,N_*2**Math.min(D-1,6));else N=s0;let b=f.error.status,E=typeof b==="number"&&Number.isFinite(b)?b:void 0,K=e(f.error),U=(typeof f.error.body==="string"?f.error.body:"").includes("invalid_grant")||K.includes("invalid_grant");return{message:K,checkedAt:f.now,nextRetryAt:f.now+N,retryCount:D,tokenHash:_,status:E,permanent:E===400&&U}}function mC(f){if(!f)return!1;if(typeof f.permanent==="boolean")return f.permanent;if(typeof f.status==="number")return f.status===400;if(typeof f.nextRetryAt==="number")return f.nextRetryAt-f.checkedAt>=s0;return!1}function Df(f,_,$){if(!f?.nextRetryAt||f.nextRetryAt<=$)return!1;if(!_)return!0;return f.tokenHash===a0(_)}function gf(f,_){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function tf(f){if(f.status===403)return!0;return/Claude quota check failed: 403\b/.test(e(f))}function Xf(f){let $=(f.previous?.retryCount??0)+1,D=D1(f.error)?Math.min(K_,E_*2**Math.min($-1,6)):G_;return{message:e(f.error),checkedAt:f.now,nextRetryAt:f.now+D,retryCount:$}}function a(f,_){if(!f?.nextRetryAt||f.nextRetryAt<=_)return!1;return!0}function QC(f,_){return`Quota API backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function w(f){let _=f?.quota?.checkIntervalMinutes??U_;return Math.max(1,_)*60000}function AC(f){return f?.logging?.level}async function RC(f,_=z()){let{setLogLevel:$}=await import("./logger-sg9wxpvj.js"),D=await F(_)??A();D.logging={...D.logging??{},level:f},await m(D,_),$(f)}function e0(f){if(!f?.quota?.mainQuota||!f.quota.mainQuotaCheckedAt)return null;return{quota:f.quota.mainQuota,checkedAt:f.quota.mainQuotaCheckedAt,tokenFingerprint:f.quota.mainQuotaToken}}function f1(f){let _=f?.quota?.refreshEveryNRequests;return typeof _==="number"&&Number.isFinite(_)&&_>0?Math.floor(_):0}function Wf(f){return f?.quota?.failClosedOnUnknownQuota??j_}function d_(f){if(typeof f!=="string")return null;let _=f.toLowerCase();if(_.includes("fable"))return"fable";if(_.includes("mythos"))return"mythos";return null}function of(f,_){let $=d_(_);if(!$)return;return f?.scoped?.find((D)=>{return[D.modelId,D.modelName,D.title].filter((N)=>typeof N==="string").join(" ").toLowerCase().includes($)})}function i_(f,_){let $=of(f,_);return Boolean($&&Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)}function y0(f,_){return!i_(f,_)}function _1(f,_){if(!bf(_))return!0;let $=o0(_);for(let D of["five_hour","seven_day"]){let C=f?.[D];if(!C)return!Wf(_);if(!Number.isFinite(C.remainingPercent))return!Wf(_);if(C.remainingPercent<$[D])return!1}return!0}var g={five_hour:5,seven_day:10,scoped:0};function Ef(f){let _=f?.five_hour??f?.["5h"],$=f?.seven_day??f?.["1w"],D=f?.scoped;return{five_hour:typeof _==="number"&&Number.isFinite(_)?_:g.five_hour,seven_day:typeof $==="number"&&Number.isFinite($)?$:g.seven_day,scoped:typeof D==="number"&&Number.isFinite(D)?D:g.scoped}}function u_(f){return f?.killswitch?.enabled===!0}function g_(f,_){if(!f?.killswitch)return g;if(_&&f.killswitch.accounts?.[_])return Ef(f.killswitch.accounts[_]);return Ef(f.killswitch.main)}function PC(f,_,$,D){if(!u_(_))return!0;let C=g_(_,$),N=!1;for(let b of["five_hour","seven_day"]){let E=f?.[b];if(!E){N=!0;continue}if(!Number.isFinite(E.remainingPercent)){N=!0;continue}if(E.remainingPercent<C[b])return!1}if(D){let b=of(f,D);if(b&&Number.isFinite(b.remainingPercent)&&b.remainingPercent<=C.scoped)return!1}if(N)return!Wf(_);return!0}function qC(f,_,$,D){let C=[],N=[f,..._.map((b)=>b.quota)];for(let b of N)if(D){let K=of(b,D)?.resetsAt;if(!K)continue;let G=Date.parse(K);if(Number.isFinite(G)&&G>$)C.push(G)}else for(let E of["five_hour","seven_day"]){let K=b?.[E]?.resetsAt;if(!K)continue;let G=Date.parse(K);if(Number.isFinite(G)&&G>$)C.push(G)}if(!C.length)return 300;return Math.max(1,Math.ceil((Math.min(...C)-$)/1000))+60}function IC(f){return f?.killswitch??{enabled:!1}}async function xC(f,_=z()){let $=await F(_)??A();return $.killswitch=f,await m($,_),$}async function TC(f,_=z()){let $=await F(_);if(!$)return!1;let D=a_($,f);if(D)await m($,_);return D}async function hC(f,_=z()){let $=await F(_);if(!$)return;e_($,f),await m($,_)}async function wC(f,_,$=z()){let D=await F($);if(!D)return!1;let C=f$(D,f,_);if(C)await m(D,$);return C}async function yC(f,_=z()){let $=await F(_)??A();o_($,f),await m($,_)}function af(f,_,$){if(!bf(_))return $+w(_);let D=o0(_),C=[];for(let N of["five_hour","seven_day"]){let b=f?.[N];if(!b)return $+w(_);if(b.remainingPercent>=D[N])continue;let E=b.resetsAt?Date.parse(b.resetsAt):Number.NaN;if(!Number.isFinite(E)||E<=$)return $+w(_);C.push(E)}if(!C.length)return $+w(_);return Math.min(...C)+60000}function i(f,_,$){return!f.access||!f.expires||f.expires-$<=l_(_)}function $1(f,_,$){if(!bf(_))return!0;let D=w(_);return["five_hour","seven_day"].every((C)=>{let N=f?.[C];return Boolean(N&&$-N.checkedAt<D)})}function sf(f,_,$){return!$1(f.quota,_,$)}function s_(f,_){if(!f)return!1;if(!f.resetsAt)return!0;let $=Date.parse(f.resetsAt);return!Number.isFinite($)||$>_}function r_(f,_){return["five_hour","seven_day"].every(($)=>s_(f?.[$],_))}function D1(f){let _=f.status;if(typeof _==="number"&&Number.isFinite(_)){if(_===429||_>=500)return!0}let $=e(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{message:D,code:C}=f;return D.includes("fetch failed")||C==="ECONNRESET"||C==="ECONNREFUSED"||C==="ETIMEDOUT"||C==="UND_ERR_CONNECT_TIMEOUT"}function n_(f,_,$,D){return D1($)&&_1(f.quota,_)&&r_(f.quota,D)}function Yf(f){if(!Number.isFinite(f))return 0;if(f<0)return 0;if(f>100)return 100;return f}function rf(f){return typeof f==="string"&&f.trim()?f.trim():void 0}function c_(f){return f.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function t_(f,_){if(!Array.isArray(f))return[];let $=new Set,D=[];for(let C of f){if(C?.kind!=="weekly_scoped"||C.group!=="weekly")continue;if(typeof C.percent!=="number"||!Number.isFinite(C.percent))continue;let N=rf(C.scope?.model?.display_name);if(!N)continue;let b=rf(C.scope?.model?.id)??N,E=c_(b);if(!E)continue;let K=`claude-weekly-scoped-${E}`;if($.has(K))continue;$.add(K);let G=Yf(C.percent),U=rf(C.scope?.model?.id);D.push({id:K,title:`${N} only`,...U&&{modelId:U},modelName:N,usedPercent:G,remainingPercent:Yf(100-G),resetsAt:C.resets_at,checkedAt:_})}return D}function k0(f,_){if(typeof f?.utilization!=="number")return;if(!Number.isFinite(f.utilization))return;let $=Yf(f.utilization);return{usedPercent:$,remainingPercent:Yf(100-$),resetsAt:f.resets_at,checkedAt:_}}async function Ff(f){let $=await(f.fetchImpl??fetch)(__,{method:"GET",headers:{Authorization:`Bearer ${f.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${p}`}});if(!$.ok){let N=await $.text().catch(()=>"");throw Object.assign(Error(`Claude quota check failed: ${$.status} — ${N}`),{status:$.status,retryAfter:uf($.headers.get("Retry-After"))})}let D=f.now?.()??Date.now(),C=await $.json();return{five_hour:k0(C.five_hour,D),seven_day:k0(C.seven_day,D),scoped:t_(C.limits,D),checkedAt:D}}function Q(f,_){let $=f.accounts.findIndex((D)=>D.id===_.id);if($>=0)f.accounts[$]=_}function o_(f,_){let $=f.accounts.findIndex((D)=>D.id===_.id||_.label&&D.label===_.label);if($>=0){f.accounts[$]={...f.accounts[$],..._,addedAt:f.accounts[$]?.addedAt??_.addedAt,..._.type==="oauth"&&{quota:_.quota,lastRefreshedAt:_.lastRefreshedAt,lastRefreshError:_.lastRefreshError,lastQuotaRefreshError:_.lastQuotaRefreshError}};return}f.accounts.push(_)}function a_(f,_){let $=f.accounts.findIndex((D)=>D.id===_);if($<0)return!1;return f.accounts.splice($,1),!0}function e_(f,_){let $=new Map(_.map((N,b)=>[N,b])),D=f.accounts.filter((N)=>$.has(N.id)),C=f.accounts.filter((N)=>!$.has(N.id));D.sort((N,b)=>($.get(N.id)??0)-($.get(b.id)??0)),f.accounts=[...D,...C]}function f$(f,_,$){let D=f.accounts.find((C)=>C.id===_);if(!D)return!1;return D.enabled=$,!0}function e(f){return f instanceof Error?f.message:String(f)}function C1(f,_,$){f.lastRefreshError=v_({error:_,now:$,refreshToken:f.refresh,previous:f.lastRefreshError})}function l0(f,_,$){if(tf(_))return;if(f.lastQuotaRefreshError=Xf({error:_,now:$,previous:f.lastQuotaRefreshError}),_.isRefreshError)C1(f,_,$)}function _$(f){return`fallback-oauth-refresh-${p0("sha256").update(f).digest("hex").slice(0,16)}`}class $${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??z(),this.quotaManager=f.quotaManager??null,this.onFallbackStorageChanged=f.onFallbackStorageChanged}seedFallbackQuota(f,_){if(!this.quotaManager)return;if(!f.quota)return;let $=Math.max(f.quota.five_hour?.checkedAt??0,f.quota.seven_day?.checkedAt??0);if($<=0)return;let D=this.quotaManager.getFallback(f.id,f.access);if(D&&D.checkedAt>=$)return;let C=w(_);this.quotaManager.setFallback(f.id,{quota:f.quota,refreshAfter:$+C,checkedAt:$},f.access)}async load(){return F(this.configPath)}async save(f,_){await x_(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(()=>{})},B_+k_(H_)),"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=[],C=!1;for(let N of $.accounts){if(N.enabled===!1||!h(N))continue;try{let b=N;if(i(b,$,this.now())){let K=b.lastRefreshError;if(K&&Df(K,b.refresh,this.now()))throw Error(gf(K,this.now()));b=await this.refreshAccount(b,$),C=!0}if(this.seedFallbackQuota(b,$),(this.quotaManager?this.quotaManager.isFallbackStale(b.id,b.access):sf(b,$,this.now()))&&!a(b.lastQuotaRefreshError,this.now()))b=await this.refreshAccountQuota(b,$),C=!0;if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount(b),$,{modelId:_.modelId}))D.push(b)}catch(b){if(n_(N,$,b,this.now())){if(u("[refresh] fallback quota using cached quota after refresh error",{accountId:N.id,error:e(b)}),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(N),$,{modelId:_.modelId}))D.push(N)}else if(!Wf($)&&y0(N.quota,_.modelId))D.push(N)}}if(C)await this.save($);return D}async markUsed(f){let _=await this.load();if(!_)return;let $=_.accounts.find((D)=>D.id===f.id);if(!$)return;$.lastUsed=this.now(),await this.save(_)}accountPassesQuotaPolicy(f,_,$={}){return _1(f.quota,_)&&y0(f.quota,$.modelId)}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||!y_(f))return;let _=!1;for(let $ of f.accounts){if($.enabled===!1||!h($))continue;if(!i($,f,this.now()))continue;if(Df($.lastRefreshError,$.refresh,this.now()))continue;try{u("[refresh] fallback oauth background due",{accountId:$.id,expiresInMs:$.expires?$.expires-this.now():void 0}),await this.refreshAccount($,f),_=!0}catch(D){I.warn("refresh","fallback oauth background failed",{accountId:$.id,error:D instanceof Error?D.message:String(D)}),C1($,D,this.now()),Q(f,$),_=!0}}if(_)await this.save(f)}async refreshQuotaForDueAccounts(){let f=await this.load();if(!f||!bf(f))return;let _=!1;for(let $ of f.accounts){if($.enabled===!1||!h($))continue;let D=$;try{if(i(D,f,this.now())){if(Df(D.lastRefreshError,D.refresh,this.now()))continue;D=await this.refreshAccount(D,f),_=!0}if(a(D.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(D,f),!(this.quotaManager?this.quotaManager.isFallbackStale(D.id,D.access):sf(D,f,this.now())))continue;await this.refreshAccountQuota(D,f),_=!0}catch(C){l0($,C,this.now()),Q(f,$),_=!0}}if(_)await this.save(f),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(f={}){let _=await this.load(),$=[];if(!_||!bf(_))return{storage:_,errors:$};let D=f.force??!1,C=!1;for(let N of _.accounts){if(N.enabled===!1||!h(N))continue;let b=N;try{if(i(b,_,this.now())){let E=b.lastRefreshError;if(E&&Df(E,b.refresh,this.now()))throw Error(gf(E,this.now()));b=await this.refreshAccount(b,_),C=!0}if(!D&&!sf(b,_,this.now())){if(b.lastQuotaRefreshError)b.lastQuotaRefreshError=void 0,Q(_,b),C=!0;continue}await this.refreshAccountQuota(b,_),C=!0}catch(E){l0(N,E,this.now()),Q(_,N),C=!0,$.push({accountId:N.id,message:e(E)})}}if(C)await this.save(_);return{storage:_,errors:$}}async refreshAccount(f,_,$={}){let D=this.refreshPromises.get(f.id);if(D){let b=await D;return Q(_,b),b}let C=this.refreshAccountNow(f,_,$).finally(()=>{this.refreshPromises.delete(f.id)});this.refreshPromises.set(f.id,C);let N=await C;return Q(_,N),N}async waitForConcurrentFallbackRefresh(f,_,$,D){let C=Date.now()+L_;while(Date.now()<C){await new Promise((G)=>setTimeout(G,O_));let N=await this.load(),b=N?.accounts.find((G)=>G.id===f.id&&h(G));if(!b)continue;if((b.access!==$.access||b.refresh!==$.refresh||(b.expires??0)>($.expires??0)+60000)&&(D.force||!i(b,N,this.now())))return Q(_,b),u("[refresh] fallback oauth joined concurrent refresh",{accountId:b.id,expiresInMs:b.expires?b.expires-this.now():void 0}),b;let K=b.lastRefreshError;if(K&&Df(K,b.refresh,this.now()))throw Q(_,b),Error(gf(K,this.now()))}return null}async refreshAccountNow(f,_,$){let D=await this.load(),C=D?.accounts.find((E)=>E.id===f.id&&h(E));if(C&&!$.force&&!i(C,D,this.now()))return Q(_,C),C;let N=C??f,b=await Zf({name:_$(N.id),ttlMs:M_,path:this.configPath,now:this.now,renew:!0});if(!b){u("[refresh] fallback oauth refresh skipped file lock",{accountId:N.id});let E=await this.waitForConcurrentFallbackRefresh(f,_,N,$);if(E)return E;throw Error("Fallback OAuth refresh is already in progress")}try{if(D=await this.load(),C=D?.accounts.find((G)=>G.id===f.id&&h(G)),C&&!$.force&&!i(C,D,this.now()))return Q(_,C),C;N=C??N;let E=N.refresh;u("[refresh] fallback oauth refresh request start",{accountId:N.id,force:$.force===!0,expiresInMs:N.expires?N.expires-this.now():void 0});let K=await P0({refreshToken:E,fetchImpl:this.fetchImpl,now:this.now});return N.access=K.access,N.refresh=K.refresh,N.expires=K.expires,N.lastRefreshedAt=K.expires-K.expiresIn*1000,N.lastRefreshError=void 0,Q(_,N),await this.save(_),u("[refresh] fallback oauth refresh succeeded",{accountId:N.id,expiresInMs:N.expires?N.expires-this.now():void 0}),N}finally{await b.release()}}async refreshAccountQuota(f,_){let $=f;if(!$.access)throw Error(`Fallback account ${f.id} has no access token`);let D=(E)=>this.quotaManager?this.quotaManager.refreshFallback($.id,E):Ff({accessToken:E,fetchImpl:this.fetchImpl,now:this.now}),C=this.now();try{$.quota=await D($.access)}catch(E){if(!(E instanceof Error?E.message:String(E)).includes("Claude quota check failed: 401"))throw E;if($=await this.refreshAccount(f,_,{force:!0}),!$.access)throw E;$.quota=await D($.access)}let N=await this.load(),b=N?.accounts.find((E)=>E.id===$.id&&h(E));if(N&&b&&b.access!==$.access)return this.seedFallbackQuota(b,N),Q(_,b),b;if(N&&b?.access===$.access&&b.quota&&Nf(b.quota)>=C&&$1(b.quota,N,this.now()))return this.seedFallbackQuota(b,N),Q(_,b),b;if($.lastQuotaRefreshError=void 0,Q(_,$),this.quotaManager&&$.quota){let E=this.now();this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:E+w(_),checkedAt:E},$.access)}return $}}var pC="claude-cache",N1="## Claude Cache Status",D$="## Claude Cache Enabled",C$="## Claude Cache Disabled",N$="## Claude Cache Usage",b$="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",Vf=!1,mf=Lf;function vC(){return Vf}function dC(){return mf}function iC(f){Vf=f.enabled,mf=f.mode}function E$(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 Kf(f){let _=f?.enabled??Vf,$=f?.mode??mf;return[N1,"",`- Enabled: ${_?"enabled":"disabled"}`,`- Mode: ${$}`,"- 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
7
|
`)}function uC(f){let _=E$(f.argumentsText),$=f.enabled??Vf,D=f.mode??mf;if(_.type==="status")return Kf({enabled:$,mode:D});if(_.type==="enable")return[D$,"",Kf({enabled:!0,mode:D})].join(`
|
|
8
8
|
`);if(_.type==="disable")return[C$,"",Kf({enabled:!1,mode:D})].join(`
|
|
9
9
|
`);if(_.type==="mode")return[N1,"",`Mode updated to \`${_.mode}\`.`,"",Kf({enabled:$,mode:_.mode})].join(`
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as dD,$a as lO,A as G_,Aa as b_,B as ID,Ba as g_,C as V_,Ca as sD,D as CD,Da as m_,E as K_,Ea as z0,F as w_,Fa as i_,G as z_,Ga as aD,H as I_,Ha as MD,I as C_,Ia as p_,J as iD,Ja as eD,K as LD,Ka as s0,L as L_,La as DO,M as U_,Ma as FD,N as x0,Na as HD,O as pD,Oa as l_,P as Q_,Pa as OO,Q as UD,Qa as _O,R as B_,Ra as d_,S as M_,Sa as WO,T as F_,Ta as n_,U as lD,Ua as NO,V as H_,Va as pO,W as QD,Wa as a0,X as r0,Xa as u_,Y as f_,Ya as c_,Z as e0,Za as o_,_ as x_,_a as r_,a as AO,aa as E_,ab as dO,b as SO,ba as T_,bb as nO,c as i0,ca as R_,cb as uO,d as p0,da as A_,db as t_,e as qO,ea as nD,eb as jO,f as v0,fa as S_,fb as s_,g as j_,gb as a_,h as vO,ha as q_,hb as JO,i as kO,ia as uD,j as yO,ja as k0,jb as e_,k as J_,ka as y0,l as KD,la as t0,lb as PO,m as wD,ma as v_,mb as fD,n as $0,na as BD,nb as D1,o as n0,oa as hO,ob as O1,p as zD,pa as bO,pb as $O,q as $_,qa as cD,r as X_,ra as gO,s as V0,sa as mO,t as T,ta as iO,ua as oD,v as u0,va as k_,w as Y_,wa as y_,x as c0,xa as rD,y as o0,ya as h_,z as Z_,za as tD}from"./index-
|
|
1
|
+
import{$ as dD,$a as lO,A as G_,Aa as b_,B as ID,Ba as g_,C as V_,Ca as sD,D as CD,Da as m_,E as K_,Ea as z0,F as w_,Fa as i_,G as z_,Ga as aD,H as I_,Ha as MD,I as C_,Ia as p_,J as iD,Ja as eD,K as LD,Ka as s0,L as L_,La as DO,M as U_,Ma as FD,N as x0,Na as HD,O as pD,Oa as l_,P as Q_,Pa as OO,Q as UD,Qa as _O,R as B_,Ra as d_,S as M_,Sa as WO,T as F_,Ta as n_,U as lD,Ua as NO,V as H_,Va as pO,W as QD,Wa as a0,X as r0,Xa as u_,Y as f_,Ya as c_,Z as e0,Za as o_,_ as x_,_a as r_,a as AO,aa as E_,ab as dO,b as SO,ba as T_,bb as nO,c as i0,ca as R_,cb as uO,d as p0,da as A_,db as t_,e as qO,ea as nD,eb as jO,f as v0,fa as S_,fb as s_,g as j_,gb as a_,h as vO,ha as q_,hb as JO,i as kO,ia as uD,j as yO,ja as k0,jb as e_,k as J_,ka as y0,l as KD,la as t0,lb as PO,m as wD,ma as v_,mb as fD,n as $0,na as BD,nb as D1,o as n0,oa as hO,ob as O1,p as zD,pa as bO,pb as $O,q as $_,qa as cD,r as X_,ra as gO,s as V0,sa as mO,t as T,ta as iO,ua as oD,v as u0,va as k_,w as Y_,wa as y_,x as c0,xa as rD,y as o0,ya as h_,z as Z_,za as tD}from"./index-fwjqfkj2.js";import{Ab as c,Bb as p,rb as P_}from"./index-se4sd5kz.js";import{Db as W1,Hb as N1}from"./index-8meqn6xw.js";import{Pb as LO}from"./index-ha0gz07d.js";import{Sb as _1}from"./index-97vmbv5w.js";import"./index-1gc9eney.js";import{randomUUID as mD}from"node:crypto";function q0(D){return typeof D==="object"&&D!==null}function G1(D){if(Array.isArray(D))return D;if(q0(D)&&Array.isArray(D.data))return D.data;return[]}function V1(D){if(!q0(D)||!q0(D.info))return;return typeof D.info.role==="string"?D.info.role:void 0}function ZO(D){if(!q0(D)||!q0(D.info))return null;let _=D.info,O=q0(_.model)?_.model:void 0,W=typeof _.agent==="string"?_.agent:void 0,j=typeof O?.providerID==="string"?O.providerID:typeof _.providerID==="string"?_.providerID:void 0,$=typeof O?.modelID==="string"?O.modelID:typeof _.modelID==="string"?_.modelID:void 0,z=typeof O?.variant==="string"?O.variant:typeof _.variant==="string"?_.variant:void 0;if(!W&&(!j||!$)&&!z)return null;let A={};if(W)A.agent=W;if(j&&$)A.model={providerID:j,modelID:$};if(z)A.variant=z;return A}function GO(D,_){return{agent:D.agent??_.agent,model:D.model??_.model,variant:D.variant??_.variant}}function VO(D){return Boolean(D.agent&&D.model&&D.variant)}async function KO(D,_){if(!D||!_)return null;let O=D;if(typeof O.session?.messages!=="function")return null;let W=[];try{W=G1(await Promise.resolve(O.session.messages({path:{id:_},query:{limit:100}})))}catch{return null}if(W.length===0)return null;let j={};for(let $=W.length-1;$>=0;$--){if(V1(W[$])!=="assistant")continue;let z=ZO(W[$]);if(!z)continue;if(j=GO(j,z),VO(j))return j}for(let $=W.length-1;$>=0;$--){let z=ZO(W[$]);if(!z)continue;if(j=GO(j,z),VO(j))return j}if(!j.agent&&!j.model&&!j.variant)return null;return j}var B0=[],K1=1,qD=0,wO=new Map;function zO(D,_){if(B0.push({id:K1++,type:"open-dialog",payload:D,sessionId:_}),B0.length>100)B0=B0.slice(B0.length-100)}function IO(D=0,_){let O=Date.now();if(qD=O,_!==void 0)wO.set(_,O);let W=(j)=>_===void 0||j.sessionId===void 0||j.sessionId===_;if(D>0)B0=B0.filter((j)=>{if(j.id>D)return!0;if(_===void 0)return!1;return j.sessionId!==_});return B0.filter((j)=>j.id>D&&W(j))}function CO(D){let _=Date.now();if(D!==void 0){let O=wO.get(D)??0;return O>0&&_-O<3000}return qD>0&&_-qD<3000}import{randomBytes as w1,timingSafeEqual as z1}from"node:crypto";import{unlink as I1}from"node:fs/promises";import{createServer as C1}from"node:http";import{join as L1}from"node:path";function U1(D){return new Promise((_,O)=>{let W=[],j=0;D.on("data",($)=>{if(j+=$.length,j>1e6){D.destroy(),O(Error("body too large"));return}W.push($)}),D.on("end",()=>_(Buffer.concat(W).toString("utf8"))),D.on("error",O)})}function Q1(D,_){if(!D?.startsWith("Bearer "))return!1;let O=Buffer.from(D.slice(7)),W=Buffer.from(_);return O.length===W.length&&z1(O,W)}async function UO(D){let _=w1(32).toString("hex"),O=C1(($,z)=>{W($,z)});async function W($,z){let A=(i,y)=>{z.writeHead(i,{"content-type":"application/json"}),z.end(JSON.stringify(y))};try{let i=$.url??"";if($.method==="GET"&&i==="/health")return A(200,{ok:!0});if($.method!=="POST"||!i.startsWith("/rpc/"))return A(404,{error:"not found"});if(!Q1($.headers.authorization,_))return A(401,{error:"unauthorized"});let y=i.slice(5),L=JSON.parse(await U1($)||"{}");if(y==="pending-notifications"){let h=D.drain(Number(L.lastReceivedId??0),typeof L.sessionId==="string"?L.sessionId:void 0);return A(200,{messages:h})}if(y==="apply"){let h=await D.apply(L);return A(200,h)}return A(404,{error:"unknown method"})}catch(i){if(!z.headersSent&&!z.writableEnded&&!z.destroyed)A(500,{error:i instanceof Error?i.message:String(i)})}}let j=await new Promise(($,z)=>{O.on("error",z),O.listen(0,"127.0.0.1",()=>{let A=O.address();if(A&&typeof A==="object")$(A.port);else z(Error("no port"))})});O.unref();try{await LO(D.dir,{port:j,token:_,pid:process.pid})}catch($){throw await new Promise((z)=>O.close(()=>z())),$}return{port:j,token:_,async stop(){await new Promise(($)=>O.close(()=>$())),await I1(L1(D.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function QO(D,_){let O=new Map,W=0,j=0,$=0,z=0,A=0,i=(h)=>{let o=performance.now(),j0=D(h);return A+=performance.now()-o,$++,j0};return{call:(h)=>{if(!_.enabled())return i(h);let o=O.get(h);if(o!==void 0)return j++,O.delete(h),O.set(h,o),o;let j0=i(h),I0=h.length+j0.length;if(I0>_.maxBytes)return j0;O.set(h,j0),W+=I0;while(W>_.maxBytes&&O.size>1){let r=O.keys().next().value,L0=O.get(r)??"";O.delete(r),W-=r.length+L0.length,z++}return j0},stats:()=>({hits:j,misses:$,evictions:z,entries:O.size,cacheBytes:W,computeMsTotal:A})}}function BO(D){return`${AO}${D.charAt(0).toUpperCase()}${D.slice(1)}`}function cO(D){if(D==="StructuredOutput")return D;return`${D.charAt(0).toLowerCase()}${D.slice(1)}`}var B1=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function MO(D){let _=cO(D);if(_.startsWith("aft_"))return _;if(B1.has(_))return`aft_${_}`;return null}function yD(D,_){let O=new Headers;if(D instanceof Request)D.headers.forEach((j,$)=>{O.set($,j)});let W=_?.headers;if(W){if(W instanceof Headers)W.forEach((j,$)=>{O.set($,j)});else if(Array.isArray(W))for(let j of W){let[$,z]=j;if(typeof z<"u")O.set($,String(z))}else for(let[j,$]of Object.entries(W))if(typeof $<"u")O.set(j,String($))}return O}function YD(D){return D.set("anthropic-beta",i0(D.get("anthropic-beta"),[SO])),D}function l0(D,_,O={}){return mO(D,_,O)}function M1(D){if(D.tools&&Array.isArray(D.tools))D.tools=D.tools.map((_)=>({..._,name:_.name?BO(_.name):_.name}));if(D.messages&&Array.isArray(D.messages))D.messages=D.messages.map((_)=>{if(_.content&&Array.isArray(_.content))_.content=_.content.map((O)=>{if(O.type==="tool_use"&&O.name)return{...O,name:BO(O.name)};return O});return _});return JSON.stringify(iO(D))}function vD(D){return D.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(_,O,W)=>{if(O)return`"name": "${MO(W)??cO(W)}"`;let j=MO(W);return j?`"name": "${j}"`:_})}function FO(D,_=!1){if(_)return{ready:vD(D),pending:""};let O=D.length,W='"name"',j=Math.max(0,D.length-W.length+1);for(let z=j;z<D.length;z++)if(W.startsWith(D.slice(z))){O=Math.min(O,z);break}let $=D.lastIndexOf(W);if($!==-1){let z=D.slice($);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(z))O=Math.min(O,$)}if(O<D.length)return{ready:vD(D.slice(0,O)),pending:D.slice(O)};return{ready:vD(D),pending:""}}function hD(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let D=process.env.ANTHROPIC_INSECURE?.trim();return D==="1"||D==="true"}function oO(D){let _=D?.trim();if(!_)return null;try{let O=new URL(_);if(O.protocol!=="http:"&&O.protocol!=="https:"||O.username||O.password)return null;return O}catch{return null}}function F1(){return oO(process.env.ANTHROPIC_BASE_URL)}function bD(D,_={}){let O=null;try{if(typeof D==="string"||D instanceof URL)O=new URL(D.toString());else if(D instanceof Request)O=new URL(D.url)}catch{O=null}if(!O)return{input:D,url:null};let W=O.href,j=_.baseURL?oO(_.baseURL):F1();if(j){if(O.protocol=j.protocol,O.host=j.host,_.baseURL)O.pathname=`${j.pathname.replace(/\/$/,"")}${O.pathname}`}if(O.pathname.endsWith("/v1/messages")&&!O.searchParams.has("beta"))O.searchParams.set("beta","true");if(O.href===W)return{input:D,url:O};return{input:D instanceof Request?new Request(O.toString(),D):O,url:O}}function H1(D){let W=D.split(/\n\n+/).filter((j)=>{if(j.includes(qO))return!1;for(let $ of kO)if(j.includes($))return!1;return!0}).join(`
|
|
2
2
|
|
|
3
3
|
`);for(let j of yO)W=W.replace(j.match,j.replacement);return W.trim()}var f1=8388608;function x1(){return process.env.OPENCODE_ANTHROPIC_AUTH_MEMO!=="0"}var E1=QO(H1,{maxBytes:f1,enabled:x1});function JD(D){return E1.call(D)}function d(D){return D!=null&&typeof D==="object"&&!Array.isArray(D)}function T1(D){let _={type:"text",text:v0};if(D==null)return[_];if(typeof D==="string"){let W=JD(D);if(W===v0)return[_];return[_,{type:"text",text:W}]}if(d(D)){let W=typeof D.type==="string"?D.type:"text",j=typeof D.text==="string"?D.text:"";return[_,{...D,type:W,text:JD(j)}]}if(!Array.isArray(D))return[_];let O=D.map((W)=>{if(typeof W==="string")return{type:"text",text:JD(W)};if(d(W)&&W.type==="text"&&typeof W.text==="string")return{...W,type:"text",text:JD(W.text)};return{type:"text",text:String(W)}});if(O[0]?.text===v0)return O;return[_,...O]}var rO={type:"ephemeral",ttl:"1h"},R1=20;function A1(D){if(d(D.cache_control))return D.cache_control;if(d(D.cacheControl))return D.cacheControl;return null}function m0(D,_){if(!d(D))return!1;return delete D.cacheControl,D.cache_control=_?{...rO}:{type:"ephemeral"},!0}function HO(D){if(!d(D))return;delete D.cache_control,delete D.cacheControl}function S1(D){if(Array.isArray(D))return D;if(typeof D==="string")return[{type:"text",text:D}];return null}function PD(D,_){if(!d(D))return;let O=A1(D);if(O?.type!=="ephemeral")return;if(_)O.ttl="1h";else delete O.ttl}function fO(D,_){if(Array.isArray(D.system))for(let O of D.system)PD(O,_);else PD(D.system,_);if(!Array.isArray(D.messages))return;for(let O of D.messages)if(PD(O,_),d(O)&&Array.isArray(O.content))for(let W of O.content)PD(W,_)}function q1(D,_){if(Array.isArray(D.system))for(let O of D.system)_(O);else _(D.system);if(!Array.isArray(D.messages))return;for(let O of D.messages)if(_(O),d(O)&&Array.isArray(O.content))for(let W of O.content)_(W)}function tO(D){HO(D),q1(D,HO)}function v1(D){tO(D),D.cache_control={...rO}}function k1(D){return d(D)&&D.type!=="thinking"&&D.type!=="redacted_thinking"}function ZD(D){let _=S1(D.content);if(!_?.length)return;let O=_.filter(k1);if(!O.length)return;return{content:_,cacheableBlocks:O}}function y1(D){if(!d(D))return!1;let _=ZD(D);if(!_)return!1;return D.content=_.content,m0(_.cacheableBlocks[0],!0)}function h1(D){if(!d(D))return!1;let _=ZD(D);if(!_||_.cacheableBlocks.length<2)return!1;return D.content=_.content,m0(_.cacheableBlocks[1],!0)}function $D(D){if(!d(D))return!1;let _=ZD(D);if(!_)return!1;let O=_.cacheableBlocks[_.cacheableBlocks.length-1];return D.content=_.content,m0(O,!0)}function b1(D){if(!d(D))return!1;return(ZD(D)?.cacheableBlocks.length??0)>1}function g1(D){if(!d(D))return 0;let _=D.content;if(Array.isArray(_))return _.length;if(_==null)return 0;return 1}function m1(D){let _=[],O=0;return D.forEach((W,j)=>{let $=g1(W);if(d(W)&&W.role==="user"&&$>0)_.push({index:j,blockPosition:O+$-1});O+=$}),_}function i1(D){let _=m1(D),O=[..._].reverse().find((z)=>z.index>1);if(!O)return{latest:void 0,bridge:void 0};let W=[..._].reverse().find((z)=>z.index<O.index),j=W?O.blockPosition-W.blockPosition+1:0,$=W&&W.index>1&&j>R1?W:void 0;return{latest:O,bridge:$}}function kD(D){return d(D)&&typeof D.text==="string"?D.text:""}function p1(D){if(!Array.isArray(D.system))return;let _=D.system,O=0;if(kD(_[O]).startsWith("x-anthropic-billing-header:"))O++;if(kD(_[O])===v0)O++;let W=O+1;if(W>=_.length-1)return;let j=_[W];if(!d(j))return;let $=_.slice(W).map(kD).join(`
|
|
4
4
|
`);_.splice(W,_.length-W,{...j,type:"text",text:$})}function xO(D){if(Array.isArray(D.system)){let _=D.system.findIndex((j)=>d(j)&&j.text===v0),O=D.system.slice(_>=0?_+1:0).filter(d),W=O[O.length-1];m0(W,!0)}else m0(D.system,!0)}function l1(D){if(tO(D),p1(D),!Array.isArray(D.messages)){xO(D);return}let{latest:_,bridge:O}=i1(D.messages);if(!O)xO(D);if(b1(D.messages[0]))y1(D.messages[0]),h1(D.messages[0]);else $D(D.messages[0]),$D(D.messages[1]);if(O)$D(D.messages[O.index]);if(_)$D(D.messages[_.index])}function d1(D){if(!Array.isArray(D.messages))return 0;let _=0;return D.messages=D.messages.filter((O)=>{if(!d(O)||!Array.isArray(O.content))return!0;if(O.role!=="assistant")return!0;let W=O.content.filter((j)=>{if(!d(j)||j.type!=="thinking")return!0;if(!uO(j.signature))return!0;return _+=1,!1});if(W.length===O.content.length)return!0;return O.content=W,W.length>0}),_}function n1(D){if(!lO(D.model))return null;let _=Object.hasOwn(D,"thinking");return D.thinking={...pO},{replacedExisting:_}}function u1(D){if(!nO(D.model))return null;let _=Object.hasOwn(D,"thinking"),O=D.thinking;if(d(O)&&O.type==="disabled")return D.thinking={type:"disabled"},{replacedExisting:_,display:"disabled"};return D.thinking={...dO},{replacedExisting:_,display:"summarized"}}function c1(D,_){if(!_.enabled){fO(D,!1),delete D.cache_control,delete D.cacheControl;return}if(_.mode==="automatic"){v1(D);return}if(_.mode==="hybrid"){l1(D);return}fO(D,!0),delete D.cacheControl}function o1(D){if(!Array.isArray(D.messages))return;while(D.messages.length){let _=D.messages[D.messages.length-1];if(!d(_)||_.role!=="assistant")break;D.messages.pop()}}function b(){return performance.now()}function Z0(D){return Math.round(D*10)/10}function EO(D){let _=0,O=0,W=0,j=Array.isArray(D.messages)?D.messages:[];_=j.length;for(let $ of j){if(!$||typeof $!=="object")continue;let z=$.content;if(!Array.isArray(z))continue;O+=z.length;for(let A of z)if(A&&typeof A==="object"&&A.type==="tool_use")W++}return{messageCount:_,contentBlockCount:O,toolDefinitionCount:Array.isArray(D.tools)?D.tools.length:0,toolUseCount:W,systemBlockCount:Array.isArray(D.system)?D.system.length:0}}async function gD(D,_={}){try{let O=b(),W=JSON.parse(D);_.perf?.("parse",{ms:Z0(b()-O),inputBytes:D.length,...EO(W)});let j=b(),$=Array.isArray(W.messages)?W.messages.length:void 0;o1(W);let z=Array.isArray(W.messages)?W.messages.length:void 0;_.perf?.("strip_trailing_assistant",{ms:Z0(b()-j),removedMessages:typeof $==="number"&&typeof z==="number"?$-z:void 0});let A=b(),i=d1(W),y=n1(W),L=u1(W);_.perf?.("model_normalize",{ms:Z0(b()-A),model:typeof W.model==="string"?W.model:void 0,fableMythosThinkingDisplay:y?"summarized":void 0,replacedFableMythosThinking:y?.replacedExisting??!1,sonnet5ThinkingDisplay:L?.display,replacedSonnet5Thinking:L?.replacedExisting??!1,removedNonAnthropicThinking:i,hasOutputConfig:Object.hasOwn(W,"output_config")});let h=b(),o=Array.isArray(W.messages)&&W.messages.some((e)=>e.role==="user")?bO(W.messages,void 0,vO):null;_.perf?.("billing_header",{ms:Z0(b()-h),hasBillingHeader:Boolean(o)});let j0=b();if(W.system=T1(W.system),_.perf?.("system_identity",{ms:Z0(b()-j0),systemBlockCount:Array.isArray(W.system)?W.system.length:0}),o&&Array.isArray(W.system))W.system.unshift({type:"text",text:o});let I0=b();if(c1(W,{enabled:_.cache1hEnabled??!1,mode:_.cache1hMode??"explicit"}),_.perf?.("cache_strategy",{ms:Z0(b()-I0),enabled:_.cache1hEnabled??!1,mode:_.cache1hMode??"explicit"}),_.fastModeEnabled&&p0(W.model))W.speed="fast";else if(W.speed==="fast")delete W.speed;let r=b();if(_.identity)gO(W,_.identity);_.perf?.("metadata",{ms:Z0(b()-r),hasAccountUuid:Boolean(_.identity?.accountUuid)});let L0=b(),W0=M1(W);_.perf?.("prefix_tools_stringify",{ms:Z0(b()-L0),outputBytesBeforeSign:W0.length,...EO(W)});let F0=b(),Y0=await hO(W0);return _.perf?.("cch_sign",{ms:Z0(b()-F0),outputBytes:Y0.length}),Y0}catch{return D}}var r1=new TextEncoder;function t1(){return{pending:"",events:0,parseErrors:0,eventCounts:{},typeCounts:{},deltaTypeCounts:{},contentBlockTypeCounts:{},textDeltaBytes:0,thinkingDeltaBytes:0,inputJsonDeltaBytes:0,signatureDeltaBytes:0,redactedThinkingBytes:0}}function XD(D,_){if(!_)return;D[_]=(D[_]??0)+1}function f0(D){return r1.encode(D).byteLength}function M0(D){return D&&typeof D==="object"&&!Array.isArray(D)?D:void 0}function J0(D,_){let O=D?.[_];return typeof O==="string"?O:void 0}function s1(D,_){let O=D?.[_];return typeof O==="number"?O:void 0}function a1(D){if(!D.trim())return null;let _,O=[];for(let h of D.split(/\r?\n/)){if(h.startsWith("event:")){_=h.slice(6).trim();continue}if(h.startsWith("data:")){let o=h.slice(5);O.push(o.startsWith(" ")?o.slice(1):o)}}let W=O.join(`
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Db as a,Eb as b,Fb as c,Gb as d,Hb as e,Ib as f,Jb as g,Kb as h,Lb as i,Mb as j,Nb as k,Ob as l}from"./index-
|
|
1
|
+
import{Db as a,Eb as b,Fb as c,Gb as d,Hb as e,Ib as f,Jb as g,Kb as h,Lb as i,Mb as j,Nb as k,Ob as l}from"./index-8meqn6xw.js";import"./index-1gc9eney.js";export{e as setSidebarState,g as resolveActiveAccount,c as normalizeSidebarState,a as getSidebarStateFile,d as getSidebarState,i as getCollapsedQuotaSummary,h as formatScopedQuotaLabel,f as drainSidebarWrites,l as computeQuotaPacing,k as SEVEN_DAY_MS,j as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-anthropic-auth",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.14.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -58,9 +58,9 @@
|
|
|
58
58
|
"@opencode-ai/plugin": "*"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@cortexkit/anthropic-auth-core": "1.
|
|
61
|
+
"@cortexkit/anthropic-auth-core": "1.14.0",
|
|
62
62
|
"@opentui/core": ">=0.4.2",
|
|
63
|
-
"@opentui/solid": ">=0.4.
|
|
63
|
+
"@opentui/solid": ">=0.4.3",
|
|
64
64
|
"jsonc-parser": "^3.3.1",
|
|
65
65
|
"solid-js": "^1.9.10"
|
|
66
66
|
}
|
package/src/sidebar-state.ts
CHANGED
|
@@ -121,7 +121,11 @@ function normalizeAccountQuota(value: unknown): AccountQuota | null {
|
|
|
121
121
|
}
|
|
122
122
|
})
|
|
123
123
|
.filter((entry): entry is ScopedQuotaWindow => entry != null)
|
|
124
|
-
|
|
124
|
+
// Preserve empty `[]` so a sidebar reader can distinguish "scoped owned
|
|
125
|
+
// by anthropic-auth, none visible" from "no quota data at all". The OUTER
|
|
126
|
+
// Array.isArray guard means pre-feature inputs without a `scoped` key are
|
|
127
|
+
// not affected — only inputs that already carried an array reach this line.
|
|
128
|
+
quota.scoped = scoped
|
|
125
129
|
}
|
|
126
130
|
|
|
127
131
|
return Object.keys(quota).length ? quota : null
|
|
@@ -284,18 +288,23 @@ export function getCollapsedQuotaSummary(quota: AccountQuota | null): {
|
|
|
284
288
|
}
|
|
285
289
|
}
|
|
286
290
|
|
|
291
|
+
const scopedSegments = scoped.map(
|
|
292
|
+
(window) =>
|
|
293
|
+
`${formatScopedQuotaLabel(window.title)}: ${Math.round(window.usedPercent)}%`,
|
|
294
|
+
)
|
|
295
|
+
const primarySegments =
|
|
296
|
+
fiveHourUsedPercent == null && sevenDayUsedPercent == null
|
|
297
|
+
? []
|
|
298
|
+
: [
|
|
299
|
+
`5h: ${fiveHourUsedPercent == null ? '—' : `${Math.round(fiveHourUsedPercent)}%`}`,
|
|
300
|
+
`7d: ${sevenDayUsedPercent == null ? '—' : `${Math.round(sevenDayUsedPercent)}%`}`,
|
|
301
|
+
]
|
|
302
|
+
|
|
287
303
|
return {
|
|
288
304
|
fiveHourUsedPercent,
|
|
289
305
|
sevenDayUsedPercent,
|
|
290
306
|
scopedUsedPercents,
|
|
291
|
-
text: [
|
|
292
|
-
`5h: ${fiveHourUsedPercent == null ? '—' : `${Math.round(fiveHourUsedPercent)}%`}`,
|
|
293
|
-
`7d: ${sevenDayUsedPercent == null ? '—' : `${Math.round(sevenDayUsedPercent)}%`}`,
|
|
294
|
-
...scoped.map(
|
|
295
|
-
(window) =>
|
|
296
|
-
`${formatScopedQuotaLabel(window.title)}: ${Math.round(window.usedPercent)}%`,
|
|
297
|
-
),
|
|
298
|
-
].join(' '),
|
|
307
|
+
text: [...primarySegments, ...scopedSegments].join(' '),
|
|
299
308
|
}
|
|
300
309
|
}
|
|
301
310
|
|
package/dist/index-bk5avdcz.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{mkdir as q,readFile as M,writeFile as b}from"node:fs/promises";import{tmpdir as L}from"node:os";import{dirname as k,join as H}from"node:path";var R="OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE",f=H(L(),"opencode-anthropic-auth"),I=H(f,"sidebar-state.json");function N(){return process.env[R]||I}var K={main:{quota:null},fallbacks:[],activeId:void 0,route:"main",relay:null,fastMode:!1,lastUpdated:0};function V(J){return J!==null&&typeof J==="object"&&!Array.isArray(J)}function g(J){if(!V(J))return;let X=Number(J.usedPercent),Y=Number(J.remainingPercent);if(!Number.isFinite(X)||!Number.isFinite(Y))return;return{usedPercent:X,remainingPercent:Y,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0}}function Q(J){if(!V(J))return null;let X={},Y=g(J.five_hour),Z=g(J.seven_day);if(Y)X.five_hour=Y;if(Z)X.seven_day=Z;if(Array.isArray(J.scoped)){let $=J.scoped.map((x)=>{if(!V(x))return;let j=g(x);if(!j)return;if(typeof x.id!=="string"||!x.id.trim())return;if(typeof x.title!=="string"||!x.title.trim())return;if(typeof x.modelName!=="string"||!x.modelName.trim())return;let G=typeof x.modelId==="string"&&x.modelId.trim()?x.modelId.trim():void 0;return{...j,id:x.id.trim(),title:x.title.trim(),...G&&{modelId:G},modelName:x.modelName.trim()}}).filter((x)=>x!=null);if($.length)X.scoped=$}return Object.keys(X).length?X:null}function F(J){if(!V(J))return{...K};let X={quota:null};if(V(J.main)){let x=J.main;if(X.quota=Q(x.quota),typeof x.quotaBackedOff==="boolean")X.quotaBackedOff=x.quotaBackedOff;if(typeof x.quotaBackoffUntil==="number")X.quotaBackoffUntil=x.quotaBackoffUntil;if(typeof x.refreshBackedOff==="boolean")X.refreshBackedOff=x.refreshBackedOff;if(typeof x.refreshBackoffUntil==="number")X.refreshBackoffUntil=x.refreshBackoffUntil}let Y=Array.isArray(J.fallbacks)?J.fallbacks.filter(V).filter((x)=>typeof x.id==="string").map((x)=>({id:x.id,label:typeof x.label==="string"?x.label:void 0,quota:Q(x.quota),enabled:typeof x.enabled==="boolean"?x.enabled:!1,needsReauth:typeof x.needsReauth==="boolean"?x.needsReauth:!1})):[],Z=null;if(V(J.relay)){let x=J.relay;if(typeof x.enabled==="boolean"&&typeof x.transport==="string")Z={enabled:x.enabled,transport:x.transport}}let $;if(V(J.cacheKeep)){let x=J.cacheKeep;if(typeof x.enabled==="boolean")$={enabled:x.enabled,window:typeof x.window==="string"?x.window:void 0,trackedSessions:typeof x.trackedSessions==="number"?x.trackedSessions:void 0}}return{main:X,fallbacks:Y,activeId:typeof J.activeId==="string"?J.activeId:void 0,route:typeof J.route==="string"?J.route:K.route,relay:Z,fastMode:typeof J.fastMode==="boolean"?J.fastMode:K.fastMode,cacheKeep:$,lastUpdated:typeof J.lastUpdated==="number"?J.lastUpdated:0}}var W=Promise.resolve();async function P(){try{let J=await M(N(),"utf8");return F(JSON.parse(J))}catch{return K}}async function A(J,X=N()){return W=W.then(async()=>{await q(k(X),{recursive:!0}),await b(X,JSON.stringify(J),"utf8")}).catch(()=>{}),W}async function m(){return W}function v(J){let X=J.activeId;if(X&&X!=="main"){let Y=J.fallbacks?.find((Z)=>Z.enabled&&Z.id===X);if(Y)return{id:Y.id,name:Y.label??Y.id,quota:Y.quota}}return{id:"main",name:"main",quota:J.main?.quota??null}}function U(J){let X=J.replace(/\s+only$/i,"").trim();return/^fable$/i.test(X)?"Fa":X}function y(J){let X=J?.five_hour?.usedPercent??null,Y=J?.seven_day?.usedPercent??null,Z=J?.scoped??[],$=Z.map((x)=>x.usedPercent);if(X==null&&Y==null&&Z.length===0)return{fiveHourUsedPercent:X,sevenDayUsedPercent:Y,scopedUsedPercents:$,text:null};return{fiveHourUsedPercent:X,sevenDayUsedPercent:Y,scopedUsedPercents:$,text:[`5h: ${X==null?"—":`${Math.round(X)}%`}`,`7d: ${Y==null?"—":`${Math.round(Y)}%`}`,...Z.map((x)=>`${U(x.title)}: ${Math.round(x.usedPercent)}%`)].join(" ")}}var u=18000000,c=604800000,D=300000,S=0.01,p=1;function l(J,X,Y){if(!J.resetsAt)return null;let Z=new Date(J.resetsAt).getTime();if(!Number.isFinite(Z))return null;let $=Z-X,x=Y-$;if(x<D)return null;if(x<X*S)return null;if(x>=X)return null;let j=J.usedPercent,G=Math.min(Math.max(x/X*100,0),100),B=j-G,h=Math.abs(B)<p?"on-pace":B>0?"deficit":"reserve",z=null;if(j>0){let C=x*100/j,O=$+C;if(O<Z)z=new Date(O).toISOString()}return{pacePercent:G,deltaPercent:B,state:h,runsOutAt:z}}
|
|
2
|
-
export{N as Db,K as Eb,F as Fb,P as Gb,A as Hb,m as Ib,v as Jb,U as Kb,y as Lb,u as Mb,c as Nb,l as Ob};
|