@cortexkit/opencode-anthropic-auth 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{m as y,n as w,p as l,q as u,r as m,sa as b,ua as k}from"./index-75s94xp3.js";import{stdin as A,stdout as $}from"node:process";import{createInterface as R}from"node:readline/promises";function v(){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 h(){console.log(`Usage:
2
+ import{m as y,n as w,p as l,q as u,r as m,sa as b,ua as k}from"./index-wc8ekdxb.js";import{stdin as A,stdout as $}from"node:process";import{createInterface as R}from"node:readline/promises";function v(){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 h(){console.log(`Usage:
3
3
  opencode-anthropic-auth login [label]
4
4
  opencode-anthropic-auth list
5
5
  opencode-anthropic-auth relay setup
@@ -1,4 +1,4 @@
1
- var d="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Rf={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.ai/oauth/authorize"},Cf="https://platform.claude.com/oauth/code/callback",Mf="https://platform.claude.com/v1/oauth/token",kf=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],S_="mcp_";var wf="fast-mode-2026-02-01";function U_(f,m){let _=(f??"").split(",").map(($)=>$.trim()).filter(Boolean);return[...new Set([..._,...m])].join(",")}function b_(f){return typeof f==="string"&&(f.startsWith("claude-opus-4-6")||f.startsWith("claude-opus-4-7")||f.startsWith("claude-opus-4-8"))}var N_="You are OpenCode",j_="You are a Claude agent, built on Anthropic's Claude Agent SDK.",K_=["<use_parallel_tool_calls>","For maximum efficiency, whenever you perform multiple independent operations, invoke all relevant tools simultaneously rather than sequentially. Prioritize calling tools in parallel whenever possible. For example, when reading 3 files, run 3 tool calls in parallel to read all 3 files into context at the same time. When running multiple read-only commands like `ls` or `list_dir`, always run all of the commands in parallel. Err on the side of maximizing parallel tool calls rather than running too many tools sequentially.","</use_parallel_tool_calls>"].join(`
1
+ var d="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Rf={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.ai/oauth/authorize"},Cf="https://platform.claude.com/oauth/code/callback",Mf="https://platform.claude.com/v1/oauth/token",kf=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],S_="mcp_";var wf="fast-mode-2026-02-01";function U_(f,m){let _=(f??"").split(",").map(($)=>$.trim()).filter(Boolean);return[...new Set([..._,...m])].join(",")}function b_(f){return typeof f==="string"&&(f.startsWith("claude-opus-4-6")||f.startsWith("claude-opus-4-7")||f.startsWith("claude-opus-4-8"))}var N_="You are OpenCode",j_="You are a Claude agent, built on Anthropic's Claude Agent SDK.",K_=["<use_parallel_tool_calls>","For maximum efficiency, whenever you perform multiple independent operations, invoke all relevant tools simultaneously rather than sequentially. Prioritize calling independent tools in parallel whenever possible. For example, when reading 3 known files, run 3 tool calls in parallel to read all 3 files into context at the same time. When running multiple independent read-only commands like `ls` or `list_dir`, run all of those commands in parallel. Err on the side of maximizing parallel tool calls for independent work rather than running too many tools sequentially.","","Do not parallelize tool calls when one call depends on the output of another call. If a tool call needs an ID, filename, search result, or any other value returned by a previous tool call, run the first call, wait for its result, then run the dependent call using the real returned value. Never invent placeholder IDs, guessed task IDs, or other guessed values for dependent tool calls just to place them in the same parallel block.","</use_parallel_tool_calls>"].join(`
2
2
  `);var X="2.1.141",Hf="67b",uf="sdk-cli",nf="0.94.0",cf="v24.3.0",lf="claude-cli/2.1.141 (external, sdk-cli)",pf=["explicit","automatic","hybrid"],v="explicit",I_=["github.com/anomalyco/opencode","opencode.ai/docs"],G_=[{match:"if OpenCode honestly",replacement:"if the assistant honestly"},{match:"Here is some useful information about the environment you are running in:",replacement:"Environment context you are running in:"}];function yf(f){let m="";for(let _ of f)m+=String.fromCharCode(_);return btoa(m).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function df(){let f=new Uint8Array(64);crypto.getRandomValues(f);let m=yf(f),_=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(m));return{verifier:m,challenge:yf(new Uint8Array(_)),method:"S256"}}function g0(f){if(!f)return;let m=Number(f);if(Number.isFinite(m)&&m>0)return Math.ceil(m);let _=Date.parse(f);if(Number.isFinite(_)){let $=Math.ceil((_-Date.now())/1000);return $>0?$:void 0}return}class T extends Error{status;body;retryAfter;constructor(f,m,_){super(`Claude OAuth refresh failed: ${f} — ${m}`);this.status=f,this.body=m,this.name="ClaudeOAuthRefreshError",this.retryAfter=g0(_??void 0)}}function s0(f){if(!(f instanceof Error))return!1;let m=f.code;return f.message.includes("fetch failed")||m==="ECONNRESET"||m==="ECONNREFUSED"||m==="ETIMEDOUT"||m==="UND_ERR_CONNECT_TIMEOUT"}async function vf(f){let m=f.fetchImpl??fetch,_=f.maxRetries??2,$=f.baseDelayMs??500;for(let D=0;D<=_;D++)try{if(D>0){let H=$*2**(D-1);await new Promise((U)=>setTimeout(U,H))}let E=await m(Mf,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":"axios/1.13.6"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:f.refreshToken,client_id:d})});if(!E.ok){if(E.status>=500&&D<_){await E.body?.cancel().catch(()=>{});continue}let H=await E.text().catch(()=>"");throw new T(E.status,H,E.headers.get("retry-after"))}let C=await E.json(),M=f.now?.()??Date.now();return{access:C.access_token,refresh:C.refresh_token??f.refreshToken,expires:M+C.expires_in*1000,expiresIn:C.expires_in}}catch(E){if(E instanceof T)throw E;if(D<_&&s0(E))continue;throw E}throw Error("Token refresh exhausted all retries")}function r0(){return crypto.randomUUID().replace(/-/g,"")}function o0(f){let m=f.trim();try{let C=new URL(m),M=C.searchParams.get("code"),H=C.searchParams.get("state");if(M&&H)return{code:M,state:H}}catch{}let _=m.split("#");if(_.length===2&&_[0]&&_[1])return{code:_[0],state:_[1]};let $=new URLSearchParams(m),D=$.get("code"),E=$.get("state");if(D&&E)return{code:D,state:E};return null}async function a0(f,m,_){let $=await fetch(Mf,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":"axios/1.13.6"},body:JSON.stringify({code:f.code,state:f.state,grant_type:"authorization_code",client_id:d,redirect_uri:_,code_verifier:m})});if(!$.ok)return{type:"failed"};let D=await $.json();return{type:"success",refresh:D.refresh_token,access:D.access_token,expires:Date.now()+D.expires_in*1000}}async function z_(f){let m=await df(),_=r0(),$=new URL(Rf[f],import.meta.url);return $.searchParams.set("code","true"),$.searchParams.set("client_id",d),$.searchParams.set("response_type","code"),$.searchParams.set("redirect_uri",Cf),$.searchParams.set("scope",kf.join(" ")),$.searchParams.set("code_challenge",m.challenge),$.searchParams.set("code_challenge_method","S256"),$.searchParams.set("state",_),{url:$.toString(),redirectUri:Cf,state:_,verifier:m.verifier}}async function B_(f,m,_,$){let D=o0(f);if(!D)return{type:"failed"};if($&&D.state!==$)return{type:"failed"};return a0(D,m,_)}import*as tf from"node:fs";import*as gf from"node:os";import*as sf from"node:path";var e0=sf.join(gf.tmpdir(),"opencode-anthropic-auth.log"),rf=!1,f1=500,m1=50,i=[],P=null;function Ff(){if(P)clearTimeout(P),P=null;if(i.length===0)return;let f=i.join("");i=[];try{tf.appendFileSync(e0,f)}catch{}}function _1(){if(P)return;P=setTimeout(()=>{P=null,Ff()},f1)}function $1(f){if(f===void 0)return"";if(f instanceof Error)return` ${f.message}${f.stack?`
3
3
  ${f.stack}`:""}`;return` ${JSON.stringify(f)}`}function L(f,m){if(rf)return;try{if(i.push(`[${new Date().toISOString()}] ${f}${$1(m)}
4
4
  `),i.length>=m1)Ff();else _1()}catch{}}function K(f,m){L(`[relay] ${f}`,m)}if(!rf)process.on("exit",Ff);import{createHash as D0,randomUUID as Nf}from"node:crypto";import{mkdir as D1,readFile as t,rename as E1,rm as of,stat as C1,writeFile as bf}from"node:fs/promises";import{homedir as M1}from"node:os";import{dirname as H1,join as g}from"node:path";var F1=globalThis.setTimeout.bind(globalThis),S1=globalThis.clearTimeout.bind(globalThis),U1="anthropic-auth.json",b1="https://api.anthropic.com/api/oauth/usage",N1=[401,403,429],E0=240,j1=E0;var K1=300000,I1=3600000,G1=86400000,J1=5,af={five_hour:0,seven_day:0},O1=!0,A1=60000,W1=60000,z1=600000,B1=1e4,L1=100;function V1(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return g(process.env.XDG_CONFIG_HOME||g(M1(),".config"),"opencode")}function B(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||g(V1(),U1)}function J(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function Q1(f){if(!J(f))return null;if(f.type!=="oauth")return null;if(typeof f.refresh!=="string"||!f.refresh.trim())return null;return{id:typeof f.id==="string"&&f.id.trim()?f.id.trim():Nf(),label:typeof f.label==="string"?f.label:void 0,type:"oauth",access:typeof f.access==="string"?f.access:void 0,refresh:f.refresh,expires:typeof f.expires==="number"?f.expires:void 0,enabled:typeof f.enabled==="boolean"?f.enabled:void 0,addedAt:typeof f.addedAt==="number"?f.addedAt:void 0,lastUsed:typeof f.lastUsed==="number"?f.lastUsed:void 0,lastRefreshedAt:typeof f.lastRefreshedAt==="number"?f.lastRefreshedAt:void 0,lastRefreshError:ef(f.lastRefreshError),lastQuotaRefreshError:ef(f.lastQuotaRefreshError),quota:X1(f.quota)}}function ef(f){if(!J(f))return;if(typeof f.message!=="string")return;let m=Number(f.checkedAt);if(!Number.isFinite(m))return;let _=Number(f.nextRetryAt),$=Number(f.retryCount);return{message:f.message,checkedAt:m,nextRetryAt:Number.isFinite(_)?_:void 0,retryCount:Number.isFinite($)?$:void 0,tokenHash:typeof f.tokenHash==="string"?f.tokenHash:void 0}}function X1(f){if(!J(f))return;let m={};for(let _ of["five_hour","seven_day"]){let $=f[_];if(!J($))continue;let D=Number($.usedPercent),E=Number($.remainingPercent),C=Number($.checkedAt);if(!Number.isFinite(D)||!Number.isFinite(E)||!Number.isFinite(C))continue;m[_]={usedPercent:D,remainingPercent:E,checkedAt:C,resetsAt:typeof $.resetsAt==="string"?$.resetsAt:void 0}}return Object.keys(m).length?m:void 0}function Z1(f){if(!J(f)||!Array.isArray(f.accounts))return null;return{version:1,main:{type:"opencode",provider:"anthropic"},routing:J(f.routing)?f.routing:void 0,fallbackOn:Array.isArray(f.fallbackOn)?f.fallbackOn.filter((m)=>Number.isInteger(m)):void 0,refresh:J(f.refresh)?f.refresh:void 0,quota:J(f.quota)?f.quota:void 0,claudeCache:J(f.claudeCache)?f.claudeCache:void 0,dump:J(f.dump)?f.dump:void 0,claudeFast:J(f.claudeFast)?f.claudeFast:void 0,cacheKeep:J(f.cacheKeep)?f.cacheKeep:void 0,relay:J(f.relay)?f.relay:void 0,accounts:f.accounts.map(Q1).filter((m)=>m!=null)}}async function V(f=B()){try{let m=await t(f,"utf8");return Z1(JSON.parse(m))}catch(m){if(m.code==="ENOENT")return null;return null}}async function T1(f){try{let m=await t(f,"utf8"),_=JSON.parse(m);return J(_)?_:{}}catch{return{}}}function Y1(f){return Object.fromEntries(Object.entries(f).filter(([,m])=>m!==void 0))}async function Q(f,m=B()){await D1(H1(m),{recursive:!0});let $={...await T1(m),...Y1(f)},D=`${m}.${Nf()}.tmp`;await bf(D,`${JSON.stringify($,null,2)}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{$ as A1,A as v1,B as U1,C as x1,D as S0,E as D0,F as q1,G as n,H as E0,I as H1,J as T0,K as S1,L as R0,M as E1,N as V0,O as K0,P as X0,Q as c,R as T1,S as W0,T as $1,U as G1,V as A0,W as D1,X as V1,Y as K1,Z as Y0,_ as R1,a as r0,aa as C1,b as s0,ba as f1,c as j0,ca as y1,d as J0,da as k1,e as e0,ea as g1,f as l,fa as P0,g as N1,ga as w0,h as j1,ha as m1,i as J1,ia as C0,j as Z1,ja as z0,k as F0,ka as b1,l as L1,la as I0,m as v0,ma as h1,n as U0,na as f0,o as H,oa as Q0,pa as u1,q as T,qa as d1,r as x0,ra as i1,s as _1,t as $0,ta as l1,u as G0,v as M1,va as O0,w as B1,wa as y0,x as q0,xa as p1,y as F1,ya as n1,z as H0,za as k0}from"./index-75s94xp3.js";import{randomUUID as Fj}from"node:crypto";function b(j){return typeof j==="object"&&j!==null}function Vj(j){if(Array.isArray(j))return j;if(b(j)&&Array.isArray(j.data))return j.data;return[]}function Kj(j){if(!b(j)||!b(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function d0(j){if(!b(j)||!b(j.info))return null;let J=j.info,Z=b(J.model)?J.model:void 0,G=typeof J.agent==="string"?J.agent:void 0,V=typeof Z?.providerID==="string"?Z.providerID:typeof J.providerID==="string"?J.providerID:void 0,K=typeof Z?.modelID==="string"?Z.modelID:typeof J.modelID==="string"?J.modelID:void 0,_=typeof Z?.variant==="string"?Z.variant:typeof J.variant==="string"?J.variant:void 0;if(!G&&(!V||!K)&&!_)return null;let C={};if(G)C.agent=G;if(V&&K)C.model={providerID:V,modelID:K};if(_)C.variant=_;return C}function i0(j,J){return{agent:j.agent??J.agent,model:j.model??J.model,variant:j.variant??J.variant}}function l0(j){return Boolean(j.agent&&j.model&&j.variant)}async function p0(j,J){if(!j||!J)return null;let Z=j;if(typeof Z.session?.messages!=="function")return null;let G=[];try{G=Vj(await Promise.resolve(Z.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(G.length===0)return null;let V={};for(let K=G.length-1;K>=0;K--){if(Kj(G[K])!=="assistant")continue;let _=d0(G[K]);if(!_)continue;if(V=i0(V,_),l0(V))return V}for(let K=G.length-1;K>=0;K--){let _=d0(G[K]);if(!_)continue;if(V=i0(V,_),l0(V))return V}if(!V.agent&&!V.model&&!V.variant)return null;return V}function n0(j){return`${r0}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function Xj(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}function X1(j,J){let Z=new Headers;if(j instanceof Request)j.headers.forEach((V,K)=>{Z.set(K,V)});let G=J?.headers;if(G){if(G instanceof Headers)G.forEach((V,K)=>{Z.set(K,V)});else if(Array.isArray(G))for(let V of G){let[K,_]=V;if(typeof _<"u")Z.set(K,String(_))}else for(let[V,K]of Object.entries(G))if(typeof K<"u")Z.set(V,String(K))}return Z}function B0(j){return j.set("anthropic-beta",j0(j.get("anthropic-beta"),[s0])),j}function p(j,J,Z={}){return V1(j,J,Z)}function Wj(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((J)=>({...J,name:J.name?n0(J.name):J.name}));if(j.messages&&Array.isArray(j.messages))j.messages=j.messages.map((J)=>{if(J.content&&Array.isArray(J.content))J.content=J.content.map((Z)=>{if(Z.type==="tool_use"&&Z.name)return{...Z,name:n0(Z.name)};return Z});return J});return JSON.stringify(K1(j))}function M0(j){return j.replace(/"name"\s*:\s*"mcp_([^"]+)"/g,(J,Z)=>`"name": "${Xj(Z)}"`)}function c0(j,J=!1){if(J)return{ready:M0(j),pending:""};let Z=j.length,G='"name"',V=Math.max(0,j.length-G.length+1);for(let _=V;_<j.length;_++)if(G.startsWith(j.slice(_))){Z=Math.min(Z,_);break}let K=j.lastIndexOf(G);if(K!==-1){let _=j.slice(K);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(_))Z=Math.min(Z,K)}if(Z<j.length)return{ready:M0(j.slice(0,Z)),pending:j.slice(Z)};return{ready:M0(j),pending:""}}function W1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function Yj(){let j=process.env.ANTHROPIC_BASE_URL?.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 Y1(j){let J=null;try{if(typeof j==="string"||j instanceof URL)J=new URL(j.toString());else if(j instanceof Request)J=new URL(j.url)}catch{J=null}if(!J)return{input:j,url:null};let Z=J.href,G=Yj();if(G)J.protocol=G.protocol,J.host=G.host;if(J.pathname==="/v1/messages"&&!J.searchParams.has("beta"))J.searchParams.set("beta","true");if(J.href===Z)return{input:j,url:J};return{input:j instanceof Request?new Request(J.toString(),j):J,url:J}}function a(j){let G=j.split(/\n\n+/).filter((V)=>{if(V.includes(e0))return!1;for(let K of J1)if(V.includes(K))return!1;return!0}).join(`
1
+ import{$ as A1,A as v1,B as U1,C as x1,D as S0,E as D0,F as q1,G as n,H as E0,I as H1,J as T0,K as S1,L as R0,M as E1,N as V0,O as K0,P as X0,Q as c,R as T1,S as W0,T as $1,U as G1,V as A0,W as D1,X as V1,Y as K1,Z as Y0,_ as R1,a as r0,aa as C1,b as s0,ba as f1,c as j0,ca as y1,d as J0,da as k1,e as e0,ea as g1,f as l,fa as P0,g as N1,ga as w0,h as j1,ha as m1,i as J1,ia as C0,j as Z1,ja as z0,k as F0,ka as b1,l as L1,la as I0,m as v0,ma as h1,n as U0,na as f0,o as H,oa as Q0,pa as u1,q as T,qa as d1,r as x0,ra as i1,s as _1,t as $0,ta as l1,u as G0,v as M1,va as O0,w as B1,wa as y0,x as q0,xa as p1,y as F1,ya as n1,z as H0,za as k0}from"./index-wc8ekdxb.js";import{randomUUID as Fj}from"node:crypto";function b(j){return typeof j==="object"&&j!==null}function Vj(j){if(Array.isArray(j))return j;if(b(j)&&Array.isArray(j.data))return j.data;return[]}function Kj(j){if(!b(j)||!b(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function d0(j){if(!b(j)||!b(j.info))return null;let J=j.info,Z=b(J.model)?J.model:void 0,G=typeof J.agent==="string"?J.agent:void 0,V=typeof Z?.providerID==="string"?Z.providerID:typeof J.providerID==="string"?J.providerID:void 0,K=typeof Z?.modelID==="string"?Z.modelID:typeof J.modelID==="string"?J.modelID:void 0,_=typeof Z?.variant==="string"?Z.variant:typeof J.variant==="string"?J.variant:void 0;if(!G&&(!V||!K)&&!_)return null;let C={};if(G)C.agent=G;if(V&&K)C.model={providerID:V,modelID:K};if(_)C.variant=_;return C}function i0(j,J){return{agent:j.agent??J.agent,model:j.model??J.model,variant:j.variant??J.variant}}function l0(j){return Boolean(j.agent&&j.model&&j.variant)}async function p0(j,J){if(!j||!J)return null;let Z=j;if(typeof Z.session?.messages!=="function")return null;let G=[];try{G=Vj(await Promise.resolve(Z.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(G.length===0)return null;let V={};for(let K=G.length-1;K>=0;K--){if(Kj(G[K])!=="assistant")continue;let _=d0(G[K]);if(!_)continue;if(V=i0(V,_),l0(V))return V}for(let K=G.length-1;K>=0;K--){let _=d0(G[K]);if(!_)continue;if(V=i0(V,_),l0(V))return V}if(!V.agent&&!V.model&&!V.variant)return null;return V}function n0(j){return`${r0}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function Xj(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}function X1(j,J){let Z=new Headers;if(j instanceof Request)j.headers.forEach((V,K)=>{Z.set(K,V)});let G=J?.headers;if(G){if(G instanceof Headers)G.forEach((V,K)=>{Z.set(K,V)});else if(Array.isArray(G))for(let V of G){let[K,_]=V;if(typeof _<"u")Z.set(K,String(_))}else for(let[V,K]of Object.entries(G))if(typeof K<"u")Z.set(V,String(K))}return Z}function B0(j){return j.set("anthropic-beta",j0(j.get("anthropic-beta"),[s0])),j}function p(j,J,Z={}){return V1(j,J,Z)}function Wj(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((J)=>({...J,name:J.name?n0(J.name):J.name}));if(j.messages&&Array.isArray(j.messages))j.messages=j.messages.map((J)=>{if(J.content&&Array.isArray(J.content))J.content=J.content.map((Z)=>{if(Z.type==="tool_use"&&Z.name)return{...Z,name:n0(Z.name)};return Z});return J});return JSON.stringify(K1(j))}function M0(j){return j.replace(/"name"\s*:\s*"mcp_([^"]+)"/g,(J,Z)=>`"name": "${Xj(Z)}"`)}function c0(j,J=!1){if(J)return{ready:M0(j),pending:""};let Z=j.length,G='"name"',V=Math.max(0,j.length-G.length+1);for(let _=V;_<j.length;_++)if(G.startsWith(j.slice(_))){Z=Math.min(Z,_);break}let K=j.lastIndexOf(G);if(K!==-1){let _=j.slice(K);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(_))Z=Math.min(Z,K)}if(Z<j.length)return{ready:M0(j.slice(0,Z)),pending:j.slice(Z)};return{ready:M0(j),pending:""}}function W1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function Yj(){let j=process.env.ANTHROPIC_BASE_URL?.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 Y1(j){let J=null;try{if(typeof j==="string"||j instanceof URL)J=new URL(j.toString());else if(j instanceof Request)J=new URL(j.url)}catch{J=null}if(!J)return{input:j,url:null};let Z=J.href,G=Yj();if(G)J.protocol=G.protocol,J.host=G.host;if(J.pathname==="/v1/messages"&&!J.searchParams.has("beta"))J.searchParams.set("beta","true");if(J.href===Z)return{input:j,url:J};return{input:j instanceof Request?new Request(J.toString(),j):J,url:J}}function a(j){let G=j.split(/\n\n+/).filter((V)=>{if(V.includes(e0))return!1;for(let K of J1)if(V.includes(K))return!1;return!0}).join(`
2
2
 
3
3
  `);for(let V of Z1)G=G.replace(V.match,V.replacement);return G.trim()}function R(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function Pj(j){let J={type:"text",text:l};if(j==null)return[J];if(typeof j==="string"){let G=a(j);if(G===l)return[J];return[J,{type:"text",text:G}]}if(R(j)){let G=typeof j.type==="string"?j.type:"text",V=typeof j.text==="string"?j.text:"";return[J,{...j,type:G,text:a(V)}]}if(!Array.isArray(j))return[J];let Z=j.map((G)=>{if(typeof G==="string")return{type:"text",text:a(G)};if(R(G)&&G.type==="text"&&typeof G.text==="string")return{...G,type:"text",text:a(G.text)};return{type:"text",text:String(G)}});if(Z[0]?.text===l)return Z;return[J,...Z]}var P1={type:"ephemeral",ttl:"1h"},wj=20;function zj(j){if(R(j.cache_control))return j.cache_control;if(R(j.cacheControl))return j.cacheControl;return null}function e(j,J){if(!R(j))return!1;return delete j.cacheControl,j.cache_control=J?{...P1}:{type:"ephemeral"},!0}function o0(j){if(!R(j))return;delete j.cache_control,delete j.cacheControl}function Ij(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function r(j,J){if(!R(j))return;let Z=zj(j);if(Z?.type!=="ephemeral")return;if(J)Z.ttl="1h";else delete Z.ttl}function t0(j,J){if(Array.isArray(j.system))for(let Z of j.system)r(Z,J);else r(j.system,J);if(!Array.isArray(j.messages))return;for(let Z of j.messages)if(r(Z,J),R(Z)&&Array.isArray(Z.content))for(let G of Z.content)r(G,J)}function Qj(j,J){if(Array.isArray(j.system))for(let Z of j.system)J(Z);else J(j.system);if(!Array.isArray(j.messages))return;for(let Z of j.messages)if(J(Z),R(Z)&&Array.isArray(Z.content))for(let G of Z.content)J(G)}function w1(j){o0(j),Qj(j,o0)}function Oj(j){w1(j),j.cache_control={...P1}}function s(j){if(!R(j))return!1;let J=Ij(j.content);if(!J?.length)return e(j,!0);j.content=J;let Z=[...J].reverse().find((G)=>R(G)&&G.type!=="thinking");return e(Z??j,!0)}function Nj(j){if(!R(j))return 0;let J=j.content;if(Array.isArray(J))return J.length;if(J==null)return 0;return 1}function Lj(j){let J=[],Z=0;return j.forEach((G,V)=>{let K=Nj(G);if(R(G)&&G.role==="user"&&K>0)J.push({index:V,blockPosition:Z+K-1});Z+=K}),J}function _j(j){let J=Lj(j),Z=[...J].reverse().find((_)=>_.index>1);if(!Z)return{latest:void 0,bridge:void 0};let G=[...J].reverse().find((_)=>_.index<Z.index),V=G?Z.blockPosition-G.blockPosition+1:0,K=G&&G.index>1&&V>wj?G:void 0;return{latest:Z,bridge:K}}function a0(j){if(Array.isArray(j.system)){let J=j.system.findIndex((V)=>R(V)&&V.text===l),Z=j.system.slice(J>=0?J+1:0).filter(R),G=Z[Z.length-1];e(G,!0)}else e(j.system,!0)}function Mj(j){if(w1(j),!Array.isArray(j.messages)){a0(j);return}let{latest:J,bridge:Z}=_j(j.messages);if(!Z)a0(j);if(s(j.messages[0]),s(j.messages[1]),Z)s(j.messages[Z.index]);if(J)s(j.messages[J.index])}function Bj(j,J){if(!J.enabled){t0(j,!1),delete j.cache_control,delete j.cacheControl;return}if(J.mode==="automatic"){Oj(j);return}if(J.mode==="hybrid"){Mj(j);return}t0(j,!0),delete j.cacheControl}async function z1(j,J={}){try{let Z=JSON.parse(j),G=Array.isArray(Z.messages)&&Z.messages.some((V)=>V.role==="user")?G1(Z.messages,void 0,j1):null;if(Z.system=Pj(Z.system),G&&Array.isArray(Z.system))Z.system.unshift({type:"text",text:G});if(Bj(Z,{enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.fastModeEnabled&&J0(Z.model))Z.speed="fast";else if(Z.speed==="fast")delete Z.speed;if(J.identity)D1(Z,J.identity);return await $1(Wj(Z))}catch{return j}}function Z0(j){if(!j.body)return j;let J=j.body.getReader(),Z=new TextDecoder,G=new TextEncoder,V="",K=new ReadableStream({async pull(_){let{done:C,value:y}=await J.read();if(C){let i=c0(`${V}${Z.decode()}`,!0);if(i.ready)_.enqueue(G.encode(i.ready));_.close();return}let L0=V+Z.decode(y,{stream:!0}),d=c0(L0);if(V=d.pending,d.ready)_.enqueue(G.encode(d.ready))}});return new Response(K,{status:j.status,statusText:j.statusText,headers:j.headers})}var vj="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",Uj=60000,xj=60000,qj=5000,I1=200,c1=240,Hj=c1,Sj=1,Q1=!1;function N0(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function B(){return performance.now()}function E(j){return Math.round(j*10)/10}function O1(j){return Math.floor(Math.random()*Math.max(0,j))}function Ej(){if(Q1||!1||!N0())return;Q1=!0;let j=100,J=250,Z=B()+j;setInterval(()=>{let G=B(),V=G-Z;if(Z=G+j,V<J)return;H("[perf] opencode event_loop_lag",{lagMs:E(V),thresholdMs:J})},j).unref?.()}function Tj(j){let J=B(),Z={requestId:String(Sj++),start:J,last:J,mark(G,V){let K=B();if(N0())H("[perf] opencode request stage",{requestId:Z.requestId,stage:G,deltaMs:E(K-Z.last),totalMs:E(K-Z.start),...V});Z.last=K},done(G,V){let K=B();if(N0())H("[perf] opencode request done",{requestId:Z.requestId,stage:G,deltaMs:E(K-Z.last),totalMs:E(K-Z.start),...V});Z.last=K}};if(N0())H("[perf] opencode request start",{requestId:Z.requestId,...j});return Z}async function h(j,J,Z){let G=j.client.session,V=await p0(j.client,J),K={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:Z,ignored:!0}]}};if(V?.agent)K.body.agent=V.agent;if(V?.model)K.body.model=V.model;if(V?.variant)K.body.variant=V.variant;if(typeof G?.promptAsync==="function"){await G.promptAsync(K);return}if(typeof G?.prompt==="function"){await Promise.resolve(G.prompt(K));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function u(){throw Error(vj)}function Rj(j){if(j.sessionID==null)return!1;let J=j.model;return J?.providerID==="anthropic"||J?.api?.npm==="@ai-sdk/anthropic"||J?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function Aj(j){if(j.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return j.push(N1),!0}var uj=async(j)=>{Ej();let{client:J}=j,Z=new E1;Z.startBackgroundRefresh();let G=null,V=new g1({loadStorage:()=>T(),prepareHeaders:async($,Y)=>{if(!C)return $;let w=await C();if(w.type!=="oauth")return $;if(!w.access||w.expires&&w.expires<Date.now()){if(!G)return $;w.access=await G()}if(!w.access)return $;try{let N=JSON.parse(Y.bodyText),S=await A0(w.access,typeof N.model==="string"?N.model:void 0);if($.delete("anthropic-beta"),p($,w.access,{body:N,identity:S}),$.set("anthropic-beta",j0($.get("anthropic-beta"),[R1])),N.speed==="fast")B0($)}catch{p($,w.access)}return $},log:H}),K=await T(),_=i1(K);c({enabled:$0(K),mode:G0(K)}),w0(q0(K)),I0(H0(K));let C=null,y=null;function L0($){let Y=$?.refresh?.refreshBeforeExpiryMinutes??Hj;return Math.max(c1,Y)*60000}function d($){return $?.refresh?.enabled!==!1}async function i($){if(!$)return;let Y=await T(),w=Y?.refresh?.mainLastRefreshError;if(!Y?.refresh||!w?.tokenHash)return;let N=D0($);if(w.tokenHash===N)return;if(w.nextRetryAt&&w.nextRetryAt>Date.now()){H("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:w.nextRetryAt,retryCount:w.retryCount,remainingMs:w.nextRetryAt-Date.now()});return}Y.refresh.mainLastRefreshError=void 0,await x0(Y),H("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:w.checkedAt,previousNextRetryAt:w.nextRetryAt,previousRetryCount:w.retryCount})}async function o1(){let $=[];if(C)try{let N=await C();if(N.type==="oauth"&&N.access)$.push({name:"OpenCode anthropic",role:"main",quota:await R0({accessToken:N.access})});else if(N.type==="oauth")$.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(N){$.push({name:"OpenCode anthropic",role:"main",error:N instanceof Error?N.message:String(N)})}let{storage:Y,errors:w}=await Z.refreshQuotaForAllAccounts();if($.push(...u1(Y,new Map(w.map((N)=>[N.accountId,N.message])))),!C)$.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return d1({accounts:$,refreshedAt:Date.now()})}async function t1($){let Y=T1($);if(Y.type==="enable"||Y.type==="disable"){let f=Y.type==="enable",k=await M1(f),g=G0(k);return c({enabled:f,mode:g}),W0({argumentsText:$,enabled:f,mode:g})}if(Y.type==="mode"){let f=await B1(Y.mode),k=$0(f);return c({enabled:k,mode:Y.mode}),W0({argumentsText:$,enabled:k,mode:Y.mode})}let w=await T(),N=$0(w),S=G0(w);return c({enabled:N,mode:S}),W0({argumentsText:$,enabled:N,mode:S})}async function a1($){let Y=A1($),w=await T();if(Y.type==="window")w=await U1(Y.startHour,Y.endHour);else if(Y.type==="disable")w=await x1(!1);let N=C1(w),S=V.stats(N);return k1({argumentsText:$,enabled:f1(w),window:N,hybridActive:y1(w),trackedSessions:S.trackedSessions,nextPrewarmAt:S.nextPrewarmAt})}async function r1($){let Y=m1($);if(Y.type==="enable"||Y.type==="disable"){let S=Y.type==="enable";return await F1(S),w0(S),C0({argumentsText:$,enabled:S})}let w=await T(),N=q0(w);return w0(N),C0({argumentsText:$,enabled:N})}async function s1($){let Y=h1($);if(Y.type==="enable"||Y.type==="disable"){let S=Y.type==="enable";return await v1(S),I0(S),f0({argumentsText:$,enabled:S})}let w=await T(),N=H0(w);return I0(N),f0({argumentsText:$,enabled:N})}async function e1($){let Y=n1($);if(Y.type==="mode")return await p1(Y.mode),k0({argumentsText:$,mode:Y.mode});let w=await T();return k0({argumentsText:$,mode:y0(w)})}return{config:async($)=>{$.command={...$.command??{},[V0]:{template:V0,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[Y0]:{template:Y0,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[Q0]:{template:Q0,description:"Show current Claude OAuth quota usage for all accounts."},[P0]:{template:P0,description:"Show or toggle Anthropic request dump capture for debugging."},[z0]:{template:z0,description:"Show or toggle Anthropic fast mode for supported Opus models."},[O0]:{template:O0,description:"Show or change Claude account routing between main-first and fallback-first."}}},"experimental.chat.system.transform":async($,Y)=>{if(!Rj($))return;Aj(Y.system)},"command.execute.before":async($)=>{if($.command===V0)await h(j,$.sessionID,await t1($.arguments)),u();if($.command===Y0)await h(j,$.sessionID,await a1($.arguments)),u();if($.command===Q0)await h(j,$.sessionID,await o1()),u();if($.command===P0)await h(j,$.sessionID,await r1($.arguments)),u();if($.command===z0)await h(j,$.sessionID,await s1($.arguments)),u();if($.command===O0)await h(j,$.sessionID,await e1($.arguments)),u()},auth:{provider:"anthropic",async loader($,Y){if(C=$,(await $()).type==="oauth"){let jj=function(){if(y)clearInterval(y),y=null;let X=async()=>{try{let W=await T();if(!d(W))return;let I=await $();if(I.type!=="oauth")return;if(await i(I.refresh),!I.expires)return;let P=I.expires-Date.now(),q=L0(W);if(P>q)return;if(H("[refresh] opencode main oauth background due",{expiresInMs:P,refreshBeforeMs:q}),I.refresh&&n(W?.refresh?.mainLastRefreshError,I.refresh,Date.now())){H("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:W?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:W?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:P});return}if(I.refresh&&W?.refresh?.mainRefreshLeaseUntil&&W.refresh.mainRefreshLeaseUntil>Date.now()&&W.refresh.mainRefreshLeaseTokenHash===D0(I.refresh))return;await g();let Q=await $();H("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:Q.expires?Q.expires-Date.now():void 0})}catch(W){H("[refresh] opencode main oauth refresh failed",{message:W instanceof Error?W.message:String(W)})}};if(y=setInterval(()=>{X()},Uj+O1(xj)),"unref"in y)y.unref()},g0=function(X,W){if(X instanceof Request&&X.body)return!1;return W==null||typeof W==="string"},Jj=function(X){return X.has("x-parent-session-id")},m0=function(X){return X.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(X)},Zj=function(X){return X?.quota?.enabled===!0},$j=function(X,W){let I=Date.now();if(f||I<k)return;f=u0(X,W).catch((P)=>{throw k=I+H1(W),P}).finally(()=>{f=null}),f.catch(()=>{})};for(let X of Object.values(Y.models))X.cost={input:0,output:0,cache:{read:0,write:0}};let N=null,S=null,f=null,k=0;async function g(){if(!N)N=(async()=>{let I=null,P=null,q=null;async function Q(z){let O=await T()??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};O.refresh=O.refresh??{},z(O),await x0(O)}async function v(z){let O=Date.now()+qj;while(Date.now()<O){await new Promise((M)=>setTimeout(M,I1+O1(I1)));let D=await $();if(D.type!=="oauth"||!D.access)continue;if((D.access!==z.access||D.refresh!==z.refresh||(D.expires??0)>(z.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return H("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:D.expires?D.expires-Date.now():void 0}),D.access}return null}for(let z=0;z<=2;z++){let O=null;try{if(z>0){let U=500*2**(z-1);await new Promise((o)=>setTimeout(o,U))}if(O=await $(),!O.refresh)throw Error("Token refresh failed: missing refresh token");let D=await T(),F=D0(O.refresh),M=D?.refresh?.mainLastRefreshError;if(H("[refresh] opencode main oauth refresh check",{attempt:z,expiresInMs:O.expires?O.expires-Date.now():void 0,hasBackoff:Boolean(M),backoffActive:M?n(M,O.refresh,Date.now()):!1,retryCount:M?.retryCount,nextRetryAt:M?.nextRetryAt}),M&&n(M,O.refresh,Date.now()))throw H("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:M.nextRetryAt,retryCount:M.retryCount}),Error(E0(M,Date.now()));if(D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===F){H("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:D.refresh.mainRefreshLeaseUntil});let U=await v(O);if(U)return U;throw Error("Claude OAuth refresh is already in progress")}let L=await _1({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!L){H("[refresh] opencode main oauth refresh skipped file lock");let U=await v(O);if(U)return U;throw Error("Claude OAuth refresh is already in progress")}q=L.release,I=Fj(),P=F,await Q((U)=>{U.refresh=U.refresh??{},U.refresh.mainRefreshLeaseId=I??void 0,U.refresh.mainRefreshLeaseUntil=Date.now()+120000,U.refresh.mainRefreshLeaseTokenHash=F});let x=await T();if(H("[refresh] opencode main oauth refresh lease acquired",{attempt:z,leaseUntil:Date.now()+120000}),x?.refresh?.mainRefreshLeaseId!==I||x.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Claude OAuth refresh is already in progress");H("[refresh] opencode main oauth refresh request start",{attempt:z});let A=await L1({refreshToken:O.refresh,maxRetries:0});return await J.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:A.refresh,access:A.access,expires:A.expires}}),await Q((U)=>{if(!U?.refresh)return;if(U.refresh.mainLastRefreshError=void 0,U.refresh.mainRefreshLeaseId===I)U.refresh.mainRefreshLeaseId=void 0,U.refresh.mainRefreshLeaseUntil=void 0,U.refresh.mainRefreshLeaseTokenHash=void 0}),H("[refresh] opencode main oauth refresh succeeded",{attempt:z,expiresInMs:A.expires-Date.now()}),A.access}catch(D){let F=D instanceof Error&&(D.message.includes("fetch failed")||("code"in D)&&(D.code==="ECONNRESET"||D.code==="ECONNREFUSED"||D.code==="ETIMEDOUT"||D.code==="UND_ERR_CONNECT_TIMEOUT"));if(z<2&&(F||D instanceof F0&&D.status>=500))continue;H("[refresh] opencode main oauth refresh attempt failed",{attempt:z,error:D instanceof Error?D.message:String(D),transient:F});let M=O?.refresh;if(M&&D instanceof F0)await Q((L)=>{L.refresh=L.refresh??{},L.refresh.mainLastRefreshError=q1({error:D,now:Date.now(),refreshToken:M,previous:L.refresh.mainLastRefreshError})});throw D}finally{if(I)await Q((D)=>{if(!D?.refresh)return;if(D.refresh.mainRefreshLeaseId===I&&D.refresh.mainRefreshLeaseTokenHash===P)D.refresh.mainRefreshLeaseId=void 0,D.refresh.mainRefreshLeaseUntil=void 0,D.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await q?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{N=null});return N}G=g,jj();async function b0(X,W){if(!X.body||X.status!==200)return W?.mark("inspect_stream_skip",{status:X.status}),{response:X,rateLimited:!1};if(X.headers.get("x-cortexkit-relay-optimistic")==="true")return W?.mark("inspect_stream_skip",{status:X.status,reason:"optimistic_relay"}),{response:X,rateLimited:!1};let I=B(),P=X.body.getReader(),q=[],Q=new TextDecoder,v="",z=0;while(!v.includes(`
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-anthropic-auth",
3
- "version": "1.4.0",
3
+ "version": "1.4.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -41,6 +41,6 @@
41
41
  "@opencode-ai/plugin": "*"
42
42
  },
43
43
  "dependencies": {
44
- "@cortexkit/anthropic-auth-core": "1.4.0"
44
+ "@cortexkit/anthropic-auth-core": "1.4.1"
45
45
  }
46
46
  }