🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@cortexkit/opencode-anthropic-auth

Package Overview
Dependencies
Maintainers
1
Versions
28
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cortexkit/opencode-anthropic-auth - npm Package Compare versions

Comparing version
1.10.2
to
1.10.3
dist/index-tes31apx.js

Sorry, the diff of this file is too big to display

+1
-1
#!/usr/bin/env node
import{Oa as I,Qa as $,m as w,n as k,p as A,r as R,t as d,u as l,v as p}from"./index-fvzta6xw.js";import"./index-p8j7mmfc.js";import{stdin as E,stdout as U}from"node:process";import{createInterface as _}from"node:readline/promises";function g(){return{version:1,main:{type:"opencode",provider:"anthropic"},fallbackOn:[401,403,429],refresh:{enabled:!0,intervalMinutes:10,refreshBeforeExpiryMinutes:240},quota:{enabled:!0,checkIntervalMinutes:5,minimumRemaining:{five_hour:10,seven_day:20},failClosedOnUnknownQuota:!0},accounts:[]}}function y(){console.log(`Usage:
import{Oa as I,Qa as $,m as w,n as k,p as A,r as R,t as d,u as l,v as p}from"./index-tes31apx.js";import"./index-p8j7mmfc.js";import{stdin as E,stdout as U}from"node:process";import{createInterface as _}from"node:readline/promises";function g(){return{version:1,main:{type:"opencode",provider:"anthropic"},fallbackOn:[401,403,429],refresh:{enabled:!0,intervalMinutes:10,refreshBeforeExpiryMinutes:240},quota:{enabled:!0,checkIntervalMinutes:5,minimumRemaining:{five_hour:10,seven_day:20},failClosedOnUnknownQuota:!0},accounts:[]}}function y(){console.log(`Usage:
opencode-anthropic-auth login [label]

@@ -4,0 +4,0 @@ opencode-anthropic-auth api add [label]

@@ -1,2 +0,2 @@

import{$ as eW,A as mW,Aa as N4,B as pW,Ba as FW,C as $1,Ca as u0,D as iW,Da as V4,E as O1,Ea as X4,F as dW,Fa as Z4,G as lW,Ga as K4,H as uW,Ha as CW,I as q1,Ia as HW,J as G1,Ja as Y4,K as nW,Ka as p1,L as x0,La as _4,M as R1,Ma as D4,N as cW,Na as i1,O as oW,P as p0,Pa as I4,Q as i0,R as N1,Ra as d1,S as rW,Sa as Y1,T as T1,Ta as z4,U as tW,Ua as w4,V as sW,Va as l1,W as aW,X as E1,Y as q0,Z as R0,_ as d0,a as YW,aa as V1,b as _W,ba as QW,c as v0,ca as LW,d as A0,da as S1,e as DW,ea as MW,f as f0,fa as UW,g as kW,ga as BW,h as IW,ha as v1,i as zW,ia as W4,j as wW,ja as j4,k as C1,ka as A1,l as yW,la as J4,m as H1,ma as k1,n as f1,na as P4,o as E,oa as $4,p as W0,pa as y1,q as h0,qa as X1,r as x1,ra as O4,s as hW,sa as h1,t as bW,ta as l0,u as A,ua as b1,va as Z1,w as b0,wa as K1,x as gW,xa as G4,y as g0,ya as g1,z as m0,za as m1}from"./index-fvzta6xw.js";import{Za as L4}from"./index-9yjbmhf1.js";import{db as WW}from"./index-jb14nj5c.js";import{gb as Q4}from"./index-3ynbghx3.js";import"./index-p8j7mmfc.js";import{randomUUID as zj}from"node:crypto";function H0(W){return typeof W==="object"&&W!==null}function H4(W){if(Array.isArray(W))return W;if(H0(W)&&Array.isArray(W.data))return W.data;return[]}function f4(W){if(!H0(W)||!H0(W.info))return;return typeof W.info.role==="string"?W.info.role:void 0}function n1(W){if(!H0(W)||!H0(W.info))return null;let J=W.info,j=H0(J.model)?J.model:void 0,$=typeof J.agent==="string"?J.agent:void 0,P=typeof j?.providerID==="string"?j.providerID:typeof J.providerID==="string"?J.providerID:void 0,N=typeof j?.modelID==="string"?j.modelID:typeof J.modelID==="string"?J.modelID:void 0,I=typeof j?.variant==="string"?j.variant:typeof J.variant==="string"?J.variant:void 0;if(!$&&(!P||!N)&&!I)return null;let H={};if($)H.agent=$;if(P&&N)H.model={providerID:P,modelID:N};if(I)H.variant=I;return H}function c1(W,J){return{agent:W.agent??J.agent,model:W.model??J.model,variant:W.variant??J.variant}}function o1(W){return Boolean(W.agent&&W.model&&W.variant)}async function r1(W,J){if(!W||!J)return null;let j=W;if(typeof j.session?.messages!=="function")return null;let $=[];try{$=H4(await Promise.resolve(j.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if($.length===0)return null;let P={};for(let N=$.length-1;N>=0;N--){if(f4($[N])!=="assistant")continue;let I=n1($[N]);if(!I)continue;if(P=c1(P,I),o1(P))return P}for(let N=$.length-1;N>=0;N--){let I=n1($[N]);if(!I)continue;if(P=c1(P,I),o1(P))return P}if(!P.agent&&!P.model&&!P.variant)return null;return P}var K0=[],x4=1,w1=0,t1=new Map;function s1(W,J){if(K0.push({id:x4++,type:"open-dialog",payload:W,sessionId:J}),K0.length>100)K0=K0.slice(K0.length-100)}function a1(W=0,J){let j=Date.now();if(w1=j,J!==void 0)t1.set(J,j);let $=(P)=>J===void 0||P.sessionId===void 0||P.sessionId===J;if(W>0)K0=K0.filter((P)=>{if(P.id>W)return!0;if(J===void 0)return!1;return P.sessionId!==J});return K0.filter((P)=>P.id>W&&$(P))}function e1(W){let J=Date.now();if(W!==void 0){let j=t1.get(W)??0;return j>0&&J-j<3000}return w1>0&&J-w1<3000}import{randomBytes as q4,timingSafeEqual as R4}from"node:crypto";import{unlink as T4}from"node:fs/promises";import{createServer as E4}from"node:http";import{join as S4}from"node:path";function v4(W){return new Promise((J,j)=>{let $=[],P=0;W.on("data",(N)=>{if(P+=N.length,P>1e6){W.destroy(),j(Error("body too large"));return}$.push(N)}),W.on("end",()=>J(Buffer.concat($).toString("utf8"))),W.on("error",j)})}function A4(W,J){if(!W?.startsWith("Bearer "))return!1;let j=Buffer.from(W.slice(7)),$=Buffer.from(J);return j.length===$.length&&R4(j,$)}async function jW(W){let J=q4(32).toString("hex"),j=E4((N,I)=>{$(N,I)});async function $(N,I){let H=(k,b)=>{I.writeHead(k,{"content-type":"application/json"}),I.end(JSON.stringify(b))};try{let k=N.url??"";if(N.method==="GET"&&k==="/health")return H(200,{ok:!0});if(N.method!=="POST"||!k.startsWith("/rpc/"))return H(404,{error:"not found"});if(!A4(N.headers.authorization,J))return H(401,{error:"unauthorized"});let b=k.slice(5),m=JSON.parse(await v4(N)||"{}");if(b==="pending-notifications"){let S=W.drain(Number(m.lastReceivedId??0),typeof m.sessionId==="string"?m.sessionId:void 0);return H(200,{messages:S})}if(b==="apply"){let S=await W.apply(m);return H(200,S)}return H(404,{error:"unknown method"})}catch(k){H(500,{error:k instanceof Error?k.message:String(k)})}}let P=await new Promise((N,I)=>{j.on("error",I),j.listen(0,"127.0.0.1",()=>{let H=j.address();if(H&&typeof H==="object")N(H.port);else I(Error("no port"))})});j.unref();try{await WW(W.dir,{port:P,token:J,pid:process.pid})}catch(N){throw await new Promise((I)=>j.close(()=>I())),N}return{port:P,token:J,async stop(){await new Promise((N)=>j.close(()=>N())),await T4(S4(W.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function JW(W,J){let j=new Map,$=0,P=0,N=0,I=0,H=0,k=(S)=>{let r=performance.now(),d=W(S);return H+=performance.now()-r,N++,d};return{call:(S)=>{if(!J.enabled())return k(S);let r=j.get(S);if(r!==void 0)return P++,j.delete(S),j.set(S,r),r;let d=k(S),O0=S.length+d.length;if(O0>J.maxBytes)return d;j.set(S,d),$+=O0;while($>J.maxBytes&&j.size>1){let l=j.keys().next().value,j0=j.get(l)??"";j.delete(l),$-=l.length+j0.length,I++}return d},stats:()=>({hits:P,misses:N,evictions:I,entries:j.size,cacheBytes:$,computeMsTotal:H})}}function PW(W){return`${YW}${W.charAt(0).toUpperCase()}${W.slice(1)}`}function fW(W){if(W==="StructuredOutput")return W;return`${W.charAt(0).toLowerCase()}${W.slice(1)}`}var k4=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function $W(W){let J=fW(W);if(J.startsWith("aft_"))return J;if(k4.has(J))return`aft_${J}`;return null}function M1(W,J){let j=new Headers;if(W instanceof Request)W.headers.forEach((P,N)=>{j.set(N,P)});let $=J?.headers;if($){if($ instanceof Headers)$.forEach((P,N)=>{j.set(N,P)});else if(Array.isArray($))for(let P of $){let[N,I]=P;if(typeof I<"u")j.set(N,String(I))}else for(let[P,N]of Object.entries($))if(typeof N<"u")j.set(P,String(N))}return j}function W1(W){return W.set("anthropic-beta",v0(W.get("anthropic-beta"),[_W])),W}function k0(W,J,j={}){return UW(W,J,j)}function y4(W){if(W.tools&&Array.isArray(W.tools))W.tools=W.tools.map((J)=>({...J,name:J.name?PW(J.name):J.name}));if(W.messages&&Array.isArray(W.messages))W.messages=W.messages.map((J)=>{if(J.content&&Array.isArray(J.content))J.content=J.content.map((j)=>{if(j.type==="tool_use"&&j.name)return{...j,name:PW(j.name)};return j});return J});return JSON.stringify(BW(W))}function Q1(W){return W.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(J,j,$)=>{if(j)return`"name": "${$W($)??fW($)}"`;let P=$W($);return P?`"name": "${P}"`:J})}function OW(W,J=!1){if(J)return{ready:Q1(W),pending:""};let j=W.length,$='"name"',P=Math.max(0,W.length-$.length+1);for(let I=P;I<W.length;I++)if($.startsWith(W.slice(I))){j=Math.min(j,I);break}let N=W.lastIndexOf($);if(N!==-1){let I=W.slice(N);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(I))j=Math.min(j,N)}if(j<W.length)return{ready:Q1(W.slice(0,j)),pending:W.slice(j)};return{ready:Q1(W),pending:""}}function U1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let W=process.env.ANTHROPIC_INSECURE?.trim();return W==="1"||W==="true"}function xW(W){let J=W?.trim();if(!J)return null;try{let j=new URL(J);if(j.protocol!=="http:"&&j.protocol!=="https:"||j.username||j.password)return null;return j}catch{return null}}function h4(){return xW(process.env.ANTHROPIC_BASE_URL)}function B1(W,J={}){let j=null;try{if(typeof W==="string"||W instanceof URL)j=new URL(W.toString());else if(W instanceof Request)j=new URL(W.url)}catch{j=null}if(!j)return{input:W,url:null};let $=j.href,P=J.baseURL?xW(J.baseURL):h4();if(P){if(j.protocol=P.protocol,j.host=P.host,J.baseURL)j.pathname=`${P.pathname.replace(/\/$/,"")}${j.pathname}`}if(j.pathname.endsWith("/v1/messages")&&!j.searchParams.has("beta"))j.searchParams.set("beta","true");if(j.href===$)return{input:W,url:j};return{input:W instanceof Request?new Request(j.toString(),W):j,url:j}}function b4(W){let $=W.split(/\n\n+/).filter((P)=>{if(P.includes(DW))return!1;for(let N of zW)if(P.includes(N))return!1;return!0}).join(`
import{$ as eW,A as mW,Aa as N4,B as pW,Ba as FW,C as $1,Ca as u0,D as iW,Da as V4,E as O1,Ea as X4,F as dW,Fa as Z4,G as lW,Ga as K4,H as uW,Ha as CW,I as q1,Ia as HW,J as G1,Ja as Y4,K as nW,Ka as p1,L as x0,La as _4,M as R1,Ma as D4,N as cW,Na as i1,O as oW,P as p0,Pa as I4,Q as i0,R as N1,Ra as d1,S as rW,Sa as Y1,T as T1,Ta as z4,U as tW,Ua as w4,V as sW,Va as l1,W as aW,X as E1,Y as q0,Z as R0,_ as d0,a as YW,aa as V1,b as _W,ba as QW,c as v0,ca as LW,d as A0,da as S1,e as DW,ea as MW,f as f0,fa as UW,g as kW,ga as BW,h as IW,ha as v1,i as zW,ia as W4,j as wW,ja as j4,k as C1,ka as A1,l as yW,la as J4,m as H1,ma as k1,n as f1,na as P4,o as E,oa as $4,p as W0,pa as y1,q as h0,qa as X1,r as x1,ra as O4,s as hW,sa as h1,t as bW,ta as l0,u as A,ua as b1,va as Z1,w as b0,wa as K1,x as gW,xa as G4,y as g0,ya as g1,z as m0,za as m1}from"./index-tes31apx.js";import{Za as L4}from"./index-9yjbmhf1.js";import{db as WW}from"./index-jb14nj5c.js";import{gb as Q4}from"./index-3ynbghx3.js";import"./index-p8j7mmfc.js";import{randomUUID as zj}from"node:crypto";function H0(W){return typeof W==="object"&&W!==null}function H4(W){if(Array.isArray(W))return W;if(H0(W)&&Array.isArray(W.data))return W.data;return[]}function f4(W){if(!H0(W)||!H0(W.info))return;return typeof W.info.role==="string"?W.info.role:void 0}function n1(W){if(!H0(W)||!H0(W.info))return null;let J=W.info,j=H0(J.model)?J.model:void 0,$=typeof J.agent==="string"?J.agent:void 0,P=typeof j?.providerID==="string"?j.providerID:typeof J.providerID==="string"?J.providerID:void 0,N=typeof j?.modelID==="string"?j.modelID:typeof J.modelID==="string"?J.modelID:void 0,I=typeof j?.variant==="string"?j.variant:typeof J.variant==="string"?J.variant:void 0;if(!$&&(!P||!N)&&!I)return null;let H={};if($)H.agent=$;if(P&&N)H.model={providerID:P,modelID:N};if(I)H.variant=I;return H}function c1(W,J){return{agent:W.agent??J.agent,model:W.model??J.model,variant:W.variant??J.variant}}function o1(W){return Boolean(W.agent&&W.model&&W.variant)}async function r1(W,J){if(!W||!J)return null;let j=W;if(typeof j.session?.messages!=="function")return null;let $=[];try{$=H4(await Promise.resolve(j.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if($.length===0)return null;let P={};for(let N=$.length-1;N>=0;N--){if(f4($[N])!=="assistant")continue;let I=n1($[N]);if(!I)continue;if(P=c1(P,I),o1(P))return P}for(let N=$.length-1;N>=0;N--){let I=n1($[N]);if(!I)continue;if(P=c1(P,I),o1(P))return P}if(!P.agent&&!P.model&&!P.variant)return null;return P}var K0=[],x4=1,w1=0,t1=new Map;function s1(W,J){if(K0.push({id:x4++,type:"open-dialog",payload:W,sessionId:J}),K0.length>100)K0=K0.slice(K0.length-100)}function a1(W=0,J){let j=Date.now();if(w1=j,J!==void 0)t1.set(J,j);let $=(P)=>J===void 0||P.sessionId===void 0||P.sessionId===J;if(W>0)K0=K0.filter((P)=>{if(P.id>W)return!0;if(J===void 0)return!1;return P.sessionId!==J});return K0.filter((P)=>P.id>W&&$(P))}function e1(W){let J=Date.now();if(W!==void 0){let j=t1.get(W)??0;return j>0&&J-j<3000}return w1>0&&J-w1<3000}import{randomBytes as q4,timingSafeEqual as R4}from"node:crypto";import{unlink as T4}from"node:fs/promises";import{createServer as E4}from"node:http";import{join as S4}from"node:path";function v4(W){return new Promise((J,j)=>{let $=[],P=0;W.on("data",(N)=>{if(P+=N.length,P>1e6){W.destroy(),j(Error("body too large"));return}$.push(N)}),W.on("end",()=>J(Buffer.concat($).toString("utf8"))),W.on("error",j)})}function A4(W,J){if(!W?.startsWith("Bearer "))return!1;let j=Buffer.from(W.slice(7)),$=Buffer.from(J);return j.length===$.length&&R4(j,$)}async function jW(W){let J=q4(32).toString("hex"),j=E4((N,I)=>{$(N,I)});async function $(N,I){let H=(k,b)=>{I.writeHead(k,{"content-type":"application/json"}),I.end(JSON.stringify(b))};try{let k=N.url??"";if(N.method==="GET"&&k==="/health")return H(200,{ok:!0});if(N.method!=="POST"||!k.startsWith("/rpc/"))return H(404,{error:"not found"});if(!A4(N.headers.authorization,J))return H(401,{error:"unauthorized"});let b=k.slice(5),m=JSON.parse(await v4(N)||"{}");if(b==="pending-notifications"){let S=W.drain(Number(m.lastReceivedId??0),typeof m.sessionId==="string"?m.sessionId:void 0);return H(200,{messages:S})}if(b==="apply"){let S=await W.apply(m);return H(200,S)}return H(404,{error:"unknown method"})}catch(k){H(500,{error:k instanceof Error?k.message:String(k)})}}let P=await new Promise((N,I)=>{j.on("error",I),j.listen(0,"127.0.0.1",()=>{let H=j.address();if(H&&typeof H==="object")N(H.port);else I(Error("no port"))})});j.unref();try{await WW(W.dir,{port:P,token:J,pid:process.pid})}catch(N){throw await new Promise((I)=>j.close(()=>I())),N}return{port:P,token:J,async stop(){await new Promise((N)=>j.close(()=>N())),await T4(S4(W.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function JW(W,J){let j=new Map,$=0,P=0,N=0,I=0,H=0,k=(S)=>{let r=performance.now(),d=W(S);return H+=performance.now()-r,N++,d};return{call:(S)=>{if(!J.enabled())return k(S);let r=j.get(S);if(r!==void 0)return P++,j.delete(S),j.set(S,r),r;let d=k(S),O0=S.length+d.length;if(O0>J.maxBytes)return d;j.set(S,d),$+=O0;while($>J.maxBytes&&j.size>1){let l=j.keys().next().value,j0=j.get(l)??"";j.delete(l),$-=l.length+j0.length,I++}return d},stats:()=>({hits:P,misses:N,evictions:I,entries:j.size,cacheBytes:$,computeMsTotal:H})}}function PW(W){return`${YW}${W.charAt(0).toUpperCase()}${W.slice(1)}`}function fW(W){if(W==="StructuredOutput")return W;return`${W.charAt(0).toLowerCase()}${W.slice(1)}`}var k4=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function $W(W){let J=fW(W);if(J.startsWith("aft_"))return J;if(k4.has(J))return`aft_${J}`;return null}function M1(W,J){let j=new Headers;if(W instanceof Request)W.headers.forEach((P,N)=>{j.set(N,P)});let $=J?.headers;if($){if($ instanceof Headers)$.forEach((P,N)=>{j.set(N,P)});else if(Array.isArray($))for(let P of $){let[N,I]=P;if(typeof I<"u")j.set(N,String(I))}else for(let[P,N]of Object.entries($))if(typeof N<"u")j.set(P,String(N))}return j}function W1(W){return W.set("anthropic-beta",v0(W.get("anthropic-beta"),[_W])),W}function k0(W,J,j={}){return UW(W,J,j)}function y4(W){if(W.tools&&Array.isArray(W.tools))W.tools=W.tools.map((J)=>({...J,name:J.name?PW(J.name):J.name}));if(W.messages&&Array.isArray(W.messages))W.messages=W.messages.map((J)=>{if(J.content&&Array.isArray(J.content))J.content=J.content.map((j)=>{if(j.type==="tool_use"&&j.name)return{...j,name:PW(j.name)};return j});return J});return JSON.stringify(BW(W))}function Q1(W){return W.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(J,j,$)=>{if(j)return`"name": "${$W($)??fW($)}"`;let P=$W($);return P?`"name": "${P}"`:J})}function OW(W,J=!1){if(J)return{ready:Q1(W),pending:""};let j=W.length,$='"name"',P=Math.max(0,W.length-$.length+1);for(let I=P;I<W.length;I++)if($.startsWith(W.slice(I))){j=Math.min(j,I);break}let N=W.lastIndexOf($);if(N!==-1){let I=W.slice(N);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(I))j=Math.min(j,N)}if(j<W.length)return{ready:Q1(W.slice(0,j)),pending:W.slice(j)};return{ready:Q1(W),pending:""}}function U1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let W=process.env.ANTHROPIC_INSECURE?.trim();return W==="1"||W==="true"}function xW(W){let J=W?.trim();if(!J)return null;try{let j=new URL(J);if(j.protocol!=="http:"&&j.protocol!=="https:"||j.username||j.password)return null;return j}catch{return null}}function h4(){return xW(process.env.ANTHROPIC_BASE_URL)}function B1(W,J={}){let j=null;try{if(typeof W==="string"||W instanceof URL)j=new URL(W.toString());else if(W instanceof Request)j=new URL(W.url)}catch{j=null}if(!j)return{input:W,url:null};let $=j.href,P=J.baseURL?xW(J.baseURL):h4();if(P){if(j.protocol=P.protocol,j.host=P.host,J.baseURL)j.pathname=`${P.pathname.replace(/\/$/,"")}${j.pathname}`}if(j.pathname.endsWith("/v1/messages")&&!j.searchParams.has("beta"))j.searchParams.set("beta","true");if(j.href===$)return{input:W,url:j};return{input:W instanceof Request?new Request(j.toString(),W):j,url:j}}function b4(W){let $=W.split(/\n\n+/).filter((P)=>{if(P.includes(DW))return!1;for(let N of zW)if(P.includes(N))return!1;return!0}).join(`

@@ -10,3 +10,3 @@ `);for(let P of wW)$=$.replace(P.match,P.replacement);return $.trim()}var g4=8388608;function m4(){return process.env.OPENCODE_ANTHROPIC_AUTH_MEMO!=="0"}var p4=JW(b4,{maxBytes:g4,enabled:m4});function t0(W){return p4.call(W)}function i(W){return W!=null&&typeof W==="object"&&!Array.isArray(W)}function i4(W){let J={type:"text",text:f0};if(W==null)return[J];if(typeof W==="string"){let $=t0(W);if($===f0)return[J];return[J,{type:"text",text:$}]}if(i(W)){let $=typeof W.type==="string"?W.type:"text",P=typeof W.text==="string"?W.text:"";return[J,{...W,type:$,text:t0(P)}]}if(!Array.isArray(W))return[J];let j=W.map(($)=>{if(typeof $==="string")return{type:"text",text:t0($)};if(i($)&&$.type==="text"&&typeof $.text==="string")return{...$,type:"text",text:t0($.text)};return{type:"text",text:String($)}});if(j[0]?.text===f0)return j;return[J,...j]}var qW={type:"ephemeral",ttl:"1h"},d4=20;function l4(W){if(i(W.cache_control))return W.cache_control;if(i(W.cacheControl))return W.cacheControl;return null}function S0(W,J){if(!i(W))return!1;return delete W.cacheControl,W.cache_control=J?{...qW}:{type:"ephemeral"},!0}function GW(W){if(!i(W))return;delete W.cache_control,delete W.cacheControl}function u4(W){if(Array.isArray(W))return W;if(typeof W==="string")return[{type:"text",text:W}];return null}function s0(W,J){if(!i(W))return;let j=l4(W);if(j?.type!=="ephemeral")return;if(J)j.ttl="1h";else delete j.ttl}function NW(W,J){if(Array.isArray(W.system))for(let j of W.system)s0(j,J);else s0(W.system,J);if(!Array.isArray(W.messages))return;for(let j of W.messages)if(s0(j,J),i(j)&&Array.isArray(j.content))for(let $ of j.content)s0($,J)}function n4(W,J){if(Array.isArray(W.system))for(let j of W.system)J(j);else J(W.system);if(!Array.isArray(W.messages))return;for(let j of W.messages)if(J(j),i(j)&&Array.isArray(j.content))for(let $ of j.content)J($)}function RW(W){GW(W),n4(W,GW)}function c4(W){RW(W),W.cache_control={...qW}}function o4(W){return i(W)&&W.type!=="thinking"&&W.type!=="redacted_thinking"}function j1(W){let J=u4(W.content);if(!J?.length)return;let j=J.filter(o4);if(!j.length)return;return{content:J,cacheableBlocks:j}}function r4(W){if(!i(W))return!1;let J=j1(W);if(!J)return!1;return W.content=J.content,S0(J.cacheableBlocks[0],!0)}function t4(W){if(!i(W))return!1;let J=j1(W);if(!J||J.cacheableBlocks.length<2)return!1;return W.content=J.content,S0(J.cacheableBlocks[1],!0)}function a0(W){if(!i(W))return!1;let J=j1(W);if(!J)return!1;let j=J.cacheableBlocks[J.cacheableBlocks.length-1];return W.content=J.content,S0(j,!0)}function s4(W){if(!i(W))return!1;return(j1(W)?.cacheableBlocks.length??0)>1}function a4(W){if(!i(W))return 0;let J=W.content;if(Array.isArray(J))return J.length;if(J==null)return 0;return 1}function e4(W){let J=[],j=0;return W.forEach(($,P)=>{let N=a4($);if(i($)&&$.role==="user"&&N>0)J.push({index:P,blockPosition:j+N-1});j+=N}),J}function Wj(W){let J=e4(W),j=[...J].reverse().find((I)=>I.index>1);if(!j)return{latest:void 0,bridge:void 0};let $=[...J].reverse().find((I)=>I.index<j.index),P=$?j.blockPosition-$.blockPosition+1:0,N=$&&$.index>1&&P>d4?$:void 0;return{latest:j,bridge:N}}function L1(W){return i(W)&&typeof W.text==="string"?W.text:""}function jj(W){if(!Array.isArray(W.system))return;let J=W.system,j=0;if(L1(J[j]).startsWith("x-anthropic-billing-header:"))j++;if(L1(J[j])===f0)j++;let $=j+1;if($>=J.length-1)return;let P=J[$];if(!i(P))return;let N=J.slice($).map(L1).join(`

`);if(J===-1)return j===-1?null:{index:j,length:4};if(j===-1||J<j)return{index:J,length:2};return{index:j,length:4}}function ZW(W,J){if(!J)return;W.pending+=J;while(!0){let j=TW(W.pending);if(!j)break;let $=W.pending.slice(0,j.index);W.pending=W.pending.slice(j.index+j.length);let P=Zj($);if(!P)continue;if(W.events++,e0(W.eventCounts,P.event??"unknown"),e0(W.typeCounts,P.type),e0(W.deltaTypeCounts,P.deltaType),e0(W.contentBlockTypeCounts,P.contentBlockType),W.textDeltaBytes+=P.textDeltaBytes??0,W.thinkingDeltaBytes+=P.thinkingDeltaBytes??0,W.inputJsonDeltaBytes+=P.inputJsonDeltaBytes??0,W.signatureDeltaBytes+=P.signatureDeltaBytes??0,W.redactedThinkingBytes+=P.redactedThinkingBytes??0,W.last=P,P.dataBytes>0&&!P.type&&!P.event)W.parseErrors++}}function Kj(){return{pending:""}}function Yj(W,J){let j=W?.toLowerCase(),$=J.toLowerCase();return j==="api_error"||j==="overloaded_error"||j==="server_error"||j==="internal_server_error"||$.includes("internal server error")||$.includes("server overloaded")}function _j(W,J){let j=W?`${W}: ${J}`:J,$=Error(`Anthropic stream error: ${j}`);if($.code="ECONNRESET",$.syscall="anthropic-sse",W)$.providerErrorType=W;return $}function Dj(W){if(!W.includes("error"))return null;let J,j=[];for(let b of W.split(/\r?\n/)){if(b.startsWith("event:")){J=b.slice(6).trim();continue}if(b.startsWith("data:")){let m=b.slice(5);j.push(m.startsWith(" ")?m.slice(1):m)}}let $=j.join(`
`);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(`
`);if(!$||$==="[DONE]")return null;let P;try{P=JSON.parse($)}catch{return null}let N=Y0(P);if(J!=="error"&&s(N,"type")!=="error")return null;let I=Y0(N?.error),H=s(I,"type")??s(I,"code")??void 0,k=s(I,"message")??s(N,"message")??H??"Anthropic stream error";if(!Yj(H,k))return null;return _j(H,k)}function KW(W,J){if(!J)return null;W.pending+=J;while(!0){let j=TW(W.pending);if(!j)break;let $=W.pending.slice(0,j.index);W.pending=W.pending.slice(j.index+j.length);let P=Dj($);if(P)return P}return null}function Ij(W){return{sseEvents:W.events,ssePendingChars:W.pending.length,sseParseErrors:W.parseErrors,sseEventCounts:{...W.eventCounts},sseTypeCounts:{...W.typeCounts},sseDeltaTypeCounts:{...W.deltaTypeCounts},sseContentBlockTypeCounts:{...W.contentBlockTypeCounts},sseTextDeltaBytes:W.textDeltaBytes,sseThinkingDeltaBytes:W.thinkingDeltaBytes,sseInputJsonDeltaBytes:W.inputJsonDeltaBytes,sseSignatureDeltaBytes:W.signatureDeltaBytes,sseRedactedThinkingBytes:W.redactedThinkingBytes,sseLastEvent:W.last?{...W.last}:void 0}}function y0(W,J={}){if(!W.body)return W;let j=W.body.getReader(),$=new TextDecoder,P=new TextEncoder,N="",I=0,H=0,k=0,b=0,m=0,S=!1,r=!1,d=v(),O0=v(),l=J.perf?Vj():void 0,j0=Kj(),N0=()=>{if(r)return;r=!0,j.releaseLock()},z0=(a={})=>({chunks:I,pulls:H,inputBytes:k,outputBytes:b,pendingChars:N.length,rewriteMs:P0(m),totalMs:P0(v()-O0),...l?Ij(l):{},...a}),J0=(a,T0={})=>{J.perf?.(a,z0(T0))};J.perf?.("stream_tool_prefix_wrapper_created",{status:W.status,hasBody:!0});let D1=new ReadableStream({async pull(a){if(H++,!S)S=!0,J0("stream_tool_prefix_first_pull");let T0=v();try{let{done:X0,value:w0}=await j.read(),E0=P0(v()-T0);if(X0){let O=$.decode();if(l)ZW(l,O);let G=KW(j0,O);if(G)throw J0("stream_tool_prefix_retryable_error",{error:G.message,providerErrorType:G.providerErrorType}),N0(),G;let Y=v(),L=OW(`${N}${O}`,!0);if(m+=v()-Y,L.ready){let K=P.encode(L.ready);b+=K.byteLength,a.enqueue(K)}J0("stream_tool_prefix_rewrite",{readMs:E0}),N0(),a.close();return}I++,k+=w0.byteLength;let Q0=$.decode(w0,{stream:!0});if(l)ZW(l,Q0);let L0=KW(j0,Q0);if(L0)throw J0("stream_tool_prefix_retryable_error",{error:L0.message,providerErrorType:L0.providerErrorType,readMs:E0,lastChunkBytes:w0.byteLength}),N0(),L0;let I1=N+Q0,M0=v(),U0=OW(I1);if(m+=v()-M0,N=U0.pending,U0.ready){let O=P.encode(U0.ready);b+=O.byteLength,a.enqueue(O)}let n0=v();if(I===1||I%25===0||n0-d>5000)d=n0,J0("stream_tool_prefix_progress",{readMs:E0,lastChunkBytes:w0.byteLength})}catch(X0){throw J0("stream_tool_prefix_error",{error:X0 instanceof Error?X0.message:String(X0)}),N0(),X0}},async cancel(a){J0("stream_tool_prefix_cancel",{reason:a instanceof Error?a.message:String(a)});try{await j.cancel(a)}finally{N0()}}});return new Response(D1,{status:W.status,statusText:W.statusText,headers:W.headers})}var wj="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",Qj=60000,Lj=60000,Mj=5000,EW=200,M4=240,Uj=M4,Bj=1,SW=!1;function _1(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function F(){return performance.now()}function h(W){return Math.round(W*10)/10}function vW(W){return Math.floor(Math.random()*Math.max(0,W))}function J1(W){if(typeof W==="string")return W;if(W instanceof URL)return W.toString();return W.url}function P1(W,J){return J?.method??(W instanceof Request?W.method:void 0)}function AW(W){return W instanceof Error?W.message:String(W)}function Fj(){if(SW||!1||!_1())return;SW=!0;let W=100,J=250,j=F()+W;setInterval(()=>{let $=F(),P=$-j;if(j=$+W,P<J)return;E("[perf] opencode event_loop_lag",{lagMs:h(P),thresholdMs:J})},W).unref?.()}function Cj(W){let J=F(),j={requestId:String(Bj++),start:J,last:J,mark($,P){let N=F();if(_1())E("[perf] opencode request stage",{requestId:j.requestId,stage:$,deltaMs:h(N-j.last),totalMs:h(N-j.start),...P});j.last=N},done($,P){let N=F();if(_1())E("[perf] opencode request done",{requestId:j.requestId,stage:$,deltaMs:h(N-j.last),totalMs:h(N-j.start),...P});j.last=N}};if(_1())E("[perf] opencode request start",{requestId:j.requestId,...W});return j}async function Hj(W,J,j){let $=W.client.session,P=await r1(W.client,J),N={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:j,ignored:!0}]}};if(P?.agent)N.body.agent=P.agent;if(P?.model)N.body.model=P.model;if(P?.variant)N.body.variant=P.variant;if(typeof $?.promptAsync==="function"){await $.promptAsync(N);return}if(typeof $?.prompt==="function"){await Promise.resolve($.prompt(N));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function fj(){throw Error(wj)}function xj(W){if(W.sessionID==null)return!1;let J=W.model;return J?.providerID==="anthropic"||J?.api?.npm==="@ai-sdk/anthropic"||J?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function qj(W){if(W.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return W.push(kW),!0}var Rj={input:0,output:0,cache:{read:0,write:0}};function Tj(W){let J=W["claude-opus-4-8"]??W["claude-opus-4-5"]??Object.values(W)[0];if(!J)return W;return{...W,...Object.fromEntries(Object.values(K4).map((j)=>[j.id,{...J,id:j.id,name:j.name,api:J.api?{...J.api,id:j.id}:void 0,cost:{input:u0.input,output:u0.output,cache:{read:u0.cacheRead,write:u0.cacheWrite5m}},limit:{...J.limit??{},context:V4,output:X4},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:Z4}]))}}function Ej(W){return Object.fromEntries(Object.entries(W).map(([J,j])=>[J,{...j,cost:Rj}]))}var ej=async(W)=>{Fj();let{client:J}=W,j=bW(),$=await A(j),P=new Y4({storage:$,onMainQuotaFetched:async(O,G,Y,L)=>{try{let K=await A(j)??{version:1,accounts:[]},T=oW(K);if(T&&T.checkedAt>=L&&sW(T.quota,K,T.checkedAt)>Date.now()){P.seedMainFromStorage(K);return}K.quota=K.quota??{},K.quota.mainQuota=O,K.quota.mainQuotaCheckedAt=G,K.quota.mainQuotaToken=Y,K.quota.mainLastQuotaApiError=void 0,await b0(K,j,{mainQuota:!0})}catch(K){E("[quota] failed to persist main quota",{error:K instanceof Error?K.message:String(K)})}},onApiError:async(O)=>{try{let G=await A(j)??{version:1,accounts:[]};G.quota=G.quota??{},G.quota.mainLastQuotaApiError=O,await b0(G,j,{mainQuota:!0})}catch(G){E("[quota] failed to persist backoff state",{error:G instanceof Error?G.message:String(G)})}}}),N=new aW({quotaManager:P,onFallbackStorageChanged:()=>{S()}});N.startBackgroundRefresh();let I=null,H=new $4({loadStorage:()=>A(j),prepareHeaders:async(O,G)=>{if(!d)return O;let Y=await d();if(Y.type!=="oauth")return O;if(!Y.access||Y.expires&&Y.expires<Date.now()){if(!I)return O;Y.access=await I()}if(!Y.access)return O;try{let L=JSON.parse(G.bodyText),K=await S1(Y.access,typeof L.model==="string"?L.model:void 0);if(O.delete("anthropic-beta"),k0(O,Y.access,{body:L,identity:K}),O.set("anthropic-beta",v0(O.get("anthropic-beta"),[W4])),L.speed==="fast")W1(O)}catch{k0(O,Y.access)}return O},log:E});d0({enabled:g0($),mode:m0($)}),X1($1($)),K1(O1($));let k=null;if(W.directory){let O=globalThis;if(O.__anthropicAuthRpcServer)await O.__anthropicAuthRpcServer.stop().catch(()=>{}),O.__anthropicAuthRpcServer=void 0;try{k=await jW({dir:Q4(W.directory),drain:a1,apply:L0}),O.__anthropicAuthRpcServer=k}catch(G){E("[rpc] failed to start",{error:G instanceof Error?G.message:String(G)})}}let b={activeId:"main",route:"main"};function m(O,G){b={activeId:G.activeId,route:G.route},P.updateStorage(O),P.seedMainFromStorage(O,G.mainAccessToken),P.seedFallbacksFromAccounts((O?.accounts??[]).filter(W0));let Y=P.getMain(G.mainAccessToken),L=P.getLastApiError(),K=O?.refresh?.mainLastRefreshError,T={main:{quota:Y?.quota??null,quotaBackedOff:P.isBackedOff(),quotaBackoffUntil:L?.nextRetryAt,refreshBackedOff:K?x0(K,G.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:K?.nextRetryAt},fallbacks:(O?.accounts??[]).filter((f)=>f.enabled!==!1&&W0(f)).map((f)=>({id:f.id,label:f.label,quota:f.access?P.getFallback(f.id,f.access)?.quota??null:null,enabled:f.enabled!==!1})),activeId:G.activeId,route:G.route,relay:(()=>{let f=i1(O);return f?{enabled:!0,transport:f.transport??"http"}:null})(),fastMode:Z1(),cacheKeep:{enabled:k1(O),window:O?.cacheKeep?.startHour!=null&&O?.cacheKeep?.endHour!=null?`${O.cacheKeep.startHour}-${O.cacheKeep.endHour}`:void 0,trackedSessions:H.trackedCount()},lastUpdated:Date.now()};return L4(T).catch((f)=>E("[sidebar] state write failed",{error:f instanceof Error?f.message:String(f)}))}async function S(){let O=await A(j),G,Y;if(d)try{let L=await d();G=L.access,Y=L.refresh}catch{}m(O,{activeId:b.activeId,route:b.route,mainAccessToken:G,mainRefreshToken:Y})}function r(O,G){if(!G)return;if(O?.quota?.enabled!==!0)return;if(P.getMain(G))return;if(O0)return;O0=!0,P.refreshMain(G).then(()=>S()).catch(()=>{}).finally(()=>{O0=!1})}let d=null,O0=!1,l=null,j0=0;function N0(O){let G=O?.refresh?.refreshBeforeExpiryMinutes??Uj;return Math.max(M4,G)*60000}function z0(O){return O?.refresh?.enabled!==!1}async function J0(O){if(!O)return;let G=await A(j),Y=G?.refresh?.mainLastRefreshError;if(!G?.refresh||!Y?.tokenHash)return;let L=G1(O);if(Y.tokenHash===L)return;if(Y.nextRetryAt&&Y.nextRetryAt>Date.now()){E("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:Y.nextRetryAt,retryCount:Y.retryCount,remainingMs:Y.nextRetryAt-Date.now()});return}G.refresh.mainLastRefreshError=void 0,await b0(G,j,{mainRefresh:!0}),E("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:Y.checkedAt,previousNextRetryAt:Y.nextRetryAt,previousRetryCount:Y.retryCount})}async function D1(){let O=[];if(d)try{let K=await d();if(K.type==="oauth"&&K.access){let T=await P.refreshMain(K.access);O.push({name:"OpenCode anthropic",role:"main",quota:T})}else if(K.type==="oauth")O.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(K){let T=K instanceof Error?K.message:String(K);O.push({name:"OpenCode anthropic",role:"main",error:T.includes("429")?"Usage API rate limited — try again in a moment":T})}let{storage:G,errors:Y}=await N.refreshQuotaForAllAccounts({force:!0}),L=new Map(Y.map((K)=>[K.accountId,K.message]));if(O.push(..._4(G,L)),!d)O.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return D4({accounts:O,refreshedAt:Date.now()})}async function a(O){let G=eW(O);if(G.type==="enable"||G.type==="disable"){let T=G.type==="enable",f=await mW(T),y=m0(f);return d0({enabled:T,mode:y}),V1({argumentsText:O,enabled:T,mode:y})}if(G.type==="mode"){let T=await pW(G.mode),f=g0(T);return d0({enabled:f,mode:G.mode}),V1({argumentsText:O,enabled:f,mode:G.mode})}let Y=await A(j),L=g0(Y),K=m0(Y);return d0({enabled:L,mode:K}),V1({argumentsText:O,enabled:L,mode:K})}async function T0(O){let G=j4(O),Y=await A(j);if(G.type==="window")Y=await lW(G.startHour,G.endHour);else if(G.type==="disable")Y=await uW(!1);let L=A1(Y),K=H.stats(L);return P4({argumentsText:O,enabled:J4(Y),window:L,hybridActive:k1(Y),trackedSessions:K.trackedSessions,nextPrewarmAt:K.nextPrewarmAt})}async function X0(O){let G=O4(O);if(G.type==="enable"||G.type==="disable"){let K=G.type==="enable";return await iW(K),X1(K),h1({argumentsText:O,enabled:K})}let Y=await A(j),L=$1(Y);return X1(L),h1({argumentsText:O,enabled:L})}async function w0(O){let G=G4(O);if(G.type==="enable"||G.type==="disable"){let K=G.type==="enable";return await dW(K),K1(K),g1({argumentsText:O,enabled:K})}let Y=await A(j),L=O1(Y);return K1(L),g1({argumentsText:O,enabled:L})}async function E0(O){let G=w4(O);if(G.type==="mode")return await z4(G.mode),l1({argumentsText:O,mode:G.mode});let Y=await A();return l1({argumentsText:O,mode:Y1(Y)})}async function Q0(O,G){if(O==="claude-quota")return{command:O,text:await D1(),knobs:{}};if(O==="claude-routing"){let f=await E0(G),y=await A(j);return{command:O,text:f,knobs:{mode:Y1(y)}}}if(O==="claude-fast"){let f=await w0(G),y=await A(j);return{command:O,text:f,knobs:{enabled:O1(y)}}}if(O==="claude-dump"){let f=await X0(G),y=await A(j);return{command:O,text:f,knobs:{enabled:$1(y)}}}if(O==="claude-cache"){let f=await a(G),y=await A(j);return{command:O,text:f,knobs:{enabled:g0(y),mode:m0(y)}}}if(O==="claude-cachekeep"){let f=await T0(G),y=await A(j);return{command:O,text:f,knobs:{window:A1(y)}}}let Y=await A(),L=T1(Y),K=(Y?.accounts??[]).filter((f)=>f.enabled!==!1).map((f)=>f.id),T=N4({argumentsText:G,config:L,accountIds:K});if(T.updatedConfig)await tW(T.updatedConfig);return{command:O,text:T.text,knobs:{config:T1(await A()),accountIds:K}}}async function L0(O){let G=await Q0(O.command,O.arguments);return{text:G.text,knobs:G.knobs}}function I1(O,G=10){let Y=Math.max(0,Math.min(Math.round(O/100*G),G));return"█".repeat(Y)+"░".repeat(G-Y)}function M0(O,G){return`${O} ${I1(G)} ${String(Math.round(G)).padStart(3)}%`}function U0(O){if(!O)return"";let G=new Date(O).getTime();if(Number.isNaN(G))return"";let Y=G-Date.now();if(Y<=0)return"resets now";let L=Math.floor(Y/60000);if(L<1)return"resets <1m";if(L<60)return`resets ${L}m`;let K=Math.floor(L/60),T=L%60;return T>0?`resets ${K}h${T}m`:`resets ${K}h`}function n0(O,G,Y){let L=[],K=0;if(O){let{five_hour:y,seven_day:$0}=O;if(y||$0){let V0=Y==="main"?"active":"idle",_0=U0(y?.resetsAt),B0=[`main · ${V0}${_0?` (${_0})`:""}`];if(y)B0.push(M0("5h",y.usedPercent)),K=Math.max(K,y.usedPercent);if($0)B0.push(M0("7d",$0.usedPercent)),K=Math.max(K,$0.usedPercent);L.push(B0.join(`
`))}}if(G?.length)for(let y of G){let $0=y.quota;if(!$0)continue;let{five_hour:Z0,seven_day:V0}=$0;if(!Z0&&!V0)continue;let _0=y.label||"alt",c0=Y===y.id?"active":"idle",F0=U0(Z0?.resetsAt),D0=[`${_0} · ${c0}${F0?` (${F0})`:""}`];if(Z0)D0.push(M0("5h",Z0.usedPercent)),K=Math.max(K,Z0.usedPercent);if(V0)D0.push(M0("7d",V0.usedPercent)),K=Math.max(K,V0.usedPercent);L.push(D0.join(`

@@ -17,2 +17,2 @@ `))}if(!L.length)return;let T=L.join(`

`)&&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};
`)&&p.length<65536){let{done:V,value:z}=await w.read();if(V)break;if(x.push(z),_+=z.byteLength,p+=Z.decode(z,{stream:!0}),$0(p))break}if($0(p)){await w.cancel().catch(()=>{});try{w.releaseLock()}catch{}let V=new ReadableStream({start(z){for(let B of x)z.enqueue(B);z.close()}});return D?.mark("inspect_stream_first_event",{ms:h(F()-q),bytes:_,rateLimited:!0}),{response:new Response(V,{status:X.status,statusText:X.statusText,headers:X.headers}),rateLimited:!0}}let R=new ReadableStream({start(V){for(let z of x)V.enqueue(z)},async pull(V){let{done:z,value:B}=await w.read();if(z){V.close();return}V.enqueue(B)},cancel(V){return w.cancel(V)}});return D?.mark("inspect_stream_first_event",{ms:h(F()-q),bytes:_,rateLimited:!1}),{response:new Response(R,{status:X.status,statusText:X.statusText,headers:X.headers}),rateLimited:!1}}async function B0(X,D,q,w,x="api_fallback",Z){let p=F(),_=M1(X,D),R=_.get("x-session-affinity")||_.get("x-opencode-session"),V=y(_);_.delete("x-parent-session-id"),_.delete("x-session-affinity"),_.delete("x-opencode-session");let z=D?.body,B=typeof z==="string"?z.length:void 0;if(z&&typeof z==="string"){let C=F(),Q=(()=>{if(!Z1())return!1;try{return A0(JSON.parse(z).model)}catch{return!1}})();if(z=await F1(z,{cache1hEnabled:!V&&q0(),cache1hMode:R0(),fastModeEnabled:Q,perf:(U,g)=>w?.mark(`rewrite_body_${U}`,{route:x,...g})}),_0(_,q),_.set("anthropic-beta",v0(_.get("anthropic-beta"),[])),Q)W1(_);w?.mark("rewrite_body",{route:x,ms:h(F()-C),originalBytes:B,rewrittenBytes:z.length,cacheEnabled:!V&&q0(),cacheMode:R0(),fastModeEnabled:Q,subagent:V})}else _0(_,q);let M=B1(X,{baseURL:q.baseURL}),c=F(),u;try{u=await fetch(M.input,{...D,body:z,headers:_,...U1()&&{tls:{rejectUnauthorized:!1}}})}catch(C){if(typeof z==="string")await l0({affinity:R,route:x,error:AW(C),bodyText:z,url:M.url?.toString()??J1(M.input),method:P1(X,D),headers:_});throw C}if(typeof z==="string")await l0({affinity:R,route:x,status:u.status,bodyText:z,url:M.url?.toString()??J1(M.input),method:P1(X,D),headers:_});return w?.mark("send_headers_received",{route:x,ms:h(F()-c),status:u.status,relayConfigured:!1,totalSendWithAccessMs:h(F()-p),baseURL:q.baseURL}),u}async function c0(X,D,q,w,x="unknown",Z){let p=F(),_=Z,R=async()=>{return _??=await A(j),_},V=M1(X,D),z=V.get("x-session-affinity")||V.get("x-opencode-session"),B=y(V);V.delete("x-parent-session-id"),V.delete("x-session-affinity"),V.delete("x-opencode-session");let M=D?.body,c;if(M&&typeof M==="string"){let o=F();try{let G0=JSON.parse(M);if(typeof G0.model==="string")c=G0.model}catch{}w?.mark("model_parse_for_identity",{route:x,ms:h(F()-o),bodyBytes:M.length})}let u=F(),C=await S1(q,c);w?.mark("resolve_claude_code_identity",{route:x,ms:h(F()-u),hasAccountUuid:Boolean(C.accountUuid)});let Q=typeof M==="string"?M.length:void 0;if(M&&typeof M==="string"){let o=F(),G0=(()=>{if(!Z1())return!1;try{return A0(JSON.parse(M).model)}catch{return!1}})();M=await F1(M,{cache1hEnabled:!B&&q0(),cache1hMode:R0(),fastModeEnabled:G0,identity:C,perf:(F4,C4)=>w?.mark(`rewrite_body_${F4}`,{route:x,...C4})});let C0=F();try{k0(V,q,{body:JSON.parse(M),identity:C}),w?.mark("set_oauth_headers_body_parse",{route:x,ms:h(F()-C0),bodyBytes:M.length,parsed:!0})}catch{k0(V,q,{identity:C}),w?.mark("set_oauth_headers_body_parse",{route:x,ms:h(F()-C0),bodyBytes:M.length,parsed:!1})}if(G0)W1(V);w?.mark("rewrite_body",{route:x,ms:h(F()-o),originalBytes:Q,rewrittenBytes:M.length,cacheEnabled:!B&&q0(),cacheMode:R0(),fastModeEnabled:G0,subagent:B})}let U=B1(X);if(x==="main"&&typeof M==="string"&&!B&&q0()&&R0()==="hybrid"){let o=await R(),G0=F(),C0=H.track({sessionId:z,url:U.url?.toString()??U.input.toString(),headers:V,bodyText:M,storage:o,cacheMode:"hybrid"});w?.mark("cachekeep_track",{session:z,ms:h(F()-G0),tracked:C0.tracked,reason:C0.tracked?void 0:C0.reason,bodyBytes:M.length})}let g=async()=>{try{let o=await fetch(U.input,{...D,body:M,headers:V,...U1()&&{tls:{rejectUnauthorized:!1}}});if(typeof M==="string")await l0({affinity:z,route:x,status:o.status,bodyText:M,url:U.url?.toString()??J1(U.input),method:P1(X,D),headers:V});return o}catch(o){if(typeof M==="string")await l0({affinity:z,route:x,error:AW(o),bodyText:M,url:U.url?.toString()??J1(U.input),method:P1(X,D),headers:V});throw o}},e=i1(await R()),n=F(),t=await I4({config:e,input:U.input,init:D,headers:V,body:M,fallback:g,affinity:z,optimisticResponse:e?.transport==="websocket"});return w?.mark("send_headers_received",{route:x,ms:h(F()-n),status:t.status,relayConfigured:e!=null,totalSendWithAccessMs:h(F()-p)}),t}async function U4(X){if(!X)return!1;try{return await P.refreshMain(X),z1(X)}catch{return!1}}async function o0(X,D={}){let q=await N.getUsableFallbackAccounts(X),w=new Map(q.map((Z)=>[Z.id,Z])),x=[];for(let Z of X?.accounts??[]){if(W0(Z)){let p=w.get(Z.id);if(p)x.push(p);continue}if(D.includeApiRoutes===!0&&h0(Z)&&Z.enabled!==!1&&Z.apiKey&&x1(Z.baseURL))x.push(Z)}if(!i0(X))return x;return x.filter((Z)=>W0(Z)?N1(F0(Z),X,Z.id):!0)}async function r0(X,D,q,w,x,Z,p){if(!q.length)return x??null;let _=p?.returnLastOnExhausted??!0;await x?.body?.cancel().catch(()=>{});let R=x??null;for(let[V,z]of q.entries()){let B;if(h0(z)){if(!z.apiKey)continue;B=await B0(X,D,z,Z,`api_fallback_${V}`,w)}else{let c=z.access;if(!c)continue;B=await c0(X,D,c,Z,`fallback_${V}`,w)}R=B;let M=q1(B.status,w);if(!M){let c=await V0(B,Z);B=c.response,R=B,M=c.rateLimited}if(!M){if(await N.markUsed(z),await p?.onSuccess?.(z),W0(z)&&z.access&&P.shouldRefreshOnRequestCount(j0))P.refreshFallback(z.id,z.access).then(()=>p?.onSuccess?.(z)).catch(()=>{});return B}if(V<q.length-1||!_)await B.body?.cancel().catch(()=>{})}return _?R:null}async function B4(X,D,q,w,x,Z,p,_){if(!f(X,D?.body))return q;let R=F(),V=Z??await A(j);if(x?.mark("fallback_load_storage",{ms:h(F()-R),cached:!!Z}),!(V?.accounts??[]).some((Q)=>Q.enabled!==!1&&(W0(Q)||h0(Q)&&Boolean(Q.apiKey)&&x1(Q.baseURL))))return q;let B=q,M=q1(B.status,V),c=u1(B,!1);if(!M){let Q=await V0(B,x);B=Q.response,M=Q.rateLimited,c=u1(B,Q.rateLimited)}if(!M)return B;let u=!1;if(w)u=w.some(h0);else if(c)u=await U4(p);let C=w;if(!C){let Q=F();C=await o0(V,{includeApiRoutes:u}),x?.mark("fallback_get_accounts",{ms:h(F()-Q),accounts:C.length})}if(i0(V)){let Q=C.length;if(C=C.filter((U)=>W0(U)?N1(F0(U),V,U.id):!0),C.length<Q)E("[killswitch] filtered fallbacks",{before:Q,after:C.length})}return await r0(X,D,C,V,B,x,{onSuccess:_})??B}return{apiKey:"",async fetch(X,D){let q=D?.body,w=Cj({bodyBytes:typeof q==="string"?q.length:void 0}),x=F(),Z=await O();if(w.mark("get_auth",{ms:h(F()-x),authType:Z.type,hasAccess:Boolean(Z.access)}),Z.type!=="oauth"){let Q=await fetch(X,D);return w.done("non_oauth_passthrough",{status:Q.status}),Q}await J0(Z.refresh);let p=F(),_=await A();w.mark("load_storage",{ms:h(F()-p)}),P.updateStorage(_),P.seedMainFromStorage(_,Z.access),P.seedFallbacksFromAccounts((_?.accounts??[]).filter(W0));let R=f(X,D?.body);if(R)j0++;if(R&&Z.access&&(!Z.expires||Z.expires>Date.now()))r(_,Z.access);let V=(Q,U)=>m(_,{activeId:Q,route:U,mainAccessToken:Z.access,mainRefreshToken:Z.refresh}),z;if(R&&Y1(_)==="fallback-first")try{let Q=F();z=await o0(_,{includeApiRoutes:z1(Z.access)}),w.mark("fallback_first_get_accounts",{ms:h(F()-Q),accounts:z.length});let U=await r0(X,D,z,_,void 0,w,{returnLastOnExhausted:!1,onSuccess:(g)=>V(g.id,"fallback-first")});if(U)return w.done("return_fallback_first",{status:U.status}),y0(U,{perf:(g,e)=>w.mark(g,e)});z=void 0}catch(Q){w.mark("fallback_first_error",{error:Q instanceof Error?Q.message:String(Q)})}if(!Z.access||!Z.expires||Z.expires<Date.now()){let U=(await A())?.refresh?.mainLastRefreshError;if(Z.refresh&&U&&x0(U,Z.refresh,Date.now()))throw E("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:U.nextRetryAt,retryCount:U.retryCount,expiresInMs:Z.expires?Z.expires-Date.now():void 0}),Error(R1(U,Date.now()));E("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(Z.access),expiresInMs:Z.expires?Z.expires-Date.now():void 0,expiredAgoMs:Z.expires&&Z.expires<Date.now()?Date.now()-Z.expires:void 0});let g=F();Z.access=await K(),w.mark("refresh_main_access",{ms:h(F()-g)})}if(!Z.access)throw w.done("missing_access_error"),Error("OAuth access token is missing after refresh");function B(){if(_?.quota?.showToasts!==!0)return;let Q=P.getMain();if(!Q)return;let U=(_?.accounts??[]).filter((n)=>n.enabled!==!1&&W0(n)).map((n)=>({...n,quota:P.getFallback(n.id,n.access)?.quota??n.quota})),g=p0(Q.quota,_),e;if(g)e="main";else e=U.find((n)=>p0(n.quota,_))?.id??"main";n0(Q.quota,U,e)}if(R&&Z0(_))try{let Q=F(),U=P.getMain(Z.access),g=U?.quota;if(!g)g=await P.refreshMain(Z.access),U=P.getMain(Z.access),B();else if(P.needsRefresh(j0))if(D0(g))g=await P.refreshMain(Z.access),U=P.getMain(Z.access);else P.refreshMain(Z.access).then(()=>{S(),B()}).catch(()=>{});if(m(_,{activeId:"main",route:"main",mainAccessToken:Z.access,mainRefreshToken:Z.refresh}),w.mark("main_quota_for_routing",{ms:h(F()-Q),passes:p0(g,_)}),!p0(g,_)){let e=F();z=await o0(_,{includeApiRoutes:Boolean(U&&U.refreshAfter>Date.now()&&D0(U.quota))}),w.mark("preselect_fallback_accounts",{ms:h(F()-e),accounts:z.length});let n=await r0(X,D,z,_,void 0,w,{onSuccess:(t)=>V(t.id,"fallback")});if(n)return w.done("return_preselected_fallback",{status:n.status}),y0(n,{perf:(t,o)=>w.mark(t,o)})}}catch(Q){w.mark("main_quota_for_routing_error",{error:Q instanceof Error?Q.message:String(Q)})}let M=P.getMain(Z.access)?.quota;if(_?.quota?.failClosedOnUnknownQuota&&!M&&P.isBackedOff()){let Q=P.getLastApiError(),U=Q?cW(Q,Date.now()):"Quota API unavailable";return E("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:Q?.nextRetryAt,retryCount:Q?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:U}}),{status:429,headers:{"content-type":"application/json","retry-after":String(Q?.nextRetryAt?Math.max(1,Math.ceil((Q.nextRetryAt-Date.now())/1000)):60)}})}if(i0(_)){if(P.needsRefresh(j0))try{let U=(_?.accounts??[]).filter((g)=>g.enabled!==!1&&W0(g)&&Boolean(g.access));await Promise.all([P.refreshMain(Z.access),P.refreshAllFallbacks(U)])}catch(U){E("[quota] killswitch refresh failed",{error:U instanceof Error?U.message:String(U),backedOff:P.isBackedOff()})}M=P.getMain(Z.access)?.quota}if(i0(_)&&!N1(M,_)){let U=f(X,D?.body)?await o0(_,{includeApiRoutes:z1(Z.access)}):[];if(U.length>0){E("[route] skipping main (killswitch), trying fallbacks");let t=await r0(X,D,U,_,void 0,w,{onSuccess:(o)=>V(o.id,"fallback")});if(t)return w.done("return_killswitch_fallback",{status:t.status}),y0(t,{perf:(o,G0)=>w.mark(o,G0)})}let g=Date.now(),e=(_?.accounts??[]).filter((t)=>t.enabled!==!1&&W0(t)).map((t)=>({...t,quota:F0(t)})),n=rW(M,e,g);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:`Killswitch: no routable accounts. Retry in ${Math.floor(n/60)}m ${n%60}s.`}}),{status:429,headers:{"content-type":"application/json","retry-after":String(n)}})}let c=await c0(X,D,Z.access,w,"main",_),u=!1,C=await B4(X,D,c,z,w,_,Z.access,(Q)=>{u=!0,V(Q.id,"fallback")});if(!u)V("main","main");return w.done("return_response",{status:C.status}),y0(C,{perf:(Q,U)=>w.mark(Q,U)})}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let O=await H1("max");return{url:O.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{return f1(G,O.verifier,O.redirectUri,O.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let O=await H1("console");return{url:O.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{let Y=await f1(G,O.verifier,O.redirectUri,O.state);if(Y.type==="failed")return Y;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${Y.access}`}}).then((K)=>K.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{ej as AnthropicAuthPlugin};

@@ -1,2 +0,2 @@

import{hb as P,ib as C,jb as _}from"./index-p8j7mmfc.js";var g=C((T,L)=>{(function(Q){if(typeof L==="object"&&typeof L.exports==="object"){var J=Q(_,T);if(J!==void 0)L.exports=J}else if(typeof define==="function"&&define.amd)define(["require","exports","./impl/format","./impl/edit","./impl/scanner","./impl/parser"],Q)})(function(Q,J){Object.defineProperty(J,"__esModule",{value:!0}),J.applyEdits=J.modify=J.format=J.printParseErrorCode=J.ParseErrorCode=J.stripComments=J.visit=J.getNodeValue=J.getNodePath=J.findNodeAtOffset=J.findNodeAtLocation=J.parseTree=J.parse=J.getLocation=J.SyntaxKind=J.ScanError=J.createScanner=void 0;let X=Q("./impl/format"),Z=Q("./impl/edit"),G=Q("./impl/scanner"),$=Q("./impl/parser");J.createScanner=G.createScanner;var W;(function(z){z[z.None=0]="None",z[z.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=2]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",z[z.InvalidUnicode=4]="InvalidUnicode",z[z.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",z[z.InvalidCharacter=6]="InvalidCharacter"})(W||(J.ScanError=W={}));var H;(function(z){z[z.OpenBraceToken=1]="OpenBraceToken",z[z.CloseBraceToken=2]="CloseBraceToken",z[z.OpenBracketToken=3]="OpenBracketToken",z[z.CloseBracketToken=4]="CloseBracketToken",z[z.CommaToken=5]="CommaToken",z[z.ColonToken=6]="ColonToken",z[z.NullKeyword=7]="NullKeyword",z[z.TrueKeyword=8]="TrueKeyword",z[z.FalseKeyword=9]="FalseKeyword",z[z.StringLiteral=10]="StringLiteral",z[z.NumericLiteral=11]="NumericLiteral",z[z.LineCommentTrivia=12]="LineCommentTrivia",z[z.BlockCommentTrivia=13]="BlockCommentTrivia",z[z.LineBreakTrivia=14]="LineBreakTrivia",z[z.Trivia=15]="Trivia",z[z.Unknown=16]="Unknown",z[z.EOF=17]="EOF"})(H||(J.SyntaxKind=H={})),J.getLocation=$.getLocation,J.parse=$.parse,J.parseTree=$.parseTree,J.findNodeAtLocation=$.findNodeAtLocation,J.findNodeAtOffset=$.findNodeAtOffset,J.getNodePath=$.getNodePath,J.getNodeValue=$.getNodeValue,J.visit=$.visit,J.stripComments=$.stripComments;var q;(function(z){z[z.InvalidSymbol=1]="InvalidSymbol",z[z.InvalidNumberFormat=2]="InvalidNumberFormat",z[z.PropertyNameExpected=3]="PropertyNameExpected",z[z.ValueExpected=4]="ValueExpected",z[z.ColonExpected=5]="ColonExpected",z[z.CommaExpected=6]="CommaExpected",z[z.CloseBraceExpected=7]="CloseBraceExpected",z[z.CloseBracketExpected=8]="CloseBracketExpected",z[z.EndOfFileExpected=9]="EndOfFileExpected",z[z.InvalidCommentToken=10]="InvalidCommentToken",z[z.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=12]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",z[z.InvalidUnicode=14]="InvalidUnicode",z[z.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",z[z.InvalidCharacter=16]="InvalidCharacter"})(q||(J.ParseErrorCode=q={}));function D(z){switch(z){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}J.printParseErrorCode=D;function m(z,U,j){return X.format(z,U,j)}J.format=m;function f(z,U,j,A){return Z.setProperty(z,U,j,A)}J.modify=f;function u(z,U){let j=U.slice(0).sort((I,Y)=>{let F=I.offset-Y.offset;if(F===0)return I.length-Y.length;return F}),A=z.length;for(let I=j.length-1;I>=0;I--){let Y=j[I];if(Y.offset+Y.length<=A)z=Z.applyEdit(z,Y);else throw Error("Overlapping edit");A=Y.offset}return z}J.applyEdits=u})});var M=P(g(),1);import{watch as K}from"node:fs";import{mkdir as c,readFile as O,rename as y,writeFile as S}from"node:fs/promises";import{homedir as E}from"node:os";import{basename as l,dirname as v,join as k}from"node:path";var p="OPENCODE_TUI_PREFERENCES_FILE",x="tui-preferences.jsonc";function w(){let Q=process.env[p];if(Q)return Q;let J=process.env.OPENCODE_CONFIG_DIR||k(process.env.XDG_CONFIG_HOME||k(E(),".config"),"opencode");return k(J,x)}function N(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}async function Xz(){try{let Q=await O(w(),"utf8"),J=[],X=M.parse(Q,J,{allowTrailingComma:!0});if(J.length>0)return{};return N(X)?X:{}}catch{return{}}}var i="anthropic-auth",s=160,b={forceToTop:!1,order:s,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"CLAUDE",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,cache:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function V(Q,J){return typeof Q==="boolean"?Q:J}function B(Q,J,X,Z){if(typeof Q!=="number"||!Number.isFinite(Q))return J;return Math.min(Math.max(Math.round(Q),X),Z)}function d(Q,J,X){if(typeof Q!=="string"||Q.length===0)return J;return Q.slice(0,X)}function h(Q,J){if(typeof Q!=="string")return J;return[...Q][0]??J}function Zz(Q){let J=Q[i];if(!N(J))return structuredClone(b);let X=b,Z=N(J.header)?J.header:{},G=N(J.sections)?J.sections:{},$=N(J.appearance)?J.appearance:{},W=B($.warnThreshold,X.appearance.warnThreshold,0,99),H=Math.max(B($.errorThreshold,X.appearance.errorThreshold,0,100),Math.min(W+1,100));return{forceToTop:V(J.forceToTop,X.forceToTop),order:B(J.order,X.order,-1e4,1e4),startCollapsed:V(J.startCollapsed,X.startCollapsed),rememberCollapsed:V(J.rememberCollapsed,X.rememberCollapsed),collapsed:typeof J.collapsed==="boolean"?J.collapsed:null,pollMs:B(J.pollMs,X.pollMs,500,30000),refreshDebounceMs:B(J.refreshDebounceMs,X.refreshDebounceMs,50,5000),header:{label:d(Z.label,X.header.label,20),showVersion:V(Z.showVersion,X.header.showVersion)},sections:{quota:V(G.quota,X.sections.quota),fallbackAccounts:V(G.fallbackAccounts,X.sections.fallbackAccounts),routing:V(G.routing,X.sections.routing),cache:V(G.cache,X.sections.cache),health:V(G.health,X.sections.health),pacing:V(G.pacing,X.sections.pacing)},appearance:{barWidth:B($.barWidth,X.appearance.barWidth,4,40),barFilledChar:h($.barFilledChar,X.appearance.barFilledChar),barEmptyChar:h($.barEmptyChar,X.appearance.barEmptyChar),warnThreshold:W,errorThreshold:H}}}var n=-1e5;function $z(Q,J,X){let Z=Q[J];if(!N(Z))return X;if(Z.forceToTop===!0)return n+Object.keys(Q).indexOf(J);return B(Z.order,X,-1e4,1e4)}var t=`// Shared preferences for opencode TUI plugins.
import{hb as K,ib as P,jb as _}from"./index-p8j7mmfc.js";var T=P((g,L)=>{(function(Q){if(typeof L==="object"&&typeof L.exports==="object"){var J=Q(_,g);if(J!==void 0)L.exports=J}else if(typeof define==="function"&&define.amd)define(["require","exports","./impl/format","./impl/edit","./impl/scanner","./impl/parser"],Q)})(function(Q,J){Object.defineProperty(J,"__esModule",{value:!0}),J.applyEdits=J.modify=J.format=J.printParseErrorCode=J.ParseErrorCode=J.stripComments=J.visit=J.getNodeValue=J.getNodePath=J.findNodeAtOffset=J.findNodeAtLocation=J.parseTree=J.parse=J.getLocation=J.SyntaxKind=J.ScanError=J.createScanner=void 0;let X=Q("./impl/format"),Z=Q("./impl/edit"),G=Q("./impl/scanner"),$=Q("./impl/parser");J.createScanner=G.createScanner;var W;(function(z){z[z.None=0]="None",z[z.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=2]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",z[z.InvalidUnicode=4]="InvalidUnicode",z[z.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",z[z.InvalidCharacter=6]="InvalidCharacter"})(W||(J.ScanError=W={}));var H;(function(z){z[z.OpenBraceToken=1]="OpenBraceToken",z[z.CloseBraceToken=2]="CloseBraceToken",z[z.OpenBracketToken=3]="OpenBracketToken",z[z.CloseBracketToken=4]="CloseBracketToken",z[z.CommaToken=5]="CommaToken",z[z.ColonToken=6]="ColonToken",z[z.NullKeyword=7]="NullKeyword",z[z.TrueKeyword=8]="TrueKeyword",z[z.FalseKeyword=9]="FalseKeyword",z[z.StringLiteral=10]="StringLiteral",z[z.NumericLiteral=11]="NumericLiteral",z[z.LineCommentTrivia=12]="LineCommentTrivia",z[z.BlockCommentTrivia=13]="BlockCommentTrivia",z[z.LineBreakTrivia=14]="LineBreakTrivia",z[z.Trivia=15]="Trivia",z[z.Unknown=16]="Unknown",z[z.EOF=17]="EOF"})(H||(J.SyntaxKind=H={})),J.getLocation=$.getLocation,J.parse=$.parse,J.parseTree=$.parseTree,J.findNodeAtLocation=$.findNodeAtLocation,J.findNodeAtOffset=$.findNodeAtOffset,J.getNodePath=$.getNodePath,J.getNodeValue=$.getNodeValue,J.visit=$.visit,J.stripComments=$.stripComments;var q;(function(z){z[z.InvalidSymbol=1]="InvalidSymbol",z[z.InvalidNumberFormat=2]="InvalidNumberFormat",z[z.PropertyNameExpected=3]="PropertyNameExpected",z[z.ValueExpected=4]="ValueExpected",z[z.ColonExpected=5]="ColonExpected",z[z.CommaExpected=6]="CommaExpected",z[z.CloseBraceExpected=7]="CloseBraceExpected",z[z.CloseBracketExpected=8]="CloseBracketExpected",z[z.EndOfFileExpected=9]="EndOfFileExpected",z[z.InvalidCommentToken=10]="InvalidCommentToken",z[z.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=12]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",z[z.InvalidUnicode=14]="InvalidUnicode",z[z.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",z[z.InvalidCharacter=16]="InvalidCharacter"})(q||(J.ParseErrorCode=q={}));function D(z){switch(z){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}J.printParseErrorCode=D;function f(z,U,j){return X.format(z,U,j)}J.format=f;function u(z,U,j,A){return Z.setProperty(z,U,j,A)}J.modify=u;function C(z,U){let j=U.slice(0).sort((I,Y)=>{let F=I.offset-Y.offset;if(F===0)return I.length-Y.length;return F}),A=z.length;for(let I=j.length-1;I>=0;I--){let Y=j[I];if(Y.offset+Y.length<=A)z=Z.applyEdit(z,Y);else throw Error("Overlapping edit");A=Y.offset}return z}J.applyEdits=C})});var M=K(T(),1);import{watch as c}from"node:fs";import{mkdir as y,readFile as O,rename as S,writeFile as E}from"node:fs/promises";import{homedir as l}from"node:os";import{basename as p,dirname as m,join as k}from"node:path";import{clearTimeout as b,setTimeout as x}from"node:timers";var i="OPENCODE_TUI_PREFERENCES_FILE",s="tui-preferences.jsonc";function w(){let Q=process.env[i];if(Q)return Q;let J=process.env.OPENCODE_CONFIG_DIR||k(process.env.XDG_CONFIG_HOME||k(l(),".config"),"opencode");return k(J,s)}function N(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}async function Gz(){try{let Q=await O(w(),"utf8"),J=[],X=M.parse(Q,J,{allowTrailingComma:!0});if(J.length>0)return{};return N(X)?X:{}}catch{return{}}}var d="anthropic-auth",n=160,h={forceToTop:!1,order:n,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"CLAUDE",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,cache:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function V(Q,J){return typeof Q==="boolean"?Q:J}function B(Q,J,X,Z){if(typeof Q!=="number"||!Number.isFinite(Q))return J;return Math.min(Math.max(Math.round(Q),X),Z)}function a(Q,J,X){if(typeof Q!=="string"||Q.length===0)return J;return Q.slice(0,X)}function v(Q,J){if(typeof Q!=="string")return J;return[...Q][0]??J}function Hz(Q){let J=Q[d];if(!N(J))return structuredClone(h);let X=h,Z=N(J.header)?J.header:{},G=N(J.sections)?J.sections:{},$=N(J.appearance)?J.appearance:{},W=B($.warnThreshold,X.appearance.warnThreshold,0,99),H=Math.max(B($.errorThreshold,X.appearance.errorThreshold,0,100),Math.min(W+1,100));return{forceToTop:V(J.forceToTop,X.forceToTop),order:B(J.order,X.order,-1e4,1e4),startCollapsed:V(J.startCollapsed,X.startCollapsed),rememberCollapsed:V(J.rememberCollapsed,X.rememberCollapsed),collapsed:typeof J.collapsed==="boolean"?J.collapsed:null,pollMs:B(J.pollMs,X.pollMs,500,30000),refreshDebounceMs:B(J.refreshDebounceMs,X.refreshDebounceMs,50,5000),header:{label:a(Z.label,X.header.label,20),showVersion:V(Z.showVersion,X.header.showVersion)},sections:{quota:V(G.quota,X.sections.quota),fallbackAccounts:V(G.fallbackAccounts,X.sections.fallbackAccounts),routing:V(G.routing,X.sections.routing),cache:V(G.cache,X.sections.cache),health:V(G.health,X.sections.health),pacing:V(G.pacing,X.sections.pacing)},appearance:{barWidth:B($.barWidth,X.appearance.barWidth,4,40),barFilledChar:v($.barFilledChar,X.appearance.barFilledChar),barEmptyChar:v($.barEmptyChar,X.appearance.barEmptyChar),warnThreshold:W,errorThreshold:H}}}var t=-1e5;function Vz(Q,J,X){let Z=Q[J];if(!N(Z))return X;if(Z.forceToTop===!0)return t+Object.keys(Q).indexOf(J);return B(Z.order,X,-1e4,1e4)}var o=`// Shared preferences for opencode TUI plugins.
// One top-level key per plugin (short name). See each plugin's README for

@@ -6,2 +6,2 @@ // its supported settings. This file is safe to hand-edit; plugins update

{}
`;async function a(Q,J,X){let Z=w();await c(v(Z),{recursive:!0});let G;try{G=await O(Z,"utf8")}catch{G=""}if(G.trim()==="")G=t;let $=M.modify(G,[Q,...J],X,{formattingOptions:{insertSpaces:!0,tabSize:2}}),W=M.applyEdits(G,$),H=`${Z}.${process.pid}.tmp`;await S(H,W,"utf8"),await y(H,Z)}var R=Promise.resolve();function Gz(Q,J,X){return R=R.then(()=>a(Q,J,X)).catch(()=>{}),R}var o=150;function Hz(Q){let J=w(),X=l(J),Z=null,G=null;O(J,"utf8").then(($)=>{if(G===null)G=$}).catch(()=>{});try{let $=K(v(J),(W,H)=>{let q=H===X||H?.startsWith(`${X}.`)&&H.endsWith(".tmp");if(H!=null&&!q)return;if(Z)clearTimeout(Z);Z=setTimeout(()=>{Z=null,O(J,"utf8").catch(()=>null).then((D)=>{if(D===null)return;if(D===G)return;G=D,Q()})},o)});return()=>{if(Z)clearTimeout(Z);$.close()}}catch{return()=>{}}}export{Hz as watchTuiPreferences,Zz as resolveAnthropicAuthPrefs,Xz as readTuiPreferencesFile,Gz as queueTuiPreferenceUpdate,w as getTuiPreferencesFile,$z as computeEffectiveOrder,p as TUI_PREFS_FILE_ENV,i as PLUGIN_KEY,s as DEFAULT_SLOT_ORDER,b as DEFAULT_PREFS};
`;async function e(Q,J,X){let Z=w();await y(m(Z),{recursive:!0});let G;try{G=await O(Z,"utf8")}catch{G=""}if(G.trim()==="")G=o;let $=M.modify(G,[Q,...J],X,{formattingOptions:{insertSpaces:!0,tabSize:2}}),W=M.applyEdits(G,$),H=`${Z}.${process.pid}.tmp`;await E(H,W,"utf8"),await S(H,Z)}var R=Promise.resolve();function Wz(Q,J,X){return R=R.then(()=>e(Q,J,X)).catch(()=>{}),R}var r=150;function Yz(Q){let J=w(),X=p(J),Z=null,G=null;O(J,"utf8").then(($)=>{if(G===null)G=$}).catch(()=>{});try{let $=c(m(J),(W,H)=>{let q=H===X||H?.startsWith(`${X}.`)&&H.endsWith(".tmp");if(H!=null&&!q)return;if(Z)b(Z);Z=x(()=>{Z=null,O(J,"utf8").catch(()=>null).then((D)=>{if(D===null)return;if(D===G)return;G=D,Q()})},r)});return()=>{if(Z)b(Z);$.close()}}catch{return()=>{}}}export{Yz as watchTuiPreferences,Hz as resolveAnthropicAuthPrefs,Gz as readTuiPreferencesFile,Wz as queueTuiPreferenceUpdate,w as getTuiPreferencesFile,Vz as computeEffectiveOrder,i as TUI_PREFS_FILE_ENV,d as PLUGIN_KEY,n as DEFAULT_SLOT_ORDER,h as DEFAULT_PREFS};
{
"name": "@cortexkit/opencode-anthropic-auth",
"version": "1.10.2",
"version": "1.10.3",
"type": "module",

@@ -61,3 +61,3 @@ "repository": {

"dependencies": {
"@cortexkit/anthropic-auth-core": "1.10.2",
"@cortexkit/anthropic-auth-core": "1.10.3",
"@opentui/core": ">=0.4.0",

@@ -64,0 +64,0 @@ "@opentui/solid": ">=0.4.0",

@@ -5,2 +5,6 @@ import { watch } from 'node:fs'

import { basename, dirname, join } from 'node:path'
import {
clearTimeout as nativeClearTimeout,
setTimeout as nativeSetTimeout,
} from 'node:timers'
import { applyEdits, modify, type ParseError, parse } from 'jsonc-parser'

@@ -294,3 +298,3 @@

const name = basename(file)
let timer: ReturnType<typeof setTimeout> | null = null
let timer: ReturnType<typeof nativeSetTimeout> | null = null
let lastSeen: string | null = null

@@ -313,4 +317,4 @@ // Seed asynchronously; a real change that fires before the seed resolves

if (filename != null && !isOurs) return
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
if (timer) nativeClearTimeout(timer)
timer = nativeSetTimeout(() => {
timer = null

@@ -328,3 +332,3 @@ void readFile(file, 'utf8')

return () => {
if (timer) clearTimeout(timer)
if (timer) nativeClearTimeout(timer)
watcher.close()

@@ -331,0 +335,0 @@ }

Sorry, the diff of this file is too big to display