@cortexkit/opencode-anthropic-auth 1.2.0 → 1.2.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{l as y,m as w,o as l,p as u,q as m,ra as b,ta as k}from"./index-sebye7nt.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{l as y,m as w,o as l,p as u,q as m,ra as b,ta as k}from"./index-16nba65t.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 y="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Of={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.ai/oauth/authorize"},Ef="https://platform.claude.com/oauth/code/callback",Ff="https://platform.claude.com/v1/oauth/token",qf=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],k$="mcp_";var hf="fast-mode-2026-02-01";function R$(f,$){let _=(f??"").split(",").map((m)=>m.trim()).filter(Boolean);return[...new Set([..._,...$])].join(",")}function i$(f){return typeof f==="string"&&(f.startsWith("claude-opus-4-6")||f.startsWith("claude-opus-4-7"))}var c$="You are OpenCode",u$="You are a Claude agent, built on Anthropic's Claude Agent SDK.";var Z="2.1.141",Mf="67b",wf="sdk-cli",xf="0.94.0",Pf="v24.3.0",kf="claude-cli/2.1.141 (external, sdk-cli)",Rf=["explicit","automatic","hybrid"],p="explicit",n$=["github.com/anomalyco/opencode","opencode.ai/docs"],l$=[{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 cf(f){let $="";for(let _ of f)$+=String.fromCharCode(_);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function uf(){let f=new Uint8Array(64);crypto.getRandomValues(f);let $=cf(f),_=await crypto.subtle.digest("SHA-256",new TextEncoder().encode($));return{verifier:$,challenge:cf(new Uint8Array(_)),method:"S256"}}class h extends Error{status;body;constructor(f,$){super(`Claude OAuth refresh failed: ${f} — ${$}`);this.status=f,this.body=$,this.name="ClaudeOAuthRefreshError"}}function l0(f){if(!(f instanceof Error))return!1;let $=f.code;return f.message.includes("fetch failed")||$==="ECONNRESET"||$==="ECONNREFUSED"||$==="ETIMEDOUT"||$==="UND_ERR_CONNECT_TIMEOUT"}async function nf(f){let $=f.fetchImpl??fetch,_=f.maxRetries??2,m=f.baseDelayMs??500;for(let D=0;D<=_;D++)try{if(D>0){let C=m*2**(D-1);await new Promise((N)=>setTimeout(N,C))}let H=await $(Ff,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:f.refreshToken,client_id:y})});if(!H.ok){if(H.status>=500&&D<_){await H.body?.cancel().catch(()=>{});continue}let C=await H.text().catch(()=>"");throw new h(H.status,C)}let E=await H.json(),F=f.now?.()??Date.now();return{access:E.access_token,refresh:E.refresh_token??f.refreshToken,expires:F+E.expires_in*1000,expiresIn:E.expires_in}}catch(H){if(H instanceof h)throw H;if(D<_&&l0(H))continue;throw H}throw Error("Token refresh exhausted all retries")}function y0(){return crypto.randomUUID().replace(/-/g,"")}function p0(f){let $=f.trim();try{let E=new URL($),F=E.searchParams.get("code"),C=E.searchParams.get("state");if(F&&C)return{code:F,state:C}}catch{}let _=$.split("#");if(_.length===2&&_[0]&&_[1])return{code:_[0],state:_[1]};let m=new URLSearchParams($),D=m.get("code"),H=m.get("state");if(D&&H)return{code:D,state:H};return null}async function v0(f,$,_){let m=await fetch(Ff,{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:y,redirect_uri:_,code_verifier:$})});if(!m.ok)return{type:"failed"};let D=await m.json();return{type:"success",refresh:D.refresh_token,access:D.access_token,expires:Date.now()+D.expires_in*1000}}async function t$(f){let $=await uf(),_=y0(),m=new URL(Of[f],import.meta.url);return m.searchParams.set("code","true"),m.searchParams.set("client_id",y),m.searchParams.set("response_type","code"),m.searchParams.set("redirect_uri",Ef),m.searchParams.set("scope",qf.join(" ")),m.searchParams.set("code_challenge",$.challenge),m.searchParams.set("code_challenge_method","S256"),m.searchParams.set("state",_),{url:m.toString(),redirectUri:Ef,state:_,verifier:$.verifier}}async function g$(f,$,_,m){let D=p0(f);if(!D)return{type:"failed"};if(m&&D.state!==m)return{type:"failed"};return v0(D,$,_)}import*as lf from"node:fs";import*as yf from"node:os";import*as pf from"node:path";var d0=pf.join(yf.tmpdir(),"opencode-anthropic-auth.log"),vf=!1,t0=500,g0=50,P=[],w=null;function Cf(){if(w)clearTimeout(w),w=null;if(P.length===0)return;let f=P.join("");P=[];try{lf.appendFileSync(d0,f)}catch{}}function s0(){if(w)return;w=setTimeout(()=>{w=null,Cf()},t0)}function r0(f){if(f===void 0)return"";if(f instanceof Error)return` ${f.message}${f.stack?`
1
+ var y="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Of={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.ai/oauth/authorize"},Ef="https://platform.claude.com/oauth/code/callback",Ff="https://api.anthropic.com/v1/oauth/token",qf=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],k$="mcp_";var hf="fast-mode-2026-02-01";function R$(f,$){let _=(f??"").split(",").map((m)=>m.trim()).filter(Boolean);return[...new Set([..._,...$])].join(",")}function i$(f){return typeof f==="string"&&(f.startsWith("claude-opus-4-6")||f.startsWith("claude-opus-4-7"))}var c$="You are OpenCode",u$="You are a Claude agent, built on Anthropic's Claude Agent SDK.";var Z="2.1.141",Mf="67b",wf="sdk-cli",xf="0.94.0",Pf="v24.3.0",kf="claude-cli/2.1.141 (external, sdk-cli)",Rf=["explicit","automatic","hybrid"],p="explicit",n$=["github.com/anomalyco/opencode","opencode.ai/docs"],l$=[{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 cf(f){let $="";for(let _ of f)$+=String.fromCharCode(_);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function uf(){let f=new Uint8Array(64);crypto.getRandomValues(f);let $=cf(f),_=await crypto.subtle.digest("SHA-256",new TextEncoder().encode($));return{verifier:$,challenge:cf(new Uint8Array(_)),method:"S256"}}class h extends Error{status;body;constructor(f,$){super(`Claude OAuth refresh failed: ${f} — ${$}`);this.status=f,this.body=$,this.name="ClaudeOAuthRefreshError"}}function l0(f){if(!(f instanceof Error))return!1;let $=f.code;return f.message.includes("fetch failed")||$==="ECONNRESET"||$==="ECONNREFUSED"||$==="ETIMEDOUT"||$==="UND_ERR_CONNECT_TIMEOUT"}async function nf(f){let $=f.fetchImpl??fetch,_=f.maxRetries??2,m=f.baseDelayMs??500;for(let D=0;D<=_;D++)try{if(D>0){let C=m*2**(D-1);await new Promise((N)=>setTimeout(N,C))}let H=await $(Ff,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:f.refreshToken,client_id:y})});if(!H.ok){if(H.status>=500&&D<_){await H.body?.cancel().catch(()=>{});continue}let C=await H.text().catch(()=>"");throw new h(H.status,C)}let E=await H.json(),F=f.now?.()??Date.now();return{access:E.access_token,refresh:E.refresh_token??f.refreshToken,expires:F+E.expires_in*1000,expiresIn:E.expires_in}}catch(H){if(H instanceof h)throw H;if(D<_&&l0(H))continue;throw H}throw Error("Token refresh exhausted all retries")}function y0(){return crypto.randomUUID().replace(/-/g,"")}function p0(f){let $=f.trim();try{let E=new URL($),F=E.searchParams.get("code"),C=E.searchParams.get("state");if(F&&C)return{code:F,state:C}}catch{}let _=$.split("#");if(_.length===2&&_[0]&&_[1])return{code:_[0],state:_[1]};let m=new URLSearchParams($),D=m.get("code"),H=m.get("state");if(D&&H)return{code:D,state:H};return null}async function v0(f,$,_){let m=await fetch(Ff,{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:y,redirect_uri:_,code_verifier:$})});if(!m.ok)return{type:"failed"};let D=await m.json();return{type:"success",refresh:D.refresh_token,access:D.access_token,expires:Date.now()+D.expires_in*1000}}async function t$(f){let $=await uf(),_=y0(),m=new URL(Of[f],import.meta.url);return m.searchParams.set("code","true"),m.searchParams.set("client_id",y),m.searchParams.set("response_type","code"),m.searchParams.set("redirect_uri",Ef),m.searchParams.set("scope",qf.join(" ")),m.searchParams.set("code_challenge",$.challenge),m.searchParams.set("code_challenge_method","S256"),m.searchParams.set("state",_),{url:m.toString(),redirectUri:Ef,state:_,verifier:$.verifier}}async function g$(f,$,_,m){let D=p0(f);if(!D)return{type:"failed"};if(m&&D.state!==m)return{type:"failed"};return v0(D,$,_)}import*as lf from"node:fs";import*as yf from"node:os";import*as pf from"node:path";var d0=pf.join(yf.tmpdir(),"opencode-anthropic-auth.log"),vf=!1,t0=500,g0=50,P=[],w=null;function Cf(){if(w)clearTimeout(w),w=null;if(P.length===0)return;let f=P.join("");P=[];try{lf.appendFileSync(d0,f)}catch{}}function s0(){if(w)return;w=setTimeout(()=>{w=null,Cf()},t0)}function r0(f){if(f===void 0)return"";if(f instanceof Error)return` ${f.message}${f.stack?`
2
2
  ${f.stack}`:""}`;return` ${JSON.stringify(f)}`}function A(f,$){if(vf)return;try{if(P.push(`[${new Date().toISOString()}] ${f}${r0($)}
3
3
  `),P.length>=g0)Cf();else s0()}catch{}}function J(f,$){A(`[relay] ${f}`,$)}if(!vf)process.on("exit",Cf);import{createHash as o0,randomUUID as Kf}from"node:crypto";import{mkdir as $0,readFile as d,rename as a0,rm as df,writeFile as _0}from"node:fs/promises";import{homedir as e0}from"node:os";import{dirname as f1,join as t}from"node:path";var $1="anthropic-auth.json",_1="https://api.anthropic.com/api/oauth/usage",m1=[401,403,429],m0=240,D1=m0;var H1=300000,E1=3600000,F1=86400000,M1=5,tf={five_hour:0,seven_day:0},C1=!0,K1=60000;function j1(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return t(process.env.XDG_CONFIG_HOME||t(e0(),".config"),"opencode")}function B(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||t(j1(),$1)}function G(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function N1(f){if(!G(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():Kf(),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:gf(f.lastRefreshError),lastQuotaRefreshError:gf(f.lastQuotaRefreshError),quota:J1(f.quota)}}function gf(f){if(!G(f))return;if(typeof f.message!=="string")return;let $=Number(f.checkedAt);if(!Number.isFinite($))return;let _=Number(f.nextRetryAt),m=Number(f.retryCount);return{message:f.message,checkedAt:$,nextRetryAt:Number.isFinite(_)?_:void 0,retryCount:Number.isFinite(m)?m:void 0,tokenHash:typeof f.tokenHash==="string"?f.tokenHash:void 0}}function J1(f){if(!G(f))return;let $={};for(let _ of["five_hour","seven_day"]){let m=f[_];if(!G(m))continue;let D=Number(m.usedPercent),H=Number(m.remainingPercent),E=Number(m.checkedAt);if(!Number.isFinite(D)||!Number.isFinite(H)||!Number.isFinite(E))continue;$[_]={usedPercent:D,remainingPercent:H,checkedAt:E,resetsAt:typeof m.resetsAt==="string"?m.resetsAt:void 0}}return Object.keys($).length?$:void 0}function b1(f){if(!G(f)||!Array.isArray(f.accounts))return null;return{version:1,main:{type:"opencode",provider:"anthropic"},fallbackOn:Array.isArray(f.fallbackOn)?f.fallbackOn.filter(($)=>Number.isInteger($)):void 0,refresh:G(f.refresh)?f.refresh:void 0,quota:G(f.quota)?f.quota:void 0,claudeCache:G(f.claudeCache)?f.claudeCache:void 0,dump:G(f.dump)?f.dump:void 0,claudeFast:G(f.claudeFast)?f.claudeFast:void 0,cacheKeep:G(f.cacheKeep)?f.cacheKeep:void 0,relay:G(f.relay)?f.relay:void 0,accounts:f.accounts.map(N1).filter(($)=>$!=null)}}async function V(f=B()){try{let $=await d(f,"utf8");return b1(JSON.parse($))}catch($){if($.code==="ENOENT")return null;return null}}async function I1(f){try{let $=await d(f,"utf8"),_=JSON.parse($);return G(_)?_:{}}catch{return{}}}function G1(f){return Object.fromEntries(Object.entries(f).filter(([,$])=>$!==void 0))}async function Y(f,$=B()){await $0(f1($),{recursive:!0});let m={...await I1($),...G1(f)},D=`${$}.${Kf()}.tmp`;await _0(D,`${JSON.stringify(m,null,2)}
4
4
  `,{encoding:"utf8",mode:384}),await a0(D,$)}async function D_(f){let _=`${f.path??B()}.${f.name}.lock`,m=t(_,"owner.json"),D=Kf(),H=f.now??Date.now;async function E(){try{return await $0(_,{mode:448}),await _0(m,`${JSON.stringify({ownerId:D,expiresAt:H()+f.ttlMs})}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{$ as H1,A as Q1,B as L1,C as x0,D as j0,E as v1,F as J0,G as N1,H as _1,I as H0,J as F1,K as q0,L as M1,M as K0,N as Z0,O as $0,P as l,Q as B1,R as G0,S as s0,T as e0,U as S0,V as j1,W as J1,X as K1,Y as D0,Z as U1,_ as x1,a as p0,aa as q1,b as c0,ba as S1,c as a,ca as A1,d as r,da as E1,e as o0,ea as V0,f as u,fa as P0,g as t0,ga as R1,h as a0,ha as A0,i as r0,ia as X0,j as N0,ja as f1,k as W1,ka as W0,l as _0,la as C1,m as F0,ma as E0,n as H,na as Y0,oa as T1,p as S,pa as y1,q as M0,qa as k1,r as Y1,s,sa as g1,t as e,u as w1,v as z1,w as B0,x as I1,y as U0,z as O1}from"./index-sebye7nt.js";import{randomUUID as Pj}from"node:crypto";function m(j){return typeof j==="object"&&j!==null}function a1(j){if(Array.isArray(j))return j;if(m(j)&&Array.isArray(j.data))return j.data;return[]}function r1(j){if(!m(j)||!m(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function m0(j){if(!m(j)||!m(j.info))return null;let J=j.info,K=m(J.model)?J.model:void 0,Z=typeof J.agent==="string"?J.agent:void 0,G=typeof K?.providerID==="string"?K.providerID:typeof J.providerID==="string"?J.providerID:void 0,D=typeof K?.modelID==="string"?K.modelID:typeof J.modelID==="string"?J.modelID:void 0,F=typeof K?.variant==="string"?K.variant:typeof J.variant==="string"?J.variant:void 0;if(!Z&&(!G||!D)&&!F)return null;let A={};if(Z)A.agent=Z;if(G&&D)A.model={providerID:G,modelID:D};if(F)A.variant=F;return A}function b0(j,J){return{agent:j.agent??J.agent,model:j.model??J.model,variant:j.variant??J.variant}}function h0(j){return Boolean(j.agent&&j.model&&j.variant)}async function u0(j,J){if(!j||!J)return null;let K=j;if(typeof K.session?.messages!=="function")return null;let Z=[];try{Z=a1(await Promise.resolve(K.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(Z.length===0)return null;let G={};for(let D=Z.length-1;D>=0;D--){if(r1(Z[D])!=="assistant")continue;let F=m0(Z[D]);if(!F)continue;if(G=b0(G,F),h0(G))return G}for(let D=Z.length-1;D>=0;D--){let F=m0(Z[D]);if(!F)continue;if(G=b0(G,F),h0(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}function d0(j){return`${p0}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function s1(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}function Z1(j,J){let K=new Headers;if(j instanceof Request)j.headers.forEach((G,D)=>{K.set(D,G)});let Z=J?.headers;if(Z){if(Z instanceof Headers)Z.forEach((G,D)=>{K.set(D,G)});else if(Array.isArray(Z))for(let G of Z){let[D,F]=G;if(typeof F<"u")K.set(D,String(F))}else for(let[G,D]of Object.entries(Z))if(typeof D<"u")K.set(G,String(D))}return K}function L0(j){return j.set("anthropic-beta",a(j.get("anthropic-beta"),[c0])),j}function d(j,J,K={}){return J1(j,J,K)}function e1(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((J)=>({...J,name:J.name?d0(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((K)=>{if(K.type==="tool_use"&&K.name)return{...K,name:d0(K.name)};return K});return J});return JSON.stringify(K1(j))}function O0(j){return j.replace(/"name"\s*:\s*"mcp_([^"]+)"/g,(J,K)=>`"name": "${s1(K)}"`)}function n0(j,J=!1){if(J)return{ready:O0(j),pending:""};let K=j.length,Z='"name"',G=Math.max(0,j.length-Z.length+1);for(let F=G;F<j.length;F++)if(Z.startsWith(j.slice(F))){K=Math.min(K,F);break}let D=j.lastIndexOf(Z);if(D!==-1){let F=j.slice(D);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(F))K=Math.min(K,D)}if(K<j.length)return{ready:O0(j.slice(0,K)),pending:j.slice(K)};return{ready:O0(j),pending:""}}function $1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function jj(){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 G1(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 K=J.href,Z=jj();if(Z)J.protocol=Z.protocol,J.host=Z.host;if(J.pathname==="/v1/messages"&&!J.searchParams.has("beta"))J.searchParams.set("beta","true");if(J.href===K)return{input:j,url:J};return{input:j instanceof Request?new Request(J.toString(),j):J,url:J}}function c(j){let Z=j.split(/\n\n+/).filter((G)=>{if(G.includes(o0))return!1;for(let D of a0)if(G.includes(D))return!1;return!0}).join(`
1
+ import{$ as H1,A as Q1,B as L1,C as x0,D as j0,E as v1,F as J0,G as N1,H as _1,I as H0,J as F1,K as q0,L as M1,M as K0,N as Z0,O as $0,P as l,Q as B1,R as G0,S as s0,T as e0,U as S0,V as j1,W as J1,X as K1,Y as D0,Z as U1,_ as x1,a as p0,aa as q1,b as c0,ba as S1,c as a,ca as A1,d as r,da as E1,e as o0,ea as V0,f as u,fa as P0,g as t0,ga as R1,h as a0,ha as A0,i as r0,ia as X0,j as N0,ja as f1,k as W1,ka as W0,l as _0,la as C1,m as F0,ma as E0,n as H,na as Y0,oa as T1,p as S,pa as y1,q as M0,qa as k1,r as Y1,s,sa as g1,t as e,u as w1,v as z1,w as B0,x as I1,y as U0,z as O1}from"./index-16nba65t.js";import{randomUUID as Pj}from"node:crypto";function m(j){return typeof j==="object"&&j!==null}function a1(j){if(Array.isArray(j))return j;if(m(j)&&Array.isArray(j.data))return j.data;return[]}function r1(j){if(!m(j)||!m(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function m0(j){if(!m(j)||!m(j.info))return null;let J=j.info,K=m(J.model)?J.model:void 0,Z=typeof J.agent==="string"?J.agent:void 0,G=typeof K?.providerID==="string"?K.providerID:typeof J.providerID==="string"?J.providerID:void 0,D=typeof K?.modelID==="string"?K.modelID:typeof J.modelID==="string"?J.modelID:void 0,F=typeof K?.variant==="string"?K.variant:typeof J.variant==="string"?J.variant:void 0;if(!Z&&(!G||!D)&&!F)return null;let A={};if(Z)A.agent=Z;if(G&&D)A.model={providerID:G,modelID:D};if(F)A.variant=F;return A}function b0(j,J){return{agent:j.agent??J.agent,model:j.model??J.model,variant:j.variant??J.variant}}function h0(j){return Boolean(j.agent&&j.model&&j.variant)}async function u0(j,J){if(!j||!J)return null;let K=j;if(typeof K.session?.messages!=="function")return null;let Z=[];try{Z=a1(await Promise.resolve(K.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(Z.length===0)return null;let G={};for(let D=Z.length-1;D>=0;D--){if(r1(Z[D])!=="assistant")continue;let F=m0(Z[D]);if(!F)continue;if(G=b0(G,F),h0(G))return G}for(let D=Z.length-1;D>=0;D--){let F=m0(Z[D]);if(!F)continue;if(G=b0(G,F),h0(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}function d0(j){return`${p0}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function s1(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}function Z1(j,J){let K=new Headers;if(j instanceof Request)j.headers.forEach((G,D)=>{K.set(D,G)});let Z=J?.headers;if(Z){if(Z instanceof Headers)Z.forEach((G,D)=>{K.set(D,G)});else if(Array.isArray(Z))for(let G of Z){let[D,F]=G;if(typeof F<"u")K.set(D,String(F))}else for(let[G,D]of Object.entries(Z))if(typeof D<"u")K.set(G,String(D))}return K}function L0(j){return j.set("anthropic-beta",a(j.get("anthropic-beta"),[c0])),j}function d(j,J,K={}){return J1(j,J,K)}function e1(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((J)=>({...J,name:J.name?d0(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((K)=>{if(K.type==="tool_use"&&K.name)return{...K,name:d0(K.name)};return K});return J});return JSON.stringify(K1(j))}function O0(j){return j.replace(/"name"\s*:\s*"mcp_([^"]+)"/g,(J,K)=>`"name": "${s1(K)}"`)}function n0(j,J=!1){if(J)return{ready:O0(j),pending:""};let K=j.length,Z='"name"',G=Math.max(0,j.length-Z.length+1);for(let F=G;F<j.length;F++)if(Z.startsWith(j.slice(F))){K=Math.min(K,F);break}let D=j.lastIndexOf(Z);if(D!==-1){let F=j.slice(D);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(F))K=Math.min(K,D)}if(K<j.length)return{ready:O0(j.slice(0,K)),pending:j.slice(K)};return{ready:O0(j),pending:""}}function $1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function jj(){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 G1(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 K=J.href,Z=jj();if(Z)J.protocol=Z.protocol,J.host=Z.host;if(J.pathname==="/v1/messages"&&!J.searchParams.has("beta"))J.searchParams.set("beta","true");if(J.href===K)return{input:j,url:J};return{input:j instanceof Request?new Request(J.toString(),j):J,url:J}}function c(j){let Z=j.split(/\n\n+/).filter((G)=>{if(G.includes(o0))return!1;for(let D of a0)if(G.includes(D))return!1;return!0}).join(`
2
2
 
3
3
  `);for(let G of r0)Z=Z.replace(G.match,G.replacement);return Z.trim()}function E(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function Jj(j){let J={type:"text",text:u};if(j==null)return[J];if(typeof j==="string"){let Z=c(j);if(Z===u)return[J];return[J,{type:"text",text:Z}]}if(E(j)){let Z=typeof j.type==="string"?j.type:"text",G=typeof j.text==="string"?j.text:"";return[J,{...j,type:Z,text:c(G)}]}if(!Array.isArray(j))return[J];let K=j.map((Z)=>{if(typeof Z==="string")return{type:"text",text:c(Z)};if(E(Z)&&Z.type==="text"&&typeof Z.text==="string")return{...Z,type:"text",text:c(Z.text)};return{type:"text",text:String(Z)}});if(K[0]?.text===u)return K;return[J,...K]}var D1={type:"ephemeral",ttl:"1h"};function Kj(j){if(E(j.cache_control))return j.cache_control;if(E(j.cacheControl))return j.cacheControl;return null}function t(j,J){if(!E(j))return!1;return delete j.cacheControl,j.cache_control=J?{...D1}:{type:"ephemeral"},!0}function i0(j){if(!E(j))return;delete j.cache_control,delete j.cacheControl}function Zj(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function o(j,J){if(!E(j))return;let K=Kj(j);if(!K||K.type!=="ephemeral")return;if(J)K.ttl="1h";else delete K.ttl}function l0(j,J){if(Array.isArray(j.system))for(let K of j.system)o(K,J);else o(j.system,J);if(!Array.isArray(j.messages))return;for(let K of j.messages)if(o(K,J),E(K)&&Array.isArray(K.content))for(let Z of K.content)o(Z,J)}function $j(j,J){if(Array.isArray(j.system))for(let K of j.system)J(K);else J(j.system);if(!Array.isArray(j.messages))return;for(let K of j.messages)if(J(K),E(K)&&Array.isArray(K.content))for(let Z of K.content)J(Z)}function V1(j){i0(j),$j(j,i0)}function Gj(j){V1(j),j.cache_control={...D1}}function Q0(j){if(!E(j))return!1;let J=Zj(j.content);if(!J?.length)return t(j,!0);j.content=J;let K=[...J].reverse().find((Z)=>E(Z)&&Z.type!=="thinking");return t(K??j,!0)}function Dj(j){if(V1(j),Array.isArray(j.system)){let K=j.system.findIndex((D)=>E(D)&&D.text===u),Z=j.system.slice(K>=0?K+1:0).filter(E),G=Z[Z.length-1];t(G,!0)}else t(j.system,!0);if(!Array.isArray(j.messages))return;Q0(j.messages[0]),Q0(j.messages[1]);let J=j.messages.length-2;if(J>1)Q0(j.messages[J])}function Vj(j,J){if(!J.enabled){l0(j,!1),delete j.cache_control,delete j.cacheControl;return}if(J.mode==="automatic"){Gj(j);return}if(J.mode==="hybrid"){Dj(j);return}l0(j,!0),delete j.cacheControl}async function P1(j,J={}){try{let K=JSON.parse(j),Z=Array.isArray(K.messages)&&K.messages.some((G)=>G.role==="user")?e0(K.messages,void 0,t0):null;if(K.system=Jj(K.system),Z&&Array.isArray(K.system))K.system.unshift({type:"text",text:Z});if(Vj(K,{enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.fastModeEnabled&&r(K.model))K.speed="fast";else if(K.speed==="fast")delete K.speed;if(J.identity)j1(K,J.identity);return await s0(e1(K))}catch{return j}}function v0(j){if(!j.body)return j;let J=j.body.getReader(),K=new TextDecoder,Z=new TextEncoder,G="",D=new ReadableStream({async pull(F){let{done:A,value:T}=await J.read();if(A){let h=n0(`${G}${K.decode()}`,!0);if(h.ready)F.enqueue(Z.encode(h.ready));F.close();return}let z0=G+K.decode(T,{stream:!0}),b=n0(z0);if(G=b.pending,b.ready)F.enqueue(Z.encode(b.ready))}});return new Response(D,{status:j.status,statusText:j.statusText,headers:j.headers})}var Xj="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",Wj=60000,m1=240,Yj=m1,wj=1,X1=!1;function w0(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function M(){return performance.now()}function q(j){return Math.round(j*10)/10}function zj(){if(X1||!1||!w0())return;X1=!0;let j=100,J=250,K=M()+j;setInterval(()=>{let Z=M(),G=Z-K;if(K=Z+j,G<J)return;H("[perf] opencode event_loop_lag",{lagMs:q(G),thresholdMs:J})},j).unref?.()}function Ij(j){let J=M(),K={requestId:String(wj++),start:J,last:J,mark(Z,G){let D=M();if(w0())H("[perf] opencode request stage",{requestId:K.requestId,stage:Z,deltaMs:q(D-K.last),totalMs:q(D-K.start),...G});K.last=D},done(Z,G){let D=M();if(w0())H("[perf] opencode request done",{requestId:K.requestId,stage:Z,deltaMs:q(D-K.last),totalMs:q(D-K.start),...G});K.last=D}};if(w0())H("[perf] opencode request start",{requestId:K.requestId,...j});return K}async function n(j,J,K){let Z=j.client.session,G=await u0(j.client,J),D={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:K,ignored:!0}]}};if(G?.agent)D.body.agent=G.agent;if(G?.model)D.body.model=G.model;if(G?.variant)D.body.variant=G.variant;if(typeof Z?.promptAsync==="function"){await Z.promptAsync(D);return}if(typeof Z?.prompt==="function"){await Promise.resolve(Z.prompt(D));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function i(){throw Error(Xj)}var Bj=async(j)=>{zj();let{client:J}=j,K=new M1;K.startBackgroundRefresh();let Z=null,G=new E1({loadStorage:()=>S(),prepareHeaders:async($,O)=>{if(!A)return $;let L=await A();if(L.type!=="oauth")return $;if(!L.access||L.expires&&L.expires<Date.now()){if(!Z)return $;L.access=await Z()}if(!L.access)return $;try{let Q=JSON.parse(O.bodyText),U=await S0(L.access,typeof Q.model==="string"?Q.model:void 0);if($.delete("anthropic-beta"),d($,L.access,{body:Q,identity:U}),$.set("anthropic-beta",a($.get("anthropic-beta"),[U1])),Q.speed==="fast")L0($)}catch{d($,L.access)}return $},log:H}),D=await S(),F=k1(D);l({enabled:s(D),mode:e(D)}),P0(B0(D)),W0(U0(D));let A=null,T=null;function z0($){let O=$?.refresh?.refreshBeforeExpiryMinutes??Yj;return Math.max(m1,O)*60000}function b($){return $?.refresh?.enabled!==!1}async function h($){if(!$)return;let O=await S(),L=O?.refresh?.mainLastRefreshError;if(!O?.refresh||!L?.tokenHash)return;let Q=j0($);if(L.tokenHash===Q)return;O.refresh.mainLastRefreshError=void 0,await M0(O),H("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:L.checkedAt,previousNextRetryAt:L.nextRetryAt,previousRetryCount:L.retryCount})}async function b1(){let $=[];if(A)try{let Q=await A();if(Q.type==="oauth"&&Q.access)$.push({name:"OpenCode anthropic",role:"main",quota:await q0({accessToken:Q.access})});else if(Q.type==="oauth")$.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(Q){$.push({name:"OpenCode anthropic",role:"main",error:Q instanceof Error?Q.message:String(Q)})}let{storage:O,errors:L}=await K.refreshQuotaForAllAccounts();if($.push(...T1(O,new Map(L.map((Q)=>[Q.accountId,Q.message])))),!A)$.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return y1({accounts:$,refreshedAt:Date.now()})}async function h1($){let O=B1($);if(O.type==="enable"||O.type==="disable"){let f=O.type==="enable",y=await w1(f),k=e(y);return l({enabled:f,mode:k}),G0({argumentsText:$,enabled:f,mode:k})}if(O.type==="mode"){let f=await z1(O.mode),y=s(f);return l({enabled:y,mode:O.mode}),G0({argumentsText:$,enabled:y,mode:O.mode})}let L=await S(),Q=s(L),U=e(L);return l({enabled:Q,mode:U}),G0({argumentsText:$,enabled:Q,mode:U})}async function u1($){let O=x1($),L=await S();if(O.type==="window")L=await Q1(O.startHour,O.endHour);else if(O.type==="disable")L=await L1(!1);let Q=H1(L),U=G.stats(Q);return A1({argumentsText:$,enabled:q1(L),window:Q,hybridActive:S1(L),trackedSessions:U.trackedSessions,nextPrewarmAt:U.nextPrewarmAt})}async function d1($){let O=R1($);if(O.type==="enable"||O.type==="disable"){let U=O.type==="enable";return await I1(U),P0(U),A0({argumentsText:$,enabled:U})}let L=await S(),Q=B0(L);return P0(Q),A0({argumentsText:$,enabled:Q})}async function n1($){let O=C1($);if(O.type==="enable"||O.type==="disable"){let U=O.type==="enable";return await O1(U),W0(U),E0({argumentsText:$,enabled:U})}let L=await S(),Q=U0(L);return W0(Q),E0({argumentsText:$,enabled:Q})}return{config:async($)=>{$.command={...$.command??{},[K0]:{template:K0,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[D0]:{template:D0,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[Y0]:{template:Y0,description:"Show current Claude OAuth quota usage for all accounts."},[V0]:{template:V0,description:"Show or toggle Anthropic request dump capture for debugging."},[X0]:{template:X0,description:"Show or toggle Anthropic fast mode for supported Opus models."}}},"command.execute.before":async($)=>{if($.command===K0)await n(j,$.sessionID,await h1($.arguments)),i();if($.command===D0)await n(j,$.sessionID,await u1($.arguments)),i();if($.command===Y0)await n(j,$.sessionID,await b1()),i();if($.command===V0)await n(j,$.sessionID,await d1($.arguments)),i();if($.command===X0)await n(j,$.sessionID,await n1($.arguments)),i()},auth:{provider:"anthropic",async loader($,O){if(A=$,(await $()).type==="oauth"){let i1=function(){if(T)clearInterval(T),T=null;let V=async()=>{try{let X=await S();if(!b(X))return;let Y=await $();if(Y.type!=="oauth")return;if(await h(Y.refresh),!Y.expires)return;let I=Y.expires-Date.now(),B=z0(X);if(I>B)return;if(H("[refresh] opencode main oauth background due",{expiresInMs:I,refreshBeforeMs:B}),Y.refresh&&J0(X?.refresh?.mainLastRefreshError,Y.refresh,Date.now())){H("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:X?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:X?.refresh?.mainLastRefreshError?.retryCount});return}if(Y.refresh&&X?.refresh?.mainRefreshLeaseUntil&&X.refresh.mainRefreshLeaseUntil>Date.now()&&X.refresh.mainRefreshLeaseTokenHash===j0(Y.refresh))return;await k(),H("[refresh] opencode main oauth refreshed in background",{expires:Y.expires})}catch(X){H("[refresh] opencode main oauth refresh failed",{message:X instanceof Error?X.message:String(X)})}};if(T=setInterval(()=>{V()},Wj),"unref"in T)T.unref()},R0=function(V,X){if(V instanceof Request&&V.body)return!1;return X==null||typeof X==="string"},l1=function(V){return V.has("x-parent-session-id")},f0=function(V){return V.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(V)},p1=function(V){return V?.quota?.enabled===!0},c1=function(V,X){let Y=Date.now();if(f||Y<y)return;f=y0(V,X).catch((I)=>{throw y=Y+_1(X),I}).finally(()=>{f=null}),f.catch(()=>{})};for(let V of Object.values(O.models))V.cost={input:0,output:0,cache:{read:0,write:0}};let Q=null,U=null,f=null,y=0;async function k(){if(!Q)Q=(async()=>{let Y=null,I=null,B=null;async function _(z){let v=await S()??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};v.refresh=v.refresh??{},z(v),await M0(v)}for(let z=0;z<=2;z++){let v=null;try{if(z>0){let x=500*2**(z-1);await new Promise((I0)=>setTimeout(I0,x))}if(v=await $(),!v.refresh)throw Error("Token refresh failed: missing refresh token");let P=await S(),W=j0(v.refresh),w=P?.refresh?.mainLastRefreshError;if(H("[refresh] opencode main oauth refresh check",{attempt:z,expiresInMs:v.expires?v.expires-Date.now():void 0,hasBackoff:Boolean(w),backoffActive:w?J0(w,v.refresh,Date.now()):!1,retryCount:w?.retryCount,nextRetryAt:w?.nextRetryAt}),w&&J0(w,v.refresh,Date.now()))throw H("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:w.nextRetryAt,retryCount:w.retryCount}),Error(N1(w,Date.now()));if(P?.refresh?.mainRefreshLeaseUntil&&P.refresh.mainRefreshLeaseUntil>Date.now()&&P.refresh.mainRefreshLeaseTokenHash===W)throw H("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:P.refresh.mainRefreshLeaseUntil}),Error("Claude OAuth refresh is already in progress");let N=await Y1({name:"opencode-main-oauth-refresh",ttlMs:120000});if(!N)throw H("[refresh] opencode main oauth refresh skipped file lock"),Error("Claude OAuth refresh is already in progress");B=N.release,Y=Pj(),I=W,await _((x)=>{x.refresh=x.refresh??{},x.refresh.mainRefreshLeaseId=Y??void 0,x.refresh.mainRefreshLeaseUntil=Date.now()+120000,x.refresh.mainRefreshLeaseTokenHash=W});let C=await S();if(H("[refresh] opencode main oauth refresh lease acquired",{attempt:z,leaseUntil:Date.now()+120000}),C?.refresh?.mainRefreshLeaseId!==Y||C.refresh.mainRefreshLeaseTokenHash!==W)throw Error("Claude OAuth refresh is already in progress");H("[refresh] opencode main oauth refresh request start",{attempt:z});let R=await W1({refreshToken:v.refresh,maxRetries:0});return await J.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:R.refresh,access:R.access,expires:R.expires}}),await _((x)=>{if(!x?.refresh)return;if(x.refresh.mainLastRefreshError=void 0,x.refresh.mainRefreshLeaseId===Y)x.refresh.mainRefreshLeaseId=void 0,x.refresh.mainRefreshLeaseUntil=void 0,x.refresh.mainRefreshLeaseTokenHash=void 0}),H("[refresh] opencode main oauth refresh succeeded",{attempt:z,expiresInMs:R.expires-Date.now()}),R.access}catch(P){let W=P instanceof Error&&(P.message.includes("fetch failed")||("code"in P)&&(P.code==="ECONNRESET"||P.code==="ECONNREFUSED"||P.code==="ETIMEDOUT"||P.code==="UND_ERR_CONNECT_TIMEOUT"));if(z<2&&(W||P instanceof N0&&P.status>=500))continue;H("[refresh] opencode main oauth refresh attempt failed",{attempt:z,error:P instanceof Error?P.message:String(P),transient:W});let w=v?.refresh;if(w&&P instanceof N0)await _((N)=>{N.refresh=N.refresh??{},N.refresh.mainLastRefreshError=v1({error:P,now:Date.now(),refreshToken:w,previous:N.refresh.mainLastRefreshError})});throw P}finally{if(Y)await _((P)=>{if(!P?.refresh)return;if(P.refresh.mainRefreshLeaseId===Y&&P.refresh.mainRefreshLeaseTokenHash===I)P.refresh.mainRefreshLeaseId=void 0,P.refresh.mainRefreshLeaseUntil=void 0,P.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await B?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{Q=null});return Q}Z=k,i1();async function C0(V,X){if(!V.body||V.status!==200)return X?.mark("inspect_stream_skip",{status:V.status}),{response:V,rateLimited:!1};if(V.headers.get("x-cortexkit-relay-optimistic")==="true")return X?.mark("inspect_stream_skip",{status:V.status,reason:"optimistic_relay"}),{response:V,rateLimited:!1};let Y=M(),I=V.body.getReader(),B=[],_=new TextDecoder,z="",v=0;while(!z.includes(`
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-anthropic-auth",
3
- "version": "1.2.0",
3
+ "version": "1.2.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.2.0"
44
+ "@cortexkit/anthropic-auth-core": "1.2.1"
45
45
  }
46
46
  }