@cortexkit/opencode-anthropic-auth 1.10.2 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.d.ts +41 -0
- package/dist/cli.js +6 -6
- package/dist/index-7f07xr7k.js +2 -0
- package/dist/{index-p8j7mmfc.js → index-7hq52c3b.js} +1 -1
- package/dist/index-c1phnbjn.js +417 -0
- package/dist/index-srn1rawx.js +2 -0
- package/dist/index-vhcx8tx6.js +1 -0
- package/dist/index-zfddfgk2.js +4 -0
- package/dist/index.js +11 -10
- package/dist/logger-q4dnhr8x.js +1 -0
- package/dist/rpc/port-file.d.ts +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +2 -1
- package/dist/rpc/rpc-client.d.ts +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.d.ts +4 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/tui/command-dialogs.d.ts +1 -0
- package/dist/tui-preferences.js +2 -2
- package/package.json +4 -4
- package/src/rpc/port-file.ts +7 -1
- package/src/rpc/protocol.ts +3 -0
- package/src/rpc/rpc-client.ts +10 -3
- package/src/rpc/rpc-dir.ts +2 -2
- package/src/rpc/rpc-server.ts +5 -3
- package/src/sidebar-state.ts +99 -11
- package/src/tui/command-dialogs.tsx +478 -1
- package/src/tui-preferences.ts +57 -18
- package/src/tui.tsx +25 -14
- package/dist/index-3ynbghx3.js +0 -1
- package/dist/index-9yjbmhf1.js +0 -2
- package/dist/index-fvzta6xw.js +0 -410
- package/dist/index-jb14nj5c.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
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 Ib,h as Jb};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as z}from"node:crypto";import{homedir as F,tmpdir as O}from"node:os";import{join as q,resolve as G}from"node:path";var J="OPENCODE_ANTHROPIC_AUTH_RPC_DIR";function T(g){let k=process.env[J]?.trim();if(k)return G(g,k);let w=z("sha256").update(g).digest("hex").slice(0,16),x=process.env.XDG_STATE_HOME||q(F(),".local","state");return q(x,"cortexkit","anthropic-auth","rpc",w)}export{O as Kb,T as Lb};
|
|
@@ -0,0 +1,4 @@
|
|
|
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
|
+
`;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
|
+
${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 kb,L as lb,i as mb,X as nb,h as ob,T as pb,k as qb,G as rb,g as sb,E as tb,m as ub,o as vb,v as wb};
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
|
-
import{$ as
|
|
1
|
+
import{$ as L4,$a as g4,A as P4,Aa as I0,B as z1,Ba as R4,C as $4,Ca as o1,D as w1,Da as B1,E as O4,Ea as T4,F as G4,Fa as r1,G as N4,Ga as s0,H as V4,Ha as t1,I as X4,Ia as F1,J as b1,Ja as C1,K as Q1,Ka as E4,L as Z4,La as s1,M as K4,Ma as a1,N as f0,Na as S4,O as g1,Oa as e1,P as Y4,Pa as v4,Q as L1,Qa as WW,R as _4,Ra as bW,S as D4,Sa as a0,T as o0,Ta as A4,U as r0,Ua as k4,V as M1,Va as y4,W as I4,Wa as h4,X as m1,Xa as gW,Y as z4,Ya as mW,Z as w4,Za as b4,_ as Q4,_a as jW,a as xW,aa as p1,ab as m4,b as qW,ba as M4,bb as JW,c as m0,d as p0,da as U4,db as p4,e as RW,ea as i1,f as v0,fa as A0,fb as PW,g as tW,ga as k0,gb as H1,h as TW,ha as t0,hb as i4,i as EW,ia as B4,ib as d4,j as SW,ja as U1,jb as $W,k as sW,ka as vW,l as _1,la as AW,m as D1,ma as d1,n as N0,na as kW,o as l0,oa as yW,p as I1,pa as hW,q as eW,qa as l1,r as W4,ra as F4,s as Y0,sa as C4,t as T,ta as u1,ua as H4,v as u0,va as n1,w as j4,wa as f4,x as n0,xa as x4,y as c0,ya as c1,z as J4,za as q4}from"./index-c1phnbjn.js";import{lb as aW,ub as u,vb as p}from"./index-zfddfgk2.js";import{Bb as n4,xb as u4}from"./index-7f07xr7k.js";import{Ib as IW}from"./index-srn1rawx.js";import{Lb as l4}from"./index-vhcx8tx6.js";import"./index-7hq52c3b.js";import{randomUUID as h1}from"node:crypto";function S0(W){return typeof W==="object"&&W!==null}function jj(W){if(Array.isArray(W))return W;if(S0(W)&&Array.isArray(W.data))return W.data;return[]}function Jj(W){if(!S0(W)||!S0(W.info))return;return typeof W.info.role==="string"?W.info.role:void 0}function NW(W){if(!S0(W)||!S0(W.info))return null;let J=W.info,j=S0(J.model)?J.model:void 0,P=typeof J.agent==="string"?J.agent:void 0,O=typeof j?.providerID==="string"?j.providerID:typeof J.providerID==="string"?J.providerID:void 0,N=typeof j?.modelID==="string"?j.modelID:typeof J.modelID==="string"?J.modelID:void 0,D=typeof j?.variant==="string"?j.variant:typeof J.variant==="string"?J.variant:void 0;if(!P&&(!O||!N)&&!D)return null;let E={};if(P)E.agent=P;if(O&&N)E.model={providerID:O,modelID:N};if(D)E.variant=D;return E}function VW(W,J){return{agent:W.agent??J.agent,model:W.model??J.model,variant:W.variant??J.variant}}function XW(W){return Boolean(W.agent&&W.model&&W.variant)}async function ZW(W,J){if(!W||!J)return null;let j=W;if(typeof j.session?.messages!=="function")return null;let P=[];try{P=jj(await Promise.resolve(j.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(P.length===0)return null;let O={};for(let N=P.length-1;N>=0;N--){if(Jj(P[N])!=="assistant")continue;let D=NW(P[N]);if(!D)continue;if(O=VW(O,D),XW(O))return O}for(let N=P.length-1;N>=0;N--){let D=NW(P[N]);if(!D)continue;if(O=VW(O,D),XW(O))return O}if(!O.agent&&!O.model&&!O.variant)return null;return O}var U0=[],Pj=1,T1=0,KW=new Map;function YW(W,J){if(U0.push({id:Pj++,type:"open-dialog",payload:W,sessionId:J}),U0.length>100)U0=U0.slice(U0.length-100)}function _W(W=0,J){let j=Date.now();if(T1=j,J!==void 0)KW.set(J,j);let P=(O)=>J===void 0||O.sessionId===void 0||O.sessionId===J;if(W>0)U0=U0.filter((O)=>{if(O.id>W)return!0;if(J===void 0)return!1;return O.sessionId!==J});return U0.filter((O)=>O.id>W&&P(O))}function DW(W){let J=Date.now();if(W!==void 0){let j=KW.get(W)??0;return j>0&&J-j<3000}return T1>0&&J-T1<3000}import{randomBytes as $j,timingSafeEqual as Oj}from"node:crypto";import{unlink as Gj}from"node:fs/promises";import{createServer as Nj}from"node:http";import{join as Vj}from"node:path";function Xj(W){return new Promise((J,j)=>{let P=[],O=0;W.on("data",(N)=>{if(O+=N.length,O>1e6){W.destroy(),j(Error("body too large"));return}P.push(N)}),W.on("end",()=>J(Buffer.concat(P).toString("utf8"))),W.on("error",j)})}function Zj(W,J){if(!W?.startsWith("Bearer "))return!1;let j=Buffer.from(W.slice(7)),P=Buffer.from(J);return j.length===P.length&&Oj(j,P)}async function zW(W){let J=$j(32).toString("hex"),j=Nj((N,D)=>{P(N,D)});async function P(N,D){let E=(m,k)=>{D.writeHead(m,{"content-type":"application/json"}),D.end(JSON.stringify(k))};try{let m=N.url??"";if(N.method==="GET"&&m==="/health")return E(200,{ok:!0});if(N.method!=="POST"||!m.startsWith("/rpc/"))return E(404,{error:"not found"});if(!Zj(N.headers.authorization,J))return E(401,{error:"unauthorized"});let k=m.slice(5),M=JSON.parse(await Xj(N)||"{}");if(k==="pending-notifications"){let y=W.drain(Number(M.lastReceivedId??0),typeof M.sessionId==="string"?M.sessionId:void 0);return E(200,{messages:y})}if(k==="apply"){let y=await W.apply(M);return E(200,y)}return E(404,{error:"unknown method"})}catch(m){if(!D.headersSent&&!D.writableEnded&&!D.destroyed)E(500,{error:m instanceof Error?m.message:String(m)})}}let O=await new Promise((N,D)=>{j.on("error",D),j.listen(0,"127.0.0.1",()=>{let E=j.address();if(E&&typeof E==="object")N(E.port);else D(Error("no port"))})});j.unref();try{await IW(W.dir,{port:O,token:J,pid:process.pid})}catch(N){throw await new Promise((D)=>j.close(()=>D())),N}return{port:O,token:J,async stop(){await new Promise((N)=>j.close(()=>N())),await Gj(Vj(W.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function wW(W,J){let j=new Map,P=0,O=0,N=0,D=0,E=0,m=(y)=>{let s=performance.now(),P0=W(y);return E+=performance.now()-s,N++,P0};return{call:(y)=>{if(!J.enabled())return m(y);let s=j.get(y);if(s!==void 0)return O++,j.delete(y),j.set(y,s),s;let P0=m(y),z0=y.length+P0.length;if(z0>J.maxBytes)return P0;j.set(y,P0),P+=z0;while(P>J.maxBytes&&j.size>1){let n=j.keys().next().value,w0=j.get(n)??"";j.delete(n),P-=n.length+w0.length,D++}return P0},stats:()=>({hits:O,misses:N,evictions:D,entries:j.size,cacheBytes:P,computeMsTotal:E})}}function QW(W){return`${xW}${W.charAt(0).toUpperCase()}${W.slice(1)}`}function pW(W){if(W==="StructuredOutput")return W;return`${W.charAt(0).toLowerCase()}${W.slice(1)}`}var Kj=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function LW(W){let J=pW(W);if(J.startsWith("aft_"))return J;if(Kj.has(J))return`aft_${J}`;return null}function v1(W,J){let j=new Headers;if(W instanceof Request)W.headers.forEach((O,N)=>{j.set(N,O)});let P=J?.headers;if(P){if(P instanceof Headers)P.forEach((O,N)=>{j.set(N,O)});else if(Array.isArray(P))for(let O of P){let[N,D]=O;if(typeof D<"u")j.set(N,String(D))}else for(let[O,N]of Object.entries(P))if(typeof N<"u")j.set(O,String(N))}return j}function X1(W){return W.set("anthropic-beta",m0(W.get("anthropic-beta"),[qW])),W}function i0(W,J,j={}){return yW(W,J,j)}function Yj(W){if(W.tools&&Array.isArray(W.tools))W.tools=W.tools.map((J)=>({...J,name:J.name?QW(J.name):J.name}));if(W.messages&&Array.isArray(W.messages))W.messages=W.messages.map((J)=>{if(J.content&&Array.isArray(J.content))J.content=J.content.map((j)=>{if(j.type==="tool_use"&&j.name)return{...j,name:QW(j.name)};return j});return J});return JSON.stringify(hW(W))}function E1(W){return W.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(J,j,P)=>{if(j)return`"name": "${LW(P)??pW(P)}"`;let O=LW(P);return O?`"name": "${O}"`:J})}function MW(W,J=!1){if(J)return{ready:E1(W),pending:""};let j=W.length,P='"name"',O=Math.max(0,W.length-P.length+1);for(let D=O;D<W.length;D++)if(P.startsWith(W.slice(D))){j=Math.min(j,D);break}let N=W.lastIndexOf(P);if(N!==-1){let D=W.slice(N);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(D))j=Math.min(j,N)}if(j<W.length)return{ready:E1(W.slice(0,j)),pending:W.slice(j)};return{ready:E1(W),pending:""}}function A1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let W=process.env.ANTHROPIC_INSECURE?.trim();return W==="1"||W==="true"}function iW(W){let J=W?.trim();if(!J)return null;try{let j=new URL(J);if(j.protocol!=="http:"&&j.protocol!=="https:"||j.username||j.password)return null;return j}catch{return null}}function _j(){return iW(process.env.ANTHROPIC_BASE_URL)}function k1(W,J={}){let j=null;try{if(typeof W==="string"||W instanceof URL)j=new URL(W.toString());else if(W instanceof Request)j=new URL(W.url)}catch{j=null}if(!j)return{input:W,url:null};let P=j.href,O=J.baseURL?iW(J.baseURL):_j();if(O){if(j.protocol=O.protocol,j.host=O.host,J.baseURL)j.pathname=`${O.pathname.replace(/\/$/,"")}${j.pathname}`}if(j.pathname.endsWith("/v1/messages")&&!j.searchParams.has("beta"))j.searchParams.set("beta","true");if(j.href===P)return{input:W,url:j};return{input:W instanceof Request?new Request(j.toString(),W):j,url:j}}function Dj(W){let P=W.split(/\n\n+/).filter((O)=>{if(O.includes(RW))return!1;for(let N of EW)if(O.includes(N))return!1;return!0}).join(`
|
|
2
2
|
|
|
3
|
-
`);for(let
|
|
4
|
-
`);J.splice(
|
|
5
|
-
`),
|
|
3
|
+
`);for(let O of SW)P=P.replace(O.match,O.replacement);return P.trim()}var Ij=8388608;function zj(){return process.env.OPENCODE_ANTHROPIC_AUTH_MEMO!=="0"}var wj=wW(Dj,{maxBytes:Ij,enabled:zj});function O1(W){return wj.call(W)}function l(W){return W!=null&&typeof W==="object"&&!Array.isArray(W)}function Qj(W){let J={type:"text",text:v0};if(W==null)return[J];if(typeof W==="string"){let P=O1(W);if(P===v0)return[J];return[J,{type:"text",text:P}]}if(l(W)){let P=typeof W.type==="string"?W.type:"text",O=typeof W.text==="string"?W.text:"";return[J,{...W,type:P,text:O1(O)}]}if(!Array.isArray(W))return[J];let j=W.map((P)=>{if(typeof P==="string")return{type:"text",text:O1(P)};if(l(P)&&P.type==="text"&&typeof P.text==="string")return{...P,type:"text",text:O1(P.text)};return{type:"text",text:String(P)}});if(j[0]?.text===v0)return j;return[J,...j]}var dW={type:"ephemeral",ttl:"1h"},Lj=20;function Mj(W){if(l(W.cache_control))return W.cache_control;if(l(W.cacheControl))return W.cacheControl;return null}function g0(W,J){if(!l(W))return!1;return delete W.cacheControl,W.cache_control=J?{...dW}:{type:"ephemeral"},!0}function UW(W){if(!l(W))return;delete W.cache_control,delete W.cacheControl}function Uj(W){if(Array.isArray(W))return W;if(typeof W==="string")return[{type:"text",text:W}];return null}function G1(W,J){if(!l(W))return;let j=Mj(W);if(j?.type!=="ephemeral")return;if(J)j.ttl="1h";else delete j.ttl}function BW(W,J){if(Array.isArray(W.system))for(let j of W.system)G1(j,J);else G1(W.system,J);if(!Array.isArray(W.messages))return;for(let j of W.messages)if(G1(j,J),l(j)&&Array.isArray(j.content))for(let P of j.content)G1(P,J)}function Bj(W,J){if(Array.isArray(W.system))for(let j of W.system)J(j);else J(W.system);if(!Array.isArray(W.messages))return;for(let j of W.messages)if(J(j),l(j)&&Array.isArray(j.content))for(let P of j.content)J(P)}function lW(W){UW(W),Bj(W,UW)}function Fj(W){lW(W),W.cache_control={...dW}}function Cj(W){return l(W)&&W.type!=="thinking"&&W.type!=="redacted_thinking"}function Z1(W){let J=Uj(W.content);if(!J?.length)return;let j=J.filter(Cj);if(!j.length)return;return{content:J,cacheableBlocks:j}}function Hj(W){if(!l(W))return!1;let J=Z1(W);if(!J)return!1;return W.content=J.content,g0(J.cacheableBlocks[0],!0)}function fj(W){if(!l(W))return!1;let J=Z1(W);if(!J||J.cacheableBlocks.length<2)return!1;return W.content=J.content,g0(J.cacheableBlocks[1],!0)}function N1(W){if(!l(W))return!1;let J=Z1(W);if(!J)return!1;let j=J.cacheableBlocks[J.cacheableBlocks.length-1];return W.content=J.content,g0(j,!0)}function xj(W){if(!l(W))return!1;return(Z1(W)?.cacheableBlocks.length??0)>1}function qj(W){if(!l(W))return 0;let J=W.content;if(Array.isArray(J))return J.length;if(J==null)return 0;return 1}function Rj(W){let J=[],j=0;return W.forEach((P,O)=>{let N=qj(P);if(l(P)&&P.role==="user"&&N>0)J.push({index:O,blockPosition:j+N-1});j+=N}),J}function Tj(W){let J=Rj(W),j=[...J].reverse().find((D)=>D.index>1);if(!j)return{latest:void 0,bridge:void 0};let P=[...J].reverse().find((D)=>D.index<j.index),O=P?j.blockPosition-P.blockPosition+1:0,N=P&&P.index>1&&O>Lj?P:void 0;return{latest:j,bridge:N}}function S1(W){return l(W)&&typeof W.text==="string"?W.text:""}function Ej(W){if(!Array.isArray(W.system))return;let J=W.system,j=0;if(S1(J[j]).startsWith("x-anthropic-billing-header:"))j++;if(S1(J[j])===v0)j++;let P=j+1;if(P>=J.length-1)return;let O=J[P];if(!l(O))return;let N=J.slice(P).map(S1).join(`
|
|
4
|
+
`);J.splice(P,J.length-P,{...O,type:"text",text:N})}function FW(W){if(Array.isArray(W.system)){let J=W.system.findIndex((O)=>l(O)&&O.text===v0),j=W.system.slice(J>=0?J+1:0).filter(l),P=j[j.length-1];g0(P,!0)}else g0(W.system,!0)}function Sj(W){if(lW(W),Ej(W),!Array.isArray(W.messages)){FW(W);return}let{latest:J,bridge:j}=Tj(W.messages);if(!j)FW(W);if(xj(W.messages[0]))Hj(W.messages[0]),fj(W.messages[0]);else N1(W.messages[0]),N1(W.messages[1]);if(j)N1(W.messages[j.index]);if(J)N1(W.messages[J.index])}function vj(W){if(!Array.isArray(W.messages))return 0;let J=0;return W.messages=W.messages.filter((j)=>{if(!l(j)||!Array.isArray(j.content))return!0;if(j.role!=="assistant")return!0;let P=j.content.filter((O)=>{if(!l(O)||O.type!=="thinking")return!0;if(!mW(O.signature))return!0;return J+=1,!1});if(P.length===j.content.length)return!0;return j.content=P,P.length>0}),J}function Aj(W){if(!gW(W.model))return null;let J=Object.hasOwn(W,"thinking");return W.thinking={...bW},{replacedExisting:J}}function kj(W,J){if(!J.enabled){BW(W,!1),delete W.cache_control,delete W.cacheControl;return}if(J.mode==="automatic"){Fj(W);return}if(J.mode==="hybrid"){Sj(W);return}BW(W,!0),delete W.cacheControl}function yj(W){if(!Array.isArray(W.messages))return;while(W.messages.length){let J=W.messages[W.messages.length-1];if(!l(J)||J.role!=="assistant")break;W.messages.pop()}}function h(){return performance.now()}function X0(W){return Math.round(W*10)/10}function CW(W){let J=0,j=0,P=0,O=Array.isArray(W.messages)?W.messages:[];J=O.length;for(let N of O){if(!N||typeof N!=="object")continue;let D=N.content;if(!Array.isArray(D))continue;j+=D.length;for(let E of D)if(E&&typeof E==="object"&&E.type==="tool_use")P++}return{messageCount:J,contentBlockCount:j,toolDefinitionCount:Array.isArray(W.tools)?W.tools.length:0,toolUseCount:P,systemBlockCount:Array.isArray(W.system)?W.system.length:0}}async function y1(W,J={}){try{let j=h(),P=JSON.parse(W);J.perf?.("parse",{ms:X0(h()-j),inputBytes:W.length,...CW(P)});let O=h(),N=Array.isArray(P.messages)?P.messages.length:void 0;yj(P);let D=Array.isArray(P.messages)?P.messages.length:void 0;J.perf?.("strip_trailing_assistant",{ms:X0(h()-O),removedMessages:typeof N==="number"&&typeof D==="number"?N-D:void 0});let E=h(),m=vj(P),k=Aj(P);J.perf?.("model_normalize",{ms:X0(h()-E),model:typeof P.model==="string"?P.model:void 0,fableMythosThinkingDisplay:k?"summarized":void 0,replacedFableMythosThinking:k?.replacedExisting??!1,removedNonAnthropicThinking:m,hasOutputConfig:Object.hasOwn(P,"output_config")});let M=h(),y=Array.isArray(P.messages)&&P.messages.some((Z0)=>Z0.role==="user")?AW(P.messages,void 0,TW):null;J.perf?.("billing_header",{ms:X0(h()-M),hasBillingHeader:Boolean(y)});let s=h();if(P.system=Qj(P.system),J.perf?.("system_identity",{ms:X0(h()-s),systemBlockCount:Array.isArray(P.system)?P.system.length:0}),y&&Array.isArray(P.system))P.system.unshift({type:"text",text:y});let P0=h();if(kj(P,{enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.perf?.("cache_strategy",{ms:X0(h()-P0),enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.fastModeEnabled&&p0(P.model))P.speed="fast";else if(P.speed==="fast")delete P.speed;let z0=h();if(J.identity)kW(P,J.identity);J.perf?.("metadata",{ms:X0(h()-z0),hasAccountUuid:Boolean(J.identity?.accountUuid)});let n=h(),w0=Yj(P);J.perf?.("prefix_tools_stringify",{ms:X0(h()-n),outputBytesBeforeSign:w0.length,...CW(P)});let $0=h(),L0=await vW(w0);return J.perf?.("cch_sign",{ms:X0(h()-$0),outputBytes:L0.length}),L0}catch{return W}}var hj=new TextEncoder;function bj(){return{pending:"",events:0,parseErrors:0,eventCounts:{},typeCounts:{},deltaTypeCounts:{},contentBlockTypeCounts:{},textDeltaBytes:0,thinkingDeltaBytes:0,inputJsonDeltaBytes:0,signatureDeltaBytes:0,redactedThinkingBytes:0}}function V1(W,J){if(!J)return;W[J]=(W[J]??0)+1}function H0(W){return hj.encode(W).byteLength}function B0(W){return W&&typeof W==="object"&&!Array.isArray(W)?W:void 0}function O0(W,J){let j=W?.[J];return typeof j==="string"?j:void 0}function gj(W,J){let j=W?.[J];return typeof j==="number"?j:void 0}function mj(W){if(!W.trim())return null;let J,j=[];for(let y of W.split(/\r?\n/)){if(y.startsWith("event:")){J=y.slice(6).trim();continue}if(y.startsWith("data:")){let s=y.slice(5);j.push(s.startsWith(" ")?s.slice(1):s)}}let P=j.join(`
|
|
5
|
+
`),O={event:J,rawBytes:H0(W),dataBytes:H0(P)};if(!P||P==="[DONE]")return O.type=P==="[DONE]"?"done":void 0,O.event??=O.type,O;let N;try{N=JSON.parse(P)}catch{return O}let D=B0(N),E=B0(D?.delta),m=B0(D?.content_block),k=B0(D?.message),M=B0(D?.usage)??B0(k?.usage);if(O.type=O0(D,"type"),O.event??=O.type,O.index=gj(D,"index"),O.contentBlockType=O0(m,"type"),O.deltaType=O0(E,"type"),O.stopReason=O0(D,"stop_reason"),O.deltaType==="text_delta")O.textDeltaBytes=H0(O0(E,"text")??"");if(O.deltaType==="thinking_delta")O.thinkingDeltaBytes=H0(O0(E,"thinking")??"");if(O.deltaType==="input_json_delta")O.inputJsonDeltaBytes=H0(O0(E,"partial_json")??"");if(O.deltaType==="signature_delta")O.signatureDeltaBytes=H0(O0(E,"signature")??"");if(O.contentBlockType==="redacted_thinking")O.redactedThinkingBytes=H0(O0(m,"data")??"");if(M)O.stopReason??=O0(k,"stop_reason");return O}function uW(W){let J=W.indexOf(`
|
|
6
6
|
|
|
7
7
|
`),j=W.indexOf(`\r
|
|
8
8
|
\r
|
|
9
|
-
`);if(J===-1)return j===-1?null:{index:j,length:4};if(j===-1||J<j)return{index:J,length:2};return{index:j,length:4}}function
|
|
10
|
-
`);if(!$||$==="[DONE]")return null;let P;try{P=JSON.parse($)}catch{return null}let N=Y0(P);if(J!=="error"&&s(N,"type")!=="error")return null;let I=Y0(N?.error),H=s(I,"type")??s(I,"code")??void 0,k=s(I,"message")??s(N,"message")??H??"Anthropic stream error";if(!Yj(H,k))return null;return _j(H,k)}function KW(W,J){if(!J)return null;W.pending+=J;while(!0){let j=TW(W.pending);if(!j)break;let $=W.pending.slice(0,j.index);W.pending=W.pending.slice(j.index+j.length);let P=Dj($);if(P)return P}return null}function Ij(W){return{sseEvents:W.events,ssePendingChars:W.pending.length,sseParseErrors:W.parseErrors,sseEventCounts:{...W.eventCounts},sseTypeCounts:{...W.typeCounts},sseDeltaTypeCounts:{...W.deltaTypeCounts},sseContentBlockTypeCounts:{...W.contentBlockTypeCounts},sseTextDeltaBytes:W.textDeltaBytes,sseThinkingDeltaBytes:W.thinkingDeltaBytes,sseInputJsonDeltaBytes:W.inputJsonDeltaBytes,sseSignatureDeltaBytes:W.signatureDeltaBytes,sseRedactedThinkingBytes:W.redactedThinkingBytes,sseLastEvent:W.last?{...W.last}:void 0}}function y0(W,J={}){if(!W.body)return W;let j=W.body.getReader(),$=new TextDecoder,P=new TextEncoder,N="",I=0,H=0,k=0,b=0,m=0,S=!1,r=!1,d=v(),O0=v(),l=J.perf?Vj():void 0,j0=Kj(),N0=()=>{if(r)return;r=!0,j.releaseLock()},z0=(a={})=>({chunks:I,pulls:H,inputBytes:k,outputBytes:b,pendingChars:N.length,rewriteMs:P0(m),totalMs:P0(v()-O0),...l?Ij(l):{},...a}),J0=(a,T0={})=>{J.perf?.(a,z0(T0))};J.perf?.("stream_tool_prefix_wrapper_created",{status:W.status,hasBody:!0});let D1=new ReadableStream({async pull(a){if(H++,!S)S=!0,J0("stream_tool_prefix_first_pull");let T0=v();try{let{done:X0,value:w0}=await j.read(),E0=P0(v()-T0);if(X0){let O=$.decode();if(l)ZW(l,O);let G=KW(j0,O);if(G)throw J0("stream_tool_prefix_retryable_error",{error:G.message,providerErrorType:G.providerErrorType}),N0(),G;let Y=v(),L=OW(`${N}${O}`,!0);if(m+=v()-Y,L.ready){let K=P.encode(L.ready);b+=K.byteLength,a.enqueue(K)}J0("stream_tool_prefix_rewrite",{readMs:E0}),N0(),a.close();return}I++,k+=w0.byteLength;let Q0=$.decode(w0,{stream:!0});if(l)ZW(l,Q0);let L0=KW(j0,Q0);if(L0)throw J0("stream_tool_prefix_retryable_error",{error:L0.message,providerErrorType:L0.providerErrorType,readMs:E0,lastChunkBytes:w0.byteLength}),N0(),L0;let I1=N+Q0,M0=v(),U0=OW(I1);if(m+=v()-M0,N=U0.pending,U0.ready){let O=P.encode(U0.ready);b+=O.byteLength,a.enqueue(O)}let n0=v();if(I===1||I%25===0||n0-d>5000)d=n0,J0("stream_tool_prefix_progress",{readMs:E0,lastChunkBytes:w0.byteLength})}catch(X0){throw J0("stream_tool_prefix_error",{error:X0 instanceof Error?X0.message:String(X0)}),N0(),X0}},async cancel(a){J0("stream_tool_prefix_cancel",{reason:a instanceof Error?a.message:String(a)});try{await j.cancel(a)}finally{N0()}}});return new Response(D1,{status:W.status,statusText:W.statusText,headers:W.headers})}var wj="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",Qj=60000,Lj=60000,Mj=5000,EW=200,M4=240,Uj=M4,Bj=1,SW=!1;function _1(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function F(){return performance.now()}function h(W){return Math.round(W*10)/10}function vW(W){return Math.floor(Math.random()*Math.max(0,W))}function J1(W){if(typeof W==="string")return W;if(W instanceof URL)return W.toString();return W.url}function P1(W,J){return J?.method??(W instanceof Request?W.method:void 0)}function AW(W){return W instanceof Error?W.message:String(W)}function Fj(){if(SW||!1||!_1())return;SW=!0;let W=100,J=250,j=F()+W;setInterval(()=>{let $=F(),P=$-j;if(j=$+W,P<J)return;E("[perf] opencode event_loop_lag",{lagMs:h(P),thresholdMs:J})},W).unref?.()}function Cj(W){let J=F(),j={requestId:String(Bj++),start:J,last:J,mark($,P){let N=F();if(_1())E("[perf] opencode request stage",{requestId:j.requestId,stage:$,deltaMs:h(N-j.last),totalMs:h(N-j.start),...P});j.last=N},done($,P){let N=F();if(_1())E("[perf] opencode request done",{requestId:j.requestId,stage:$,deltaMs:h(N-j.last),totalMs:h(N-j.start),...P});j.last=N}};if(_1())E("[perf] opencode request start",{requestId:j.requestId,...W});return j}async function Hj(W,J,j){let $=W.client.session,P=await r1(W.client,J),N={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:j,ignored:!0}]}};if(P?.agent)N.body.agent=P.agent;if(P?.model)N.body.model=P.model;if(P?.variant)N.body.variant=P.variant;if(typeof $?.promptAsync==="function"){await $.promptAsync(N);return}if(typeof $?.prompt==="function"){await Promise.resolve($.prompt(N));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function fj(){throw Error(wj)}function xj(W){if(W.sessionID==null)return!1;let J=W.model;return J?.providerID==="anthropic"||J?.api?.npm==="@ai-sdk/anthropic"||J?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function qj(W){if(W.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return W.push(kW),!0}var Rj={input:0,output:0,cache:{read:0,write:0}};function Tj(W){let J=W["claude-opus-4-8"]??W["claude-opus-4-5"]??Object.values(W)[0];if(!J)return W;return{...W,...Object.fromEntries(Object.values(K4).map((j)=>[j.id,{...J,id:j.id,name:j.name,api:J.api?{...J.api,id:j.id}:void 0,cost:{input:u0.input,output:u0.output,cache:{read:u0.cacheRead,write:u0.cacheWrite5m}},limit:{...J.limit??{},context:V4,output:X4},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:Z4}]))}}function Ej(W){return Object.fromEntries(Object.entries(W).map(([J,j])=>[J,{...j,cost:Rj}]))}var ej=async(W)=>{Fj();let{client:J}=W,j=bW(),$=await A(j),P=new Y4({storage:$,onMainQuotaFetched:async(O,G,Y,L)=>{try{let K=await A(j)??{version:1,accounts:[]},T=oW(K);if(T&&T.checkedAt>=L&&sW(T.quota,K,T.checkedAt)>Date.now()){P.seedMainFromStorage(K);return}K.quota=K.quota??{},K.quota.mainQuota=O,K.quota.mainQuotaCheckedAt=G,K.quota.mainQuotaToken=Y,K.quota.mainLastQuotaApiError=void 0,await b0(K,j,{mainQuota:!0})}catch(K){E("[quota] failed to persist main quota",{error:K instanceof Error?K.message:String(K)})}},onApiError:async(O)=>{try{let G=await A(j)??{version:1,accounts:[]};G.quota=G.quota??{},G.quota.mainLastQuotaApiError=O,await b0(G,j,{mainQuota:!0})}catch(G){E("[quota] failed to persist backoff state",{error:G instanceof Error?G.message:String(G)})}}}),N=new aW({quotaManager:P,onFallbackStorageChanged:()=>{S()}});N.startBackgroundRefresh();let I=null,H=new $4({loadStorage:()=>A(j),prepareHeaders:async(O,G)=>{if(!d)return O;let Y=await d();if(Y.type!=="oauth")return O;if(!Y.access||Y.expires&&Y.expires<Date.now()){if(!I)return O;Y.access=await I()}if(!Y.access)return O;try{let L=JSON.parse(G.bodyText),K=await S1(Y.access,typeof L.model==="string"?L.model:void 0);if(O.delete("anthropic-beta"),k0(O,Y.access,{body:L,identity:K}),O.set("anthropic-beta",v0(O.get("anthropic-beta"),[W4])),L.speed==="fast")W1(O)}catch{k0(O,Y.access)}return O},log:E});d0({enabled:g0($),mode:m0($)}),X1($1($)),K1(O1($));let k=null;if(W.directory){let O=globalThis;if(O.__anthropicAuthRpcServer)await O.__anthropicAuthRpcServer.stop().catch(()=>{}),O.__anthropicAuthRpcServer=void 0;try{k=await jW({dir:Q4(W.directory),drain:a1,apply:L0}),O.__anthropicAuthRpcServer=k}catch(G){E("[rpc] failed to start",{error:G instanceof Error?G.message:String(G)})}}let b={activeId:"main",route:"main"};function m(O,G){b={activeId:G.activeId,route:G.route},P.updateStorage(O),P.seedMainFromStorage(O,G.mainAccessToken),P.seedFallbacksFromAccounts((O?.accounts??[]).filter(W0));let Y=P.getMain(G.mainAccessToken),L=P.getLastApiError(),K=O?.refresh?.mainLastRefreshError,T={main:{quota:Y?.quota??null,quotaBackedOff:P.isBackedOff(),quotaBackoffUntil:L?.nextRetryAt,refreshBackedOff:K?x0(K,G.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:K?.nextRetryAt},fallbacks:(O?.accounts??[]).filter((f)=>f.enabled!==!1&&W0(f)).map((f)=>({id:f.id,label:f.label,quota:f.access?P.getFallback(f.id,f.access)?.quota??null:null,enabled:f.enabled!==!1})),activeId:G.activeId,route:G.route,relay:(()=>{let f=i1(O);return f?{enabled:!0,transport:f.transport??"http"}:null})(),fastMode:Z1(),cacheKeep:{enabled:k1(O),window:O?.cacheKeep?.startHour!=null&&O?.cacheKeep?.endHour!=null?`${O.cacheKeep.startHour}-${O.cacheKeep.endHour}`:void 0,trackedSessions:H.trackedCount()},lastUpdated:Date.now()};L4(T).catch((f)=>E("[sidebar] state write failed",{error:f instanceof Error?f.message:String(f)}))}async function S(){let O=await A(j),G,Y;if(d)try{let L=await d();G=L.access,Y=L.refresh}catch{}m(O,{activeId:b.activeId,route:b.route,mainAccessToken:G,mainRefreshToken:Y})}function r(O,G){if(!G)return;if(O?.quota?.enabled!==!0)return;if(P.getMain(G))return;if(O0)return;O0=!0,P.refreshMain(G).then(()=>S()).catch(()=>{}).finally(()=>{O0=!1})}let d=null,O0=!1,l=null,j0=0;function N0(O){let G=O?.refresh?.refreshBeforeExpiryMinutes??Uj;return Math.max(M4,G)*60000}function z0(O){return O?.refresh?.enabled!==!1}async function J0(O){if(!O)return;let G=await A(j),Y=G?.refresh?.mainLastRefreshError;if(!G?.refresh||!Y?.tokenHash)return;let L=G1(O);if(Y.tokenHash===L)return;if(Y.nextRetryAt&&Y.nextRetryAt>Date.now()){E("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:Y.nextRetryAt,retryCount:Y.retryCount,remainingMs:Y.nextRetryAt-Date.now()});return}G.refresh.mainLastRefreshError=void 0,await b0(G,j,{mainRefresh:!0}),E("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:Y.checkedAt,previousNextRetryAt:Y.nextRetryAt,previousRetryCount:Y.retryCount})}async function D1(){let O=[];if(d)try{let K=await d();if(K.type==="oauth"&&K.access){let T=await P.refreshMain(K.access);O.push({name:"OpenCode anthropic",role:"main",quota:T})}else if(K.type==="oauth")O.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(K){let T=K instanceof Error?K.message:String(K);O.push({name:"OpenCode anthropic",role:"main",error:T.includes("429")?"Usage API rate limited — try again in a moment":T})}let{storage:G,errors:Y}=await N.refreshQuotaForAllAccounts({force:!0}),L=new Map(Y.map((K)=>[K.accountId,K.message]));if(O.push(..._4(G,L)),!d)O.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return D4({accounts:O,refreshedAt:Date.now()})}async function a(O){let G=eW(O);if(G.type==="enable"||G.type==="disable"){let T=G.type==="enable",f=await mW(T),y=m0(f);return d0({enabled:T,mode:y}),V1({argumentsText:O,enabled:T,mode:y})}if(G.type==="mode"){let T=await pW(G.mode),f=g0(T);return d0({enabled:f,mode:G.mode}),V1({argumentsText:O,enabled:f,mode:G.mode})}let Y=await A(j),L=g0(Y),K=m0(Y);return d0({enabled:L,mode:K}),V1({argumentsText:O,enabled:L,mode:K})}async function T0(O){let G=j4(O),Y=await A(j);if(G.type==="window")Y=await lW(G.startHour,G.endHour);else if(G.type==="disable")Y=await uW(!1);let L=A1(Y),K=H.stats(L);return P4({argumentsText:O,enabled:J4(Y),window:L,hybridActive:k1(Y),trackedSessions:K.trackedSessions,nextPrewarmAt:K.nextPrewarmAt})}async function X0(O){let G=O4(O);if(G.type==="enable"||G.type==="disable"){let K=G.type==="enable";return await iW(K),X1(K),h1({argumentsText:O,enabled:K})}let Y=await A(j),L=$1(Y);return X1(L),h1({argumentsText:O,enabled:L})}async function w0(O){let G=G4(O);if(G.type==="enable"||G.type==="disable"){let K=G.type==="enable";return await dW(K),K1(K),g1({argumentsText:O,enabled:K})}let Y=await A(j),L=O1(Y);return K1(L),g1({argumentsText:O,enabled:L})}async function E0(O){let G=w4(O);if(G.type==="mode")return await z4(G.mode),l1({argumentsText:O,mode:G.mode});let Y=await A();return l1({argumentsText:O,mode:Y1(Y)})}async function Q0(O,G){if(O==="claude-quota")return{command:O,text:await D1(),knobs:{}};if(O==="claude-routing"){let f=await E0(G),y=await A(j);return{command:O,text:f,knobs:{mode:Y1(y)}}}if(O==="claude-fast"){let f=await w0(G),y=await A(j);return{command:O,text:f,knobs:{enabled:O1(y)}}}if(O==="claude-dump"){let f=await X0(G),y=await A(j);return{command:O,text:f,knobs:{enabled:$1(y)}}}if(O==="claude-cache"){let f=await a(G),y=await A(j);return{command:O,text:f,knobs:{enabled:g0(y),mode:m0(y)}}}if(O==="claude-cachekeep"){let f=await T0(G),y=await A(j);return{command:O,text:f,knobs:{window:A1(y)}}}let Y=await A(),L=T1(Y),K=(Y?.accounts??[]).filter((f)=>f.enabled!==!1).map((f)=>f.id),T=N4({argumentsText:G,config:L,accountIds:K});if(T.updatedConfig)await tW(T.updatedConfig);return{command:O,text:T.text,knobs:{config:T1(await A()),accountIds:K}}}async function L0(O){let G=await Q0(O.command,O.arguments);return{text:G.text,knobs:G.knobs}}function I1(O,G=10){let Y=Math.max(0,Math.min(Math.round(O/100*G),G));return"█".repeat(Y)+"░".repeat(G-Y)}function M0(O,G){return`${O} ${I1(G)} ${String(Math.round(G)).padStart(3)}%`}function U0(O){if(!O)return"";let G=new Date(O).getTime();if(Number.isNaN(G))return"";let Y=G-Date.now();if(Y<=0)return"resets now";let L=Math.floor(Y/60000);if(L<1)return"resets <1m";if(L<60)return`resets ${L}m`;let K=Math.floor(L/60),T=L%60;return T>0?`resets ${K}h${T}m`:`resets ${K}h`}function n0(O,G,Y){let L=[],K=0;if(O){let{five_hour:y,seven_day:$0}=O;if(y||$0){let V0=Y==="main"?"active":"idle",_0=U0(y?.resetsAt),B0=[`main · ${V0}${_0?` (${_0})`:""}`];if(y)B0.push(M0("5h",y.usedPercent)),K=Math.max(K,y.usedPercent);if($0)B0.push(M0("7d",$0.usedPercent)),K=Math.max(K,$0.usedPercent);L.push(B0.join(`
|
|
11
|
-
|
|
12
|
-
`))}if(
|
|
9
|
+
`);if(J===-1)return j===-1?null:{index:j,length:4};if(j===-1||J<j)return{index:J,length:2};return{index:j,length:4}}function HW(W,J){if(!J)return;W.pending+=J;while(!0){let j=uW(W.pending);if(!j)break;let P=W.pending.slice(0,j.index);W.pending=W.pending.slice(j.index+j.length);let O=mj(P);if(!O)continue;if(W.events++,V1(W.eventCounts,O.event??"unknown"),V1(W.typeCounts,O.type),V1(W.deltaTypeCounts,O.deltaType),V1(W.contentBlockTypeCounts,O.contentBlockType),W.textDeltaBytes+=O.textDeltaBytes??0,W.thinkingDeltaBytes+=O.thinkingDeltaBytes??0,W.inputJsonDeltaBytes+=O.inputJsonDeltaBytes??0,W.signatureDeltaBytes+=O.signatureDeltaBytes??0,W.redactedThinkingBytes+=O.redactedThinkingBytes??0,W.last=O,O.dataBytes>0&&!O.type&&!O.event)W.parseErrors++}}function pj(){return{pending:""}}function ij(W,J){let j=W?.toLowerCase(),P=J.toLowerCase();return j==="api_error"||j==="overloaded_error"||j==="server_error"||j==="internal_server_error"||P.includes("internal server error")||P.includes("server overloaded")}function dj(W,J){let j=W?`${W}: ${J}`:J,P=Error(`Anthropic stream error: ${j}`);if(P.code="ECONNRESET",P.syscall="anthropic-sse",W)P.providerErrorType=W;return P}function lj(W){if(!W.includes("error"))return null;let J,j=[];for(let k of W.split(/\r?\n/)){if(k.startsWith("event:")){J=k.slice(6).trim();continue}if(k.startsWith("data:")){let M=k.slice(5);j.push(M.startsWith(" ")?M.slice(1):M)}}let P=j.join(`
|
|
10
|
+
`);if(!P||P==="[DONE]")return null;let O;try{O=JSON.parse(P)}catch{return null}let N=B0(O);if(J!=="error"&&O0(N,"type")!=="error")return null;let D=B0(N?.error),E=O0(D,"type")??O0(D,"code")??void 0,m=O0(D,"message")??O0(N,"message")??E??"Anthropic stream error";if(!ij(E,m))return null;return dj(E,m)}function fW(W,J){if(!J)return null;W.pending+=J;while(!0){let j=uW(W.pending);if(!j)break;let P=W.pending.slice(0,j.index);W.pending=W.pending.slice(j.index+j.length);let O=lj(P);if(O)return O}return null}function uj(W){return{sseEvents:W.events,ssePendingChars:W.pending.length,sseParseErrors:W.parseErrors,sseEventCounts:{...W.eventCounts},sseTypeCounts:{...W.typeCounts},sseDeltaTypeCounts:{...W.deltaTypeCounts},sseContentBlockTypeCounts:{...W.contentBlockTypeCounts},sseTextDeltaBytes:W.textDeltaBytes,sseThinkingDeltaBytes:W.thinkingDeltaBytes,sseInputJsonDeltaBytes:W.inputJsonDeltaBytes,sseSignatureDeltaBytes:W.signatureDeltaBytes,sseRedactedThinkingBytes:W.redactedThinkingBytes,sseLastEvent:W.last?{...W.last}:void 0}}function d0(W,J={}){if(!W.body)return W;let j=W.body.getReader(),P=new TextDecoder,O=new TextEncoder,N="",D=0,E=0,m=0,k=0,M=0,y=!1,s=!1,P0=h(),z0=h(),n=J.perf?bj():void 0,w0=pj(),$0=()=>{if(s)return;s=!0,j.releaseLock()},L0=(j0={})=>({chunks:D,pulls:E,inputBytes:m,outputBytes:k,pendingChars:N.length,rewriteMs:X0(M),totalMs:X0(h()-z0),...n?uj(n):{},...j0}),Z0=(j0,_0={})=>{J.perf?.(j0,L0(_0))};J.perf?.("stream_tool_prefix_wrapper_created",{status:W.status,hasBody:!0});let W0=new ReadableStream({async pull(j0){if(E++,!y)y=!0,Z0("stream_tool_prefix_first_pull");let _0=h();try{let{done:K0,value:x0}=await j.read(),y0=X0(h()-_0);if(K0){let M0=P.decode();if(n)HW(n,M0);let T0=fW(w0,M0);if(T0)throw Z0("stream_tool_prefix_retryable_error",{error:T0.message,providerErrorType:T0.providerErrorType}),$0(),T0;let q1=h(),j1=MW(`${N}${M0}`,!0);if(M+=h()-q1,j1.ready){let b0=O.encode(j1.ready);k+=b0.byteLength,j0.enqueue(b0)}Z0("stream_tool_prefix_rewrite",{readMs:y0}),$0(),j0.close();return}D++,m+=x0.byteLength;let q0=P.decode(x0,{stream:!0});if(n)HW(n,q0);let R0=fW(w0,q0);if(R0)throw Z0("stream_tool_prefix_retryable_error",{error:R0.message,providerErrorType:R0.providerErrorType,readMs:y0,lastChunkBytes:x0.byteLength}),$0(),R0;let e0=N+q0,x1=h(),h0=MW(e0);if(M+=h()-x1,N=h0.pending,h0.ready){let M0=O.encode(h0.ready);k+=M0.byteLength,j0.enqueue(M0)}let W1=h();if(D===1||D%25===0||W1-P0>5000)P0=W1,Z0("stream_tool_prefix_progress",{readMs:y0,lastChunkBytes:x0.byteLength})}catch(K0){throw Z0("stream_tool_prefix_error",{error:K0 instanceof Error?K0.message:String(K0)}),$0(),K0}},async cancel(j0){Z0("stream_tool_prefix_cancel",{reason:j0 instanceof Error?j0.message:String(j0)});try{await j.cancel(j0)}finally{$0()}}});return new Response(W0,{status:W.status,statusText:W.statusText,headers:W.headers})}var nj="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",cj=60000,oj=60000,rj=5000,nW=200,c4=240,tj=c4,sj=1,cW=!1;function f1(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function f(){return performance.now()}function g(W){return Math.round(W*10)/10}function oW(W){return Math.floor(Math.random()*Math.max(0,W))}function K1(W){if(typeof W==="string")return W;if(W instanceof URL)return W.toString();return W.url}function Y1(W,J){return J?.method??(W instanceof Request?W.method:void 0)}function rW(W){return W instanceof Error?W.message:String(W)}function aj(){if(cW||!1||!f1())return;cW=!0;let W=100,J=250,j=f()+W;setInterval(()=>{let P=f(),O=P-j;if(j=P+W,O<J)return;p("[perf] opencode event_loop_lag",{lagMs:g(O),thresholdMs:J})},W).unref?.()}function ej(W){let J=f(),j={requestId:String(sj++),start:J,last:J,mark(P,O){let N=f();if(f1())p("[perf] opencode request stage",{requestId:j.requestId,stage:P,deltaMs:g(N-j.last),totalMs:g(N-j.start),...O});j.last=N},done(P,O){let N=f();if(f1())p("[perf] opencode request done",{requestId:j.requestId,stage:P,deltaMs:g(N-j.last),totalMs:g(N-j.start),...O});j.last=N}};if(f1())p("[perf] opencode request start",{requestId:j.requestId,...W});return j}async function WJ(W,J,j){let P=W.client.session,O=await ZW(W.client,J),N={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:j,ignored:!0}]}};if(O?.agent)N.body.agent=O.agent;if(O?.model)N.body.model=O.model;if(O?.variant)N.body.variant=O.variant;if(typeof P?.promptAsync==="function"){await P.promptAsync(N);return}if(typeof P?.prompt==="function"){await Promise.resolve(P.prompt(N));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function jJ(){throw Error(nj)}function JJ(W){if(W.sessionID==null)return!1;let J=W.model;return J?.providerID==="anthropic"||J?.api?.npm==="@ai-sdk/anthropic"||J?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function PJ(W){if(W.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return W.push(tW),!0}var $J={input:0,output:0,cache:{read:0,write:0}};function OJ(W){let J=W["claude-opus-4-8"]??W["claude-opus-4-5"]??Object.values(W)[0];if(!J)return W;return{...W,...Object.fromEntries(Object.values(h4).map((j)=>[j.id,{...J,id:j.id,name:j.name,api:J.api?{...J.api,id:j.id}:void 0,cost:{input:a0.input,output:a0.output,cache:{read:a0.cacheRead,write:a0.cacheWrite5m}},limit:{...J.limit??{},context:A4,output:k4},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:y4}]))}}function GJ(W){return Object.fromEntries(Object.entries(W).map(([J,j])=>[J,{...j,cost:$J}]))}var qJ=async(W)=>{aj();let{client:J}=W,j=W4(),P=600000,O=50,N=new Map;function D(){let $=Date.now();for(let[G,X]of N)if($-X.createdAt>P)N.delete(G)}function E($,G){if(D(),N.size>=O){let X="",w=1/0;for(let[V,A]of N)if(A.createdAt<w)w=A.createdAt,X=V;if(X)N.delete(X)}N.set($,G)}function m($){D();let G=N.get($);if(!G)return;if(Date.now()-G.createdAt>P){N.delete($);return}return G}let k;try{k=await T(j)}catch($){let G=$ instanceof Error?$.message:String($);throw Error(`Failed to load account store: ${G}`,{cause:$ instanceof Error?$:void 0})}let M=new b4({storage:k,onMainQuotaFetched:async($,G,X,w)=>{try{let V=await T(j)??Y0(),A=D4(V);if(A&&A.checkedAt>=w&&M4(A.quota,V,A.checkedAt)>Date.now()){M.seedMainFromStorage(V);return}V.quota=V.quota??{},V.quota.mainQuota=$,V.quota.mainQuotaCheckedAt=G,V.quota.mainQuotaToken=X,V.quota.mainLastQuotaApiError=void 0,await u0(V,j,{mainQuota:!0})}catch(V){u.warn("quota","failed to persist main quota",{error:V instanceof Error?V.message:String(V)})}},onApiError:async($)=>{try{let G=await T(j)??Y0();G.quota=G.quota??{},G.quota.mainLastQuotaApiError=$,await u0(G,j,{mainQuota:!0})}catch(G){u.warn("quota","failed to persist backoff state",{error:G instanceof Error?G.message:String(G)})}}}),y=new U4({quotaManager:M,onFallbackStorageChanged:()=>{L0().catch(()=>{})}});y.startBackgroundRefresh();let s=null,P0=new x4({loadStorage:()=>T(j),prepareHeaders:async($,G)=>{if(!W0)return $;let X=await W0();if(X.type!=="oauth")return $;if(!X.access||X.expires&&X.expires<Date.now()){if(!s)return $;X.access=await s()}if(!X.access)return $;try{let w=JSON.parse(G.bodyText),V=await d1(X.access,typeof w.model==="string"?w.model:void 0);if($.delete("anthropic-beta"),i0($,X.access,{body:w,identity:V}),$.set("anthropic-beta",m0($.get("anthropic-beta"),[F4])),w.speed==="fast")X1($)}catch{i0($,X.access)}return $}});if(t0({enabled:n0(k),mode:c0(k)}),B1(z1(k)),C1(w1(k)),!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)aW(L1(k)??"info");let z0=null;if(W.directory){let $=globalThis;if($.__anthropicAuthRpcServer)await $.__anthropicAuthRpcServer.stop().catch(()=>{}),$.__anthropicAuthRpcServer=void 0;try{z0=await zW({dir:l4(W.directory),drain:_W,apply:o4}),$.__anthropicAuthRpcServer=z0}catch(G){u.warn("rpc","failed to start",{error:G instanceof Error?G.message:String(G)})}}let n={activeId:"main",route:"main"},w0=u4();function $0($,G){n={activeId:G.activeId,route:G.route},M.updateStorage($),M.seedMainFromStorage($,G.mainAccessToken),M.seedFallbacksFromAccounts(($?.accounts??[]).filter(N0));let X=M.getMain(G.mainAccessToken),w=M.getLastApiError(),V=$?.refresh?.mainLastRefreshError,A={main:{quota:X?.quota??null,quotaBackedOff:M.isBackedOff(),quotaBackoffUntil:w?.nextRetryAt,refreshBackedOff:V?f0(V,G.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:V?.nextRetryAt},fallbacks:($?.accounts??[]).filter((x)=>x.enabled!==!1&&N0(x)).map((x)=>({id:x.id,label:x.label,quota:x.access?M.getFallback(x.id,x.access)?.quota??null:null,needsReauth:x.lastRefreshError!=null&&f0(x.lastRefreshError,x.refresh,Date.now())&&K4(x.lastRefreshError),enabled:x.enabled!==!1})),activeId:G.activeId,route:G.route,relay:(()=>{let x=JW($);return x?{enabled:!0,transport:x.transport??"http"}:null})(),fastMode:F1(),cacheKeep:{enabled:n1($),window:$?.cacheKeep?.startHour!=null&&$?.cacheKeep?.endHour!=null?`${$.cacheKeep.startHour}-${$.cacheKeep.endHour}`:void 0,trackedSessions:P0.trackedCount()},lastUpdated:Date.now()};return n4(A,w0).catch((x)=>u.warn("sidebar","state write failed",{error:x instanceof Error?x.message:String(x)}))}async function L0(){let $=await T(j),G,X;if(W0)try{let w=await W0();G=w.access,X=w.refresh}catch{}$0($,{activeId:n.activeId,route:n.route,mainAccessToken:G,mainRefreshToken:X})}function Z0($,G){if(!G)return;if($?.quota?.enabled!==!0)return;if(M.getMain(G))return;if(j0)return;j0=!0,M.refreshMain(G).then(()=>L0()).catch(()=>{}).finally(()=>{j0=!1})}let W0=null,j0=!1,_0=null,K0=0;function x0($){let G=$?.refresh?.refreshBeforeExpiryMinutes??tj;return Math.max(c4,G)*60000}function y0($){return $?.refresh?.enabled!==!1}async function q0($){if(!$)return;let G=await T(j),X=G?.refresh?.mainLastRefreshError;if(!G?.refresh||!X?.tokenHash)return;let w=Q1($);if(X.tokenHash===w)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}G.refresh.mainLastRefreshError=void 0,await u0(G,j,{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 $=[];if(W0)try{let V=await W0();if(V.type==="oauth"&&V.access){let A=await M.refreshMain(V.access);$.push({name:"OpenCode anthropic",role:"main",quota:A})}else if(V.type==="oauth")$.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(V){let A=V instanceof Error?V.message:String(V);$.push({name:"OpenCode anthropic",role:"main",error:A.includes("429")?"Usage API rate limited — try again in a moment":A})}let{storage:G,errors:X}=await y.refreshQuotaForAllAccounts({force:!0}),w=new Map(X.map((V)=>[V.accountId,V.message]));if($.push(...g4(G,w)),!W0)$.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return m4({accounts:$,refreshedAt:Date.now()})}async function e0($){if(W0)try{let G=await W0();$0($,{activeId:n.activeId,route:n.route,mainAccessToken:G.access,mainRefreshToken:G.refresh})}catch{}}async function x1($){let G=B4($);if(G.type==="enable"||G.type==="disable"){let A=G.type==="enable",x=await J4(A),B=c0(x);return t0({enabled:A,mode:B}),u.info("commands","cache enabled changed",{enabled:A}),U1({argumentsText:$,enabled:A,mode:B})}if(G.type==="mode"){let A=await P4(G.mode),x=n0(A);return t0({enabled:x,mode:G.mode}),u.info("commands","cache mode changed",{mode:G.mode}),U1({argumentsText:$,enabled:x,mode:G.mode})}let X=await T(j),w=n0(X),V=c0(X);return t0({enabled:w,mode:V}),U1({argumentsText:$,enabled:w,mode:V})}async function h0($){let G=C4($),X=await T(j);if(G.type==="window")X=await G4(G.startHour,G.endHour),u.info("commands","cachekeep enabled changed",{enabled:!0});else if(G.type==="disable")X=await N4(!1),u.info("commands","cachekeep enabled changed",{enabled:!1});else if(G.type==="subagents")X=await X4(G.enabled),u.info("commands","cachekeep subagents changed",{subagents:G.enabled});let w=u1(X),V=P0.stats(w);return f4({argumentsText:$,enabled:H4(X),window:w,hybridActive:n1(X),trackedSessions:V.trackedSessions,nextPrewarmAt:V.nextPrewarmAt})}async function W1($){let G=T4($);if(G.type==="enable"||G.type==="disable"){let V=G.type==="enable";return await $4(V),B1(V),u.info("commands","dump changed",{enabled:V}),r1({argumentsText:$,enabled:V})}let X=await T(j),w=z1(X);return B1(w),r1({argumentsText:$,enabled:w})}async function M0($){let G=E4($);if(G.type==="enable"||G.type==="disable"){let V=G.type==="enable";return await O4(V),C1(V),u.info("commands","fast mode changed",{enabled:V}),s1({argumentsText:$,enabled:V})}let X=await T(j),w=w1(X);return C1(w),s1({argumentsText:$,enabled:w})}async function T0($){let G=d4($);if(G.type==="mode")return await i4(G.mode),u.info("commands","routing mode changed",{mode:G.mode}),$W({argumentsText:$,mode:G.mode});let X=await T();return $W({argumentsText:$,mode:H1(X)})}async function q1($){let G=v4($);if(G.type==="level")return await _4(G.level),u.info("commands","log level changed",{level:G.level}),WW({argumentsText:$,level:G.level});let X=await T(j),w=L1(X)??"info";return WW({argumentsText:$,level:w})}async function j1($,G){let X=q4($);if(X.type==="add-apikey"){if(!X.apiKey)return{text:"API key is required",accounts:I0(await T(j)??Y0())};let B=X.label?.trim()||void 0,F=Date.now(),b=X.baseURL?.trim()||"https://api.kie.ai/claude";if(!I1(b))return{text:"Invalid base URL. Must be an http(s) URL without embedded credentials.",accounts:I0(await T(j)??Y0())};let c=X.authHeader??"authorization-bearer",o={id:B||h1(),label:B||void 0,type:"api",apiKey:X.apiKey,baseURL:b,authHeader:c,enabled:!0,addedAt:F,lastUsed:F};await p1(o,j),u.info("commands","account added",{id:o.id,label:o.label,type:"apikey"});let V0=await T(j);await e0(V0);let F0=I0(V0??{version:1,accounts:[]});return{text:`API key account "${o.label??o.id}" added.`,accounts:F0}}if(X.type==="add-oauth-start"){let B=await _1("max"),F={state:B.state,verifier:B.verifier,redirectUri:B.redirectUri,createdAt:Date.now()};return E(G??"default",F),{text:`Open this URL in your browser:
|
|
11
|
+
${B.url}`,knobs:{oauthUrl:B.url},accounts:I0(await T(j)??Y0())}}if(X.type==="add-oauth-finish"){let B=G??"default",F=m(B);if(!F)return{text:"OAuth session expired. Please start again.",accounts:I0(await T(j)??Y0())};try{let b=await D1(X.code,F.verifier,F.redirectUri,F.state);if(b.type==="failed")return{text:"OAuth authentication failed. Please check the code and try again.",accounts:I0(await T(j)??Y0())};let c=Date.now(),o={id:h1(),type:"oauth",label:X.label||void 0,access:b.access,refresh:b.refresh,expires:b.expires,enabled:!0,addedAt:c,lastUsed:c};await p1(o,j),u.info("commands","account added",{id:o.id,label:o.label,type:"oauth"});let V0=await T(j);return await e0(V0),{text:"OAuth account added.",accounts:I0(V0??Y0())}}catch{return{text:"OAuth exchange failed due to a network error. Please try again.",accounts:I0(await T(j)??Y0())}}finally{N.delete(B)}}let w=await T(j),V=R4({argumentsText:$,storage:w??{version:1,accounts:[]}});if(V.updated){if(V.updated.action==="enable"||V.updated.action==="disable"){let F=V.updated.action==="enable";await L4(V.updated.id,F,j);let b=V.updated.id,c=w?.accounts.find((o)=>o.id===b);u.info("commands",`account ${V.updated.action}d`,{id:b,label:c?.label,enabled:F})}else if(V.updated.action==="remove"){await w4(V.updated.id,j);let F=V.updated.id,b=w?.accounts.find((c)=>c.id===F);u.info("commands","account removed",{id:F,label:b?.label})}else if(V.updated.action==="reorder"){await Q4(V.updated.newOrder??V.updated.previousOrder??[],j);let F=V.updated.id,b=w?.accounts.find((c)=>c.id===F);u.info("commands","account reordered",{id:F,label:b?.label})}let B=await T(j);if(W0)try{let F=await W0();$0(B,{activeId:n.activeId,route:n.route,mainAccessToken:F.access,mainRefreshToken:F.refresh})}catch{}}let A=await T(j),x=I0(A??{version:1,accounts:[]});return{text:V.text,accounts:x}}async function b0($,G,X){if($==="claude-quota")return{command:$,text:await R0(),knobs:{}};if($==="claude-logging"){let B=await q1(G),F=await T(j);return{command:$,text:B,knobs:{level:L1(F)??"info"}}}if($==="claude-account"){let B=await j1(G,X),F={accounts:B.accounts};if("knobs"in B&&B.knobs)Object.assign(F,B.knobs);return{command:$,text:B.text,knobs:F}}if($==="claude-routing"){let B=await T0(G),F=await T(j);return{command:$,text:B,knobs:{mode:H1(F)}}}if($==="claude-fast"){let B=await M0(G),F=await T(j);return{command:$,text:B,knobs:{enabled:w1(F)}}}if($==="claude-dump"){let B=await W1(G),F=await T(j);return{command:$,text:B,knobs:{enabled:z1(F)}}}if($==="claude-cache"){let B=await x1(G),F=await T(j);return{command:$,text:B,knobs:{enabled:n0(F),mode:c0(F)}}}if($==="claude-cachekeep"){let B=await h0(G),F=await T(j);return{command:$,text:B,knobs:{window:u1(F)}}}let w=await T(),V=m1(w),A=(w?.accounts??[]).filter((B)=>B.enabled!==!1).map((B)=>B.id),x=S4({argumentsText:G,config:V,accountIds:A});if(x.updatedConfig){if(await z4(x.updatedConfig),V.enabled!==x.updatedConfig.enabled)u.info("commands","killswitch changed",{enabled:x.updatedConfig.enabled===!0});if(JSON.stringify(V.main)!==JSON.stringify(x.updatedConfig.main)||JSON.stringify(V.accounts)!==JSON.stringify(x.updatedConfig.accounts))u.info("commands","killswitch thresholds changed",{thresholds:x.updatedConfig.main??x.updatedConfig.accounts})}return{command:$,text:x.text,knobs:{config:m1(await T()),accountIds:A}}}async function o4($){let G=await b0($.command,$.arguments,$.sessionId);return{text:G.text,knobs:G.knobs}}function r4($,G=10){let X=Math.max(0,Math.min(Math.round($/100*G),G));return"█".repeat(X)+"░".repeat(G-X)}function J1($,G){return`${$} ${r4(G)} ${String(Math.round(G)).padStart(3)}%`}function OW($){if(!$)return"";let G=new Date($).getTime();if(Number.isNaN(G))return"";let X=G-Date.now();if(X<=0)return"resets now";let w=Math.floor(X/60000);if(w<1)return"resets <1m";if(w<60)return`resets ${w}m`;let V=Math.floor(w/60),A=w%60;return A>0?`resets ${V}h${A}m`:`resets ${V}h`}function t4($,G,X){let w=[],V=0;if($){let{five_hour:B,seven_day:F}=$;if(B||F){let c=X==="main"?"active":"idle",o=OW(B?.resetsAt),V0=[`main · ${c}${o?` (${o})`:""}`];if(B)V0.push(J1("5h",B.usedPercent)),V=Math.max(V,B.usedPercent);if(F)V0.push(J1("7d",F.usedPercent)),V=Math.max(V,F.usedPercent);w.push(V0.join(`
|
|
12
|
+
`))}}if(G?.length)for(let B of G){let F=B.quota;if(!F)continue;let{five_hour:b,seven_day:c}=F;if(!b&&!c)continue;let o=B.label||"alt",F0=X===B.id?"active":"idle",Q0=OW(b?.resetsAt),C0=[`${o} · ${F0}${Q0?` (${Q0})`:""}`];if(b)C0.push(J1("5h",b.usedPercent)),V=Math.max(V,b.usedPercent);if(c)C0.push(J1("7d",c.usedPercent)),V=Math.max(V,c.usedPercent);w.push(C0.join(`
|
|
13
|
+
`))}if(!w.length)return;let A=w.join(`
|
|
13
14
|
|
|
14
|
-
`),
|
|
15
|
+
`),x=V>=90?"error":V>=70?"warning":"info";J.tui?.showToast?.({body:{title:"Claude Quota",message:A,variant:x,duration:x==="error"?8000:5000}})?.catch?.(()=>{})}return{config:async($)=>{$.command={...$.command??{},[i1]:{template:i1,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[c1]:{template:c1,description:"Manage fallback accounts — list, enable/disable, reorder, remove, or add (API key or OAuth)."},[l1]:{template:l1,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[jW]:{template:jW,description:"Show current Claude OAuth quota usage for all accounts."},[o1]:{template:o1,description:"Show or toggle Anthropic request dump capture for debugging."},[t1]:{template:t1,description:"Show or toggle Anthropic fast mode for supported Opus models."},[e1]:{template:e1,description:"Show or set the plugin log level (error, warn, info, debug, trace)."},[PW]:{template:PW,description:"Show or change Claude account routing between main-first and fallback-first."},[a1]:{template:a1,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."}}},"experimental.chat.system.transform":async($,G)=>{if(!JJ($))return;PJ(G.system)},provider:{id:"anthropic",async models($,G){let X=OJ($.models);if(G.auth?.type!=="oauth"||!eW(k??{}))return X;return GJ(X)}},"command.execute.before":async($)=>{if(!["claude-account","claude-cache","claude-cachekeep","claude-quota","claude-dump","claude-fast","claude-routing","claude-killswitch","claude-logging"].includes($.command))return;let X=$.command,w=await b0(X,$.arguments,$.sessionID);if(X==="claude-quota"){let V=await T(),A=W0?await W0().catch(()=>{return}):void 0;$0(V,{activeId:"main",route:"main",mainAccessToken:A?.access,mainRefreshToken:A?.refresh})}if(DW($.sessionID))YW(w,$.sessionID);else await WJ(W,$.sessionID,w.text);jJ()},auth:{provider:"anthropic",async loader($,G){W0=$;let X=await $();if(X.type==="oauth"){let A=function(){if(_0)clearInterval(_0),_0=null;let K=async()=>{try{let I=await T(j);if(!y0(I))return;let S=await $();if(S.type!=="oauth")return;if(await q0(S.refresh),!S.expires)return;let Q=S.expires-Date.now(),R=x0(I);if(Q>R)return;if(p("[refresh] opencode main oauth background due",{expiresInMs:Q,refreshBeforeMs:R}),S.refresh&&f0(I?.refresh?.mainLastRefreshError,S.refresh,Date.now())){p("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:I?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:I?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:Q});return}if(S.refresh&&I?.refresh?.mainRefreshLeaseUntil&&I.refresh.mainRefreshLeaseUntil>Date.now()&&I.refresh.mainRefreshLeaseTokenHash===Q1(S.refresh))return;await V();let Y=await $();p("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:Y.expires?Y.expires-Date.now():void 0})}catch(I){u.warn("refresh","opencode main oauth refresh failed",{message:I instanceof Error?I.message:String(I)})}};if(_0=setInterval(()=>{K()},cj+oW(oj)),"unref"in _0)_0.unref()},x=function(K,I){if(K instanceof Request&&K.body)return!1;return I==null||typeof I==="string"},B=function(K){return K.has("x-parent-session-id")},F=function(K){return K.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(K)},b=function(K){return K?.quota?.enabled===!0},o=function(K,I){if(K.delete("authorization"),K.delete("x-api-key"),I.authHeader==="x-api-key")K.set("x-api-key",I.apiKey??"");else K.set("Authorization",`Bearer ${I.apiKey??""}`);K.set("Content-Type","application/json")},Q0=function(K){return M.getFallback(K.id,K.access)?.quota??K.quota},C0=function(K){return Object.values(K??{}).some((I)=>I&&I.remainingPercent<=0)},GW=function(K,I){return K.status===429||I},R1=function(K){if(!K)return!1;let I=M.getMain(K);return Boolean(I&&I.refreshAfter>Date.now()&&C0(I.quota))},w=null;async function V(){if(!w)w=(async()=>{let S=null,Q=null,R=null;async function Y(_){let v=await T(j)??Y0();v.refresh=v.refresh??{},_(v),await u0(v,j,{mainRefresh:!0})}async function d(_){let v=Date.now()+rj;while(Date.now()<v){await new Promise((H)=>setTimeout(H,nW+oW(nW)));let Z=await $();if(Z.type!=="oauth"||!Z.access)continue;if((Z.access!==_.access||Z.refresh!==_.refresh||(Z.expires??0)>(_.expires??0)+60000)&&(!Z.expires||Z.expires>Date.now()))return p("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:Z.expires?Z.expires-Date.now():void 0}),Z.access}return null}for(let _=0;_<=2;_++){let v=null;try{if(_>0){let q=500*2**(_-1);await new Promise((L)=>setTimeout(L,q))}if(v=await $(),!v.refresh)throw Error("Token refresh failed: missing refresh token");let Z=await T(j),z=Q1(v.refresh),H=Z?.refresh?.mainLastRefreshError;if(p("[refresh] opencode main oauth refresh check",{attempt:_,expiresInMs:v.expires?v.expires-Date.now():void 0,hasBackoff:Boolean(H),backoffActive:H?f0(H,v.refresh,Date.now()):!1,retryCount:H?.retryCount,nextRetryAt:H?.nextRetryAt}),H&&f0(H,v.refresh,Date.now()))throw p("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:H.nextRetryAt,retryCount:H.retryCount}),Error(g1(H,Date.now()));if(Z?.refresh?.mainRefreshLeaseUntil&&Z.refresh.mainRefreshLeaseUntil>Date.now()&&Z.refresh.mainRefreshLeaseTokenHash===z){p("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:Z.refresh.mainRefreshLeaseUntil});let q=await d(v);if(q)return q;throw Error("Claude OAuth refresh is already in progress")}let U=await j4({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!U){p("[refresh] opencode main oauth refresh skipped file lock");let q=await d(v);if(q)return q;throw Error("Claude OAuth refresh is already in progress")}R=U.release,S=h1(),Q=z,await Y((q)=>{q.refresh=q.refresh??{},q.refresh.mainRefreshLeaseId=S??void 0,q.refresh.mainRefreshLeaseUntil=Date.now()+120000,q.refresh.mainRefreshLeaseTokenHash=z});let a=await T(j);if(p("[refresh] opencode main oauth refresh lease acquired",{attempt:_,leaseUntil:Date.now()+120000}),a?.refresh?.mainRefreshLeaseId!==S||a.refresh.mainRefreshLeaseTokenHash!==z)throw Error("Claude OAuth refresh is already in progress");p("[refresh] opencode main oauth refresh request start",{attempt:_});let r=await sW({refreshToken:v.refresh,maxRetries:0});return await J.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:r.refresh,access:r.access,expires:r.expires}}),await Y((q)=>{if(!q?.refresh)return;if(q.refresh.mainLastRefreshError=void 0,q.refresh.mainRefreshLeaseId===S)q.refresh.mainRefreshLeaseId=void 0,q.refresh.mainRefreshLeaseUntil=void 0,q.refresh.mainRefreshLeaseTokenHash=void 0}),p("[refresh] opencode main oauth refresh succeeded",{attempt:_,expiresInMs:r.expires-Date.now()}),r.access}catch(Z){let z=Z instanceof Error&&(Z.message.includes("fetch failed")||("code"in Z)&&(Z.code==="ECONNRESET"||Z.code==="ECONNREFUSED"||Z.code==="ETIMEDOUT"||Z.code==="UND_ERR_CONNECT_TIMEOUT"));if(_<2&&(z||(()=>{let U=Z.status;return typeof U==="number"&&U>=500})()))continue;p("[refresh] opencode main oauth refresh attempt failed",{attempt:_,error:Z instanceof Error?Z.message:String(Z),transient:z});let H=v?.refresh;if(H&&Z.isRefreshError)await Y((U)=>{U.refresh=U.refresh??{},U.refresh.mainLastRefreshError=Z4({error:Z,now:Date.now(),refreshToken:H,previous:U.refresh.mainLastRefreshError})});throw Z}finally{if(S)await Y((Z)=>{if(!Z?.refresh)return;if(Z.refresh.mainRefreshLeaseId===S&&Z.refresh.mainRefreshLeaseTokenHash===Q)Z.refresh.mainRefreshLeaseId=void 0,Z.refresh.mainRefreshLeaseUntil=void 0,Z.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await R?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{w=null});return w}s=V,A(),M.seedFallbacksFromAccounts((k?.accounts??[]).filter(N0)),$0(k,{activeId:"main",route:"main",mainAccessToken:X.access,mainRefreshToken:X.refresh});async function c(K,I){if(!K.body||K.status!==200)return I?.mark("inspect_stream_skip",{status:K.status}),{response:K,rateLimited:!1};if(K.headers.get("x-cortexkit-relay-optimistic")==="true")return I?.mark("inspect_stream_skip",{status:K.status,reason:"optimistic_relay"}),{response:K,rateLimited:!1};let S=f(),Q=K.body.getReader(),R=[],Y=new TextDecoder,d="",_=0;while(!d.includes(`
|
|
15
16
|
|
|
16
|
-
`)&&p.length<65536){let{done:V,value:z}=await w.read();if(V)break;if(x.push(z),_+=z.byteLength,p+=Z.decode(z,{stream:!0}),$0(p))break}if($0(p)){await w.cancel().catch(()=>{});try{w.releaseLock()}catch{}let V=new ReadableStream({start(z){for(let B of x)z.enqueue(B);z.close()}});return D?.mark("inspect_stream_first_event",{ms:h(F()-q),bytes:_,rateLimited:!0}),{response:new Response(V,{status:X.status,statusText:X.statusText,headers:X.headers}),rateLimited:!0}}let R=new ReadableStream({start(V){for(let z of x)V.enqueue(z)},async pull(V){let{done:z,value:B}=await w.read();if(z){V.close();return}V.enqueue(B)},cancel(V){return w.cancel(V)}});return D?.mark("inspect_stream_first_event",{ms:h(F()-q),bytes:_,rateLimited:!1}),{response:new Response(R,{status:X.status,statusText:X.statusText,headers:X.headers}),rateLimited:!1}}async function B0(X,D,q,w,x="api_fallback",Z){let p=F(),_=M1(X,D),R=_.get("x-session-affinity")||_.get("x-opencode-session"),V=y(_);_.delete("x-parent-session-id"),_.delete("x-session-affinity"),_.delete("x-opencode-session");let z=D?.body,B=typeof z==="string"?z.length:void 0;if(z&&typeof z==="string"){let C=F(),Q=(()=>{if(!Z1())return!1;try{return A0(JSON.parse(z).model)}catch{return!1}})();if(z=await F1(z,{cache1hEnabled:!V&&q0(),cache1hMode:R0(),fastModeEnabled:Q,perf:(U,g)=>w?.mark(`rewrite_body_${U}`,{route:x,...g})}),_0(_,q),_.set("anthropic-beta",v0(_.get("anthropic-beta"),[])),Q)W1(_);w?.mark("rewrite_body",{route:x,ms:h(F()-C),originalBytes:B,rewrittenBytes:z.length,cacheEnabled:!V&&q0(),cacheMode:R0(),fastModeEnabled:Q,subagent:V})}else _0(_,q);let M=B1(X,{baseURL:q.baseURL}),c=F(),u;try{u=await fetch(M.input,{...D,body:z,headers:_,...U1()&&{tls:{rejectUnauthorized:!1}}})}catch(C){if(typeof z==="string")await l0({affinity:R,route:x,error:AW(C),bodyText:z,url:M.url?.toString()??J1(M.input),method:P1(X,D),headers:_});throw C}if(typeof z==="string")await l0({affinity:R,route:x,status:u.status,bodyText:z,url:M.url?.toString()??J1(M.input),method:P1(X,D),headers:_});return w?.mark("send_headers_received",{route:x,ms:h(F()-c),status:u.status,relayConfigured:!1,totalSendWithAccessMs:h(F()-p),baseURL:q.baseURL}),u}async function c0(X,D,q,w,x="unknown",Z){let p=F(),_=Z,R=async()=>{return _??=await A(j),_},V=M1(X,D),z=V.get("x-session-affinity")||V.get("x-opencode-session"),B=y(V);V.delete("x-parent-session-id"),V.delete("x-session-affinity"),V.delete("x-opencode-session");let M=D?.body,c;if(M&&typeof M==="string"){let o=F();try{let G0=JSON.parse(M);if(typeof G0.model==="string")c=G0.model}catch{}w?.mark("model_parse_for_identity",{route:x,ms:h(F()-o),bodyBytes:M.length})}let u=F(),C=await S1(q,c);w?.mark("resolve_claude_code_identity",{route:x,ms:h(F()-u),hasAccountUuid:Boolean(C.accountUuid)});let Q=typeof M==="string"?M.length:void 0;if(M&&typeof M==="string"){let o=F(),G0=(()=>{if(!Z1())return!1;try{return A0(JSON.parse(M).model)}catch{return!1}})();M=await F1(M,{cache1hEnabled:!B&&q0(),cache1hMode:R0(),fastModeEnabled:G0,identity:C,perf:(F4,C4)=>w?.mark(`rewrite_body_${F4}`,{route:x,...C4})});let C0=F();try{k0(V,q,{body:JSON.parse(M),identity:C}),w?.mark("set_oauth_headers_body_parse",{route:x,ms:h(F()-C0),bodyBytes:M.length,parsed:!0})}catch{k0(V,q,{identity:C}),w?.mark("set_oauth_headers_body_parse",{route:x,ms:h(F()-C0),bodyBytes:M.length,parsed:!1})}if(G0)W1(V);w?.mark("rewrite_body",{route:x,ms:h(F()-o),originalBytes:Q,rewrittenBytes:M.length,cacheEnabled:!B&&q0(),cacheMode:R0(),fastModeEnabled:G0,subagent:B})}let U=B1(X);if(x==="main"&&typeof M==="string"&&!B&&q0()&&R0()==="hybrid"){let o=await R(),G0=F(),C0=H.track({sessionId:z,url:U.url?.toString()??U.input.toString(),headers:V,bodyText:M,storage:o,cacheMode:"hybrid"});w?.mark("cachekeep_track",{session:z,ms:h(F()-G0),tracked:C0.tracked,reason:C0.tracked?void 0:C0.reason,bodyBytes:M.length})}let g=async()=>{try{let o=await fetch(U.input,{...D,body:M,headers:V,...U1()&&{tls:{rejectUnauthorized:!1}}});if(typeof M==="string")await l0({affinity:z,route:x,status:o.status,bodyText:M,url:U.url?.toString()??J1(U.input),method:P1(X,D),headers:V});return o}catch(o){if(typeof M==="string")await l0({affinity:z,route:x,error:AW(o),bodyText:M,url:U.url?.toString()??J1(U.input),method:P1(X,D),headers:V});throw o}},e=i1(await R()),n=F(),t=await I4({config:e,input:U.input,init:D,headers:V,body:M,fallback:g,affinity:z,optimisticResponse:e?.transport==="websocket"});return w?.mark("send_headers_received",{route:x,ms:h(F()-n),status:t.status,relayConfigured:e!=null,totalSendWithAccessMs:h(F()-p)}),t}async function U4(X){if(!X)return!1;try{return await P.refreshMain(X),z1(X)}catch{return!1}}async function o0(X,D={}){let q=await N.getUsableFallbackAccounts(X),w=new Map(q.map((Z)=>[Z.id,Z])),x=[];for(let Z of X?.accounts??[]){if(W0(Z)){let p=w.get(Z.id);if(p)x.push(p);continue}if(D.includeApiRoutes===!0&&h0(Z)&&Z.enabled!==!1&&Z.apiKey&&x1(Z.baseURL))x.push(Z)}if(!i0(X))return x;return x.filter((Z)=>W0(Z)?N1(F0(Z),X,Z.id):!0)}async function r0(X,D,q,w,x,Z,p){if(!q.length)return x??null;let _=p?.returnLastOnExhausted??!0;await x?.body?.cancel().catch(()=>{});let R=x??null;for(let[V,z]of q.entries()){let B;if(h0(z)){if(!z.apiKey)continue;B=await B0(X,D,z,Z,`api_fallback_${V}`,w)}else{let c=z.access;if(!c)continue;B=await c0(X,D,c,Z,`fallback_${V}`,w)}R=B;let M=q1(B.status,w);if(!M){let c=await V0(B,Z);B=c.response,R=B,M=c.rateLimited}if(!M){if(await N.markUsed(z),p?.onSuccess?.(z),W0(z)&&z.access&&P.shouldRefreshOnRequestCount(j0))P.refreshFallback(z.id,z.access).then(()=>p?.onSuccess?.(z)).catch(()=>{});return B}if(V<q.length-1||!_)await B.body?.cancel().catch(()=>{})}return _?R:null}async function B4(X,D,q,w,x,Z,p,_){if(!f(X,D?.body))return q;let R=F(),V=Z??await A(j);if(x?.mark("fallback_load_storage",{ms:h(F()-R),cached:!!Z}),!(V?.accounts??[]).some((Q)=>Q.enabled!==!1&&(W0(Q)||h0(Q)&&Boolean(Q.apiKey)&&x1(Q.baseURL))))return q;let B=q,M=q1(B.status,V),c=u1(B,!1);if(!M){let Q=await V0(B,x);B=Q.response,M=Q.rateLimited,c=u1(B,Q.rateLimited)}if(!M)return B;let u=!1;if(w)u=w.some(h0);else if(c)u=await U4(p);let C=w;if(!C){let Q=F();C=await o0(V,{includeApiRoutes:u}),x?.mark("fallback_get_accounts",{ms:h(F()-Q),accounts:C.length})}if(i0(V)){let Q=C.length;if(C=C.filter((U)=>W0(U)?N1(F0(U),V,U.id):!0),C.length<Q)E("[killswitch] filtered fallbacks",{before:Q,after:C.length})}return await r0(X,D,C,V,B,x,{onSuccess:_})??B}return{apiKey:"",async fetch(X,D){let q=D?.body,w=Cj({bodyBytes:typeof q==="string"?q.length:void 0}),x=F(),Z=await O();if(w.mark("get_auth",{ms:h(F()-x),authType:Z.type,hasAccess:Boolean(Z.access)}),Z.type!=="oauth"){let Q=await fetch(X,D);return w.done("non_oauth_passthrough",{status:Q.status}),Q}await J0(Z.refresh);let p=F(),_=await A();w.mark("load_storage",{ms:h(F()-p)}),P.updateStorage(_),P.seedMainFromStorage(_,Z.access),P.seedFallbacksFromAccounts((_?.accounts??[]).filter(W0));let R=f(X,D?.body);if(R)j0++;if(R&&Z.access&&(!Z.expires||Z.expires>Date.now()))r(_,Z.access);let V=(Q,U)=>m(_,{activeId:Q,route:U,mainAccessToken:Z.access,mainRefreshToken:Z.refresh}),z;if(R&&Y1(_)==="fallback-first")try{let Q=F();z=await o0(_,{includeApiRoutes:z1(Z.access)}),w.mark("fallback_first_get_accounts",{ms:h(F()-Q),accounts:z.length});let U=await r0(X,D,z,_,void 0,w,{returnLastOnExhausted:!1,onSuccess:(g)=>V(g.id,"fallback-first")});if(U)return w.done("return_fallback_first",{status:U.status}),y0(U,{perf:(g,e)=>w.mark(g,e)});z=void 0}catch(Q){w.mark("fallback_first_error",{error:Q instanceof Error?Q.message:String(Q)})}if(!Z.access||!Z.expires||Z.expires<Date.now()){let U=(await A())?.refresh?.mainLastRefreshError;if(Z.refresh&&U&&x0(U,Z.refresh,Date.now()))throw E("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:U.nextRetryAt,retryCount:U.retryCount,expiresInMs:Z.expires?Z.expires-Date.now():void 0}),Error(R1(U,Date.now()));E("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(Z.access),expiresInMs:Z.expires?Z.expires-Date.now():void 0,expiredAgoMs:Z.expires&&Z.expires<Date.now()?Date.now()-Z.expires:void 0});let g=F();Z.access=await K(),w.mark("refresh_main_access",{ms:h(F()-g)})}if(!Z.access)throw w.done("missing_access_error"),Error("OAuth access token is missing after refresh");function B(){if(_?.quota?.showToasts!==!0)return;let Q=P.getMain();if(!Q)return;let U=(_?.accounts??[]).filter((n)=>n.enabled!==!1&&W0(n)).map((n)=>({...n,quota:P.getFallback(n.id,n.access)?.quota??n.quota})),g=p0(Q.quota,_),e;if(g)e="main";else e=U.find((n)=>p0(n.quota,_))?.id??"main";n0(Q.quota,U,e)}if(R&&Z0(_))try{let Q=F(),U=P.getMain(Z.access),g=U?.quota;if(!g)g=await P.refreshMain(Z.access),U=P.getMain(Z.access),B();else if(P.needsRefresh(j0))if(D0(g))g=await P.refreshMain(Z.access),U=P.getMain(Z.access);else P.refreshMain(Z.access).then(()=>{S(),B()}).catch(()=>{});if(m(_,{activeId:"main",route:"main",mainAccessToken:Z.access,mainRefreshToken:Z.refresh}),w.mark("main_quota_for_routing",{ms:h(F()-Q),passes:p0(g,_)}),!p0(g,_)){let e=F();z=await o0(_,{includeApiRoutes:Boolean(U&&U.refreshAfter>Date.now()&&D0(U.quota))}),w.mark("preselect_fallback_accounts",{ms:h(F()-e),accounts:z.length});let n=await r0(X,D,z,_,void 0,w,{onSuccess:(t)=>V(t.id,"fallback")});if(n)return w.done("return_preselected_fallback",{status:n.status}),y0(n,{perf:(t,o)=>w.mark(t,o)})}}catch(Q){w.mark("main_quota_for_routing_error",{error:Q instanceof Error?Q.message:String(Q)})}let M=P.getMain(Z.access)?.quota;if(_?.quota?.failClosedOnUnknownQuota&&!M&&P.isBackedOff()){let Q=P.getLastApiError(),U=Q?cW(Q,Date.now()):"Quota API unavailable";return E("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:Q?.nextRetryAt,retryCount:Q?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:U}}),{status:429,headers:{"content-type":"application/json","retry-after":String(Q?.nextRetryAt?Math.max(1,Math.ceil((Q.nextRetryAt-Date.now())/1000)):60)}})}if(i0(_)){if(P.needsRefresh(j0))try{let U=(_?.accounts??[]).filter((g)=>g.enabled!==!1&&W0(g)&&Boolean(g.access));await Promise.all([P.refreshMain(Z.access),P.refreshAllFallbacks(U)])}catch(U){E("[quota] killswitch refresh failed",{error:U instanceof Error?U.message:String(U),backedOff:P.isBackedOff()})}M=P.getMain(Z.access)?.quota}if(i0(_)&&!N1(M,_)){let U=f(X,D?.body)?await o0(_,{includeApiRoutes:z1(Z.access)}):[];if(U.length>0){E("[route] skipping main (killswitch), trying fallbacks");let t=await r0(X,D,U,_,void 0,w,{onSuccess:(o)=>V(o.id,"fallback")});if(t)return w.done("return_killswitch_fallback",{status:t.status}),y0(t,{perf:(o,G0)=>w.mark(o,G0)})}let g=Date.now(),e=(_?.accounts??[]).filter((t)=>t.enabled!==!1&&W0(t)).map((t)=>({...t,quota:F0(t)})),n=rW(M,e,g);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:`Killswitch: no routable accounts. Retry in ${Math.floor(n/60)}m ${n%60}s.`}}),{status:429,headers:{"content-type":"application/json","retry-after":String(n)}})}let c=await c0(X,D,Z.access,w,"main",_),u=!1,C=await B4(X,D,c,z,w,_,Z.access,(Q)=>{u=!0,V(Q.id,"fallback")});if(!u)V("main","main");return w.done("return_response",{status:C.status}),y0(C,{perf:(Q,U)=>w.mark(Q,U)})}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let O=await H1("max");return{url:O.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{return f1(G,O.verifier,O.redirectUri,O.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let O=await H1("console");return{url:O.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{let Y=await f1(G,O.verifier,O.redirectUri,O.state);if(Y.type==="failed")return Y;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${Y.access}`}}).then((K)=>K.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{ej as AnthropicAuthPlugin};
|
|
17
|
+
`)&&d.length<65536){let{done:Z,value:z}=await Q.read();if(Z)break;if(R.push(z),_+=z.byteLength,d+=Y.decode(z,{stream:!0}),F(d))break}if(F(d)){await Q.cancel().catch(()=>{});try{Q.releaseLock()}catch{}let Z=new ReadableStream({start(z){for(let H of R)z.enqueue(H);z.close()}});return I?.mark("inspect_stream_first_event",{ms:g(f()-S),bytes:_,rateLimited:!0}),{response:new Response(Z,{status:K.status,statusText:K.statusText,headers:K.headers}),rateLimited:!0}}let v=new ReadableStream({start(Z){for(let z of R)Z.enqueue(z)},async pull(Z){let{done:z,value:H}=await Q.read();if(z){Z.close();return}Z.enqueue(H)},cancel(Z){return Q.cancel(Z)}});return I?.mark("inspect_stream_first_event",{ms:g(f()-S),bytes:_,rateLimited:!1}),{response:new Response(v,{status:K.status,statusText:K.statusText,headers:K.headers}),rateLimited:!1}}async function V0(K,I,S,Q,R="api_fallback",Y){let d=f(),_=v1(K,I),v=_.get("x-session-affinity")||_.get("x-opencode-session"),Z=B(_);_.delete("x-parent-session-id"),_.delete("x-session-affinity"),_.delete("x-opencode-session");let z=I?.body,H=typeof z==="string"?z.length:void 0;if(z&&typeof z==="string"){let q=f(),L=(()=>{if(!F1())return!1;try{return p0(JSON.parse(z).model)}catch{return!1}})();if(z=await y1(z,{cache1hEnabled:!Z&&A0(),cache1hMode:k0(),fastModeEnabled:L,perf:(C,i)=>Q?.mark(`rewrite_body_${C}`,{route:R,...i})}),o(_,S),_.set("anthropic-beta",m0(_.get("anthropic-beta"),[])),L)X1(_);Q?.mark("rewrite_body",{route:R,ms:g(f()-q),originalBytes:H,rewrittenBytes:z.length,cacheEnabled:!Z&&A0(),cacheMode:k0(),fastModeEnabled:L,subagent:Z})}else o(_,S);let U=k1(K,{baseURL:S.baseURL}),a=f(),r;try{r=await fetch(U.input,{...I,body:z,headers:_,...A1()&&{tls:{rejectUnauthorized:!1}}})}catch(q){if(typeof z==="string")await s0({affinity:v,route:R,error:rW(q),bodyText:z,url:U.url?.toString()??K1(U.input),method:Y1(K,I),headers:_});throw q}if(typeof z==="string")await s0({affinity:v,route:R,status:r.status,bodyText:z,url:U.url?.toString()??K1(U.input),method:Y1(K,I),headers:_});return Q?.mark("send_headers_received",{route:R,ms:g(f()-a),status:r.status,relayConfigured:!1,totalSendWithAccessMs:g(f()-d),baseURL:S.baseURL}),r}async function F0(K,I,S,Q,R="unknown",Y){let d=f(),_=Y,v=async()=>{return _??=await T(j),_},Z=v1(K,I),z=Z.get("x-session-affinity")||Z.get("x-opencode-session"),H=B(Z);Z.delete("x-parent-session-id"),Z.delete("x-session-affinity"),Z.delete("x-opencode-session");let U=I?.body,a;if(U&&typeof U==="string"){let e=f();try{let D0=JSON.parse(U);if(typeof D0.model==="string")a=D0.model}catch{}Q?.mark("model_parse_for_identity",{route:R,ms:g(f()-e),bodyBytes:U.length})}let r=f(),q=await d1(S,a);Q?.mark("resolve_claude_code_identity",{route:R,ms:g(f()-r),hasAccountUuid:Boolean(q.accountUuid)});let L=typeof U==="string"?U.length:void 0;if(U&&typeof U==="string"){let e=f(),D0=(()=>{if(!F1())return!1;try{return p0(JSON.parse(U).model)}catch{return!1}})();U=await y1(U,{cache1hEnabled:!H&&A0(),cache1hMode:k0(),fastModeEnabled:D0,identity:q,perf:(e4,Wj)=>Q?.mark(`rewrite_body_${e4}`,{route:R,...Wj})});let E0=f();try{i0(Z,S,{body:JSON.parse(U),identity:q}),Q?.mark("set_oauth_headers_body_parse",{route:R,ms:g(f()-E0),bodyBytes:U.length,parsed:!0})}catch{i0(Z,S,{identity:q}),Q?.mark("set_oauth_headers_body_parse",{route:R,ms:g(f()-E0),bodyBytes:U.length,parsed:!1})}if(D0)X1(Z);Q?.mark("rewrite_body",{route:R,ms:g(f()-e),originalBytes:L,rewrittenBytes:U.length,cacheEnabled:!H&&A0(),cacheMode:k0(),fastModeEnabled:D0,subagent:H})}let C=k1(K);if(R==="main"&&typeof U==="string"&&A0()&&k0()==="hybrid"){let e=await v();if(!H||V4(e)){let D0=f(),E0=P0.track({sessionId:z,url:C.url?.toString()??C.input.toString(),headers:Z,bodyText:U,storage:e,cacheMode:"hybrid"});Q?.mark("cachekeep_track",{session:z,ms:g(f()-D0),tracked:E0.tracked,reason:E0.tracked?void 0:E0.reason,bodyBytes:U.length})}}let i=async()=>{try{let e=await fetch(C.input,{...I,body:U,headers:Z,...A1()&&{tls:{rejectUnauthorized:!1}}});if(typeof U==="string")await s0({affinity:z,route:R,status:e.status,bodyText:U,url:C.url?.toString()??K1(C.input),method:Y1(K,I),headers:Z});return e}catch(e){if(typeof U==="string")await s0({affinity:z,route:R,error:rW(e),bodyText:U,url:C.url?.toString()??K1(C.input),method:Y1(K,I),headers:Z});throw e}},G0=JW(await v()),t=f(),J0=await p4({config:G0,input:C.input,init:I,headers:Z,body:U,fallback:i,affinity:z,optimisticResponse:G0?.transport==="websocket"});return Q?.mark("send_headers_received",{route:R,ms:g(f()-t),status:J0.status,relayConfigured:G0!=null,totalSendWithAccessMs:g(f()-d)}),J0}async function s4(K){if(!K)return!1;try{return await M.refreshMain(K),R1(K)}catch{return!1}}async function P1(K,I={}){let S=await y.getUsableFallbackAccounts(K),Q=new Map(S.map((Y)=>[Y.id,Y])),R=[];for(let Y of K?.accounts??[]){if(N0(Y)){let d=Q.get(Y.id);if(d)R.push(d);continue}if(I.includeApiRoutes===!0&&l0(Y)&&Y.enabled!==!1&&Y.apiKey&&I1(Y.baseURL))R.push(Y)}if(!r0(K))return R;return R.filter((Y)=>N0(Y)?M1(Q0(Y),K,Y.id):!0)}async function $1(K,I,S,Q,R,Y,d){if(!S.length)return R??null;let _=d?.returnLastOnExhausted??!0;await R?.body?.cancel().catch(()=>{});let v=R??null;for(let[Z,z]of S.entries()){let H;if(l0(z)){if(!z.apiKey)continue;H=await V0(K,I,z,Y,`api_fallback_${Z}`,Q)}else{let a=z.access;if(!a)continue;H=await F0(K,I,a,Y,`fallback_${Z}`,Q)}v=H;let U=b1(H.status,Q);if(!U){let a=await c(H,Y);H=a.response,v=H,U=a.rateLimited}if(!U){if(await y.markUsed(z),await d?.onSuccess?.(z),N0(z)&&z.access&&M.shouldRefreshOnRequestCount(K0))M.refreshFallback(z.id,z.access).then(()=>d?.onSuccess?.(z)).catch(()=>{});return H}if(Z<S.length-1||!_)await H.body?.cancel().catch(()=>{})}return _?v:null}async function a4(K,I,S,Q,R,Y,d,_){if(!x(K,I?.body))return S;let v=f(),Z=Y??await T(j);if(R?.mark("fallback_load_storage",{ms:g(f()-v),cached:!!Y}),!(Z?.accounts??[]).some((L)=>L.enabled!==!1&&(N0(L)||l0(L)&&Boolean(L.apiKey)&&I1(L.baseURL))))return S;let H=S,U=b1(H.status,Z),a=GW(H,!1);if(!U){let L=await c(H,R);H=L.response,U=L.rateLimited,a=GW(H,L.rateLimited)}if(!U)return H;let r=!1;if(Q)r=Q.some(l0);else if(a)r=await s4(d);let q=Q;if(!q){let L=f();q=await P1(Z,{includeApiRoutes:r}),R?.mark("fallback_get_accounts",{ms:g(f()-L),accounts:q.length})}if(r0(Z)){let L=q.length;if(q=q.filter((C)=>N0(C)?M1(Q0(C),Z,C.id):!0),q.length<L)p("[killswitch] filtered fallbacks",{before:L,after:q.length})}return await $1(K,I,q,Z,H,R,{onSuccess:_})??H}return{apiKey:"",async fetch(K,I){let S=I?.body,Q=ej({bodyBytes:typeof S==="string"?S.length:void 0}),R=f(),Y=await $();if(Q.mark("get_auth",{ms:g(f()-R),authType:Y.type,hasAccess:Boolean(Y.access)}),Y.type!=="oauth"){let L=await fetch(K,I);return Q.done("non_oauth_passthrough",{status:L.status}),L}await q0(Y.refresh);let d=f(),_=await T();Q.mark("load_storage",{ms:g(f()-d)}),M.updateStorage(_),M.seedMainFromStorage(_,Y.access),M.seedFallbacksFromAccounts((_?.accounts??[]).filter(N0));let v=x(K,I?.body);if(v)K0++;if(v&&Y.access&&(!Y.expires||Y.expires>Date.now()))Z0(_,Y.access);let Z=(L,C)=>$0(_,{activeId:L,route:C,mainAccessToken:Y.access,mainRefreshToken:Y.refresh}),z;if(v&&H1(_)==="fallback-first")try{let L=f();z=await P1(_,{includeApiRoutes:R1(Y.access)}),Q.mark("fallback_first_get_accounts",{ms:g(f()-L),accounts:z.length});let C=await $1(K,I,z,_,void 0,Q,{returnLastOnExhausted:!1,onSuccess:(i)=>Z(i.id,"fallback-first")});if(C)return Q.done("return_fallback_first",{status:C.status}),d0(C,{perf:(i,G0)=>Q.mark(i,G0)});z=void 0}catch(L){Q.mark("fallback_first_error",{error:L instanceof Error?L.message:String(L)})}if(!Y.access||!Y.expires||Y.expires<Date.now()){let C=(await T())?.refresh?.mainLastRefreshError;if(Y.refresh&&C&&f0(C,Y.refresh,Date.now()))throw p("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:C.nextRetryAt,retryCount:C.retryCount,expiresInMs:Y.expires?Y.expires-Date.now():void 0}),Error(g1(C,Date.now()));p("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(Y.access),expiresInMs:Y.expires?Y.expires-Date.now():void 0,expiredAgoMs:Y.expires&&Y.expires<Date.now()?Date.now()-Y.expires:void 0});let i=f();Y.access=await V(),Q.mark("refresh_main_access",{ms:g(f()-i)})}if(!Y.access)throw Q.done("missing_access_error"),Error("OAuth access token is missing after refresh");function H(){if(_?.quota?.showToasts!==!0)return;let L=M.getMain();if(!L)return;let C=(_?.accounts??[]).filter((t)=>t.enabled!==!1&&N0(t)).map((t)=>({...t,quota:M.getFallback(t.id,t.access)?.quota??t.quota})),i=o0(L.quota,_),G0;if(i)G0="main";else G0=C.find((t)=>o0(t.quota,_))?.id??"main";t4(L.quota,C,G0)}if(v&&b(_))try{let L=f(),C=M.getMain(Y.access),i=C?.quota;if(!i)i=await M.refreshMain(Y.access),C=M.getMain(Y.access),H();else if(M.needsRefresh(K0))if(C0(i))i=await M.refreshMain(Y.access),C=M.getMain(Y.access);else M.refreshMain(Y.access).then(()=>{L0().catch(()=>{}),H()}).catch(()=>{});if($0(_,{activeId:"main",route:"main",mainAccessToken:Y.access,mainRefreshToken:Y.refresh}),Q.mark("main_quota_for_routing",{ms:g(f()-L),passes:o0(i,_)}),!o0(i,_)){let G0=f();z=await P1(_,{includeApiRoutes:Boolean(C&&C.refreshAfter>Date.now()&&C0(C.quota))}),Q.mark("preselect_fallback_accounts",{ms:g(f()-G0),accounts:z.length});let t=await $1(K,I,z,_,void 0,Q,{onSuccess:(J0)=>Z(J0.id,"fallback")});if(t)return Q.done("return_preselected_fallback",{status:t.status}),d0(t,{perf:(J0,e)=>Q.mark(J0,e)})}}catch(L){Q.mark("main_quota_for_routing_error",{error:L instanceof Error?L.message:String(L)})}let U=M.getMain(Y.access)?.quota;if(_?.quota?.failClosedOnUnknownQuota&&!U&&M.isBackedOff()){let L=M.getLastApiError(),C=L?Y4(L,Date.now()):"Quota API unavailable";return p("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:L?.nextRetryAt,retryCount:L?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:C}}),{status:429,headers:{"content-type":"application/json","retry-after":String(L?.nextRetryAt?Math.max(1,Math.ceil((L.nextRetryAt-Date.now())/1000)):60)}})}if(r0(_)){if(M.needsRefresh(K0))try{let C=(_?.accounts??[]).filter((i)=>i.enabled!==!1&&N0(i)&&Boolean(i.access));await Promise.all([M.refreshMain(Y.access),M.refreshAllFallbacks(C)])}catch(C){p("[quota] killswitch refresh failed",{error:C instanceof Error?C.message:String(C),backedOff:M.isBackedOff()})}U=M.getMain(Y.access)?.quota}if(r0(_)&&!M1(U,_)){let C=x(K,I?.body)?await P1(_,{includeApiRoutes:R1(Y.access)}):[];if(C.length>0){p("[route] skipping main (killswitch), trying fallbacks");let J0=await $1(K,I,C,_,void 0,Q,{onSuccess:(e)=>Z(e.id,"fallback")});if(J0)return Q.done("return_killswitch_fallback",{status:J0.status}),d0(J0,{perf:(e,D0)=>Q.mark(e,D0)})}let i=Date.now(),G0=(_?.accounts??[]).filter((J0)=>J0.enabled!==!1&&N0(J0)).map((J0)=>({...J0,quota:Q0(J0)})),t=I4(U,G0,i);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:`Killswitch: no routable accounts. Retry in ${Math.floor(t/60)}m ${t%60}s.`}}),{status:429,headers:{"content-type":"application/json","retry-after":String(t)}})}let a=await F0(K,I,Y.access,Q,"main",_),r=!1,q=await a4(K,I,a,z,Q,_,Y.access,(L)=>{r=!0,Z(L.id,"fallback")});if(!r)Z("main","main");return Q.done("return_response",{status:q.status}),d0(q,{perf:(L,C)=>Q.mark(L,C)})}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let $=await _1("max");return{url:$.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{return D1(G,$.verifier,$.redirectUri,$.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let $=await _1("console");return{url:$.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{let X=await D1(G,$.verifier,$.redirectUri,$.state);if(X.type==="failed")return X;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${X.access}`}}).then((V)=>V.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{qJ as AnthropicAuthPlugin};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{kb as a,lb as b,mb as c,nb as d,ob as e,pb as f,qb as g,rb as h,sb as i,tb as j,ub as k,vb as l,wb as m}from"./index-zfddfgk2.js";import"./index-7hq52c3b.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.d.ts
CHANGED
|
@@ -9,4 +9,4 @@ export declare function writePortFile(dir: string, entry: {
|
|
|
9
9
|
token: string;
|
|
10
10
|
pid: number;
|
|
11
11
|
}): Promise<string>;
|
|
12
|
-
export declare function discoverPortFile(dir: string): Promise<PortFileEntry | null>;
|
|
12
|
+
export declare function discoverPortFile(dir: string, expectedPid?: number): Promise<PortFileEntry | null>;
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ib as a,Jb as b}from"../index-srn1rawx.js";import"../index-7hq52c3b.js";export{a as writePortFile,b as discoverPortFile};
|
package/dist/rpc/protocol.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type CommandModalName = 'claude-cache' | 'claude-cachekeep' | 'claude-quota' | 'claude-dump' | 'claude-fast' | 'claude-routing' | 'claude-killswitch';
|
|
1
|
+
export type CommandModalName = 'claude-account' | 'claude-cache' | 'claude-cachekeep' | 'claude-quota' | 'claude-dump' | 'claude-fast' | 'claude-routing' | 'claude-killswitch' | 'claude-logging';
|
|
2
2
|
export interface OpenDialogPayload {
|
|
3
3
|
command: CommandModalName;
|
|
4
4
|
text: string;
|
|
@@ -13,6 +13,7 @@ export interface RpcNotification {
|
|
|
13
13
|
export interface ApplyRequest {
|
|
14
14
|
command: CommandModalName;
|
|
15
15
|
arguments: string;
|
|
16
|
+
sessionId?: string;
|
|
16
17
|
}
|
|
17
18
|
export interface ApplyResult {
|
|
18
19
|
text: string;
|
package/dist/rpc/rpc-client.d.ts
CHANGED
|
@@ -3,4 +3,4 @@ export interface RpcClient {
|
|
|
3
3
|
pending: (lastReceivedId: number, sessionId?: string) => Promise<RpcNotification[]>;
|
|
4
4
|
apply: (request: ApplyRequest) => Promise<ApplyResult>;
|
|
5
5
|
}
|
|
6
|
-
export declare function createRpcClient(dir: string): RpcClient;
|
|
6
|
+
export declare function createRpcClient(dir: string, expectedPid?: number): RpcClient;
|
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Jb as l}from"../index-srn1rawx.js";import"../index-7hq52c3b.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{Kb as a,Lb as b}from"../index-vhcx8tx6.js";import"../index-7hq52c3b.js";export{a as tmpdir,b as getRpcDir};
|
package/dist/sidebar-state.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ export interface SidebarAccountState {
|
|
|
12
12
|
label: string | undefined;
|
|
13
13
|
quota: AccountQuota | null;
|
|
14
14
|
enabled: boolean;
|
|
15
|
+
needsReauth: boolean;
|
|
15
16
|
}
|
|
16
17
|
export interface SidebarState {
|
|
17
18
|
main: {
|
|
@@ -38,8 +39,10 @@ export interface SidebarState {
|
|
|
38
39
|
}
|
|
39
40
|
export declare function getSidebarStateFile(): string;
|
|
40
41
|
export declare const DEFAULT_SIDEBAR_STATE: SidebarState;
|
|
42
|
+
export declare function normalizeSidebarState(raw: unknown): SidebarState;
|
|
41
43
|
export declare function getSidebarState(): Promise<SidebarState>;
|
|
42
|
-
export declare function setSidebarState(state: SidebarState): Promise<void>;
|
|
44
|
+
export declare function setSidebarState(state: SidebarState, stateFile?: string): Promise<void>;
|
|
45
|
+
export declare function drainSidebarWrites(): Promise<void>;
|
|
43
46
|
export declare function resolveActiveAccount(state: SidebarState): {
|
|
44
47
|
id: string;
|
|
45
48
|
name: string;
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ab as d,Bb as e,Cb as f,Db as g,Eb as h,Fb as i,Gb as j,Hb as k,xb as a,yb as b,zb as c}from"./index-7f07xr7k.js";import"./index-7hq52c3b.js";export{e as setSidebarState,g as resolveActiveAccount,c as normalizeSidebarState,a as getSidebarStateFile,d as getSidebarState,h as getCollapsedQuotaSummary,f as drainSidebarWrites,k as computeQuotaPacing,j as SEVEN_DAY_MS,i as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
|
|
@@ -3,6 +3,7 @@ import type { TuiPluginApi } from '@opencode-ai/plugin/tui';
|
|
|
3
3
|
import type { OpenDialogPayload } from '../rpc/protocol.js';
|
|
4
4
|
type ApplyFn = (command: OpenDialogPayload['command'], args: string) => Promise<{
|
|
5
5
|
text: string;
|
|
6
|
+
knobs: Record<string, unknown>;
|
|
6
7
|
}>;
|
|
7
8
|
export declare function openCommandDialog(api: TuiPluginApi, payload: OpenDialogPayload, apply: ApplyFn): void;
|
|
8
9
|
export {};
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Mb as c,Nb as C,Ob as h}from"./index-7hq52c3b.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.
|
|
5
5
|
{}
|
|
6
|
-
`;async function
|
|
6
|
+
`;async function e(Q,J,X){let Z=b();await S(P(Z),{recursive:!0});let $;try{$=await w(Z,"utf8")}catch{$=""}if($.trim()==="")$=o;let G=q.modify($,[Q,...J],X,{formattingOptions:{insertSpaces:!0,tabSize:2}}),V=q.applyEdits($,G),Y=`${Z}.${process.pid}.tmp`;await p(Y,V,"utf8"),await E(Y,Z)}var g=Promise.resolve();function Wz(Q,J,X){return g=g.then(()=>e(Q,J,X)).catch(()=>{}),g}var r=150,zz=100;function Bz(Q){let J=b(),X=x(J),Z=null,$=null,G=!1,V=!1,Y=async()=>{let B=await w(J,"utf8").catch(()=>null);if(V||B===null)return;if(B===$)return;$=B,Q()},L=()=>{if(G=!0,Z)F(Z);Z=f(()=>{Z=null,Y()},r)};w(J,"utf8").then((B)=>{if(!G&&$===null)$=B}).catch(()=>{});try{let B=y(P(J),(z,H)=>{let N=H===X||H?.startsWith(`${X}.`)&&H.endsWith(".tmp");if(H!=null&&!N)return;L()}),j=null,A=!1,O=()=>{if(V||j)return;j=f(()=>{if(j=null,V||A)return;A=!0,Y().finally(()=>{A=!1,O()})},zz),j.unref?.()};return O(),()=>{if(V=!0,Z)F(Z);if(j)F(j);B.close()}}catch{return()=>{}}}export{Bz as watchTuiPreferences,Yz as resolveAnthropicAuthPrefs,Vz as readTuiPreferencesFile,Wz as queueTuiPreferenceUpdate,b as getTuiPreferencesFile,Hz as computeEffectiveOrder,i as TUI_PREFS_FILE_ENV,d as PLUGIN_KEY,n as DEFAULT_SLOT_ORDER,u as DEFAULT_PREFS};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-anthropic-auth",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.11.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.
|
|
62
|
-
"@opentui/core": ">=0.4.
|
|
63
|
-
"@opentui/solid": ">=0.4.
|
|
61
|
+
"@cortexkit/anthropic-auth-core": "1.11.0",
|
|
62
|
+
"@opentui/core": ">=0.4.2",
|
|
63
|
+
"@opentui/solid": ">=0.4.2",
|
|
64
64
|
"jsonc-parser": "^3.3.1",
|
|
65
65
|
"solid-js": "^1.9.10"
|
|
66
66
|
}
|
package/src/rpc/port-file.ts
CHANGED
|
@@ -39,6 +39,7 @@ export async function writePortFile(
|
|
|
39
39
|
|
|
40
40
|
export async function discoverPortFile(
|
|
41
41
|
dir: string,
|
|
42
|
+
expectedPid?: number,
|
|
42
43
|
): Promise<PortFileEntry | null> {
|
|
43
44
|
let names: string[]
|
|
44
45
|
try {
|
|
@@ -60,5 +61,10 @@ export async function discoverPortFile(
|
|
|
60
61
|
} catch {}
|
|
61
62
|
}
|
|
62
63
|
if (live.length === 0) return null
|
|
63
|
-
|
|
64
|
+
const candidates =
|
|
65
|
+
expectedPid && expectedPid >= 1
|
|
66
|
+
? live.filter((entry) => entry.pid === expectedPid)
|
|
67
|
+
: []
|
|
68
|
+
const entries = candidates.length > 0 ? candidates : live
|
|
69
|
+
return entries.sort((a, b) => b.startedAt - a.startedAt)[0] ?? null
|
|
64
70
|
}
|