@cortexkit/opencode-anthropic-auth 1.12.2 → 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/README.md +8 -5
- package/dist/cli.js +5 -5
- package/dist/{index-ptdkq8gx.js → index-1gc9eney.js} +1 -1
- package/dist/index-8meqn6xw.js +2 -0
- package/dist/{index-9rxvhx0b.js → index-97vmbv5w.js} +1 -1
- package/dist/index-fwjqfkj2.js +417 -0
- package/dist/{index-ggyzz0xr.js → index-ha0gz07d.js} +1 -1
- package/dist/{index-z86v5q5a.js → index-se4sd5kz.js} +1 -1
- package/dist/index.d.ts +37 -0
- package/dist/index.js +11 -11
- package/dist/{logger-59cepv7b.js → logger-sg9wxpvj.js} +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.d.ts +9 -0
- package/dist/sidebar-state.js +1 -1
- package/dist/tui/command-dialogs.d.ts +6 -0
- package/dist/tui-preferences.js +1 -1
- package/package.json +3 -3
- package/src/sidebar-state.ts +101 -5
- package/src/tui/command-dialogs.tsx +29 -19
- package/src/tui.tsx +26 -1
- package/dist/index-67j80sm1.js +0 -417
- package/dist/index-erkja50x.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{mkdir as l,readdir as u,readFile as c,rename as p,unlink as m,writeFile as d}from"node:fs/promises";import{join as a}from"node:path";function f(t){try{return process.kill(t,0),!0}catch(r){return r.code==="EPERM"}}async function b(t,r){await l(t,{recursive:!0});let s={...r,startedAt:Date.now()},e=a(t,`port-${r.pid}.json`),i=`${e}.${process.pid}.tmp`;return await d(i,JSON.stringify(s),{encoding:"utf8",mode:384}),await p(i,e),e}async function h(t,r){let s;try{s=await u(t)}catch{return null}let e=[];for(let n of s){if(!n.startsWith("port-")||!n.endsWith(".json"))continue;try{let o=JSON.parse(await c(a(t,n),"utf8"));if(Number.isFinite(o.port))if(f(o.pid))e.push(o);else m(a(t,n)).catch(()=>{})}catch{}}if(e.length===0)return null;let i=r&&r>=1?e.filter((n)=>n.pid===r):[];return(i.length>0?i:e).sort((n,o)=>o.startedAt-n.startedAt)[0]??null}
|
|
2
|
-
export{b as
|
|
2
|
+
export{b as Pb,h as Qb};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import*as j from"node:fs";import*as P from"node:os";import*as V from"node:path";var U={error:0,warn:1,info:2,debug:3,trace:4},O=new Set(Object.keys(U));function F(q){if(!q)return null;let Q=q.trim().toLowerCase();return O.has(Q)?Q:null}var S=F(process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL),M=S??"info";function L(q){M=q}function i(){return M}function X(q){return U[q]<=U[M]}var J=process.env.OPENCODE_ANTHROPIC_AUTH_LOG_FILE??V.join(P.tmpdir(),"opencode-anthropic-auth.log");function h(){return J}var R=5242880,N=3;function I(){try{if(!j.existsSync(J))return;if(j.statSync(J).size<R)return}catch{return}try{for(let q=N;q>=1;q--){let Q=q===1?J:`${J}.${q-1}`,W=`${J}.${q}`;try{if(q===N)try{j.unlinkSync(W)}catch{}if(j.existsSync(Q))j.renameSync(Q,W)}catch{}}}catch{}}var T=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function k(q){if(T.test(q))return!0;let Q=q.toLowerCase().replace(/[-_]/g,"");if(Q.includes("apikey"))return!0;if(Q.endsWith("secret")||Q.endsWith("password"))return!0;if(Q.endsWith("token")&&!Q.endsWith("tokens"))return!0;return!1}var f=[/Bearer\s+\S+/,/sk-[A-Za-z0-9-]+/,/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/];function _(q){if(typeof q!=="string")return!1;return f.some((Q)=>Q.test(q))}function G(q){if(q==null||Object.keys(q).length===0)return;let Q=new WeakSet;function W($){if($==null||typeof $!=="object"){if(_($))return"***REDACTED***";return $}if(Q.has($))return"[Circular]";Q.add($);try{if(Array.isArray($))return $.map(W);let x=$,B={};for(let[H,C]of Object.entries(x)){if(k(H)){B[H]="***REDACTED***";continue}B[H]=W(C)}return B}finally{Q.delete($)}}return W(q)}function g(q,Q,W,$){let x=new Date().toISOString(),B=q.toUpperCase().padEnd(5),H=Q?` [${Q}]`:"",C=(()=>{try{let w=G($),A=w?{...w,pid:process.pid}:{pid:process.pid};return` ${JSON.stringify(A)}`}catch{return` {"pid":${process.pid},"payload":"[unserializable]"}`}})();return`[${x}] ${B}${H} ${W}${C}`}var D=null;function E(q){D=q}function Y(q,Q,W,$){if(!X(q))return;if(D)try{D({level:q,channel:Q,message:W,payload:G($)})}catch{}if(Z)return;try{let x=`${g(q,Q,W,$)}
|
|
2
2
|
`;if(K.push(x),K.length>=p)b();else r()}catch{}}var m={error(q,Q,W){Y("error",q,Q,W)},warn(q,Q,W){Y("warn",q,Q,W)},info(q,Q,W){Y("info",q,Q,W)},debug(q,Q,W){Y("debug",q,Q,W)},trace(q,Q,W){Y("trace",q,Q,W)}},Z=!1,c=500,p=50,K=[],z=null;function b(){if(z)clearTimeout(z),z=null;if(K.length===0)return;let q=K.join("");K=[];try{I(),j.appendFileSync(J,q)}catch{}}function r(){if(z)return;z=setTimeout(()=>{z=null,b()},c)}var y=/^\[([\w-]+)\]\s*/;function o(q,Q){if(!X("debug"))return;if(Z)return;try{let W="",$=q,x=q.match(y);if(x)W=x[1]??"",$=q.slice(x[0].length);let B;if(Q!=null){if(Q instanceof Error)B={error:`${Q.message}${Q.stack?`
|
|
3
3
|
${Q.stack}`:""}`};else if(typeof Q==="object")B=Q}Y("debug",W,$,B)}catch{}}function v(q,Q){if(!X("debug"))return;if(Z)return;try{let W;if(Q!=null){if(typeof Q==="object"&&!(Q instanceof Error))W=Q}Y("debug","relay",q,W)}catch{}}if(!Z)process.on("exit",b);
|
|
4
|
-
export{F as
|
|
4
|
+
export{F as qb,L as rb,i as sb,X as tb,h as ub,T as vb,k as wb,G as xb,g as yb,E as zb,m as Ab,o as Bb,v as Cb};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,39 @@
|
|
|
1
|
+
import { type AccountStorage, type OAuthQuotaSnapshot } from '@cortexkit/anthropic-auth-core';
|
|
1
2
|
import type { Plugin } from '@opencode-ai/plugin';
|
|
3
|
+
/**
|
|
4
|
+
* Format the user-facing 429 message for a killswitch block. When the block
|
|
5
|
+
* is scoped-driven (the request's model matches a scoped window that is at
|
|
6
|
+
* or below the killswitch threshold), the message names the model so the
|
|
7
|
+
* operator can distinguish a per-model weekly block from a whole-account
|
|
8
|
+
* kill. Otherwise the generic account-level message is used.
|
|
9
|
+
*/
|
|
10
|
+
export declare function formatKillswitchBlockMessage(input: {
|
|
11
|
+
retryAfterSeconds: number;
|
|
12
|
+
modelName?: string;
|
|
13
|
+
}): string;
|
|
14
|
+
/**
|
|
15
|
+
* Decide whether a killswitch block is scoped-driven (a per-model weekly
|
|
16
|
+
* block) versus a whole-account 5h/7d-driven block. A block is scoped-driven
|
|
17
|
+
* only when the request's model matches a scoped window AND that window is
|
|
18
|
+
* actually at or below the per-account scoped threshold. A Fable request
|
|
19
|
+
* with a healthy Fable window is therefore correctly classified as
|
|
20
|
+
* account-level (the 5h/7d breach killed the account, not the Fable quota).
|
|
21
|
+
*
|
|
22
|
+
* Priority: account-level 5h/7d always wins. `killswitchPassesPolicy` called
|
|
23
|
+
* WITHOUT a modelId evaluates only 5h/7d; if it returns false, 5h/7d drove
|
|
24
|
+
* the block, so this is account-level regardless of the scoped window's
|
|
25
|
+
* state. Only when 5h/7d pass AND the matched scoped window is at/below the
|
|
26
|
+
* scoped threshold do we call it scoped-driven.
|
|
27
|
+
*/
|
|
28
|
+
export declare function resolveScopedDrivenBlock(input: {
|
|
29
|
+
mainQuota: OAuthQuotaSnapshot | undefined;
|
|
30
|
+
requestModelId: string | undefined;
|
|
31
|
+
storage: AccountStorage | null;
|
|
32
|
+
}): {
|
|
33
|
+
isScopedDriven: true;
|
|
34
|
+
modelName: string;
|
|
35
|
+
modelId: string;
|
|
36
|
+
} | {
|
|
37
|
+
isScopedDriven: false;
|
|
38
|
+
};
|
|
2
39
|
export declare const AnthropicAuthPlugin: Plugin;
|
package/dist/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import{$ as
|
|
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
|
-
`);for(let j of
|
|
4
|
-
`);_.splice(W,_.length-W,{...j,type:"text",text
|
|
5
|
-
`),j={event:_,rawBytes:
|
|
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
|
+
`);_.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(`
|
|
5
|
+
`),j={event:_,rawBytes:f0(D),dataBytes:f0(W)};if(!W||W==="[DONE]")return j.type=W==="[DONE]"?"done":void 0,j.event??=j.type,j;let $;try{$=JSON.parse(W)}catch{return j}let z=M0($),A=M0(z?.delta),i=M0(z?.content_block),y=M0(z?.message),L=M0(z?.usage)??M0(y?.usage);if(j.type=J0(z,"type"),j.event??=j.type,j.index=s1(z,"index"),j.contentBlockType=J0(i,"type"),j.deltaType=J0(A,"type"),j.stopReason=J0(z,"stop_reason"),j.deltaType==="text_delta")j.textDeltaBytes=f0(J0(A,"text")??"");if(j.deltaType==="thinking_delta")j.thinkingDeltaBytes=f0(J0(A,"thinking")??"");if(j.deltaType==="input_json_delta")j.inputJsonDeltaBytes=f0(J0(A,"partial_json")??"");if(j.deltaType==="signature_delta")j.signatureDeltaBytes=f0(J0(A,"signature")??"");if(j.contentBlockType==="redacted_thinking")j.redactedThinkingBytes=f0(J0(i,"data")??"");if(L)j.stopReason??=J0(y,"stop_reason");return j}function sO(D){let _=D.indexOf(`
|
|
6
6
|
|
|
7
7
|
`),O=D.indexOf(`\r
|
|
8
8
|
\r
|
|
9
|
-
`);if(_===-1)return O===-1?null:{index:O,length:4};if(O===-1||_<O)return{index:_,length:2};return{index:O,length:4}}function
|
|
10
|
-
`);if(!W||W==="[DONE]")return null;let j;try{j=JSON.parse(W)}catch{return null}let J=Q0(j);if(_!=="error"&&j0(J,"type")!=="error")return null;let V=Q0(J?.error),q=j0(V,"type")??j0(V,"code")??void 0,m=j0(V,"message")??j0(J,"message")??q??"Anthropic stream error";if(!o1(q,m))return null;return r1(q,m)}function fO(D,_){if(!_)return null;D.pending+=_;while(!0){let O=cO(D.pending);if(!O)break;let W=D.pending.slice(0,O.index);D.pending=D.pending.slice(O.index+O.length);let j=t1(W);if(j)return j}return null}function s1(D){return{sseEvents:D.events,ssePendingChars:D.pending.length,sseParseErrors:D.parseErrors,sseEventCounts:{...D.eventCounts},sseTypeCounts:{...D.typeCounts},sseDeltaTypeCounts:{...D.deltaTypeCounts},sseContentBlockTypeCounts:{...D.contentBlockTypeCounts},sseTextDeltaBytes:D.textDeltaBytes,sseThinkingDeltaBytes:D.thinkingDeltaBytes,sseInputJsonDeltaBytes:D.inputJsonDeltaBytes,sseSignatureDeltaBytes:D.signatureDeltaBytes,sseRedactedThinkingBytes:D.redactedThinkingBytes,sseLastEvent:D.last?{...D.last}:void 0}}function l0(D,_={}){if(!D.body)return D;let O=D.body.getReader(),W=new TextDecoder,j=new TextEncoder,J="",V=0,q=0,m=0,k=0,L=0,y=!1,u=!1,N0=h(),z0=h(),c=_.perf?d1():void 0,C0=c1(),O0=()=>{if(u)return;u=!0,O.releaseLock()},U0=(_0={})=>({chunks:V,pulls:q,inputBytes:m,outputBytes:k,pendingChars:J.length,rewriteMs:Y0(L),totalMs:Y0(h()-z0),...c?s1(c):{},..._0}),$0=(_0,I0={})=>{_.perf?.(_0,U0(I0))};_.perf?.("stream_tool_prefix_wrapper_created",{status:D.status,hasBody:!0});let a=new ReadableStream({async pull(_0){if(q++,!y)y=!0,$0("stream_tool_prefix_first_pull");let I0=h();try{let{done:Z0,value:x0}=await O.read(),y0=Y0(h()-I0);if(Z0){let L0=W.decode();if(c)HO(c,L0);let T0=fO(C0,L0);if(T0)throw $0("stream_tool_prefix_retryable_error",{error:T0.message,providerErrorType:T0.providerErrorType}),O0(),T0;let ED=h(),OD=MO(`${J}${L0}`,!0);if(L+=h()-ED,OD.ready){let b0=j.encode(OD.ready);k+=b0.byteLength,_0.enqueue(b0)}$0("stream_tool_prefix_rewrite",{readMs:y0}),O0(),_0.close();return}V++,m+=x0.byteLength;let E0=W.decode(x0,{stream:!0});if(c)HO(c,E0);let R0=fO(C0,E0);if(R0)throw $0("stream_tool_prefix_retryable_error",{error:R0.message,providerErrorType:R0.providerErrorType,readMs:y0,lastChunkBytes:x0.byteLength}),O0(),R0;let e0=J+E0,xD=h(),h0=MO(e0);if(L+=h()-xD,J=h0.pending,h0.ready){let L0=j.encode(h0.ready);k+=L0.byteLength,_0.enqueue(L0)}let DD=h();if(V===1||V%25===0||DD-N0>5000)N0=DD,$0("stream_tool_prefix_progress",{readMs:y0,lastChunkBytes:x0.byteLength})}catch(Z0){throw $0("stream_tool_prefix_error",{error:Z0 instanceof Error?Z0.message:String(Z0)}),O0(),Z0}},async cancel(_0){$0("stream_tool_prefix_cancel",{reason:_0 instanceof Error?_0.message:String(_0)});try{await O.cancel(_0)}finally{O0()}}});return new Response(a,{status:D.status,statusText:D.statusText,headers:D.headers})}var a1="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",oO="~effect/http/HttpServerResponse",rO="~effect/http/Cookies",tO="~effect/http/HttpBody",e1="~effect/ErrorReporter/ignore",DW=60000,OW=60000,_W=5000,sO=200,a_=240,WW=a_,NW=1,aO=!1;function fD(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function f(){return performance.now()}function g(D){return Math.round(D*10)/10}function eO(D){return Math.floor(Math.random()*Math.max(0,D))}function ZD(D){if(typeof D==="string")return D;if(D instanceof URL)return D.toString();return D.url}function GD(D,_){return _?.method??(D instanceof Request?D.method:void 0)}function D_(D){return D instanceof Error?D.message:String(D)}function jW(){if(aO||!1||!fD())return;aO=!0;let D=100,_=250,O=f()+D;setInterval(()=>{let W=f(),j=W-O;if(O=W+D,j<_)return;i("[perf] opencode event_loop_lag",{lagMs:g(j),thresholdMs:_})},D).unref?.()}function PW(D){let _=f(),O={requestId:String(NW++),start:_,last:_,mark(W,j){let J=f();if(fD())i("[perf] opencode request stage",{requestId:O.requestId,stage:W,deltaMs:g(J-O.last),totalMs:g(J-O.start),...j});O.last=J},done(W,j){let J=f();if(fD())i("[perf] opencode request done",{requestId:O.requestId,stage:W,deltaMs:g(J-O.last),totalMs:g(J-O.start),...j});O.last=J}};if(fD())i("[perf] opencode request start",{requestId:O.requestId,...D});return O}async function JW(D,_,O){let W=D.client.session,j=await YO(D.client,_),J={path:{id:_},body:{noReply:!0,parts:[{type:"text",text:O,ignored:!0}]}};if(j?.agent)J.body.agent=j.agent;if(j?.model)J.body.model=j.model;if(j?.variant)J.body.variant=j.variant;if(typeof W?.promptAsync==="function"){await W.promptAsync(J);return}if(typeof W?.prompt==="function"){await Promise.resolve(W.prompt(J));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function $W(){let D=Error(a1);throw D[oO]=oO,D[e1]=!0,D.status=204,D.statusText=void 0,D.headers={},D.cookies={[rO]:rO,cookies:{}},D.body={[tO]:tO,_tag:"Empty"},D}function XW(D){if(D.sessionID==null)return!1;let _=D.model;return _?.providerID==="anthropic"||_?.api?.npm==="@ai-sdk/anthropic"||_?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function YW(D){if(D.some((_)=>_.includes("<use_parallel_tool_calls>")))return!1;return D.push(O_),!0}var ZW={input:0,output:0,cache:{read:0,write:0}};function GW(D){let _=D["claude-opus-4-8"]??D["claude-opus-4-5"]??Object.values(D)[0];if(!_)return D;return{...D,...Object.fromEntries(Object.values(p_).map((O)=>[O.id,{..._,id:O.id,name:O.name,api:_.api?{..._.api,id:O.id}:void 0,cost:{input:a0.input,output:a0.output,cache:{read:a0.cacheRead,write:a0.cacheWrite5m}},limit:{..._.limit??{},context:g_,output:m_},capabilities:{..._.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:i_}]))}}function IW(D){return Object.fromEntries(Object.entries(D).map(([_,O])=>[_,{...O,cost:ZW}]))}var kW=async(D)=>{jW();let{client:_}=D,O=j_(),W=600000,j=50,J=new Map;function V(){let N=Date.now();for(let[P,X]of J)if(N-X.createdAt>W)J.delete(P)}function q(N,P){if(V(),J.size>=j){let X="",w=1/0;for(let[$,v]of J)if(v.createdAt<w)w=v.createdAt,X=$;if(X)J.delete(X)}J.set(N,P)}function m(N){V();let P=J.get(N);if(!P)return;if(Date.now()-P.createdAt>W){J.delete(N);return}return P}let k;try{k=await T(O)}catch(N){let P=N instanceof Error?N.message:String(N);throw Error(`Failed to load account store: ${P}`,{cause:N instanceof Error?N:void 0})}let L=new l_({storage:k,onMainQuotaFetched:async(N,P,X,w)=>{try{let $=await T(O)??G0(),v=L_($);if(v&&v.checkedAt>=w&&H_(v.quota,$,v.checkedAt)>Date.now()){L.seedMainFromStorage($);return}$.quota=$.quota??{},$.quota.mainQuota=N,$.quota.mainQuotaCheckedAt=P,$.quota.mainQuotaToken=X,$.quota.mainLastQuotaApiError=void 0,await n0($,O,{mainQuota:!0})}catch($){n.warn("quota","failed to persist main quota",{error:$ instanceof Error?$.message:String($)})}},onApiError:async(N)=>{try{let P=await T(O)??G0();P.quota=P.quota??{},P.quota.mainLastQuotaApiError=N,await n0(P,O,{mainQuota:!0})}catch(P){n.warn("quota","failed to persist backoff state",{error:P instanceof Error?P.message:String(P)})}}}),y=new f_({quotaManager:L,onFallbackStorageChanged:()=>{U0().catch(()=>{})}});y.startBackgroundRefresh();let u=null,N0=new A_({loadStorage:()=>T(O),prepareHeaders:async(N,P)=>{if(!a)return N;let X=await a();if(X.type!=="oauth")return N;if(!X.access||X.expires&&X.expires<Date.now()){if(!u)return N;X.access=await u()}if(!X.access)return N;try{let w=JSON.parse(P.bodyText),$=await lD(X.access,typeof w.model==="string"?w.model:void 0);if(N.delete("anthropic-beta"),p0(N,X.access,{body:w,identity:$}),N.set("anthropic-beta",m0(N.get("anthropic-beta"),[E_])),w.speed==="fast")XD(N)}catch{p0(N,X.access)}return N}});if(t0({enabled:u0(k),mode:c0(k)}),UD(zD(k)),FD(wD(k)),!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)W_(LD(k)??"info");let z0=null;if(D.directory){let N=globalThis;if(N.__anthropicAuthRpcServer)await N.__anthropicAuthRpcServer.stop().catch(()=>{}),N.__anthropicAuthRpcServer=void 0;try{z0=await zO({dir:r_(D.directory),drain:IO,apply:e_}),N.__anthropicAuthRpcServer=z0}catch(P){n.warn("rpc","failed to start",{error:P instanceof Error?P.message:String(P)})}}let c={activeId:"main",route:"main"},C0=t_();function O0(N,P){c={activeId:P.activeId,route:P.route},L.updateStorage(N),L.seedMainFromStorage(N,P.mainAccessToken),L.seedFallbacksFromAccounts((N?.accounts??[]).filter(J0));let X=L.getMain(P.mainAccessToken),w=L.getLastApiError(),$=N?.refresh?.mainLastRefreshError,v={main:{quota:X?.quota??null,quotaBackedOff:L.isBackedOff(),quotaBackoffUntil:w?.nextRetryAt,refreshBackedOff:$?f0($,P.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:$?.nextRetryAt},fallbacks:(N?.accounts??[]).filter((x)=>x.enabled!==!1&&J0(x)).map((x)=>({id:x.id,label:x.label,quota:x.access?L.getFallback(x.id,x.access)?.quota??null:null,needsReauth:x.lastRefreshError!=null&&f0(x.lastRefreshError,x.refresh,Date.now())&&z_(x.lastRefreshError),enabled:x.enabled!==!1})),activeId:P.activeId,route:P.route,relay:(()=>{let x=_O(N);return x?{enabled:!0,transport:x.transport??"http"}:null})(),fastMode:BD(),cacheKeep:{enabled:uD(N),window:N?.cacheKeep?.startHour!=null&&N?.cacheKeep?.endHour!=null?`${N.cacheKeep.startHour}-${N.cacheKeep.endHour}`:void 0,trackedSessions:N0.trackedCount()},lastUpdated:Date.now()};return s_(v,C0).catch((x)=>n.warn("sidebar","state write failed",{error:x instanceof Error?x.message:String(x)}))}async function U0(){let N=await T(O),P,X;if(a)try{let w=await a();P=w.access,X=w.refresh}catch{}O0(N,{activeId:c.activeId,route:c.route,mainAccessToken:P,mainRefreshToken:X})}function $0(N,P){if(!P)return;if(N?.quota?.enabled!==!0)return;if(L.getMain(P))return;if(_0)return;_0=!0,L.refreshMain(P).then(()=>U0()).catch(()=>{}).finally(()=>{_0=!1})}let a=null,_0=!1,I0=null,Z0=0;function x0(N){let P=N?.refresh?.refreshBeforeExpiryMinutes??WW;return Math.max(a_,P)*60000}function y0(N){return N?.refresh?.enabled!==!1}async function E0(N){if(!N)return;let P=await T(O),X=P?.refresh?.mainLastRefreshError;if(!P?.refresh||!X?.tokenHash)return;let w=CD(N);if(X.tokenHash===w)return;if(X.nextRetryAt&&X.nextRetryAt>Date.now()){i("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:X.nextRetryAt,retryCount:X.retryCount,remainingMs:X.nextRetryAt-Date.now()});return}P.refresh.mainLastRefreshError=void 0,await n0(P,O,{mainRefresh:!0}),i("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:X.checkedAt,previousNextRetryAt:X.nextRetryAt,previousRetryCount:X.retryCount})}async function R0(){let N=[];if(a)try{let $=await a();if($.type==="oauth"&&$.access){let v=await L.refreshMain($.access);N.push({name:"OpenCode anthropic",role:"main",quota:v})}else if($.type==="oauth")N.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch($){let v=$ instanceof Error?$.message:String($);N.push({name:"OpenCode anthropic",role:"main",error:v.includes("429")?"Usage API rate limited — try again in a moment":v})}let{storage:P,errors:X}=await y.refreshQuotaForAllAccounts({force:!0}),w=new Map(X.map(($)=>[$.accountId,$.message]));if(N.push(...d_(P,w)),!a)N.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return n_({accounts:N,refreshedAt:Date.now()})}async function e0(N){if(a)try{let P=await a();O0(N,{activeId:c.activeId,route:c.route,mainAccessToken:P.access,mainRefreshToken:P.refresh})}catch{}}async function xD(N){let P=x_(N);if(P.type==="enable"||P.type==="disable"){let v=P.type==="enable",x=await J_(v),U=c0(x);return t0({enabled:v,mode:U}),n.info("commands","cache enabled changed",{enabled:v}),QD({argumentsText:N,enabled:v,mode:U})}if(P.type==="mode"){let v=await $_(P.mode),x=u0(v);return t0({enabled:x,mode:P.mode}),n.info("commands","cache mode changed",{mode:P.mode}),QD({argumentsText:N,enabled:x,mode:P.mode})}let X=await T(O),w=u0(X),$=c0(X);return t0({enabled:w,mode:$}),QD({argumentsText:N,enabled:w,mode:$})}async function h0(N){let P=R_(N),X=await T(O);if(P.type==="window")X=await Z_(P.startHour,P.endHour),n.info("commands","cachekeep enabled changed",{enabled:!0});else if(P.type==="disable")X=await G_(!1),n.info("commands","cachekeep enabled changed",{enabled:!1});else if(P.type==="subagents")X=await V_(P.enabled),n.info("commands","cachekeep subagents changed",{subagents:P.enabled});let w=nD(X),$=N0.stats(w);return q_({argumentsText:N,enabled:T_(X),window:w,hybridActive:uD(X),trackedSessions:$.trackedSessions,nextPrewarmAt:$.nextPrewarmAt})}async function DD(N){let P=k_(N);if(P.type==="enable"||P.type==="disable"){let $=P.type==="enable";return await X_($),UD($),n.info("commands","dump changed",{enabled:$}),rD({argumentsText:N,enabled:$})}let X=await T(O),w=zD(X);return UD(w),rD({argumentsText:N,enabled:w})}async function L0(N){let P=y_(N);if(P.type==="enable"||P.type==="disable"){let $=P.type==="enable";return await Y_($),FD($),n.info("commands","fast mode changed",{enabled:$}),sD({argumentsText:N,enabled:$})}let X=await T(O),w=wD(X);return FD(w),sD({argumentsText:N,enabled:w})}async function T0(N){let P=o_(N);if(P.type==="mode")return await c_(P.mode),n.info("commands","routing mode changed",{mode:P.mode}),NO({argumentsText:N,mode:P.mode});let X=await T();return NO({argumentsText:N,mode:HD(X)})}async function ED(N){let P=b_(N);if(P.type==="level")return await C_(P.level),n.info("commands","log level changed",{level:P.level}),DO({argumentsText:N,level:P.level});let X=await T(O),w=LD(X)??"info";return DO({argumentsText:N,level:w})}async function OD(N,P){let X=S_(N);if(X.type==="add-apikey"){if(!X.apiKey)return{text:"API key is required",accounts:K0(await T(O)??G0())};let U=X.label?.trim()||void 0,B=Date.now(),b=X.baseURL?.trim()||"https://api.kie.ai/claude";if(!KD(b))return{text:"Invalid base URL. Must be an http(s) URL without embedded credentials.",accounts:K0(await T(O)??G0())};let o=X.authHeader??"authorization-bearer",r={id:U||hD(),label:U||void 0,type:"api",apiKey:X.apiKey,baseURL:b,authHeader:o,enabled:!0,addedAt:B,lastUsed:B};await iD(r,O),n.info("commands","account added",{id:r.id,label:r.label,type:"apikey"});let X0=await T(O);await e0(X0);let B0=K0(X0??{version:1,accounts:[]});return{text:`API key account "${r.label??r.id}" added.`,accounts:B0}}if(X.type==="add-oauth-start"){let U=await ID("max"),B={state:U.state,verifier:U.verifier,redirectUri:U.redirectUri,createdAt:Date.now()};return q(P??"default",B),{text:`Open this URL in your browser:
|
|
11
|
-
${U.url}`,knobs:{oauthUrl:U.url},accounts:
|
|
12
|
-
`))}}if(
|
|
13
|
-
`))}if(!
|
|
9
|
+
`);if(_===-1)return O===-1?null:{index:O,length:4};if(O===-1||_<O)return{index:_,length:2};return{index:O,length:4}}function TO(D,_){if(!_)return;D.pending+=_;while(!0){let O=sO(D.pending);if(!O)break;let W=D.pending.slice(0,O.index);D.pending=D.pending.slice(O.index+O.length);let j=a1(W);if(!j)continue;if(D.events++,XD(D.eventCounts,j.event??"unknown"),XD(D.typeCounts,j.type),XD(D.deltaTypeCounts,j.deltaType),XD(D.contentBlockTypeCounts,j.contentBlockType),D.textDeltaBytes+=j.textDeltaBytes??0,D.thinkingDeltaBytes+=j.thinkingDeltaBytes??0,D.inputJsonDeltaBytes+=j.inputJsonDeltaBytes??0,D.signatureDeltaBytes+=j.signatureDeltaBytes??0,D.redactedThinkingBytes+=j.redactedThinkingBytes??0,D.last=j,j.dataBytes>0&&!j.type&&!j.event)D.parseErrors++}}function e1(){return{pending:""}}function DW(D,_){let O=D?.toLowerCase(),W=_.toLowerCase();return O==="api_error"||O==="overloaded_error"||O==="server_error"||O==="internal_server_error"||W.includes("internal server error")||W.includes("server overloaded")}function OW(D,_){let O=D?`${D}: ${_}`:_,W=Error(`Anthropic stream error: ${O}`);if(W.code="ECONNRESET",W.syscall="anthropic-sse",D)W.providerErrorType=D;return W}function _W(D){if(!D.includes("error"))return null;let _,O=[];for(let y of D.split(/\r?\n/)){if(y.startsWith("event:")){_=y.slice(6).trim();continue}if(y.startsWith("data:")){let L=y.slice(5);O.push(L.startsWith(" ")?L.slice(1):L)}}let W=O.join(`
|
|
10
|
+
`);if(!W||W==="[DONE]")return null;let j;try{j=JSON.parse(W)}catch{return null}let $=M0(j);if(_!=="error"&&J0($,"type")!=="error")return null;let z=M0($?.error),A=J0(z,"type")??J0(z,"code")??void 0,i=J0(z,"message")??J0($,"message")??A??"Anthropic stream error";if(!DW(A,i))return null;return OW(A,i)}function RO(D,_){if(!_)return null;D.pending+=_;while(!0){let O=sO(D.pending);if(!O)break;let W=D.pending.slice(0,O.index);D.pending=D.pending.slice(O.index+O.length);let j=_W(W);if(j)return j}return null}function WW(D){return{sseEvents:D.events,ssePendingChars:D.pending.length,sseParseErrors:D.parseErrors,sseEventCounts:{...D.eventCounts},sseTypeCounts:{...D.typeCounts},sseDeltaTypeCounts:{...D.deltaTypeCounts},sseContentBlockTypeCounts:{...D.contentBlockTypeCounts},sseTextDeltaBytes:D.textDeltaBytes,sseThinkingDeltaBytes:D.thinkingDeltaBytes,sseInputJsonDeltaBytes:D.inputJsonDeltaBytes,sseSignatureDeltaBytes:D.signatureDeltaBytes,sseRedactedThinkingBytes:D.redactedThinkingBytes,sseLastEvent:D.last?{...D.last}:void 0}}function d0(D,_={}){if(!D.body)return D;let O=D.body.getReader(),W=new TextDecoder,j=new TextEncoder,$="",z=0,A=0,i=0,y=0,L=0,h=!1,o=!1,j0=b(),I0=b(),r=_.perf?t1():void 0,L0=e1(),W0=()=>{if(o)return;o=!0,O.releaseLock()},F0=(N0={})=>({chunks:z,pulls:A,inputBytes:i,outputBytes:y,pendingChars:$.length,rewriteMs:Z0(L),totalMs:Z0(b()-I0),...r?WW(r):{},...N0}),Y0=(N0,K0={})=>{_.perf?.(N0,F0(K0))};_.perf?.("stream_tool_prefix_wrapper_created",{status:D.status,hasBody:!0});let e=new ReadableStream({async pull(N0){if(A++,!h)h=!0,Y0("stream_tool_prefix_first_pull");let K0=b();try{let{done:G0,value:E0}=await O.read(),h0=Z0(b()-K0);if(G0){let U0=W.decode();if(r)TO(r,U0);let A0=RO(L0,U0);if(A0)throw Y0("stream_tool_prefix_retryable_error",{error:A0.message,providerErrorType:A0.providerErrorType}),W0(),A0;let TD=b(),_D=FO(`${$}${U0}`,!0);if(L+=b()-TD,_D.ready){let g0=j.encode(_D.ready);y+=g0.byteLength,N0.enqueue(g0)}Y0("stream_tool_prefix_rewrite",{readMs:h0}),W0(),N0.close();return}z++,i+=E0.byteLength;let T0=W.decode(E0,{stream:!0});if(r)TO(r,T0);let R0=RO(L0,T0);if(R0)throw Y0("stream_tool_prefix_retryable_error",{error:R0.message,providerErrorType:R0.providerErrorType,readMs:h0,lastChunkBytes:E0.byteLength}),W0(),R0;let DD=$+T0,ED=b(),b0=FO(DD);if(L+=b()-ED,$=b0.pending,b0.ready){let U0=j.encode(b0.ready);y+=U0.byteLength,N0.enqueue(U0)}let OD=b();if(z===1||z%25===0||OD-j0>5000)j0=OD,Y0("stream_tool_prefix_progress",{readMs:h0,lastChunkBytes:E0.byteLength})}catch(G0){throw Y0("stream_tool_prefix_error",{error:G0 instanceof Error?G0.message:String(G0)}),W0(),G0}},async cancel(N0){Y0("stream_tool_prefix_cancel",{reason:N0 instanceof Error?N0.message:String(N0)});try{await O.cancel(N0)}finally{W0()}}});return new Response(e,{status:D.status,statusText:D.statusText,headers:D.headers})}var NW="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",aO="~effect/http/HttpServerResponse",eO="~effect/http/Cookies",D_="~effect/http/HttpBody",jW="~effect/ErrorReporter/ignore",JW=60000,PW=60000,$W=5000,O_=200,j1=240,XW=j1;function YW(D){let _=Math.floor(D.retryAfterSeconds/60),O=D.retryAfterSeconds%60,W=`Retry in ${_}m ${O}s.`;return D.modelName?`${D.modelName} weekly limit reached, no routable accounts. ${W}`:`Killswitch: no routable accounts. ${W}`}function ZW(D){if(!D.requestModelId)return{isScopedDriven:!1};if(!e0(D.mainQuota,D.storage))return{isScopedDriven:!1};let _=F_(D.mainQuota,D.requestModelId);if(!_)return{isScopedDriven:!1};if(!Number.isFinite(_.remainingPercent))return{isScopedDriven:!1};let O=f_(D.storage);if(_.remainingPercent<=O.scoped)return{isScopedDriven:!0,modelName:_.modelName,modelId:D.requestModelId};return{isScopedDriven:!1}}var GW=1,__=!1;function xD(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function x(){return performance.now()}function m(D){return Math.round(D*10)/10}function W_(D){return Math.floor(Math.random()*Math.max(0,D))}function GD(D){if(typeof D==="string")return D;if(D instanceof URL)return D.toString();return D.url}function VD(D,_){return _?.method??(D instanceof Request?D.method:void 0)}function N_(D){return D instanceof Error?D.message:String(D)}function VW(){if(__||!1||!xD())return;__=!0;let D=100,_=250,O=x()+D;setInterval(()=>{let W=x(),j=W-O;if(O=W+D,j<_)return;p("[perf] opencode event_loop_lag",{lagMs:m(j),thresholdMs:_})},D).unref?.()}function KW(D){let _=x(),O={requestId:String(GW++),start:_,last:_,mark(W,j){let $=x();if(xD())p("[perf] opencode request stage",{requestId:O.requestId,stage:W,deltaMs:m($-O.last),totalMs:m($-O.start),...j});O.last=$},done(W,j){let $=x();if(xD())p("[perf] opencode request done",{requestId:O.requestId,stage:W,deltaMs:m($-O.last),totalMs:m($-O.start),...j});O.last=$}};if(xD())p("[perf] opencode request start",{requestId:O.requestId,...D});return O}async function wW(D,_,O){let W=D.client.session,j=await KO(D.client,_),$={path:{id:_},body:{noReply:!0,parts:[{type:"text",text:O,ignored:!0}]}};if(j?.agent)$.body.agent=j.agent;if(j?.model)$.body.model=j.model;if(j?.variant)$.body.variant=j.variant;if(typeof W?.promptAsync==="function"){await W.promptAsync($);return}if(typeof W?.prompt==="function"){await Promise.resolve(W.prompt($));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function zW(){let D=Error(NW);throw D[aO]=aO,D[jW]=!0,D.status=204,D.statusText=void 0,D.headers={},D.cookies={[eO]:eO,cookies:{}},D.body={[D_]:D_,_tag:"Empty"},D}function IW(D){if(D.sessionID==null)return!1;let _=D.model;return _?.providerID==="anthropic"||_?.api?.npm==="@ai-sdk/anthropic"||_?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function CW(D){if(D.some((_)=>_.includes("<use_parallel_tool_calls>")))return!1;return D.push(j_),!0}var LW={input:0,output:0,cache:{read:0,write:0}};function UW(D){let _=D["claude-opus-4-8"]??D["claude-opus-4-5"]??Object.values(D)[0];if(!_)return D;return{...D,...Object.fromEntries(Object.values(r_).map((O)=>[O.id,{..._,id:O.id,name:O.name,api:_.api?{..._.api,id:O.id}:void 0,cost:{input:a0.input,output:a0.output,cache:{read:a0.cacheRead,write:a0.cacheWrite5m}},limit:{..._.limit??{},context:u_,output:c_},capabilities:{..._.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:o_}]))}}function QW(D){return Object.fromEntries(Object.entries(D).map(([_,O])=>[_,{...O,cost:LW}]))}var lW=async(D)=>{VW();let{client:_}=D,O=X_(),W=600000,j=50,$=new Map;function z(){let N=Date.now();for(let[J,X]of $)if(N-X.createdAt>W)$.delete(J)}function A(N,J){if(z(),$.size>=j){let X="",I=1/0;for(let[P,E]of $)if(E.createdAt<I)I=E.createdAt,X=P;if(X)$.delete(X)}$.set(N,J)}function i(N){z();let J=$.get(N);if(!J)return;if(Date.now()-J.createdAt>W){$.delete(N);return}return J}let y;try{y=await T(O)}catch(N){let J=N instanceof Error?N.message:String(N);throw Error(`Failed to load account store: ${J}`,{cause:N instanceof Error?N:void 0})}let L=new t_({storage:y,onMainQuotaFetched:async(N,J,X,I)=>{try{let P=await T(O)??V0(),E=M_(P);if(E&&E.checkedAt>=I&&S_(E.quota,P,E.checkedAt)>Date.now()){L.seedMainFromStorage(P);return}P.quota=P.quota??{},P.quota.mainQuota=N,P.quota.mainQuotaCheckedAt=J,P.quota.mainQuotaToken=X,P.quota.mainLastQuotaApiError=void 0,await u0(P,O,{mainQuota:!0})}catch(P){c.warn("quota","failed to persist main quota",{error:P instanceof Error?P.message:String(P)})}},onApiError:async(N)=>{try{let J=await T(O)??V0();J.quota=J.quota??{},J.quota.mainLastQuotaApiError=N,await u0(J,O,{mainQuota:!0})}catch(J){c.warn("quota","failed to persist backoff state",{error:J instanceof Error?J.message:String(J)})}}}),h=new q_({quotaManager:L,onFallbackStorageChanged:()=>{F0().catch(()=>{})}});h.startBackgroundRefresh();let o=null,j0=new g_({loadStorage:()=>T(O),prepareHeaders:async(N,J)=>{let X,I=J.oauthAccountId;if(I&&I!=="main"){let P=await T(O),E=P?.accounts.find((B)=>B.id===I&&B.enabled!==!1&&$0(B));if(E&&P){let B=E;try{B=await h.refreshAccount(E,P)}catch(U){c.warn("cachekeep","fallback token refresh failed",{accountId:I,error:U instanceof Error?U.message:String(U)})}X=B.access}X??=N.get("authorization")?.match(/^Bearer\s+(.+)$/i)?.[1]}else{if(!e)return N;let P=await e();if(P.type!=="oauth")return N;if(!P.access||P.expires&&P.expires<Date.now()){if(!o)return N;P.access=await o()}X=P.access}if(!X)return N;try{let P=JSON.parse(J.bodyText),E=await cD(X,typeof P.model==="string"?P.model:void 0);if(N.delete("anthropic-beta"),l0(N,X,{body:P,identity:E}),N.set("anthropic-beta",i0(N.get("anthropic-beta"),[k_])),P.speed==="fast")YD(N)}catch{l0(N,X)}return N}});if(t0({enabled:c0(y),mode:o0(y)}),MD(ID(y)),HD(CD(y)),!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)P_(UD(y)??"info");let I0=null;if(D.directory){let N=globalThis;if(N.__anthropicAuthRpcServer)await N.__anthropicAuthRpcServer.stop().catch(()=>{}),N.__anthropicAuthRpcServer=void 0;try{I0=await UO({dir:_1(D.directory),drain:IO,apply:J1}),N.__anthropicAuthRpcServer=I0}catch(J){c.warn("rpc","failed to start",{error:J instanceof Error?J.message:String(J)})}}let r={activeId:"main",route:"main"},L0=W1();function W0(N,J){r={activeId:J.activeId,route:J.route},L.updateStorage(N),L.seedMainFromStorage(N,J.mainAccessToken),L.seedFallbacksFromAccounts((N?.accounts??[]).filter($0));let X=L.getMain(J.mainAccessToken),I=L.getLastApiError(),P=N?.refresh?.mainLastRefreshError,E={main:{quota:X?.quota??null,quotaBackedOff:L.isBackedOff(),quotaBackoffUntil:I?.nextRetryAt,refreshBackedOff:P?x0(P,J.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:P?.nextRetryAt},fallbacks:(N?.accounts??[]).filter((B)=>B.enabled!==!1&&$0(B)).map((B)=>({id:B.id,label:B.label,quota:B.access?L.getFallback(B.id,B.access)?.quota??null:null,needsReauth:B.lastRefreshError!=null&&x0(B.lastRefreshError,B.refresh,Date.now())&&U_(B.lastRefreshError),enabled:B.enabled!==!1})),activeId:J.activeId,route:J.route,relay:(()=>{let B=JO(N);return B?{enabled:!0,transport:B.transport??"http"}:null})(),fastMode:FD(),cacheKeep:{enabled:tD(N),window:N?.cacheKeep?.startHour!=null&&N?.cacheKeep?.endHour!=null?`${N.cacheKeep.startHour}-${N.cacheKeep.endHour}`:void 0,trackedSessions:j0.trackedCount()},lastUpdated:Date.now()};return N1(E,L0).catch((B)=>c.warn("sidebar","state write failed",{error:B instanceof Error?B.message:String(B)}))}async function F0(){let N=await T(O),J,X;if(e)try{let I=await e();J=I.access,X=I.refresh}catch{}W0(N,{activeId:r.activeId,route:r.route,mainAccessToken:J,mainRefreshToken:X})}function Y0(N,J){if(!J)return;if(N?.quota?.enabled!==!0)return;if(L.getMain(J))return;if(N0)return;N0=!0,L.refreshMain(J).then(()=>F0()).catch(()=>{}).finally(()=>{N0=!1})}let e=null,N0=!1,K0=null,G0=0;function E0(N){let J=N?.refresh?.refreshBeforeExpiryMinutes??XW;return Math.max(j1,J)*60000}function h0(N){return N?.refresh?.enabled!==!1}async function T0(N){if(!N)return;let J=await T(O),X=J?.refresh?.mainLastRefreshError;if(!J?.refresh||!X?.tokenHash)return;let I=LD(N);if(X.tokenHash===I)return;if(X.nextRetryAt&&X.nextRetryAt>Date.now()){p("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:X.nextRetryAt,retryCount:X.retryCount,remainingMs:X.nextRetryAt-Date.now()});return}J.refresh.mainLastRefreshError=void 0,await u0(J,O,{mainRefresh:!0}),p("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:X.checkedAt,previousNextRetryAt:X.nextRetryAt,previousRetryCount:X.retryCount})}async function R0(){let N=[];if(e)try{let P=await e();if(P.type==="oauth"&&P.access){let E=await L.refreshMain(P.access);N.push({name:"OpenCode anthropic",role:"main",quota:E})}else if(P.type==="oauth")N.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(P){let E=P instanceof Error?P.message:String(P);N.push({name:"OpenCode anthropic",role:"main",error:E.includes("429")?"Usage API rate limited — try again in a moment":E})}let{storage:J,errors:X}=await h.refreshQuotaForAllAccounts({force:!0}),I=new Map(X.map((P)=>[P.accountId,P.message]));if(N.push(...s_(J,I)),!e)N.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return a_({accounts:N,refreshedAt:Date.now()})}async function DD(N){if(e)try{let J=await e();W0(N,{activeId:r.activeId,route:r.route,mainAccessToken:J.access,mainRefreshToken:J.refresh})}catch{}}async function ED(N){let J=v_(N);if(J.type==="enable"||J.type==="disable"){let E=J.type==="enable",B=await Z_(E),U=o0(B);return t0({enabled:E,mode:U}),c.info("commands","cache enabled changed",{enabled:E}),BD({argumentsText:N,enabled:E,mode:U})}if(J.type==="mode"){let E=await G_(J.mode),B=c0(E);return t0({enabled:B,mode:J.mode}),c.info("commands","cache mode changed",{mode:J.mode}),BD({argumentsText:N,enabled:B,mode:J.mode})}let X=await T(O),I=c0(X),P=o0(X);return t0({enabled:I,mode:P}),BD({argumentsText:N,enabled:I,mode:P})}async function b0(N){let J=y_(N),X=await T(O);if(J.type==="window")X=await w_(J.startHour,J.endHour),c.info("commands","cachekeep enabled changed",{enabled:!0});else if(J.type==="disable")X=await z_(!1),c.info("commands","cachekeep enabled changed",{enabled:!1});else if(J.type==="subagents")X=await C_(J.enabled),c.info("commands","cachekeep subagents changed",{subagents:J.enabled});let I=rD(X),P=j0.stats(I);return b_({argumentsText:N,enabled:h_(X),window:I,hybridActive:tD(X),trackedSessions:P.trackedSessions,nextPrewarmAt:P.nextPrewarmAt})}async function OD(N){let J=p_(N);if(J.type==="enable"||J.type==="disable"){let P=J.type==="enable";return await V_(P),MD(P),c.info("commands","dump changed",{enabled:P}),eD({argumentsText:N,enabled:P})}let X=await T(O),I=ID(X);return MD(I),eD({argumentsText:N,enabled:I})}async function U0(N){let J=l_(N);if(J.type==="enable"||J.type==="disable"){let P=J.type==="enable";return await K_(P),HD(P),c.info("commands","fast mode changed",{enabled:P}),OO({argumentsText:N,enabled:P})}let X=await T(O),I=CD(X);return HD(I),OO({argumentsText:N,enabled:I})}async function A0(N){let J=O1(N);if(J.type==="mode")return await D1(J.mode),c.info("commands","routing mode changed",{mode:J.mode}),$O({argumentsText:N,mode:J.mode});let X=await T();return $O({argumentsText:N,mode:fD(X)})}async function TD(N){let J=n_(N);if(J.type==="level")return await B_(J.level),c.info("commands","log level changed",{level:J.level}),NO({argumentsText:N,level:J.level});let X=await T(O),I=UD(X)??"info";return NO({argumentsText:N,level:I})}async function _D(N,J){let X=m_(N);if(X.type==="add-apikey"){if(!X.apiKey)return{text:"API key is required",accounts:z0(await T(O)??V0())};let U=X.label?.trim()||void 0,M=Date.now(),g=X.baseURL?.trim()||"https://api.kie.ai/claude";if(!zD(g))return{text:"Invalid base URL. Must be an http(s) URL without embedded credentials.",accounts:z0(await T(O)??V0())};let t=X.authHeader??"authorization-bearer",a={id:U||mD(),label:U||void 0,type:"api",apiKey:X.apiKey,baseURL:g,authHeader:t,enabled:!0,addedAt:M,lastUsed:M};await nD(a,O),c.info("commands","account added",{id:a.id,label:a.label,type:"apikey"});let X0=await T(O);await DD(X0);let S0=z0(X0??{version:1,accounts:[]});return{text:`API key account "${a.label??a.id}" added.`,accounts:S0}}if(X.type==="add-oauth-start"){let U=await KD("max"),M={state:U.state,verifier:U.verifier,redirectUri:U.redirectUri,createdAt:Date.now()};return A(J??"default",M),{text:`Open this URL in your browser:
|
|
11
|
+
${U.url}`,knobs:{oauthUrl:U.url},accounts:z0(await T(O)??V0())}}if(X.type==="add-oauth-finish"){let U=J??"default",M=i(U);if(!M)return{text:"OAuth session expired. Please start again.",accounts:z0(await T(O)??V0())};try{let g=await wD(X.code,M.verifier,M.redirectUri,M.state);if(g.type==="failed")return{text:"OAuth authentication failed. Please check the code and try again.",accounts:z0(await T(O)??V0())};let t=Date.now(),a={id:mD(),type:"oauth",label:X.label||void 0,access:g.access,refresh:g.refresh,expires:g.expires,enabled:!0,addedAt:t,lastUsed:t,lastRefreshedAt:t};await nD(a,O),c.info("commands","account added",{id:a.id,label:a.label,type:"oauth"});let X0=await T(O);return await DD(X0),{text:"OAuth account added.",accounts:z0(X0??V0())}}catch{return{text:"OAuth exchange failed due to a network error. Please try again.",accounts:z0(await T(O)??V0())}}finally{$.delete(U)}}let I=await T(O),P=i_({argumentsText:N,storage:I??{version:1,accounts:[]}});if(P.updated){if(P.updated.action==="enable"||P.updated.action==="disable"){let M=P.updated.action==="enable";await A_(P.updated.id,M,O);let g=P.updated.id,t=I?.accounts.find((a)=>a.id===g);c.info("commands",`account ${P.updated.action}d`,{id:g,label:t?.label,enabled:M})}else if(P.updated.action==="remove"){await T_(P.updated.id,O);let M=P.updated.id,g=I?.accounts.find((t)=>t.id===M);c.info("commands","account removed",{id:M,label:g?.label})}else if(P.updated.action==="reorder"){await R_(P.updated.newOrder??P.updated.previousOrder??[],O);let M=P.updated.id,g=I?.accounts.find((t)=>t.id===M);c.info("commands","account reordered",{id:M,label:g?.label})}let U=await T(O);if(e)try{let M=await e();W0(U,{activeId:r.activeId,route:r.route,mainAccessToken:M.access,mainRefreshToken:M.refresh})}catch{}}let E=await T(O),B=z0(E??{version:1,accounts:[]});return{text:P.text,accounts:B}}async function g0(N,J,X){if(N==="claude-quota")return{command:N,text:await R0(),knobs:{}};if(N==="claude-logging"){let U=await TD(J),M=await T(O);return{command:N,text:U,knobs:{level:UD(M)??"info"}}}if(N==="claude-account"){let U=await _D(J,X),M={accounts:U.accounts};if("knobs"in U&&U.knobs)Object.assign(M,U.knobs);return{command:N,text:U.text,knobs:M}}if(N==="claude-routing"){let U=await A0(J),M=await T(O);return{command:N,text:U,knobs:{mode:fD(M)}}}if(N==="claude-fast"){let U=await U0(J),M=await T(O);return{command:N,text:U,knobs:{enabled:CD(M)}}}if(N==="claude-dump"){let U=await OD(J),M=await T(O);return{command:N,text:U,knobs:{enabled:ID(M)}}}if(N==="claude-cache"){let U=await ED(J),M=await T(O);return{command:N,text:U,knobs:{enabled:c0(M),mode:o0(M)}}}if(N==="claude-cachekeep"){let U=await b0(J),M=await T(O);return{command:N,text:U,knobs:{window:rD(M)}}}let I=await T(),P=dD(I),E=(I?.accounts??[]).filter((U)=>U.enabled!==!1).map((U)=>U.id),B=d_({argumentsText:J,config:P,accountIds:E});if(B.updatedConfig){if(await E_(B.updatedConfig),P.enabled!==B.updatedConfig.enabled)c.info("commands","killswitch changed",{enabled:B.updatedConfig.enabled===!0});if(JSON.stringify(P.main)!==JSON.stringify(B.updatedConfig.main)||JSON.stringify(P.accounts)!==JSON.stringify(B.updatedConfig.accounts))c.info("commands","killswitch thresholds changed",{thresholds:B.updatedConfig.main??B.updatedConfig.accounts})}return{command:N,text:B.text,knobs:{config:dD(await T()),accountIds:E}}}async function J1(N){let J=await g0(N.command,N.arguments,N.sessionId);return{text:J.text,knobs:J.knobs}}function P1(N,J=10){let X=Math.max(0,Math.min(Math.round(N/100*J),J));return"█".repeat(X)+"░".repeat(J-X)}function WD(N,J){return`${N} ${P1(J)} ${String(Math.round(J)).padStart(3)}%`}function XO(N){if(!N)return"";let J=new Date(N).getTime();if(Number.isNaN(J))return"";let X=J-Date.now();if(X<=0)return"resets now";let I=Math.floor(X/60000);if(I<1)return"resets <1m";if(I<60)return`resets ${I}m`;let P=Math.floor(I/60),E=I%60;return E>0?`resets ${P}h${E}m`:`resets ${P}h`}function $1(N,J,X){let I=[],P=0;if(N){let{five_hour:U,seven_day:M}=N;if(U||M){let t=X==="main"?"active":"idle",a=XO(U?.resetsAt),X0=[`main · ${t}${a?` (${a})`:""}`];if(U)X0.push(WD("5h",U.usedPercent)),P=Math.max(P,U.usedPercent);if(M)X0.push(WD("7d",M.usedPercent)),P=Math.max(P,M.usedPercent);I.push(X0.join(`
|
|
12
|
+
`))}}if(J?.length)for(let U of J){let M=U.quota;if(!M)continue;let{five_hour:g,seven_day:t}=M;if(!g&&!t)continue;let a=U.label||"alt",S0=X===U.id?"active":"idle",Q0=XO(g?.resetsAt),H0=[`${a} · ${S0}${Q0?` (${Q0})`:""}`];if(g)H0.push(WD("5h",g.usedPercent)),P=Math.max(P,g.usedPercent);if(t)H0.push(WD("7d",t.usedPercent)),P=Math.max(P,t.usedPercent);I.push(H0.join(`
|
|
13
|
+
`))}if(!I.length)return;let E=I.join(`
|
|
14
14
|
|
|
15
|
-
`),
|
|
15
|
+
`),B=P>=90?"error":P>=70?"warning":"info";_.tui?.showToast?.({body:{title:"Claude Quota",message:E,variant:B,duration:B==="error"?8000:5000}})?.catch?.(()=>{})}return{config:async(N)=>{N.command={...N.command??{},[uD]:{template:uD,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[sD]:{template:sD,description:"Manage fallback accounts — list, enable/disable, reorder, remove, or add (API key or OAuth)."},[oD]:{template:oD,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[jO]:{template:jO,description:"Show current Claude OAuth quota usage for all accounts."},[aD]:{template:aD,description:"Show or toggle Anthropic request dump capture for debugging."},[DO]:{template:DO,description:"Show or toggle Anthropic fast mode for supported Opus models."},[WO]:{template:WO,description:"Show or set the plugin log level (error, warn, info, debug, trace)."},[PO]:{template:PO,description:"Show or change Claude account routing between main-first and fallback-first."},[_O]:{template:_O,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."}}},"experimental.chat.system.transform":async(N,J)=>{if(!IW(N))return;CW(J.system)},provider:{id:"anthropic",async models(N,J){let X=UW(N.models);if(J.auth?.type!=="oauth"||!$_(y??{}))return X;return QW(X)}},"command.execute.before":async(N)=>{if(!["claude-account","claude-cache","claude-cachekeep","claude-quota","claude-dump","claude-fast","claude-routing","claude-killswitch","claude-logging"].includes(N.command))return;let X=N.command,I=await g0(X,N.arguments,N.sessionID);if(X==="claude-quota"){let P=await T(),E=e?await e().catch(()=>{return}):void 0;W0(P,{activeId:"main",route:"main",mainAccessToken:E?.access,mainRefreshToken:E?.refresh})}if(CO(N.sessionID))zO(I,N.sessionID);else await wW(D,N.sessionID,I.text);zW()},auth:{provider:"anthropic",async loader(N,J){e=N;let X=await N();if(X.type==="oauth"){let E=function(){if(K0)clearInterval(K0),K0=null;let Y=async()=>{try{let w=await T(O);if(!h0(w))return;let S=await N();if(S.type!=="oauth")return;if(await T0(S.refresh),!S.expires)return;let C=S.expires-Date.now(),R=E0(w);if(C>R)return;if(p("[refresh] opencode main oauth background due",{expiresInMs:C,refreshBeforeMs:R}),S.refresh&&x0(w?.refresh?.mainLastRefreshError,S.refresh,Date.now())){p("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:w?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:w?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:C});return}if(S.refresh&&w?.refresh?.mainRefreshLeaseUntil&&w.refresh.mainRefreshLeaseUntil>Date.now()&&w.refresh.mainRefreshLeaseTokenHash===LD(S.refresh))return;await P();let Z=await N();p("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:Z.expires?Z.expires-Date.now():void 0})}catch(w){c.warn("refresh","opencode main oauth refresh failed",{message:w instanceof Error?w.message:String(w)})}};if(K0=setInterval(()=>{Y()},JW+W_(PW)),"unref"in K0)K0.unref()},B=function(Y,w){if(Y instanceof Request&&Y.body)return!1;return w==null||typeof w==="string"},U=function(Y){if(typeof Y!=="string")return;try{let w=JSON.parse(Y);return typeof w.model==="string"?w.model:void 0}catch{return}},M=function(Y){return Y.has("x-parent-session-id")},g=function(Y){return Y.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(Y)},t=function(Y){return Y?.quota?.enabled===!0},X0=function(Y,w){if(Y.delete("authorization"),Y.delete("x-api-key"),w.authHeader==="x-api-key")Y.set("x-api-key",w.apiKey??"");else Y.set("Authorization",`Bearer ${w.apiKey??""}`);Y.set("Content-Type","application/json")},H0=function(Y){return L.getFallback(Y.id,Y.access)?.quota??Y.quota},RD=function(Y){return["five_hour","seven_day"].some((w)=>(Y?.[w]?.remainingPercent??1)<=0)},YO=function(Y,w){return Y.status===429||w},AD=function(Y){if(!Y)return!1;let w=L.getMain(Y);return Boolean(w&&w.refreshAfter>Date.now()&&RD(w.quota))},I=null;async function P(){if(!I)I=(async()=>{let S=null,C=null,R=null;async function Z(K){let q=await T(O)??V0();q.refresh=q.refresh??{},K(q),await u0(q,O,{mainRefresh:!0})}async function n(K){let q=Date.now()+$W;while(Date.now()<q){await new Promise((H)=>setTimeout(H,O_+W_(O_)));let V=await N();if(V.type!=="oauth"||!V.access)continue;if((V.access!==K.access||V.refresh!==K.refresh||(V.expires??0)>(K.expires??0)+60000)&&(!V.expires||V.expires>Date.now()))return p("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:V.expires?V.expires-Date.now():void 0}),V.access}return null}for(let K=0;K<=2;K++){let q=null;try{if(K>0){let k=500*2**(K-1);await new Promise((u)=>setTimeout(u,k))}if(q=await N(),!q.refresh)throw Error("Token refresh failed: missing refresh token");let V=await T(O),G=LD(q.refresh),H=V?.refresh?.mainLastRefreshError;if(p("[refresh] opencode main oauth refresh check",{attempt:K,expiresInMs:q.expires?q.expires-Date.now():void 0,hasBackoff:Boolean(H),backoffActive:H?x0(H,q.refresh,Date.now()):!1,retryCount:H?.retryCount,nextRetryAt:H?.nextRetryAt}),H&&x0(H,q.refresh,Date.now()))throw p("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:H.nextRetryAt,retryCount:H.retryCount}),Error(pD(H,Date.now()));if(V?.refresh?.mainRefreshLeaseUntil&&V.refresh.mainRefreshLeaseUntil>Date.now()&&V.refresh.mainRefreshLeaseTokenHash===G){p("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:V.refresh.mainRefreshLeaseUntil});let k=await n(q);if(k)return k;throw Error("Claude OAuth refresh is already in progress")}let v=await Y_({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!v){p("[refresh] opencode main oauth refresh skipped file lock");let k=await n(q);if(k)return k;throw Error("Claude OAuth refresh is already in progress")}R=v.release,S=mD(),C=G,await Z((k)=>{k.refresh=k.refresh??{},k.refresh.mainRefreshLeaseId=S??void 0,k.refresh.mainRefreshLeaseUntil=Date.now()+120000,k.refresh.mainRefreshLeaseTokenHash=G});let f=await T(O);if(p("[refresh] opencode main oauth refresh lease acquired",{attempt:K,leaseUntil:Date.now()+120000}),f?.refresh?.mainRefreshLeaseId!==S||f.refresh.mainRefreshLeaseTokenHash!==G)throw Error("Claude OAuth refresh is already in progress");p("[refresh] opencode main oauth refresh request start",{attempt:K});let D0=await J_({refreshToken:q.refresh,maxRetries:0});return await _.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:D0.refresh,access:D0.access,expires:D0.expires}}),await Z((k)=>{if(!k?.refresh)return;if(k.refresh.mainLastRefreshError=void 0,k.refresh.mainRefreshLeaseId===S)k.refresh.mainRefreshLeaseId=void 0,k.refresh.mainRefreshLeaseUntil=void 0,k.refresh.mainRefreshLeaseTokenHash=void 0}),p("[refresh] opencode main oauth refresh succeeded",{attempt:K,expiresInMs:D0.expires-Date.now()}),D0.access}catch(V){let G=V instanceof Error&&(V.message.includes("fetch failed")||("code"in V)&&(V.code==="ECONNRESET"||V.code==="ECONNREFUSED"||V.code==="ETIMEDOUT"||V.code==="UND_ERR_CONNECT_TIMEOUT"));if(K<2&&(G||(()=>{let v=V.status;return typeof v==="number"&&v>=500})()))continue;p("[refresh] opencode main oauth refresh attempt failed",{attempt:K,error:V instanceof Error?V.message:String(V),transient:G});let H=q?.refresh;if(H&&V.isRefreshError)await Z((v)=>{v.refresh=v.refresh??{},v.refresh.mainLastRefreshError=L_({error:V,now:Date.now(),refreshToken:H,previous:v.refresh.mainLastRefreshError})});throw V}finally{if(S)await Z((V)=>{if(!V?.refresh)return;if(V.refresh.mainRefreshLeaseId===S&&V.refresh.mainRefreshLeaseTokenHash===C)V.refresh.mainRefreshLeaseId=void 0,V.refresh.mainRefreshLeaseUntil=void 0,V.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await R?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{I=null});return I}o=P,E(),L.seedFallbacksFromAccounts((y?.accounts??[]).filter($0)),W0(y,{activeId:"main",route:"main",mainAccessToken:X.access,mainRefreshToken:X.refresh});async function a(Y,w){if(!Y.body||Y.status!==200)return w?.mark("inspect_stream_skip",{status:Y.status}),{response:Y,rateLimited:!1};if(Y.headers.get("x-cortexkit-relay-optimistic")==="true")return w?.mark("inspect_stream_skip",{status:Y.status,reason:"optimistic_relay"}),{response:Y,rateLimited:!1};let S=x(),C=Y.body.getReader(),R=[],Z=new TextDecoder,n="",K=0;while(!n.includes(`
|
|
16
16
|
|
|
17
|
-
`)&&d.length<65536){let{done:Y,value:z}=await C.read();if(Y)break;if(R.push(z),I+=z.byteLength,d+=G.decode(z,{stream:!0}),B(d))break}if(B(d)){await C.cancel().catch(()=>{});try{C.releaseLock()}catch{}let Y=new ReadableStream({start(z){for(let H of R)z.enqueue(H);z.close()}});return K?.mark("inspect_stream_first_event",{ms:g(f()-A),bytes:I,rateLimited:!0}),{response:new Response(Y,{status:Z.status,statusText:Z.statusText,headers:Z.headers}),rateLimited:!0}}let S=new ReadableStream({start(Y){for(let z of R)Y.enqueue(z)},async pull(Y){let{done:z,value:H}=await C.read();if(z){Y.close();return}Y.enqueue(H)},cancel(Y){return C.cancel(Y)}});return K?.mark("inspect_stream_first_event",{ms:g(f()-A),bytes:I,rateLimited:!1}),{response:new Response(S,{status:Z.status,statusText:Z.statusText,headers:Z.headers}),rateLimited:!1}}async function X0(Z,K,A,C,R="api_fallback",G){let d=f(),I=SD(Z,K),S=I.get("x-session-affinity")||I.get("x-opencode-session"),Y=U(I);I.delete("x-parent-session-id"),I.delete("x-session-affinity"),I.delete("x-opencode-session");let z=K?.body,H=typeof z==="string"?z.length:void 0;if(z&&typeof z==="string"){let E=f(),M=(()=>{if(!BD())return!1;try{return i0(JSON.parse(z).model)}catch{return!1}})();if(z=await yD(z,{cache1hEnabled:!Y&&v0(),cache1hMode:k0(),fastModeEnabled:M,perf:(F,p)=>C?.mark(`rewrite_body_${F}`,{route:R,...p})}),r(I,A),I.set("anthropic-beta",m0(I.get("anthropic-beta"),[])),M)XD(I);C?.mark("rewrite_body",{route:R,ms:g(f()-E),originalBytes:H,rewrittenBytes:z.length,cacheEnabled:!Y&&v0(),cacheMode:k0(),fastModeEnabled:M,subagent:Y})}else r(I,A);let Q=kD(Z,{baseURL:A.baseURL}),e=f(),t;try{t=await fetch(Q.input,{...K,body:z,headers:I,...vD()&&{tls:{rejectUnauthorized:!1}}})}catch(E){if(typeof z==="string")await s0({affinity:S,route:R,error:D_(E),bodyText:z,url:Q.url?.toString()??ZD(Q.input),method:GD(Z,K),headers:I});throw E}if(typeof z==="string")await s0({affinity:S,route:R,status:t.status,bodyText:z,url:Q.url?.toString()??ZD(Q.input),method:GD(Z,K),headers:I});return C?.mark("send_headers_received",{route:R,ms:g(f()-e),status:t.status,relayConfigured:!1,totalSendWithAccessMs:g(f()-d),baseURL:A.baseURL}),t}async function B0(Z,K,A,C,R="unknown",G){let d=f(),I=G,S=async()=>{return I??=await T(O),I},Y=SD(Z,K),z=Y.get("x-session-affinity")||Y.get("x-opencode-session"),H=U(Y);Y.delete("x-parent-session-id"),Y.delete("x-session-affinity"),Y.delete("x-opencode-session");let Q=K?.body,e;if(Q&&typeof Q==="string"){let D0=f();try{let V0=JSON.parse(Q);if(typeof V0.model==="string")e=V0.model}catch{}C?.mark("model_parse_for_identity",{route:R,ms:g(f()-D0),bodyBytes:Q.length})}let t=f(),E=await lD(A,e);C?.mark("resolve_claude_code_identity",{route:R,ms:g(f()-t),hasAccountUuid:Boolean(E.accountUuid)});let M=typeof Q==="string"?Q.length:void 0;if(Q&&typeof Q==="string"){let D0=f(),V0=(()=>{if(!BD())return!1;try{return i0(JSON.parse(Q).model)}catch{return!1}})();Q=await yD(Q,{cache1hEnabled:!H&&v0(),cache1hMode:k0(),fastModeEnabled:V0,identity:E,perf:(N1,j1)=>C?.mark(`rewrite_body_${N1}`,{route:R,...j1})});let q0=f();try{p0(Y,A,{body:JSON.parse(Q),identity:E}),C?.mark("set_oauth_headers_body_parse",{route:R,ms:g(f()-q0),bodyBytes:Q.length,parsed:!0})}catch{p0(Y,A,{identity:E}),C?.mark("set_oauth_headers_body_parse",{route:R,ms:g(f()-q0),bodyBytes:Q.length,parsed:!1})}if(V0)XD(Y);C?.mark("rewrite_body",{route:R,ms:g(f()-D0),originalBytes:M,rewrittenBytes:Q.length,cacheEnabled:!H&&v0(),cacheMode:k0(),fastModeEnabled:V0,subagent:H})}let F=kD(Z);if(R==="main"&&typeof Q==="string"&&v0()&&k0()==="hybrid"){let D0=await S();if(!H||I_(D0)){let V0=f(),q0=N0.track({sessionId:z,url:F.url?.toString()??F.input.toString(),headers:Y,bodyText:Q,storage:D0,cacheMode:"hybrid"});C?.mark("cachekeep_track",{session:z,ms:g(f()-V0),tracked:q0.tracked,reason:q0.tracked?void 0:q0.reason,bodyBytes:Q.length})}}let p=async()=>{try{let D0=await fetch(F.input,{...K,body:Q,headers:Y,...vD()&&{tls:{rejectUnauthorized:!1}}});if(typeof Q==="string")await s0({affinity:z,route:R,status:D0.status,bodyText:Q,url:F.url?.toString()??ZD(F.input),method:GD(Z,K),headers:Y});return D0}catch(D0){if(typeof Q==="string")await s0({affinity:z,route:R,error:D_(D0),bodyText:Q,url:F.url?.toString()??ZD(F.input),method:GD(Z,K),headers:Y});throw D0}},P0=_O(await S()),s=f(),W0=await u_({config:P0,input:F.input,init:K,headers:Y,body:Q,fallback:p,affinity:z,optimisticResponse:P0?.transport==="websocket"});return C?.mark("send_headers_received",{route:R,ms:g(f()-s),status:W0.status,relayConfigured:P0!=null,totalSendWithAccessMs:g(f()-d)}),W0}async function _1(Z){if(!Z)return!1;try{return await L.refreshMain(Z),RD(Z)}catch{return!1}}async function WD(Z,K={}){let A=await y.getUsableFallbackAccounts(Z),C=new Map(A.map((G)=>[G.id,G])),R=[];for(let G of Z?.accounts??[]){if(J0(G)){let d=C.get(G.id);if(d)R.push(d);continue}if(K.includeApiRoutes===!0&&d0(G)&&G.enabled!==!1&&G.apiKey&&KD(G.baseURL))R.push(G)}if(!r0(Z))return R;return R.filter((G)=>J0(G)?MD(w0(G),Z,G.id):!0)}async function ND(Z,K,A,C,R,G,d){if(!A.length)return R??null;let I=d?.returnLastOnExhausted??!0;await R?.body?.cancel().catch(()=>{});let S=R??null;for(let[Y,z]of A.entries()){let H;if(d0(z)){if(!z.apiKey)continue;H=await X0(Z,K,z,G,`api_fallback_${Y}`,C)}else{let e=z.access;if(!e)continue;H=await B0(Z,K,e,G,`fallback_${Y}`,C)}S=H;let Q=bD(H.status,C);if(!Q){let e=await o(H,G);H=e.response,S=H,Q=e.rateLimited}if(!Q){if(await y.markUsed(z),await d?.onSuccess?.(z),J0(z)&&z.access&&L.shouldRefreshOnRequestCount(Z0))L.refreshFallback(z.id,z.access).then(()=>d?.onSuccess?.(z)).catch(()=>{});return H}if(Y<A.length-1||!I)await H.body?.cancel().catch(()=>{})}return I?S:null}async function W1(Z,K,A,C,R,G,d,I){if(!x(Z,K?.body))return A;let S=f(),Y=G??await T(O);if(R?.mark("fallback_load_storage",{ms:g(f()-S),cached:!!G}),!(Y?.accounts??[]).some((M)=>M.enabled!==!1&&(J0(M)||d0(M)&&Boolean(M.apiKey)&&KD(M.baseURL))))return A;let H=A,Q=bD(H.status,Y),e=PO(H,!1);if(!Q){let M=await o(H,R);H=M.response,Q=M.rateLimited,e=PO(H,M.rateLimited)}if(!Q)return H;let t=!1;if(C)t=C.some(d0);else if(e)t=await _1(d);let E=C;if(!E){let M=f();E=await WD(Y,{includeApiRoutes:t}),R?.mark("fallback_get_accounts",{ms:g(f()-M),accounts:E.length})}if(r0(Y)){let M=E.length;if(E=E.filter((F)=>J0(F)?MD(w0(F),Y,F.id):!0),E.length<M)i("[killswitch] filtered fallbacks",{before:M,after:E.length})}return await ND(Z,K,E,Y,H,R,{onSuccess:I})??H}return{apiKey:"",async fetch(Z,K){let A=K?.body,C=PW({bodyBytes:typeof A==="string"?A.length:void 0}),R=f(),G=await N();if(C.mark("get_auth",{ms:g(f()-R),authType:G.type,hasAccess:Boolean(G.access)}),G.type!=="oauth"){let M=await fetch(Z,K);return C.done("non_oauth_passthrough",{status:M.status}),M}await E0(G.refresh);let d=f(),I=await T();C.mark("load_storage",{ms:g(f()-d)}),L.updateStorage(I),L.seedMainFromStorage(I,G.access),L.seedFallbacksFromAccounts((I?.accounts??[]).filter(J0));let S=x(Z,K?.body);if(S)Z0++;if(S&&G.access&&(!G.expires||G.expires>Date.now()))$0(I,G.access);let Y=(M,F)=>O0(I,{activeId:M,route:F,mainAccessToken:G.access,mainRefreshToken:G.refresh}),z;if(S&&HD(I)==="fallback-first")try{let M=f();z=await WD(I,{includeApiRoutes:RD(G.access)}),C.mark("fallback_first_get_accounts",{ms:g(f()-M),accounts:z.length});let F=await ND(Z,K,z,I,void 0,C,{returnLastOnExhausted:!1,onSuccess:(p)=>Y(p.id,"fallback-first")});if(F)return C.done("return_fallback_first",{status:F.status}),l0(F,{perf:(p,P0)=>C.mark(p,P0)});z=void 0}catch(M){C.mark("fallback_first_error",{error:M instanceof Error?M.message:String(M)})}if(!G.access||!G.expires||G.expires<Date.now()){let F=(await T())?.refresh?.mainLastRefreshError;if(G.refresh&&F&&f0(F,G.refresh,Date.now()))throw i("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:F.nextRetryAt,retryCount:F.retryCount,expiresInMs:G.expires?G.expires-Date.now():void 0}),Error(gD(F,Date.now()));i("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(G.access),expiresInMs:G.expires?G.expires-Date.now():void 0,expiredAgoMs:G.expires&&G.expires<Date.now()?Date.now()-G.expires:void 0});let p=f();G.access=await $(),C.mark("refresh_main_access",{ms:g(f()-p)})}if(!G.access)throw C.done("missing_access_error"),Error("OAuth access token is missing after refresh");function H(){if(I?.quota?.showToasts!==!0)return;let M=L.getMain();if(!M)return;let F=(I?.accounts??[]).filter((s)=>s.enabled!==!1&&J0(s)).map((s)=>({...s,quota:L.getFallback(s.id,s.access)?.quota??s.quota})),p=o0(M.quota,I),P0;if(p)P0="main";else P0=F.find((s)=>o0(s.quota,I))?.id??"main";O1(M.quota,F,P0)}if(S&&b(I))try{let M=f(),F=L.getMain(G.access),p=F?.quota;if(!p)p=await L.refreshMain(G.access),F=L.getMain(G.access),H();else if(L.needsRefresh(Z0))if(F0(p))p=await L.refreshMain(G.access),F=L.getMain(G.access);else L.refreshMain(G.access).then(()=>{U0().catch(()=>{}),H()}).catch(()=>{});if(O0(I,{activeId:"main",route:"main",mainAccessToken:G.access,mainRefreshToken:G.refresh}),C.mark("main_quota_for_routing",{ms:g(f()-M),passes:o0(p,I)}),!o0(p,I)){let P0=f();z=await WD(I,{includeApiRoutes:Boolean(F&&F.refreshAfter>Date.now()&&F0(F.quota))}),C.mark("preselect_fallback_accounts",{ms:g(f()-P0),accounts:z.length});let s=await ND(Z,K,z,I,void 0,C,{onSuccess:(W0)=>Y(W0.id,"fallback")});if(s)return C.done("return_preselected_fallback",{status:s.status}),l0(s,{perf:(W0,D0)=>C.mark(W0,D0)})}}catch(M){C.mark("main_quota_for_routing_error",{error:M instanceof Error?M.message:String(M)})}let Q=L.getMain(G.access)?.quota;if(I?.quota?.failClosedOnUnknownQuota&&!Q&&L.isBackedOff()){let M=L.getLastApiError(),F=M?w_(M,Date.now()):"Quota API unavailable";return i("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:M?.nextRetryAt,retryCount:M?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:F}}),{status:429,headers:{"content-type":"application/json","retry-after":String(M?.nextRetryAt?Math.max(1,Math.ceil((M.nextRetryAt-Date.now())/1000)):60)}})}if(r0(I)){if(L.needsRefresh(Z0))try{let F=(I?.accounts??[]).filter((p)=>p.enabled!==!1&&J0(p)&&Boolean(p.access));await Promise.all([L.refreshMain(G.access),L.refreshAllFallbacks(F)])}catch(F){i("[quota] killswitch refresh failed",{error:F instanceof Error?F.message:String(F),backedOff:L.isBackedOff()})}Q=L.getMain(G.access)?.quota}if(r0(I)&&!MD(Q,I)){let F=x(Z,K?.body)?await WD(I,{includeApiRoutes:RD(G.access)}):[];if(F.length>0){i("[route] skipping main (killswitch), trying fallbacks");let W0=await ND(Z,K,F,I,void 0,C,{onSuccess:(D0)=>Y(D0.id,"fallback")});if(W0)return C.done("return_killswitch_fallback",{status:W0.status}),l0(W0,{perf:(D0,V0)=>C.mark(D0,V0)})}let p=Date.now(),P0=(I?.accounts??[]).filter((W0)=>W0.enabled!==!1&&J0(W0)).map((W0)=>({...W0,quota:w0(W0)})),s=M_(Q,P0,p);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:`Killswitch: no routable accounts. Retry in ${Math.floor(s/60)}m ${s%60}s.`}}),{status:429,headers:{"content-type":"application/json","retry-after":String(s)}})}let e=await B0(Z,K,G.access,C,"main",I),t=!1,E=await W1(Z,K,e,z,C,I,G.access,(M)=>{t=!0,Y(M.id,"fallback")});if(!t)Y("main","main");return C.done("return_response",{status:E.status}),l0(E,{perf:(M,F)=>C.mark(M,F)})}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let N=await ID("max");return{url:N.url,instructions:"Paste the authorization code here:",method:"code",callback:async(P)=>{return VD(P,N.verifier,N.redirectUri,N.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let N=await ID("console");return{url:N.url,instructions:"Paste the authorization code here:",method:"code",callback:async(P)=>{let X=await VD(P,N.verifier,N.redirectUri,N.state);if(X.type==="failed")return X;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${X.access}`}}).then(($)=>$.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{kW as AnthropicAuthPlugin};
|
|
17
|
+
`)&&n.length<65536){let{done:V,value:G}=await C.read();if(V)break;if(R.push(G),K+=G.byteLength,n+=Z.decode(G,{stream:!0}),g(n))break}if(g(n)){await C.cancel().catch(()=>{});try{C.releaseLock()}catch{}let V=new ReadableStream({start(G){for(let H of R)G.enqueue(H);G.close()}});return w?.mark("inspect_stream_first_event",{ms:m(x()-S),bytes:K,rateLimited:!0}),{response:new Response(V,{status:Y.status,statusText:Y.statusText,headers:Y.headers}),rateLimited:!0}}let q=new ReadableStream({start(V){for(let G of R)V.enqueue(G)},async pull(V){let{done:G,value:H}=await C.read();if(G){V.close();return}V.enqueue(H)},cancel(V){return C.cancel(V)}});return w?.mark("inspect_stream_first_event",{ms:m(x()-S),bytes:K,rateLimited:!1}),{response:new Response(q,{status:Y.status,statusText:Y.statusText,headers:Y.headers}),rateLimited:!1}}async function S0(Y,w,S,C,R="api_fallback",Z){let n=x(),K=yD(Y,w),q=K.get("x-session-affinity")||K.get("x-opencode-session"),V=M(K);K.delete("x-parent-session-id"),K.delete("x-session-affinity"),K.delete("x-opencode-session");let G=w?.body,H=typeof G==="string"?G.length:void 0;if(G&&typeof G==="string"){let k=x(),u=(()=>{if(!FD())return!1;try{return p0(JSON.parse(G).model)}catch{return!1}})();if(G=await gD(G,{cache1hEnabled:!V&&k0(),cache1hMode:y0(),fastModeEnabled:u,perf:(Q,F)=>C?.mark(`rewrite_body_${Q}`,{route:R,...F})}),X0(K,S),K.set("anthropic-beta",i0(K.get("anthropic-beta"),[])),u)YD(K);C?.mark("rewrite_body",{route:R,ms:m(x()-k),originalBytes:H,rewrittenBytes:G.length,cacheEnabled:!V&&k0(),cacheMode:y0(),fastModeEnabled:u,subagent:V})}else X0(K,S);let v=bD(Y,{baseURL:S.baseURL}),f=x(),D0;try{D0=await fetch(v.input,{...w,body:G,headers:K,...hD()&&{tls:{rejectUnauthorized:!1}}})}catch(k){if(typeof G==="string")await s0({affinity:q,route:R,error:N_(k),bodyText:G,url:v.url?.toString()??GD(v.input),method:VD(Y,w),headers:K});throw k}if(typeof G==="string")await s0({affinity:q,route:R,status:D0.status,bodyText:G,url:v.url?.toString()??GD(v.input),method:VD(Y,w),headers:K});return C?.mark("send_headers_received",{route:R,ms:m(x()-f),status:D0.status,relayConfigured:!1,totalSendWithAccessMs:m(x()-n),baseURL:S.baseURL}),D0}async function Q0(Y,w,S,C,R="unknown",Z,n="main"){let K=x(),q=Z,V=async()=>{return q??=await T(O),q},G=yD(Y,w),H=G.get("x-session-affinity")||G.get("x-opencode-session"),v=M(G);G.delete("x-parent-session-id"),G.delete("x-session-affinity"),G.delete("x-opencode-session");let f=w?.body,D0;if(f&&typeof f==="string"){let _0=x();try{let s=JSON.parse(f);if(typeof s.model==="string")D0=s.model}catch{}C?.mark("model_parse_for_identity",{route:R,ms:m(x()-_0),bodyBytes:f.length})}let k=x(),u=await cD(S,D0);C?.mark("resolve_claude_code_identity",{route:R,ms:m(x()-k),hasAccountUuid:Boolean(u.accountUuid)});let Q=typeof f==="string"?f.length:void 0;if(f&&typeof f==="string"){let _0=x(),s=(()=>{if(!FD())return!1;try{return p0(JSON.parse(f).model)}catch{return!1}})();f=await gD(f,{cache1hEnabled:!v&&k0(),cache1hMode:y0(),fastModeEnabled:s,identity:u,perf:(SD,Z1)=>C?.mark(`rewrite_body_${SD}`,{route:R,...Z1})});let w0=x();try{l0(G,S,{body:JSON.parse(f),identity:u}),C?.mark("set_oauth_headers_body_parse",{route:R,ms:m(x()-w0),bodyBytes:f.length,parsed:!0})}catch{l0(G,S,{identity:u}),C?.mark("set_oauth_headers_body_parse",{route:R,ms:m(x()-w0),bodyBytes:f.length,parsed:!1})}if(s)YD(G);C?.mark("rewrite_body",{route:R,ms:m(x()-_0),originalBytes:Q,rewrittenBytes:f.length,cacheEnabled:!v&&k0(),cacheMode:y0(),fastModeEnabled:s,subagent:v})}let F=bD(Y);if(typeof f==="string"&&k0()&&y0()==="hybrid"){let _0=await V();if(!v||I_(_0)){let s=x(),w0=j0.track({sessionId:H,url:F.url?.toString()??F.input.toString(),headers:G,bodyText:f,storage:_0,cacheMode:"hybrid",oauthAccountId:n});C?.mark("cachekeep_track",{session:H,ms:m(x()-s),tracked:w0.tracked,reason:w0.tracked?void 0:w0.reason,bodyBytes:f.length})}}let l=async()=>{try{let _0=await fetch(F.input,{...w,body:f,headers:G,...hD()&&{tls:{rejectUnauthorized:!1}}});if(typeof f==="string")await s0({affinity:H,route:R,status:_0.status,bodyText:f,url:F.url?.toString()??GD(F.input),method:VD(Y,w),headers:G});return _0}catch(_0){if(typeof f==="string")await s0({affinity:H,route:R,error:N_(_0),bodyText:f,url:F.url?.toString()??GD(F.input),method:VD(Y,w),headers:G});throw _0}},P0=JO(await V()),O0=x(),C0=await e_({config:P0,input:F.input,init:w,headers:G,body:f,fallback:l,affinity:H,optimisticResponse:P0?.transport==="websocket"});return C?.mark("send_headers_received",{route:R,ms:m(x()-O0),status:C0.status,relayConfigured:P0!=null,totalSendWithAccessMs:m(x()-K)}),C0}async function X1(Y){if(!Y)return!1;try{return await L.refreshMain(Y),AD(Y)}catch{return!1}}async function ND(Y,w={}){let S=await h.getUsableFallbackAccounts(Y,{modelId:w.modelId}),C=new Map(S.map((Z)=>[Z.id,Z])),R=[];for(let Z of Y?.accounts??[]){if($0(Z)){let n=C.get(Z.id);if(n)R.push(n);continue}if(w.includeApiRoutes===!0&&n0(Z)&&Z.enabled!==!1&&Z.apiKey&&zD(Z.baseURL))R.push(Z)}if(!r0(Y))return R;return R.filter((Z)=>$0(Z)?e0(H0(Z),Y,Z.id,w.modelId):!0)}async function jD(Y,w,S,C,R,Z,n){if(!S.length)return R??null;let K=n?.returnLastOnExhausted??!0;await R?.body?.cancel().catch(()=>{});let q=R??null;for(let[V,G]of S.entries()){let H;if(n0(G)){if(!G.apiKey)continue;H=await S0(Y,w,G,Z,`api_fallback_${V}`,C)}else{let f=G.access;if(!f)continue;H=await Q0(Y,w,f,Z,`fallback_${V}`,C,G.id)}q=H;let v=iD(H.status,C);if(!v){let f=await a(H,Z);H=f.response,q=H,v=f.rateLimited}if(!v){if(await h.markUsed(G),await n?.onSuccess?.(G),$0(G)&&G.access&&L.shouldRefreshOnRequestCount(G0))L.refreshFallback(G.id,G.access).then(()=>n?.onSuccess?.(G)).catch(()=>{});return H}if(V<S.length-1||!K)await H.body?.cancel().catch(()=>{})}return K?q:null}async function Y1(Y,w,S,C,R,Z,n,K,q){if(!B(Y,w?.body))return S;let V=x(),G=Z??await T(O);if(R?.mark("fallback_load_storage",{ms:m(x()-V),cached:!!Z}),!(G?.accounts??[]).some((Q)=>Q.enabled!==!1&&($0(Q)||n0(Q)&&Boolean(Q.apiKey)&&zD(Q.baseURL))))return S;let v=S,f=iD(v.status,G),D0=YO(v,!1);if(!f){let Q=await a(v,R);v=Q.response,f=Q.rateLimited,D0=YO(v,Q.rateLimited)}if(!f)return v;let k=!1;if(C)k=C.some(n0);else if(D0)k=await X1(n);let u=C;if(!u){let Q=x();u=await ND(G,{includeApiRoutes:k,modelId:q}),R?.mark("fallback_get_accounts",{ms:m(x()-Q),accounts:u.length})}if(r0(G)){let Q=u.length;if(u=u.filter((F)=>$0(F)?e0(H0(F),G,F.id,q):!0),u.length<Q)p("[killswitch] filtered fallbacks",{before:Q,after:u.length})}return await jD(Y,w,u,G,v,R,{onSuccess:K})??v}return{apiKey:"",async fetch(Y,w){let S=w?.body,C=KW({bodyBytes:typeof S==="string"?S.length:void 0}),R=x(),Z=await N();if(C.mark("get_auth",{ms:m(x()-R),authType:Z.type,hasAccess:Boolean(Z.access)}),Z.type!=="oauth"){let Q=await fetch(Y,w);return C.done("non_oauth_passthrough",{status:Q.status}),Q}await T0(Z.refresh);let n=x(),K=await T();C.mark("load_storage",{ms:m(x()-n)}),L.updateStorage(K),L.seedMainFromStorage(K,Z.access),L.seedFallbacksFromAccounts((K?.accounts??[]).filter($0));let q=B(Y,w?.body),V=U(w?.body);if(q)G0++;if(q&&Z.access&&(!Z.expires||Z.expires>Date.now()))Y0(K,Z.access);let G=(Q,F)=>W0(K,{activeId:Q,route:F,mainAccessToken:Z.access,mainRefreshToken:Z.refresh}),H;if(q&&fD(K)==="fallback-first")try{let Q=x();H=await ND(K,{includeApiRoutes:AD(Z.access),modelId:V}),C.mark("fallback_first_get_accounts",{ms:m(x()-Q),accounts:H.length});let F=await jD(Y,w,H,K,void 0,C,{returnLastOnExhausted:!1,onSuccess:(l)=>G(l.id,"fallback-first")});if(F)return C.done("return_fallback_first",{status:F.status}),d0(F,{perf:(l,P0)=>C.mark(l,P0)});H=void 0}catch(Q){C.mark("fallback_first_error",{error:Q instanceof Error?Q.message:String(Q)})}if(!Z.access||!Z.expires||Z.expires<Date.now()){let F=(await T())?.refresh?.mainLastRefreshError;if(Z.refresh&&F&&x0(F,Z.refresh,Date.now()))throw p("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:F.nextRetryAt,retryCount:F.retryCount,expiresInMs:Z.expires?Z.expires-Date.now():void 0}),Error(pD(F,Date.now()));p("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(Z.access),expiresInMs:Z.expires?Z.expires-Date.now():void 0,expiredAgoMs:Z.expires&&Z.expires<Date.now()?Date.now()-Z.expires:void 0});let l=x();Z.access=await P(),C.mark("refresh_main_access",{ms:m(x()-l)})}if(!Z.access)throw C.done("missing_access_error"),Error("OAuth access token is missing after refresh");function v(){if(K?.quota?.showToasts!==!0)return;let Q=L.getMain();if(!Q)return;let F=(K?.accounts??[]).filter((O0)=>O0.enabled!==!1&&$0(O0)).map((O0)=>({...O0,quota:L.getFallback(O0.id,O0.access)?.quota??O0.quota})),l=QD(Q.quota,K),P0;if(l)P0="main";else P0=F.find((O0)=>QD(O0.quota,K))?.id??"main";$1(Q.quota,F,P0)}if(q&&t(K))try{let Q=x(),F=L.getMain(Z.access),l=F?.quota;if(!l)l=await L.refreshMain(Z.access),F=L.getMain(Z.access),v();else if(L.needsRefresh(G0))if(RD(l)||lD(l,V))l=await L.refreshMain(Z.access),F=L.getMain(Z.access);else L.refreshMain(Z.access).then(()=>{F0().catch(()=>{}),v()}).catch(()=>{});W0(K,{activeId:"main",route:"main",mainAccessToken:Z.access,mainRefreshToken:Z.refresh});let P0=QD(l,K)&&H_(l,V);if(C.mark("main_quota_for_routing",{ms:m(x()-Q),passes:P0,model:V,modelScopedExhausted:lD(l,V)}),!P0){let O0=x();H=await ND(K,{includeApiRoutes:Boolean(F&&F.refreshAfter>Date.now()&&RD(F.quota)),modelId:V}),C.mark("preselect_fallback_accounts",{ms:m(x()-O0),accounts:H.length});let C0=await jD(Y,w,H,K,void 0,C,{onSuccess:(_0)=>G(_0.id,"fallback")});if(C0)return C.done("return_preselected_fallback",{status:C0.status}),d0(C0,{perf:(_0,s)=>C.mark(_0,s)})}}catch(Q){C.mark("main_quota_for_routing_error",{error:Q instanceof Error?Q.message:String(Q)})}let f=L.getMain(Z.access)?.quota;if(K?.quota?.failClosedOnUnknownQuota&&!f&&L.isBackedOff()){let Q=L.getLastApiError(),F=Q?Q_(Q,Date.now()):"Quota API unavailable";return p("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:Q?.nextRetryAt,retryCount:Q?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:F}}),{status:429,headers:{"content-type":"application/json","retry-after":String(Q?.nextRetryAt?Math.max(1,Math.ceil((Q.nextRetryAt-Date.now())/1000)):60)}})}if(r0(K)){if(L.needsRefresh(G0))try{let F=(K?.accounts??[]).filter((l)=>l.enabled!==!1&&$0(l)&&Boolean(l.access));await Promise.all([L.refreshMain(Z.access),L.refreshAllFallbacks(F)])}catch(F){p("[quota] killswitch refresh failed",{error:F instanceof Error?F.message:String(F),backedOff:L.isBackedOff()})}f=L.getMain(Z.access)?.quota}if(r0(K)&&!e0(f,K,void 0,V)){let F=B(Y,w?.body)?await ND(K,{includeApiRoutes:AD(Z.access),modelId:V}):[];if(F.length>0){p("[route] skipping main (killswitch), trying fallbacks");let s=await jD(Y,w,F,K,void 0,C,{onSuccess:(w0)=>G(w0.id,"fallback")});if(s)return C.done("return_killswitch_fallback",{status:s.status}),d0(s,{perf:(w0,SD)=>C.mark(w0,SD)})}let l=Date.now(),P0=(K?.accounts??[]).filter((s)=>s.enabled!==!1&&$0(s)).map((s)=>({...s,quota:H0(s)})),O0=ZW({mainQuota:f,requestModelId:V,storage:K}),C0=x_(f,P0,l,O0.isScopedDriven?O0.modelId:void 0),_0=YW({retryAfterSeconds:C0,...O0.isScopedDriven&&{modelName:O0.modelName}});return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:_0}}),{status:429,headers:{"content-type":"application/json","retry-after":String(C0)}})}let D0=await Q0(Y,w,Z.access,C,"main",K),k=!1,u=await Y1(Y,w,D0,H,C,K,Z.access,(Q)=>{k=!0,G(Q.id,"fallback")},V);if(!k)G("main","main");return C.done("return_response",{status:u.status}),d0(u,{perf:(Q,F)=>C.mark(Q,F)})}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let N=await KD("max");return{url:N.url,instructions:"Paste the authorization code here:",method:"code",callback:async(J)=>{return wD(J,N.verifier,N.redirectUri,N.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let N=await KD("console");return{url:N.url,instructions:"Paste the authorization code here:",method:"code",callback:async(J)=>{let X=await wD(J,N.verifier,N.redirectUri,N.state);if(X.type==="failed")return X;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${X.access}`}}).then((P)=>P.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{ZW as resolveScopedDrivenBlock,YW as formatKillswitchBlockMessage,lW as AnthropicAuthPlugin};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ab as k,Bb as l,Cb as m,qb as a,rb as b,sb as c,tb as d,ub as e,vb as f,wb as g,xb as h,yb as i,zb as j}from"./index-se4sd5kz.js";import"./index-1gc9eney.js";export{d as shouldEmit,b as setLogLevel,m as relayLog,h as redactPayload,a as parseLogLevel,k as logger,l as log,g as isSecretKey,c as getLogLevel,e as getLogFilePath,i as formatLogLine,j as __setLogTestSink,f as SECRET_KEY_EXACT};
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Pb as a,Qb as b}from"../index-ha0gz07d.js";import"../index-1gc9eney.js";export{a as writePortFile,b as discoverPortFile};
|
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Qb as l}from"../index-ha0gz07d.js";import"../index-1gc9eney.js";async function a(n,e,t,o){let r=await l(n,o);if(!r)return null;let i=new AbortController,p=setTimeout(()=>i.abort(),2000);try{let s=await fetch(`http://127.0.0.1:${r.port}/rpc/${e}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r.token}`},body:JSON.stringify(t),signal:i.signal});if(!s.ok)return null;return await s.json()}catch{return null}finally{clearTimeout(p)}}function u(n,e){return{async pending(t,o){return(await a(n,"pending-notifications",{lastReceivedId:t,sessionId:o},e))?.messages??[]},async apply(t){return await a(n,"apply",{...t},e)??{text:"apply failed",knobs:{}}}}}export{u as createRpcClient};
|
package/dist/rpc/rpc-dir.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Rb as a,Sb as b}from"../index-97vmbv5w.js";import"../index-1gc9eney.js";export{a as tmpdir,b as getRpcDir};
|
package/dist/sidebar-state.d.ts
CHANGED
|
@@ -3,9 +3,16 @@ export interface QuotaWindow {
|
|
|
3
3
|
remainingPercent: number;
|
|
4
4
|
resetsAt?: string;
|
|
5
5
|
}
|
|
6
|
+
export interface ScopedQuotaWindow extends QuotaWindow {
|
|
7
|
+
id: string;
|
|
8
|
+
title: string;
|
|
9
|
+
modelId?: string;
|
|
10
|
+
modelName: string;
|
|
11
|
+
}
|
|
6
12
|
export interface AccountQuota {
|
|
7
13
|
five_hour?: QuotaWindow;
|
|
8
14
|
seven_day?: QuotaWindow;
|
|
15
|
+
scoped?: ScopedQuotaWindow[];
|
|
9
16
|
}
|
|
10
17
|
export interface SidebarAccountState {
|
|
11
18
|
id: string;
|
|
@@ -48,9 +55,11 @@ export declare function resolveActiveAccount(state: SidebarState): {
|
|
|
48
55
|
name: string;
|
|
49
56
|
quota: AccountQuota | null;
|
|
50
57
|
};
|
|
58
|
+
export declare function formatScopedQuotaLabel(title: string): string;
|
|
51
59
|
export declare function getCollapsedQuotaSummary(quota: AccountQuota | null): {
|
|
52
60
|
fiveHourUsedPercent: number | null;
|
|
53
61
|
sevenDayUsedPercent: number | null;
|
|
62
|
+
scopedUsedPercents: number[];
|
|
54
63
|
text: string | null;
|
|
55
64
|
};
|
|
56
65
|
export declare const FIVE_HOUR_MS: number;
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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};
|
|
@@ -5,5 +5,11 @@ type ApplyFn = (command: OpenDialogPayload['command'], args: string) => Promise<
|
|
|
5
5
|
text: string;
|
|
6
6
|
knobs: Record<string, unknown>;
|
|
7
7
|
}>;
|
|
8
|
+
type KillswitchDialogConfig = {
|
|
9
|
+
enabled?: boolean;
|
|
10
|
+
main?: Record<string, number>;
|
|
11
|
+
accounts?: Record<string, Record<string, number>>;
|
|
12
|
+
};
|
|
13
|
+
export declare function buildKillswitchThresholdSeed(config: KillswitchDialogConfig, accountIds: string[]): string;
|
|
8
14
|
export declare function openCommandDialog(api: TuiPluginApi, payload: OpenDialogPayload, apply: ApplyFn): void;
|
|
9
15
|
export {};
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Tb as c,Ub as C,Vb as h}from"./index-1gc9eney.js";var m=C((v,k)=>{(function(Q){if(typeof k==="object"&&typeof k.exports==="object"){var J=Q(h,v);if(J!==void 0)k.exports=J}else if(typeof define==="function"&&define.amd)define(["require","exports","./impl/format","./impl/edit","./impl/scanner","./impl/parser"],Q)})(function(Q,J){Object.defineProperty(J,"__esModule",{value:!0}),J.applyEdits=J.modify=J.format=J.printParseErrorCode=J.ParseErrorCode=J.stripComments=J.visit=J.getNodeValue=J.getNodePath=J.findNodeAtOffset=J.findNodeAtLocation=J.parseTree=J.parse=J.getLocation=J.SyntaxKind=J.ScanError=J.createScanner=void 0;let X=Q("./impl/format"),Z=Q("./impl/edit"),$=Q("./impl/scanner"),G=Q("./impl/parser");J.createScanner=$.createScanner;var V;(function(z){z[z.None=0]="None",z[z.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=2]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",z[z.InvalidUnicode=4]="InvalidUnicode",z[z.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",z[z.InvalidCharacter=6]="InvalidCharacter"})(V||(J.ScanError=V={}));var Y;(function(z){z[z.OpenBraceToken=1]="OpenBraceToken",z[z.CloseBraceToken=2]="CloseBraceToken",z[z.OpenBracketToken=3]="OpenBracketToken",z[z.CloseBracketToken=4]="CloseBracketToken",z[z.CommaToken=5]="CommaToken",z[z.ColonToken=6]="ColonToken",z[z.NullKeyword=7]="NullKeyword",z[z.TrueKeyword=8]="TrueKeyword",z[z.FalseKeyword=9]="FalseKeyword",z[z.StringLiteral=10]="StringLiteral",z[z.NumericLiteral=11]="NumericLiteral",z[z.LineCommentTrivia=12]="LineCommentTrivia",z[z.BlockCommentTrivia=13]="BlockCommentTrivia",z[z.LineBreakTrivia=14]="LineBreakTrivia",z[z.Trivia=15]="Trivia",z[z.Unknown=16]="Unknown",z[z.EOF=17]="EOF"})(Y||(J.SyntaxKind=Y={})),J.getLocation=G.getLocation,J.parse=G.parse,J.parseTree=G.parseTree,J.findNodeAtLocation=G.findNodeAtLocation,J.findNodeAtOffset=G.findNodeAtOffset,J.getNodePath=G.getNodePath,J.getNodeValue=G.getNodeValue,J.visit=G.visit,J.stripComments=G.stripComments;var L;(function(z){z[z.InvalidSymbol=1]="InvalidSymbol",z[z.InvalidNumberFormat=2]="InvalidNumberFormat",z[z.PropertyNameExpected=3]="PropertyNameExpected",z[z.ValueExpected=4]="ValueExpected",z[z.ColonExpected=5]="ColonExpected",z[z.CommaExpected=6]="CommaExpected",z[z.CloseBraceExpected=7]="CloseBraceExpected",z[z.CloseBracketExpected=8]="CloseBracketExpected",z[z.EndOfFileExpected=9]="EndOfFileExpected",z[z.InvalidCommentToken=10]="InvalidCommentToken",z[z.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=12]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",z[z.InvalidUnicode=14]="InvalidUnicode",z[z.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",z[z.InvalidCharacter=16]="InvalidCharacter"})(L||(J.ParseErrorCode=L={}));function B(z){switch(z){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}J.printParseErrorCode=B;function j(z,H,N){return X.format(z,H,N)}J.format=j;function A(z,H,N,R){return Z.setProperty(z,H,N,R)}J.modify=A;function O(z,H){let N=H.slice(0).sort((U,D)=>{let T=U.offset-D.offset;if(T===0)return U.length-D.length;return T}),R=z.length;for(let U=N.length-1;U>=0;U--){let D=N[U];if(D.offset+D.length<=R)z=Z.applyEdit(z,D);else throw Error("Overlapping edit");R=D.offset}return z}J.applyEdits=O})});var q=c(m(),1);import{watch as y}from"node:fs";import{mkdir as S,readFile as w,rename as E,writeFile as p}from"node:fs/promises";import{homedir as l}from"node:os";import{basename as x,dirname as P,join as _}from"node:path";import{clearTimeout as F,setTimeout as f}from"node:timers";var i="OPENCODE_TUI_PREFERENCES_FILE",s="tui-preferences.jsonc";function b(){let Q=process.env[i];if(Q)return Q;let J=process.env.OPENCODE_CONFIG_DIR||_(process.env.XDG_CONFIG_HOME||_(l(),".config"),"opencode");return _(J,s)}function I(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}async function Vz(){try{let Q=await w(b(),"utf8"),J=[],X=q.parse(Q,J,{allowTrailingComma:!0});if(J.length>0)return{};return I(X)?X:{}}catch{return{}}}var d="anthropic-auth",n=160,u={forceToTop:!1,order:n,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"CLAUDE",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,cache:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function W(Q,J){return typeof Q==="boolean"?Q:J}function M(Q,J,X,Z){if(typeof Q!=="number"||!Number.isFinite(Q))return J;return Math.min(Math.max(Math.round(Q),X),Z)}function a(Q,J,X){if(typeof Q!=="string"||Q.length===0)return J;return Q.slice(0,X)}function K(Q,J){if(typeof Q!=="string")return J;return[...Q][0]??J}function Yz(Q){let J=Q[d];if(!I(J))return structuredClone(u);let X=u,Z=I(J.header)?J.header:{},$=I(J.sections)?J.sections:{},G=I(J.appearance)?J.appearance:{},V=M(G.warnThreshold,X.appearance.warnThreshold,0,99),Y=Math.max(M(G.errorThreshold,X.appearance.errorThreshold,0,100),Math.min(V+1,100));return{forceToTop:W(J.forceToTop,X.forceToTop),order:M(J.order,X.order,-1e4,1e4),startCollapsed:W(J.startCollapsed,X.startCollapsed),rememberCollapsed:W(J.rememberCollapsed,X.rememberCollapsed),collapsed:typeof J.collapsed==="boolean"?J.collapsed:null,pollMs:M(J.pollMs,X.pollMs,500,30000),refreshDebounceMs:M(J.refreshDebounceMs,X.refreshDebounceMs,50,5000),header:{label:a(Z.label,X.header.label,20),showVersion:W(Z.showVersion,X.header.showVersion)},sections:{quota:W($.quota,X.sections.quota),fallbackAccounts:W($.fallbackAccounts,X.sections.fallbackAccounts),routing:W($.routing,X.sections.routing),cache:W($.cache,X.sections.cache),health:W($.health,X.sections.health),pacing:W($.pacing,X.sections.pacing)},appearance:{barWidth:M(G.barWidth,X.appearance.barWidth,4,40),barFilledChar:K(G.barFilledChar,X.appearance.barFilledChar),barEmptyChar:K(G.barEmptyChar,X.appearance.barEmptyChar),warnThreshold:V,errorThreshold:Y}}}var t=-1e5;function Hz(Q,J,X){let Z=Q[J];if(!I(Z))return X;if(Z.forceToTop===!0)return t+Object.keys(Q).indexOf(J);return M(Z.order,X,-1e4,1e4)}var o=`// Shared preferences for opencode TUI plugins.
|
|
2
2
|
// One top-level key per plugin (short name). See each plugin's README for
|
|
3
3
|
// its supported settings. This file is safe to hand-edit; plugins update
|
|
4
4
|
// individual keys in place and preserve comments.
|
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
|
}
|