@cortexkit/opencode-anthropic-auth 1.18.0 → 1.19.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/README.md CHANGED
@@ -32,7 +32,7 @@ This repo is a Bun workspace monorepo with two user-facing integrations and one
32
32
  - **Cache keepalive**: use `/claude-cachekeep always` or `/claude-cachekeep HH-HH` to pre-warm hybrid cache anchors for active sessions before the 1-hour TTL expires.
33
33
  - **Fast mode toggle**: use `/claude-fast on|off` to request Anthropic fast mode for supported Opus models.
34
34
  - **Adaptive reasoning visibility**: request summarized adaptive thinking for Claude Fable 5, Mythos 5, and Opus 5. OpenCode receives native `low`, `medium`, `high`, `xhigh`, and `max` Opus 5 effort variants rather than legacy manual-thinking budgets.
35
- - **Fable/Opus 5 content-filter recovery**: when Fable or Opus 5 ends a session response with Anthropic's `refusal` content-filter reason, transparently retry that source-model family with Opus 4.8 for 10 successful model responses. Recovery state and pending cache warms remain independent when a session switches between Fable and Opus 5. After each downgraded response, a zero-output prewarm advances the source model's prompt cache using the OAuth account that served the filtered request. The latest Opus cache boundary is retained so a later refusal can bridge back even after more than 20 content blocks. The TUI sidebar and OpenCode Desktop report both transitions while preserving the selected model.
35
+ - **Fable/Opus 5 safety fallback**: eligible OAuth requests try Anthropic's server-side safety fallback first. The plugin preserves Anthropic's fallback conversation boundary across OpenCode history and automatically starts its deterministic 10-response Opus 4.8 recovery if the response still ends in refusal. The TUI sidebar and OpenCode Desktop report the active target model and restoration. Set `OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE=legacy` to bypass the server policy and use client-side recovery exclusively.
36
36
  - **Live quota visibility**: use `/claude-quota` to see main and fallback quota state, reset times, and refresh errors.
37
37
  - **Killswitch**: per-account hard-block thresholds that stop requests before hitting Anthropic's rate limits, with synthetic 429 retry-after when all accounts are exhausted.
38
38
  - **User-owned Cloudflare relay**: optionally provision your own Worker relay to reduce repeated client upload bytes for large OpenCode or Pi requests.
@@ -289,6 +289,22 @@ In OpenCode, this includes the main Anthropic account and sidecar fallback accou
289
289
 
290
290
  Reset times are rendered as relative durations, such as `resets in 10m` or `resets in 1h 15m`.
291
291
 
292
+ ## Safety fallback
293
+
294
+ Eligible Fable 5 and Opus 5 OAuth requests try Anthropic's server-side safety fallback first. The plugin sends `fallbacks: "default"` with Anthropic's server-side fallback beta, preserves fallback conversation boundaries in OpenCode history, and reports model handoffs and restoration in the TUI sidebar or OpenCode Desktop. Follow-up requests may remain on Anthropic's selected fallback model for approximately one hour.
295
+
296
+ If an eligible OAuth response still ends in refusal, CortexKit automatically starts its deterministic 10-successful-response Opus 4.8 recovery, prewarms the selected source model without the server-fallback opt-in, and then restores that model. If the refused response already completed a tool call, the plugin preserves that call and continues with its existing tool result instead of replaying the tool.
297
+
298
+ Custom API-key routes do not receive the server-side fallback beta or request field.
299
+
300
+ To bypass Anthropic's server policy and use deterministic client recovery from the first refusal, start OpenCode with:
301
+
302
+ ```bash
303
+ OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE=legacy opencode
304
+ ```
305
+
306
+ Legacy mode routes a refused Fable 5 or Opus 5 session through Opus 4.8 for 10 successful responses, prewarms the selected source model's cache, and then restores that model without first opting into Anthropic's server policy. Unset the variable and restart OpenCode to return to the default server-first policy with the same client recovery as a backstop.
307
+
292
308
  ## Killswitch
293
309
 
294
310
  The killswitch is a per-account hard-block that stops requests when remaining quota drops below configured thresholds, even if Anthropic's API would still accept them. Unlike `minimumRemaining` (which routes to fallback accounts), the killswitch removes accounts from the routing pool entirely.
@@ -517,6 +533,7 @@ Dump state is persisted in the active sidecar config as `dump.enabled` (`~/.conf
517
533
  | `ANTHROPIC_BASE_URL` | Override the Anthropic API endpoint. Must be HTTP(S). |
518
534
  | `ANTHROPIC_INSECURE` | Set to `1` or `true` to skip TLS verification when `ANTHROPIC_BASE_URL` is set. |
519
535
  | `OPENCODE_ANTHROPIC_AUTH_FILE` | Override the OpenCode sidecar config path. |
536
+ | `OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE` | Set to `legacy` to bypass Anthropic's server policy and use deterministic 10-response client recovery exclusively. The default tries server-side safety fallback first and uses client recovery as a backstop. |
520
537
  | `PI_ANTHROPIC_AUTH_FILE` | Override the Pi sidecar config path. |
521
538
  | `PI_AGENT_DIR` | Override Pi's agent directory when deriving the default sidecar path. |
522
539
  | `CLOUDFLARE_API_TOKEN` | Cloudflare token used by `bunx @cortexkit/opencode-anthropic-auth relay setup`. Not stored. |
@@ -532,7 +549,8 @@ For Claude Pro/Max OAuth requests, the plugin works at the final Anthropic wire-
532
549
  4. Prepends Claude Code identity and billing-header blocks.
533
550
  5. Rewrites cache controls according to `/claude-cache` mode.
534
551
  6. Renames MCP tool names into Claude-compatible PascalCase form.
535
- 7. Computes final-body `cch` over the fully serialized request body.
552
+ 7. Opts eligible Fable 5 and Opus 5 OAuth requests into Anthropic's server-side safety fallback, restores stored fallback boundaries, and activates replay-safe client recovery if the response still refuses.
553
+ 8. Computes final-body `cch` over the fully serialized request body.
536
554
 
537
555
  The sanitizer is anchor-based: it removes paragraphs containing known OpenCode documentation or source anchors, performs a small set of inline replacements, and preserves the rest of the prompt including user/project instructions, tool policy, environment context, and file paths.
538
556
 
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{D as z,E as N,G as P,I as L,K as E,M as K,N as S,Ob as T,Qb as q,za as U}from"./index-h0pmqm96.js";import"./index-1ets4bf8.js";import{uc as w}from"./index-9aeag0wm.js";import{stdin as x,stdout as v}from"node:process";import{createInterface as y}from"node:readline/promises";function R(){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 _(){console.log(`Usage:
2
+ import{D as z,E as N,G as P,I as L,K as E,M as K,N as S,Ob as T,Qb as q,za as U}from"./index-vwgzgh5x.js";import"./index-dex8fs0m.js";import{vc as w}from"./index-dzs7w297.js";import{stdin as x,stdout as v}from"node:process";import{createInterface as y}from"node:readline/promises";function R(){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 _(){console.log(`Usage:
3
3
  opencode-anthropic-auth login [label]
4
4
  opencode-anthropic-auth api add [label]
5
5
  opencode-anthropic-auth list
@@ -19,6 +19,18 @@ export type FableFallbackPlan = {
19
19
  requestSequence?: number;
20
20
  completed?: boolean;
21
21
  };
22
+ /**
23
+ * Models whose content-filter refusal we recover from by downgrading to Opus 4.8
24
+ * for a short window. Fable 5 is the original case; Opus 5 is identical in
25
+ * shape (cyber safety classifiers that can return `stop_reason: "refusal"`,
26
+ * Anthropic's own fallback default is `claude-opus-4-8`, same pricing). Mythos
27
+ * has no classifiers and Sonnet 5 is not flagged — both stay outside this
28
+ * gate. The single shared fallback id matches Anthropic's default for both
29
+ * source models, so the recovery period is uniform.
30
+ */
31
+ export type RecoverableRefusalFamily = 'fable-5' | 'opus-5';
32
+ export declare function recoverableRefusalFamily(model: unknown): RecoverableRefusalFamily | null;
33
+ export declare function isRecoverableRefusalModel(model: unknown): model is string;
22
34
  export declare class FableFallbackManager {
23
35
  private readonly now;
24
36
  private readonly recoveries;
@@ -1 +1 @@
1
- import{createHash as z}from"node:crypto";import{homedir as F,tmpdir as O}from"node:os";import{join as q,resolve as G}from"node:path";var J="OPENCODE_ANTHROPIC_AUTH_RPC_DIR";function T(g){let k=process.env[J]?.trim();if(k)return G(g,k);let w=z("sha256").update(g).digest("hex").slice(0,16),x=process.env.XDG_STATE_HOME||q(F(),".local","state");return q(x,"cortexkit","anthropic-auth","rpc",w)}export{O as qc,T as rc};
1
+ import{createHash as z}from"node:crypto";import{homedir as F,tmpdir as O}from"node:os";import{join as q,resolve as G}from"node:path";var J="OPENCODE_ANTHROPIC_AUTH_RPC_DIR";function T(g){let k=process.env[J]?.trim();if(k)return G(g,k);let w=z("sha256").update(g).digest("hex").slice(0,16),x=process.env.XDG_STATE_HOME||q(F(),".local","state");return q(x,"cortexkit","anthropic-auth","rpc",w)}export{O as rc,T as sc};
@@ -1,2 +1,2 @@
1
1
  import{mkdir as l,readdir as u,readFile as c,rename as p,unlink as m,writeFile as d}from"node:fs/promises";import{join as a}from"node:path";function f(t){try{return process.kill(t,0),!0}catch(r){return r.code==="EPERM"}}async function b(t,r){await l(t,{recursive:!0});let s={...r,startedAt:Date.now()},e=a(t,`port-${r.pid}.json`),i=`${e}.${process.pid}.tmp`;return await d(i,JSON.stringify(s),{encoding:"utf8",mode:384}),await p(i,e),e}async function h(t,r){let s;try{s=await u(t)}catch{return null}let e=[];for(let n of s){if(!n.startsWith("port-")||!n.endsWith(".json"))continue;try{let o=JSON.parse(await c(a(t,n),"utf8"));if(Number.isFinite(o.port))if(f(o.pid))e.push(o);else m(a(t,n)).catch(()=>{})}catch{}}if(e.length===0)return null;let i=r&&r>=1?e.filter((n)=>n.pid===r):[];return(i.length>0?i:e).sort((n,o)=>o.startedAt-n.startedAt)[0]??null}
2
- export{b as oc,h as pc};
2
+ export{b as pc,h as qc};
@@ -0,0 +1,2 @@
1
+ import{mc as Q}from"./index-dex8fs0m.js";import{randomUUID as H}from"node:crypto";import{mkdir as R,readFile as T,rename as _,rm as O,rmdir as p,stat as P,unlink as S,writeFile as A}from"node:fs/promises";import{tmpdir as k}from"node:os";import{dirname as F,join as f}from"node:path";var m="OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE",w=f(k(),"opencode-anthropic-auth"),y=f(w,"sidebar-state.json");function g(){return process.env[m]||y}var C={main:{quota:null},fallbacks:[],activeId:void 0,route:"main",relay:null,fastMode:!1,lastUpdated:0};function N(J){return J!==null&&typeof J==="object"&&!Array.isArray(J)}function q(J){if(!N(J))return;let $=Number(J.usedPercent),V=Number(J.remainingPercent);if(!Number.isFinite($)||!Number.isFinite(V))return;return{usedPercent:$,remainingPercent:V,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0}}function L(J){if(!N(J))return null;let $={},V=q(J.five_hour),x=q(J.seven_day);if(V)$.five_hour=V;if(x)$.seven_day=x;if(Array.isArray(J.scoped)){let G=J.scoped.map((X)=>{if(!N(X))return;let Z=q(X);if(!Z)return;if(typeof X.id!=="string"||!X.id.trim())return;if(typeof X.title!=="string"||!X.title.trim())return;if(typeof X.modelName!=="string"||!X.modelName.trim())return;let j=typeof X.modelId==="string"&&X.modelId.trim()?X.modelId.trim():void 0;return{...Z,id:X.id.trim(),title:X.title.trim(),...j&&{modelId:j},modelName:X.modelName.trim()}}).filter((X)=>X!=null);$.scoped=G}if(N(J.extraUsage)){let G=M(J.extraUsage.used),X=M(J.extraUsage.limit);if(G&&X&&typeof J.extraUsage.exhausted==="boolean")$.extraUsage={used:G,limit:X,...typeof J.extraUsage.utilizationPercent==="number"&&Number.isFinite(J.extraUsage.utilizationPercent)&&{utilizationPercent:J.extraUsage.utilizationPercent},...typeof J.extraUsage.severity==="string"&&{severity:J.extraUsage.severity},exhausted:J.extraUsage.exhausted}}if(typeof J.bindingWindow==="string"&&J.bindingWindow.trim())$.bindingWindow=J.bindingWindow.trim();if(typeof J.fallbackAdvised==="boolean")$.fallbackAdvised=J.fallbackAdvised;return Object.keys($).length?$:null}function M(J){if(!N(J))return;if(!Number.isInteger(J.amountMinor)||typeof J.currency!=="string"||!/^[A-Za-z]{3}$/.test(J.currency.trim())||!Number.isInteger(J.exponent)||J.exponent<0||J.exponent>20)return;return{amountMinor:J.amountMinor,currency:J.currency.trim(),exponent:J.exponent}}function u(J){if(!N(J))return{...C};let $={quota:null};if(N(J.main)){let Z=J.main;if($.quota=L(Z.quota),typeof Z.tierLabel==="string"&&Z.tierLabel.trim())$.tierLabel=Z.tierLabel.trim();if(typeof Z.quotaBackedOff==="boolean")$.quotaBackedOff=Z.quotaBackedOff;if(typeof Z.quotaBackoffUntil==="number")$.quotaBackoffUntil=Z.quotaBackoffUntil;if(typeof Z.refreshBackedOff==="boolean")$.refreshBackedOff=Z.refreshBackedOff;if(typeof Z.refreshBackoffUntil==="number")$.refreshBackoffUntil=Z.refreshBackoffUntil}let V=Array.isArray(J.fallbacks)?J.fallbacks.filter(N).filter((Z)=>typeof Z.id==="string").map((Z)=>({id:Z.id,label:typeof Z.label==="string"?Z.label:void 0,quota:L(Z.quota),enabled:typeof Z.enabled==="boolean"?Z.enabled:!1,needsReauth:typeof Z.needsReauth==="boolean"?Z.needsReauth:!1,tierLabel:typeof Z.tierLabel==="string"&&Z.tierLabel.trim()?Z.tierLabel.trim():void 0})):[],x=null;if(N(J.relay)){let Z=J.relay;if(typeof Z.enabled==="boolean"&&typeof Z.transport==="string")x={enabled:Z.enabled,transport:Z.transport}}let G;if(N(J.cacheKeep)){let Z=J.cacheKeep;if(typeof Z.enabled==="boolean")G={enabled:Z.enabled,window:typeof Z.window==="string"?Z.window:void 0,trackedSessions:typeof Z.trackedSessions==="number"?Z.trackedSessions:void 0}}let X=Array.isArray(J.fableRecoveries)?J.fableRecoveries.filter(N).flatMap((Z)=>{if(typeof Z.sessionId!=="string"||Z.mode!=="opus"&&Z.mode!=="fable"&&Z.mode!=="server"||typeof Z.remaining!=="number"||!Number.isFinite(Z.remaining)||typeof Z.changedAt!=="number"||!Number.isFinite(Z.changedAt))return[];return[{sessionId:Z.sessionId,mode:Z.mode,remaining:Math.max(0,Math.floor(Z.remaining)),changedAt:Z.changedAt,requestedModelId:typeof Z.requestedModelId==="string"?Z.requestedModelId:void 0,targetModelId:typeof Z.targetModelId==="string"?Z.targetModelId:void 0}]}):[];return{main:$,fallbacks:V,activeId:typeof J.activeId==="string"?J.activeId:void 0,route:typeof J.route==="string"?J.route:C.route,relay:x,fastMode:typeof J.fastMode==="boolean"?J.fastMode:C.fastMode,cacheKeep:G,fableRecoveries:X.length>0?X:void 0,lastUpdated:typeof J.lastUpdated==="number"?J.lastUpdated:0}}var h=Promise.resolve(),v=1000,c=2000,d=5,n=15,z=null;function VJ(J){z=J}var b=null;function XJ(J){b=J}function xJ(){return b}function l(J){return new Promise(($)=>setTimeout($,J))}async function D(J){let $=`${J}.lock`,V=z?.lockBudgetMs??v,x=z?.lockRetryMinMs??d,G=z?.lockRetryMaxMs??n,X=Date.now()+V;while(!0){try{await R($);let Y=H(),K=f($,Y);return await A(K,"",{encoding:"utf8",mode:384,flag:"wx"}),await z?.onLockAcquired?.($),{ownsLock:async()=>{try{return await P(K),!0}catch{return!1}},release:async()=>{try{await S(K)}catch{return}await z?.beforeReleaseDirectoryRemoval?.($),await p($).catch(()=>{})}}}catch(Y){if(Y.code!=="EEXIST")return Q.trace("sidebar","state lock unavailable; write skipped",{stateFile:J,error:Y instanceof Error?Y.message:String(Y)}),null}try{let Y=await P($);if(Date.now()-Y.mtimeMs>c){await z?.afterStaleLockStat?.($);let K=`${$}.evict-${process.pid}-${H()}`;try{await _($,K)}catch(B){if(B.code==="ENOENT")continue;throw B}await z?.onStaleLockClaimed?.($),await O(K,{recursive:!0,force:!0}).catch(()=>{});continue}}catch(Y){if(Y.code==="ENOENT")continue;return Q.trace("sidebar","state lock inspection failed; write skipped",{stateFile:J,error:Y instanceof Error?Y.message:String(Y)}),null}let Z=X-Date.now();if(Z<=0)return Q.warn("sidebar","lock budget exhausted, write skipped",{stateFile:J,budgetMs:V}),null;let j=x+Math.floor(Math.random()*(G-x+1));await l(Math.min(j,Z))}}async function YJ(J){return(await D(J))?.release??null}async function i(J,$,V){let x=`${J}.${process.pid}.${H()}.tmp`;await A(x,JSON.stringify($),{encoding:"utf8",mode:384});try{if(!await V())return Q.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await O(x,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await z?.beforeRename?.(J,x),!await V())return Q.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await O(x,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await _(x,J),await z?.afterRename?.(J),!await V())return"lock-lost-after-rename";return"written"}catch(G){throw await O(x,{force:!0}).catch(()=>{}),G}}async function E(J=g()){try{let $=await T(J,"utf8");return u(JSON.parse($))}catch{return C}}async function GJ(J,$=g(),V={}){return h=h.then(async()=>{await R(F($),{recursive:!0});for(let x=0;x<2;x++){let G=x===1,X=await D($);if(!X){if(G)Q.warn("sidebar","post-rename repair lock unavailable; write skipped",{stateFile:$});return}let Z=J,j;try{if(V.routingAuthoritative===!1){let Y=await E($),K=await V.resolvePreservedRouting?.(Y);if(K){let B=K.state??J;Z={...B,activeId:K.activeId,route:K.route,lastUpdated:Math.max(B.lastUpdated,Y.lastUpdated)}}await z?.afterMergeRead?.($)}else if(G){let Y=await E($);Z={...Y,activeId:J.activeId,route:J.route,relay:J.relay,fastMode:J.fastMode,cacheKeep:J.cacheKeep,lastUpdated:Math.max(Y.lastUpdated,J.lastUpdated)}}j=await i($,Z,X.ownsLock)}finally{await X.release()}if(j==="lock-lost-after-rename"){if(G){Q.warn("sidebar","post-rename repair lost lock; write skipped",{stateFile:$});return}Q.warn("sidebar","state lock lost after rename; repairing write",{stateFile:$});continue}if(j==="lock-lost-before-rename")return;V.onRoutingResolved?.({activeId:Z.activeId,route:Z.route});return}}).catch(()=>{}),h}async function jJ(){return h}function KJ(J){let $=J.activeId;if($&&$!=="main"){let V=J.fallbacks?.find((x)=>x.enabled&&x.id===$);if(V)return{id:V.id,name:V.label??V.id,quota:V.quota}}return{id:"main",name:"main",quota:J.main?.quota??null}}function s(J){let $=J.replace(/\s+only$/i,"").trim();return/^fable$/i.test($)?"Fa":$}function W(J){if(J==="claude-fable-5"||J?.startsWith("claude-fable-5-"))return"Fable 5";if(J==="claude-opus-5"||J?.startsWith("claude-opus-5-"))return"Opus 5";if(J==="claude-opus-4-8"||J?.startsWith("claude-opus-4-8-"))return"Opus 4.8";return J??"Fable 5"}function zJ(J,$){let V=J.fableRecoveries?.find((x)=>x.sessionId===$);if(!V)return;if(V.mode==="fable")return`${W(V.requestedModelId)} · restored`;if(V.mode==="server")return`${W(V.requestedModelId)}→${W(V.targetModelId)} · safety`;return`Opus 4.8 · ${V.remaining} left`}function NJ(J){let $=J?.five_hour?.usedPercent??null,V=J?.seven_day?.usedPercent??null,x=J?.scoped??[],G=x.map((j)=>j.usedPercent);if($==null&&V==null&&x.length===0)return{fiveHourUsedPercent:$,sevenDayUsedPercent:V,scopedUsedPercents:G,text:null};let X=x.map((j)=>`${s(j.title)}: ${Math.round(j.usedPercent)}%`),Z=$==null&&V==null?[]:[`5h: ${$==null?"—":`${Math.round($)}%`}`,`7d: ${V==null?"—":`${Math.round(V)}%`}`];return{fiveHourUsedPercent:$,sevenDayUsedPercent:V,scopedUsedPercents:G,text:[...Z,...X].join(" ")}}var QJ=18000000,BJ=604800000,o=300000,a=0.01,r=1;function OJ(J,$,V){if(!J.resetsAt)return null;let x=new Date(J.resetsAt).getTime();if(!Number.isFinite(x))return null;let G=x-$,X=V-G;if(X<o)return null;if(X<$*a)return null;if(X>=$)return null;let Z=J.usedPercent,j=Math.min(Math.max(X/$*100,0),100),Y=Z-j,K=Math.abs(Y)<r?"on-pace":Y>0?"deficit":"reserve",B=null;if(Z>0){let I=X*100/Z,U=G+I;if(U<x)B=new Date(U).toISOString()}return{pacePercent:j,deltaPercent:Y,state:K,runsOutAt:B}}
2
+ export{g as a,C as b,u as c,VJ as d,XJ as e,xJ as f,YJ as g,E as h,GJ as i,jJ as j,KJ as k,s as l,W as m,zJ as n,NJ as o,QJ as p,BJ as q,OJ as r};
@@ -1,4 +1,4 @@
1
1
  import*as j from"node:fs";import*as P from"node:os";import*as V from"node:path";var U={error:0,warn:1,info:2,debug:3,trace:4},O=new Set(Object.keys(U));function F(q){if(!q)return null;let Q=q.trim().toLowerCase();return O.has(Q)?Q:null}var S=F(process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL),M=S??"info";function L(q){M=q}function i(){return M}function X(q){return U[q]<=U[M]}var J=process.env.OPENCODE_ANTHROPIC_AUTH_LOG_FILE??V.join(P.tmpdir(),"opencode-anthropic-auth.log");function h(){return J}var R=5242880,N=3;function I(){try{if(!j.existsSync(J))return;if(j.statSync(J).size<R)return}catch{return}try{for(let q=N;q>=1;q--){let Q=q===1?J:`${J}.${q-1}`,W=`${J}.${q}`;try{if(q===N)try{j.unlinkSync(W)}catch{}if(j.existsSync(Q))j.renameSync(Q,W)}catch{}}}catch{}}var T=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function k(q){if(T.test(q))return!0;let Q=q.toLowerCase().replace(/[-_]/g,"");if(Q.includes("apikey"))return!0;if(Q.endsWith("secret")||Q.endsWith("password"))return!0;if(Q.endsWith("token")&&!Q.endsWith("tokens"))return!0;return!1}var f=[/Bearer\s+\S+/,/sk-[A-Za-z0-9-]+/,/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/];function _(q){if(typeof q!=="string")return!1;return f.some((Q)=>Q.test(q))}function G(q){if(q==null||Object.keys(q).length===0)return;let Q=new WeakSet;function W($){if($==null||typeof $!=="object"){if(_($))return"***REDACTED***";return $}if(Q.has($))return"[Circular]";Q.add($);try{if(Array.isArray($))return $.map(W);let x=$,B={};for(let[H,C]of Object.entries(x)){if(k(H)){B[H]="***REDACTED***";continue}B[H]=W(C)}return B}finally{Q.delete($)}}return W(q)}function g(q,Q,W,$){let x=new Date().toISOString(),B=q.toUpperCase().padEnd(5),H=Q?` [${Q}]`:"",C=(()=>{try{let w=G($),A=w?{...w,pid:process.pid}:{pid:process.pid};return` ${JSON.stringify(A)}`}catch{return` {"pid":${process.pid},"payload":"[unserializable]"}`}})();return`[${x}] ${B}${H} ${W}${C}`}var D=null;function E(q){D=q}function Y(q,Q,W,$){if(!X(q))return;if(D)try{D({level:q,channel:Q,message:W,payload:G($)})}catch{}if(Z)return;try{let x=`${g(q,Q,W,$)}
2
2
  `;if(K.push(x),K.length>=p)b();else r()}catch{}}var m={error(q,Q,W){Y("error",q,Q,W)},warn(q,Q,W){Y("warn",q,Q,W)},info(q,Q,W){Y("info",q,Q,W)},debug(q,Q,W){Y("debug",q,Q,W)},trace(q,Q,W){Y("trace",q,Q,W)}},Z=!1,c=500,p=50,K=[],z=null;function b(){if(z)clearTimeout(z),z=null;if(K.length===0)return;let q=K.join("");K=[];try{I(),j.appendFileSync(J,q)}catch{}}function r(){if(z)return;z=setTimeout(()=>{z=null,b()},c)}var y=/^\[([\w-]+)\]\s*/;function o(q,Q){if(!X("debug"))return;if(Z)return;try{let W="",$=q,x=q.match(y);if(x)W=x[1]??"",$=q.slice(x[0].length);let B;if(Q!=null){if(Q instanceof Error)B={error:`${Q.message}${Q.stack?`
3
3
  ${Q.stack}`:""}`};else if(typeof Q==="object")B=Q}Y("debug",W,$,B)}catch{}}function v(q,Q){if(!X("debug"))return;if(Z)return;try{let W;if(Q!=null){if(typeof Q==="object"&&!(Q instanceof Error))W=Q}Y("debug","relay",q,W)}catch{}}if(!Z)process.on("exit",b);
4
- export{F as bc,L as cc,i as dc,X as ec,h as fc,T as gc,k as hc,G as ic,g as jc,E as kc,m as lc,o as mc,v as nc};
4
+ export{F as cc,L as dc,i as ec,X as fc,h as gc,T as hc,k as ic,G as jc,g as kc,E as lc,m as mc,o as nc,v as oc};
@@ -1,2 +1,2 @@
1
1
  import{createRequire as q}from"node:module";var j=Object.create;var{getPrototypeOf:k,defineProperty:i,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,r=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?j(k(a)):{};let c=b||!a||!a.__esModule?i(d,"default",{value:a,enumerable:!0}):d;for(let e of l(a))if(!m.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0});if(f)g.set(a,c);return c};var s=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var u=q(import.meta.url);
2
- export{r as sc,s as tc,u as uc};
2
+ export{r as tc,s as uc,u as vc};