@cortexkit/opencode-anthropic-auth 1.17.0 → 1.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -4
- package/dist/cli.js +1 -1
- package/dist/fable-fallback.d.ts +15 -2
- package/dist/{index-y2n9h7p6.js → index-1ets4bf8.js} +1 -1
- package/dist/{index-f5r96vyv.js → index-9aeag0wm.js} +1 -1
- package/dist/index-h0pmqm96.js +422 -0
- package/dist/{index-63keqwnf.js → index-k5enth8h.js} +1 -1
- package/dist/{index-am5pq04s.js → index-kckdabb4.js} +1 -1
- package/dist/index-szybnfvk.js +2 -0
- package/dist/index.js +20 -12
- package/dist/{logger-ywfmddsw.js → logger-whpn7rjx.js} +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/server-fallback.d.ts +25 -0
- package/dist/sidebar-state.d.ts +15 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/transform.d.ts +5 -0
- package/dist/tui-preferences.js +1 -1
- package/package.json +2 -2
- package/src/sidebar-state.ts +41 -3
- package/src/tui-compiled/sidebar-state.ts +41 -3
- package/src/tui-compiled/tui.tsx +1 -1
- package/src/tui.tsx +3 -3
- package/dist/index-gj7emmj5.js +0 -2
- package/dist/index-xvfesm3w.js +0 -422
|
@@ -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
|
|
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,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
|
|
2
|
+
export{b as oc,h as pc};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{lc as Q}from"./index-1ets4bf8.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};
|
package/dist/index.js
CHANGED
|
@@ -1,17 +1,25 @@
|
|
|
1
|
-
import{a as UN,f as YW,h as CN,i as QN}from"./index-gj7emmj5.js";import{$ as Fj,$a as sj,A as A4,Aa as hj,Ab as ON,B as Dj,Ba as vW,Bb as $N,C as d1,Ca as G1,Cb as YN,D as c1,Da as X1,Db as b4,E as u1,Ea as I1,Eb as p4,F as W0,Fa as mj,Fb as i4,G as Y1,Ga as e1,Gb as l4,H as n1,Ha as R4,Hb as dW,I as _j,Ia as k4,Ib as ZN,J as zj,Ja as SW,Jb as GN,K as H0,Ka as g4,Kb as cW,L as f,La as y4,Ma as h4,Mb as XN,N as s0,Na as fW,O as wj,Oa as bj,Ob as uW,P as Pj,Pa as pj,Pb as D1,Q as M1,Qa as qW,Qb as VN,R as B1,Ra as AW,Rb as DN,S as Uj,Sa as ij,Sb as nW,T as Cj,Ta as RW,Tb as R0,U as o1,Ua as lj,Ub as V1,V as Qj,Va as dj,Vb as KN,W as r1,Wa as cj,Wb as $W,X as Hj,Xa as uj,Xb as _N,Y as Lj,Ya as nj,Yb as zN,Z as Mj,Za as oj,Zb as wN,_ as Bj,_a as rj,aa as Ij,ab as WW,ba as s1,bb as kW,ca as a1,cb as jW,da as Tj,db as gW,ea as Z1,eb as aj,fa as a0,fb as A0,ga as FW,gb as tj,ha as xj,hb as yW,ia as t1,ib as NW,ja as Ej,jb as ej,ka as vj,kb as hW,la as Sj,lb as T1,ma as IW,mb as mW,na as TW,nb as JW,oa as F1,ob as OW,pa as t0,pb as WN,qa as fj,qb as bW,r as E4,ra as e0,rb as pW,s as v4,sa as qj,sb as jN,t as Q1,ta as xW,tb as iW,u as H1,ua as Aj,ub as NN,v as S4,va as Rj,vb as lW,w as $1,wa as kj,wb as U1,x as Vj,xa as gj,xb as m4,y as f4,ya as EW,yb as x1,z as q4,za as yj,zb as JN}from"./index-xvfesm3w.js";import{$b as Kj,ic as k,jc as a}from"./index-y2n9h7p6.js";import{lc as w4}from"./index-am5pq04s.js";import{oc as PN}from"./index-63keqwnf.js";import"./index-f5r96vyv.js";import{randomUUID as BW}from"node:crypto";var O4="claude-opus-4-8",hN=10,mN=128,bN=86400000;function $4(W){return typeof W==="string"&&(W===U1||W.startsWith(`${U1}-`))}function pN(W){try{let j=JSON.parse(W);return typeof j.model==="string"?{body:j,model:j.model}:null}catch{return null}}class KW{now;sessions=new Map;nextCycle=1;constructor(W=Date.now){this.now=W}prune(){let W=this.now();for(let[j,N]of this.sessions)if(W-N.updatedAt>=bN)this.sessions.delete(j);while(this.sessions.size>mN){let j=this.sessions.keys().next().value;if(typeof j!=="string")break;this.sessions.delete(j)}}plan(W,j){if(!W||typeof j!=="string")return null;let N=pN(j);if(!N||!$4(N.model))return null;this.prune();let J=this.sessions.get(W);if(!J||J.remaining<=0)return{sessionId:W,requestedModel:N.model,effectiveModel:N.model,bodyText:j,downgraded:!1,standbyCacheAnchor:J?.standbyCacheAnchor};return J.updatedAt=this.now(),J.nextRequestSequence++,this.sessions.delete(W),this.sessions.set(W,J),N.body.model=O4,{sessionId:W,requestedModel:J.model,effectiveModel:O4,bodyText:JSON.stringify(N.body),downgraded:!0,cycle:J.cycle,cacheAccountId:J.cacheAccountId,standbyCacheAnchor:J.standbyCacheAnchor,requestSequence:J.nextRequestSequence}}recoveryAccount(W){if(W.cycle===void 0)return W.cacheAccountId;let j=this.sessions.get(W.sessionId);return j?.cycle===W.cycle?j.cacheAccountId:W.cacheAccountId}bindRecoveryAccount(W,j){if(!W.downgraded||W.cycle===void 0)return!1;let N=this.sessions.get(W.sessionId);if(!N||N.cycle!==W.cycle)return!1;if(N.cacheAccountId===j)return!1;return N.cacheAccountId=j,N.standbyCacheAnchor=void 0,N.standbyAnchorSequence=0,N.updatedAt=this.now(),W.cacheAccountId=j,W.standbyCacheAnchor=void 0,!0}activate(W,j){if(W.downgraded||!$4(W.requestedModel))return this.remaining(W.sessionId);let N={model:W.requestedModel,remaining:hN,cycle:this.nextCycle++,cacheAccountId:j,standbyCacheAnchor:W.standbyCacheAnchor,nextRequestSequence:0,standbyAnchorSequence:0,updatedAt:this.now()};return this.sessions.delete(W.sessionId),this.sessions.set(W.sessionId,N),this.prune(),N.remaining}complete(W,j){if(!W.downgraded||W.cycle==null||W.completed)return{counted:!1,remaining:this.remaining(W.sessionId)};W.completed=!0;let N=this.sessions.get(W.sessionId);if(!N||N.cycle!==W.cycle||N.remaining<=0)return{counted:!1,remaining:N?.remaining??0};if(N.remaining--,j&&(!N.cacheAccountId||j.oauthAccountId===N.cacheAccountId)&&W.requestSequence!=null&&W.requestSequence>=N.standbyAnchorSequence)N.standbyCacheAnchor=j,N.standbyAnchorSequence=W.requestSequence;return N.updatedAt=this.now(),this.sessions.delete(W.sessionId),this.sessions.set(W.sessionId,N),{counted:!0,remaining:N.remaining}}remaining(W){return this.prune(),this.sessions.get(W)?.remaining??0}}function O1(W){return typeof W==="object"&&W!==null}function iN(W){if(Array.isArray(W))return W;if(O1(W)&&Array.isArray(W.data))return W.data;return[]}function V4(W){if(!O1(W)||!O1(W.info))return;return W.info}function Y4(W){let j=V4(W);return typeof j?.role==="string"?j.role:void 0}function lN(W){let j=V4(W);return typeof j?.id==="string"?j.id:void 0}function Z4(W){if(!O1(W)||!O1(W.info))return null;let j=W.info,N=O1(j.model)?j.model:void 0,J=typeof j.agent==="string"?j.agent:void 0,Y=typeof N?.providerID==="string"?N.providerID:typeof j.providerID==="string"?j.providerID:void 0,D=typeof N?.modelID==="string"?N.modelID:typeof j.modelID==="string"?j.modelID:void 0,K=typeof N?.variant==="string"?N.variant:typeof j.variant==="string"?j.variant:void 0;if(!J&&(!Y||!D)&&!K)return null;let M={};if(J)M.agent=J;if(Y&&D)M.model={providerID:Y,modelID:D};if(K)M.variant=K;return M}function G4(W,j){return{agent:W.agent??j.agent,model:W.model??j.model,variant:W.variant??j.variant,latestAssistantMessageId:W.latestAssistantMessageId??j.latestAssistantMessageId,latestUserMessageId:W.latestUserMessageId??j.latestUserMessageId}}function X4(W){return Boolean(W.agent&&W.model&&W.variant)}async function D4(W,j){if(!W||!j)return null;let N=W;if(typeof N.session?.messages!=="function")return null;let J=[];try{J=iN(await Promise.resolve(N.session.messages({path:{id:j},query:{limit:100}})))}catch{return null}if(J.length===0)return null;let Y,D;for(let M of J){let y=lN(M);if(!y)continue;let r=Y4(M);if(r==="assistant"&&(!Y||y>Y))Y=y;if(r==="user"&&(!D||y>D))D=y}let K={latestAssistantMessageId:Y,latestUserMessageId:D};for(let M=J.length-1;M>=0;M--){if(Y4(J[M])!=="assistant")continue;let y=Z4(J[M]);if(!y)continue;if(K=G4(K,y),X4(K))return K}for(let M=J.length-1;M>=0;M--){let y=Z4(J[M]);if(!y)continue;if(K=G4(K,y),X4(K))return K}if(!K.agent&&!K.model&&!K.variant&&!K.latestAssistantMessageId&&!K.latestUserMessageId)return null;return K}var l0=[],dN=1,_W=0,K4=new Map;function _4(W,j){if(l0.push({id:dN++,type:"open-dialog",payload:W,sessionId:j}),l0.length>100)l0=l0.slice(l0.length-100)}function z4(W=0,j){let N=Date.now();if(_W=N,j!==void 0)K4.set(j,N);let J=(Y)=>j===void 0||Y.sessionId===void 0||Y.sessionId===j;if(W>0)l0=l0.filter((Y)=>{if(Y.id>W)return!0;if(j===void 0)return!1;return Y.sessionId!==j});return l0.filter((Y)=>Y.id>W&&J(Y))}function zW(W){let j=Date.now();if(W!==void 0){let N=K4.get(W)??0;return N>0&&j-N<3000}return _W>0&&j-_W<3000}import{randomBytes as cN,timingSafeEqual as uN}from"node:crypto";import{unlink as nN}from"node:fs/promises";import{createServer as oN}from"node:http";import{join as rN}from"node:path";function sN(W){return new Promise((j,N)=>{let J=[],Y=0;W.on("data",(D)=>{if(Y+=D.length,Y>1e6){W.destroy(),N(Error("body too large"));return}J.push(D)}),W.on("end",()=>j(Buffer.concat(J).toString("utf8"))),W.on("error",N)})}function aN(W,j){if(!W?.startsWith("Bearer "))return!1;let N=Buffer.from(W.slice(7)),J=Buffer.from(j);return N.length===J.length&&uN(N,J)}async function P4(W){let j=cN(32).toString("hex"),N=oN((D,K)=>{J(D,K)});async function J(D,K){let M=(y,r)=>{K.writeHead(y,{"content-type":"application/json"}),K.end(JSON.stringify(r))};try{let y=D.url??"";if(D.method==="GET"&&y==="/health")return M(200,{ok:!0});if(D.method!=="POST"||!y.startsWith("/rpc/"))return M(404,{error:"not found"});if(!aN(D.headers.authorization,j))return M(401,{error:"unauthorized"});let r=y.slice(5),i=JSON.parse(await sN(D)||"{}");if(r==="pending-notifications"){let l=W.drain(Number(i.lastReceivedId??0),typeof i.sessionId==="string"?i.sessionId:void 0);return M(200,{messages:l})}if(r==="apply"){let l=await W.apply(i);return M(200,l)}return M(404,{error:"unknown method"})}catch(y){if(!K.headersSent&&!K.writableEnded&&!K.destroyed)M(500,{error:y instanceof Error?y.message:String(y)})}}let Y=await new Promise((D,K)=>{N.on("error",K),N.listen(0,"127.0.0.1",()=>{let M=N.address();if(M&&typeof M==="object")D(M.port);else K(Error("no port"))})});N.unref();try{await w4(W.dir,{port:Y,token:j,pid:process.pid})}catch(D){throw await new Promise((K)=>N.close(()=>K())),D}return{port:Y,token:j,async stop(){await new Promise((D)=>N.close(()=>D())),await nN(rN(W.dir,`port-${process.pid}.json`)).catch(()=>{})}}}import{createHash as tN}from"node:crypto";function U4(W,j){let N=new Map,J=0,Y=0,D=0,K=0,M=0,y=(l)=>{let $0=performance.now(),F=W(l);return M+=performance.now()-$0,D++,F};return{call:(l)=>{if(!j.enabled())return y(l);let $0=N.get(l);if($0!==void 0)return Y++,N.delete(l),N.set(l,$0),$0;let F=y(l),T0=l.length+F.length;if(T0>j.maxBytes)return F;N.set(l,F),J+=T0;while(J>j.maxBytes&&N.size>1){let U0=N.keys().next().value,x0=N.get(U0)??"";N.delete(U0),J-=U0.length+x0.length,K++}return F},stats:()=>({hits:Y,misses:D,evictions:K,entries:N.size,cacheBytes:J,computeMsTotal:M})}}function C4(W){return`${E4}${W.charAt(0).toUpperCase()}${W.slice(1)}`}function d4(W){if(W==="StructuredOutput")return W;return`${W.charAt(0).toLowerCase()}${W.slice(1)}`}var eN=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function Q4(W){let j=d4(W);if(j.startsWith("aft_"))return j;if(eN.has(j))return`aft_${j}`;return null}function m1(W,j){let N=new Headers;if(W instanceof Request)W.headers.forEach((Y,D)=>{N.set(D,Y)});let J=j?.headers;if(J){if(J instanceof Headers)J.forEach((Y,D)=>{N.set(D,Y)});else if(Array.isArray(J))for(let Y of J){let[D,K]=Y;if(typeof K<"u")N.set(D,String(K))}else for(let[Y,D]of Object.entries(J))if(typeof D<"u")N.set(Y,String(D))}return N}function b1(W){return W.set("anthropic-beta",Q1(W.get("anthropic-beta"),[v4])),W}function L1(W,j,N={}){return y4(W,j,N)}function WJ(W){if(W.tools&&Array.isArray(W.tools))W.tools=W.tools.map((j)=>({...j,name:j.name?C4(j.name):j.name}));if(W.messages&&Array.isArray(W.messages))W.messages=W.messages.map((j)=>{if(j.content&&Array.isArray(j.content))j.content=j.content.map((N)=>{if(N.type==="tool_use"&&N.name)return{...N,name:C4(N.name)};return N});return j});return JSON.stringify(h4(W))}function wW(W){return W.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(j,N,J)=>{if(N)return`"name": "${Q4(J)??d4(J)}"`;let Y=Q4(J);return Y?`"name": "${Y}"`:j})}function H4(W,j=!1){if(j)return{ready:wW(W),pending:""};let N=W.length,J='"name"',Y=Math.max(0,W.length-J.length+1);for(let K=Y;K<W.length;K++)if(J.startsWith(W.slice(K))){N=Math.min(N,K);break}let D=W.lastIndexOf(J);if(D!==-1){let K=W.slice(D);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(K))N=Math.min(N,D)}if(N<W.length)return{ready:wW(W.slice(0,N)),pending:W.slice(N)};return{ready:wW(W),pending:""}}function CW(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let W=process.env.ANTHROPIC_INSECURE?.trim();return W==="1"||W==="true"}function c4(W){let j=W?.trim();if(!j)return null;try{let N=new URL(j);if(N.protocol!=="http:"&&N.protocol!=="https:"||N.username||N.password)return null;return N}catch{return null}}function jJ(){return c4(process.env.ANTHROPIC_BASE_URL)}function QW(W,j={}){let N=null;try{if(typeof W==="string"||W instanceof URL)N=new URL(W.toString());else if(W instanceof Request)N=new URL(W.url)}catch{N=null}if(!N)return{input:W,url:null};let J=N.href,Y=j.baseURL?c4(j.baseURL):jJ();if(Y){if(N.protocol=Y.protocol,N.host=Y.host,j.baseURL)N.pathname=`${Y.pathname.replace(/\/$/,"")}${N.pathname}`}if(N.pathname.endsWith("/v1/messages")&&!N.searchParams.has("beta"))N.searchParams.set("beta","true");if(N.href===J)return{input:W,url:N};return{input:W instanceof Request?new Request(N.toString(),W):N,url:N}}function NJ(W){let J=W.split(/\n\n+/).filter((Y)=>{if(Y.includes(S4))return!1;for(let D of q4)if(Y.includes(D))return!1;return!0}).join(`
|
|
1
|
+
import{a as mJ,f as w4,h as bJ,i as pJ}from"./index-szybnfvk.js";import{$ as dW,$a as QJ,$b as gJ,A as aj,Aa as $J,Ab as MJ,B as ej,Ba as ZJ,Bb as xJ,C as vW,Ca as c4,Cb as FJ,D as J4,Da as Q1,Db as EJ,E as N4,Ea as w1,Eb as ZW,F as O4,Fa as g1,Fb as YW,G as $0,Ga as YJ,Gb as DW,H as U1,Ha as V4,Hb as GW,I as $4,Ia as jW,Ib as A0,J as kW,Ja as WW,Jb as XW,K as gW,Ka as l4,Kb as Oj,L as T0,La as JW,Lb as SJ,M as k,Ma as NW,Mb as qJ,Na as OW,Nb as $j,O as N1,Oa as d4,P as hW,Pa as DJ,Pb as AJ,Q as yW,Qa as GJ,R as v1,Ra as u4,Rb as Zj,S as R1,Sa as n4,Sb as C1,T as mW,Ta as XJ,Tb as fJ,U as bW,Ua as o4,Ub as vJ,V as Z4,Va as VJ,Vb as Yj,W as pW,Wa as zJ,Wb as b0,X as Y4,Xa as KJ,Xb as H1,Y as iW,Ya as _J,Yb as RJ,Z as cW,Za as UJ,Zb as Q4,_ as lW,_a as PJ,_b as kJ,aa as uW,ab as wJ,ac as hJ,ba as nW,bb as z4,ca as D4,cb as r4,da as G4,db as K4,ea as oW,eb as s4,fa as P1,fb as HJ,ga as O1,gb as m0,ha as y4,hb as CJ,ia as rW,ib as t4,ja as X4,jb as _4,ka as sW,kb as LJ,la as tW,lb as a4,ma as aW,mb as h1,na as m4,nb as e4,oa as b4,ob as U4,pa as k1,pb as P4,qa as $1,qb as BJ,ra as eW,rb as jj,s as oj,sa as Z1,sb as Wj,t as rj,ta as jJ,tb as IJ,u as q1,ua as p4,ub as Jj,v as A1,va as WJ,vb as TJ,w as sj,wa as JJ,wb as Nj,x as _1,xa as NJ,xb as E1,y as fW,ya as OJ,yb as $W,z as tj,za as i4,zb as y1}from"./index-h0pmqm96.js";import{cc as RW,lc as h,mc as N0}from"./index-1ets4bf8.js";import{oc as Sj}from"./index-kckdabb4.js";import{rc as yJ}from"./index-k5enth8h.js";import"./index-9aeag0wm.js";import{randomUUID as h4}from"node:crypto";var Hj="claude-opus-4-8",G3=10,X3=128,V3=86400000;function y0(j){if(typeof j!=="string")return null;if(A0(j))return"opus-5";if(j===E1||j.startsWith(`${E1}-`))return"fable-5";return null}function X1(j){return y0(j)!==null}function z3(j,W){let J=y0(W);return J?`${j}\x00${J}`:null}function K3(j){try{let W=JSON.parse(j);return typeof W.model==="string"?{body:W,model:W.model}:null}catch{return null}}class x4{now;recoveries=new Map;nextCycle=1;constructor(j=Date.now){this.now=j}prune(){let j=this.now();for(let[W,J]of this.recoveries)if(j-J.updatedAt>=V3)this.recoveries.delete(W);while(this.recoveries.size>X3){let W=this.recoveries.keys().next().value;if(typeof W!=="string")break;this.recoveries.delete(W)}}plan(j,W){if(!j||typeof W!=="string")return null;let J=K3(W);if(!J||!X1(J.model))return null;let N=z3(j,J.model);if(!N)return null;this.prune();let Z=this.recoveries.get(N);if(!Z||Z.remaining<=0)return{sessionId:j,recoveryKey:N,requestedModel:J.model,effectiveModel:J.model,bodyText:W,downgraded:!1,standbyCacheAnchor:Z?.standbyCacheAnchor};return Z.updatedAt=this.now(),Z.nextRequestSequence++,this.recoveries.delete(N),this.recoveries.set(N,Z),J.body.model=Hj,{sessionId:j,recoveryKey:N,requestedModel:Z.model,effectiveModel:Hj,bodyText:JSON.stringify(J.body),downgraded:!0,cycle:Z.cycle,cacheAccountId:Z.cacheAccountId,standbyCacheAnchor:Z.standbyCacheAnchor,requestSequence:Z.nextRequestSequence}}recoveryAccount(j){if(j.cycle===void 0)return j.cacheAccountId;let W=this.recoveries.get(j.recoveryKey);return W?.cycle===j.cycle?W.cacheAccountId:j.cacheAccountId}bindRecoveryAccount(j,W){if(!j.downgraded||j.cycle===void 0)return!1;let J=this.recoveries.get(j.recoveryKey);if(!J||J.cycle!==j.cycle)return!1;if(J.cacheAccountId===W)return!1;return J.cacheAccountId=W,J.standbyCacheAnchor=void 0,J.standbyAnchorSequence=0,J.updatedAt=this.now(),j.cacheAccountId=W,j.standbyCacheAnchor=void 0,!0}activate(j,W){if(j.downgraded||!X1(j.requestedModel))return this.remaining(j);let J={model:j.requestedModel,remaining:G3,cycle:this.nextCycle++,cacheAccountId:W,standbyCacheAnchor:j.standbyCacheAnchor,nextRequestSequence:0,standbyAnchorSequence:0,updatedAt:this.now()};return this.recoveries.delete(j.recoveryKey),this.recoveries.set(j.recoveryKey,J),this.prune(),J.remaining}complete(j,W){if(!j.downgraded||j.cycle==null||j.completed)return{counted:!1,remaining:this.remaining(j)};j.completed=!0;let J=this.recoveries.get(j.recoveryKey);if(!J||J.cycle!==j.cycle||J.remaining<=0)return{counted:!1,remaining:J?.remaining??0};if(J.remaining--,W&&(!J.cacheAccountId||W.oauthAccountId===J.cacheAccountId)&&j.requestSequence!=null&&j.requestSequence>=J.standbyAnchorSequence)J.standbyCacheAnchor=W,J.standbyAnchorSequence=j.requestSequence;return J.updatedAt=this.now(),this.recoveries.delete(j.recoveryKey),this.recoveries.set(j.recoveryKey,J),{counted:!0,remaining:J.remaining}}remaining(j){return this.prune(),this.recoveries.get(j.recoveryKey)?.remaining??0}}function V1(j){return typeof j==="object"&&j!==null}function _3(j){if(Array.isArray(j))return j;if(V1(j)&&Array.isArray(j.data))return j.data;return[]}function Tj(j){if(!V1(j)||!V1(j.info))return;return j.info}function Cj(j){let W=Tj(j);return typeof W?.role==="string"?W.role:void 0}function U3(j){let W=Tj(j);return typeof W?.id==="string"?W.id:void 0}function Lj(j){if(!V1(j)||!V1(j.info))return null;let W=j.info,J=V1(W.model)?W.model:void 0,N=typeof W.agent==="string"?W.agent:void 0,Z=typeof J?.providerID==="string"?J.providerID:typeof W.providerID==="string"?W.providerID:void 0,G=typeof J?.modelID==="string"?J.modelID:typeof W.modelID==="string"?W.modelID:void 0,V=typeof J?.variant==="string"?J.variant:typeof W.variant==="string"?W.variant:void 0;if(!N&&(!Z||!G)&&!V)return null;let B={};if(N)B.agent=N;if(Z&&G)B.model={providerID:Z,modelID:G};if(V)B.variant=V;return B}function Bj(j,W){return{agent:j.agent??W.agent,model:j.model??W.model,variant:j.variant??W.variant,latestAssistantMessageId:j.latestAssistantMessageId??W.latestAssistantMessageId,latestUserMessageId:j.latestUserMessageId??W.latestUserMessageId}}function Ij(j){return Boolean(j.agent&&j.model&&j.variant)}async function Mj(j,W){if(!j||!W)return null;let J=j;if(typeof J.session?.messages!=="function")return null;let N=[];try{N=_3(await Promise.resolve(J.session.messages({path:{id:W},query:{limit:100}})))}catch{return null}if(N.length===0)return null;let Z,G;for(let B of N){let f=U3(B);if(!f)continue;let r=Cj(B);if(r==="assistant"&&(!Z||f>Z))Z=f;if(r==="user"&&(!G||f>G))G=f}let V={latestAssistantMessageId:Z,latestUserMessageId:G};for(let B=N.length-1;B>=0;B--){if(Cj(N[B])!=="assistant")continue;let f=Lj(N[B]);if(!f)continue;if(V=Bj(V,f),Ij(V))return V}for(let B=N.length-1;B>=0;B--){let f=Lj(N[B]);if(!f)continue;if(V=Bj(V,f),Ij(V))return V}if(!V.agent&&!V.model&&!V.variant&&!V.latestAssistantMessageId&&!V.latestUserMessageId)return null;return V}var d0=[],P3=1,F4=0,xj=new Map;function Fj(j,W){if(d0.push({id:P3++,type:"open-dialog",payload:j,sessionId:W}),d0.length>100)d0=d0.slice(d0.length-100)}function Ej(j=0,W){let J=Date.now();if(F4=J,W!==void 0)xj.set(W,J);let N=(Z)=>W===void 0||Z.sessionId===void 0||Z.sessionId===W;if(j>0)d0=d0.filter((Z)=>{if(Z.id>j)return!0;if(W===void 0)return!1;return Z.sessionId!==W});return d0.filter((Z)=>Z.id>j&&N(Z))}function E4(j){let W=Date.now();if(j!==void 0){let J=xj.get(j)??0;return J>0&&W-J<3000}return F4>0&&W-F4<3000}import{randomBytes as Q3,timingSafeEqual as w3}from"node:crypto";import{unlink as H3}from"node:fs/promises";import{createServer as C3}from"node:http";import{join as L3}from"node:path";function B3(j){return new Promise((W,J)=>{let N=[],Z=0;j.on("data",(G)=>{if(Z+=G.length,Z>1e6){j.destroy(),J(Error("body too large"));return}N.push(G)}),j.on("end",()=>W(Buffer.concat(N).toString("utf8"))),j.on("error",J)})}function I3(j,W){if(!j?.startsWith("Bearer "))return!1;let J=Buffer.from(j.slice(7)),N=Buffer.from(W);return J.length===N.length&&w3(J,N)}async function qj(j){let W=Q3(32).toString("hex"),J=C3((G,V)=>{N(G,V)});async function N(G,V){let B=(f,r)=>{V.writeHead(f,{"content-type":"application/json"}),V.end(JSON.stringify(r))};try{let f=G.url??"";if(G.method==="GET"&&f==="/health")return B(200,{ok:!0});if(G.method!=="POST"||!f.startsWith("/rpc/"))return B(404,{error:"not found"});if(!I3(G.headers.authorization,W))return B(401,{error:"unauthorized"});let r=f.slice(5),E=JSON.parse(await B3(G)||"{}");if(r==="pending-notifications"){let v=j.drain(Number(E.lastReceivedId??0),typeof E.sessionId==="string"?E.sessionId:void 0);return B(200,{messages:v})}if(r==="apply"){let v=await j.apply(E);return B(200,v)}return B(404,{error:"unknown method"})}catch(f){if(!V.headersSent&&!V.writableEnded&&!V.destroyed)B(500,{error:f instanceof Error?f.message:String(f)})}}let Z=await new Promise((G,V)=>{J.on("error",V),J.listen(0,"127.0.0.1",()=>{let B=J.address();if(B&&typeof B==="object")G(B.port);else V(Error("no port"))})});J.unref();try{await Sj(j.dir,{port:Z,token:W,pid:process.pid})}catch(G){throw await new Promise((V)=>J.close(()=>V())),G}return{port:Z,token:W,async stop(){await new Promise((G)=>J.close(()=>G())),await H3(L3(j.dir,`port-${process.pid}.json`)).catch(()=>{})}}}var fj="server-side-fallback-2026-07-01",vj="",u1="cortexkit-server-fallback-v1:";function f0(j){return j!==null&&typeof j==="object"&&!Array.isArray(j)?j:void 0}function z1(j,W){let J=j?.[W];return typeof J==="string"?J:void 0}function K1(j){return typeof j==="string"&&j.length>0&&j.length<=128&&/^claude-[a-z0-9-]+$/i.test(j)}function T3(j){return`${u1}${j.fromModel}|${j.toModel}`}function M3(j){if(typeof j!=="string"||!j.startsWith(u1))return null;let W=j.slice(u1.length),J=W.indexOf("|");if(J<=0||J!==W.lastIndexOf("|"))return null;let N=W.slice(0,J),Z=W.slice(J+1);if(!K1(N)||!K1(Z))return null;return{fromModel:N,toModel:Z}}function x3(j){if(j.type!=="fallback")return null;let W=z1(f0(j.from),"model"),J=z1(f0(j.to),"model");if(!K1(W)||!K1(J))return null;return{fromModel:W,toModel:J}}function F3(j){return{type:"fallback",from:{model:j.fromModel},to:{model:j.toModel}}}function E3(j,W){let J=0,N=0;if(!Array.isArray(j.messages))return{restoredMarkers:J,droppedMarkers:N};for(let Z of j.messages){let G=f0(Z);if(G?.role!=="assistant"||!Array.isArray(G.content))continue;let V=[];for(let B of G.content){let f=f0(B);if(!(f?.type==="thinking"&&(f.thinking===vj||f.thinking==="")&&typeof f.signature==="string"&&f.signature.startsWith(u1))){V.push(B);continue}let E=M3(f.signature);if(W&&E)V.push(F3(E)),J++;else N++}G.content=V}return{restoredMarkers:J,droppedMarkers:N}}function Rj(j){return j?.trim().toLowerCase()==="legacy"?"legacy":"server"}function kj(j,W){let J=W&&X1(j.model),N=E3(j,J);if(J)j.fallbacks="default";else if(j.fallbacks==="default")delete j.fallbacks;return{enabled:J,...N}}function S3(j){let W,J=[];for(let Z of j.split(/\r?\n/))if(Z.startsWith("event:"))W=Z.slice(6).trim();else if(Z.startsWith("data:")){let G=Z.slice(5);J.push(G.startsWith(" ")?G.slice(1):G)}let N=J.join(`
|
|
2
|
+
`);if(!N||N==="[DONE]")return{event:W};try{return{event:W,data:f0(JSON.parse(N))}}catch{return{event:W}}}function q3(j){let W=j.indexOf(`
|
|
2
3
|
|
|
3
|
-
`)
|
|
4
|
-
|
|
5
|
-
`)
|
|
4
|
+
`),J=j.indexOf(`\r
|
|
5
|
+
\r
|
|
6
|
+
`);if(W===-1)return J===-1?null:{index:J,length:4};if(J===-1||W<J)return{index:W,length:2};return{index:J,length:4}}function Aj(j,W){return`event: ${j}
|
|
7
|
+
data: ${JSON.stringify(W)}
|
|
8
|
+
|
|
9
|
+
`}function A3(j,W){return Aj("content_block_start",{type:"content_block_start",index:j,content_block:{type:"thinking",thinking:vj}})+Aj("content_block_delta",{type:"content_block_delta",index:j,delta:{type:"signature_delta",signature:T3(W)}})}function f3(j,W){let J=y0(j),N=y0(W);if(J&&N)return J===N;return j===W}function gj(j){let W="",J,N,Z,G=!1,V=(E)=>{if(!Array.isArray(E?.iterations))return;for(let v of E.iterations){let n=f0(v);if(n?.type!=="fallback_message")continue;let l=z1(n,"model");if(K1(l))Z=l}},B=(E)=>{if(G)return;G=!0;let v=N?.toModel??Z??(J&&!f3(j.requestedModel,J)?J:void 0);j.onOutcome?.({requestedModel:j.requestedModel,servedModel:J,targetModel:v,fallback:Boolean(v),handoff:Boolean(N),stopReason:E})},f=(E,v)=>{let n=S3(E),l=n.data,Y0=z1(l,"type")??n.event;if(Y0==="message_start"){let t=f0(l?.message),w0=z1(t,"model");if(K1(w0))J=w0;V(f0(t?.usage))}else if(Y0==="content_block_start"){let t=f0(l?.content_block),w0=t?x3(t):null;if(w0){N=w0;let F=l?.index;if(typeof F==="number"&&Number.isInteger(F)&&F>=0)return A3(F,w0)}}else if(Y0==="message_delta"){V(f0(l?.usage));let t=z1(f0(l?.delta),"stop_reason");if(t)B(t)}return E+v},r=()=>{let E="";while(!0){let v=q3(W);if(!v)break;let n=W.slice(0,v.index),l=W.slice(v.index,v.index+v.length);W=W.slice(v.index+v.length),E+=f(n,l)}return E};return{push(E){return W+=E,r()},flush(){let E=r();if(!W)return E;let v=f(W,"");return W="",E+v}}}import{createHash as v3}from"node:crypto";function hj(j,W){let J=new Map,N=0,Z=0,G=0,V=0,B=0,f=(v)=>{let n=performance.now(),l=j(v);return B+=performance.now()-n,G++,l};return{call:(v)=>{if(!W.enabled())return f(v);let n=J.get(v);if(n!==void 0)return Z++,J.delete(v),J.set(v,n),n;let l=f(v),Y0=v.length+l.length;if(Y0>W.maxBytes)return l;J.set(v,l),N+=Y0;while(N>W.maxBytes&&J.size>1){let t=J.keys().next().value,w0=J.get(t)??"";J.delete(t),N-=t.length+w0.length,V++}return l},stats:()=>({hits:Z,misses:G,evictions:V,entries:J.size,cacheBytes:N,computeMsTotal:B})}}function yj(j){return`${oj}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function VW(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}var R3=new Set(["callgraph","conflicts","delete","import","inspect","move","navigate","outline","refactor","safety","search","transform","zoom"]);function mj(j){let W=VW(j);if(W.startsWith("aft_"))return W;if(R3.has(W))return`aft_${W}`;return null}function t1(j,W){let J=new Headers;if(j instanceof Request)j.headers.forEach((Z,G)=>{J.set(G,Z)});let N=W?.headers;if(N){if(N instanceof Headers)N.forEach((Z,G)=>{J.set(G,Z)});else if(Array.isArray(N))for(let Z of N){let[G,V]=Z;if(typeof V<"u")J.set(G,String(V))}else for(let[Z,G]of Object.entries(N))if(typeof G<"u")J.set(Z,String(G))}return J}function a1(j){return j.set("anthropic-beta",q1(j.get("anthropic-beta"),[rj])),j}function f1(j,W,J={}){return NW(j,W,{...J,extraBetas:J.body?.fallbacks==="default"?[fj]:void 0})}function k3(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((W)=>({...W,name:W.name?yj(W.name):W.name}));if(j.messages&&Array.isArray(j.messages))j.messages=j.messages.map((W)=>{if(W.content&&Array.isArray(W.content))W.content=W.content.map((J)=>{if(J.type==="tool_use"&&J.name)return{...J,name:yj(J.name)};return J});return W});return JSON.stringify(OW(j))}function S4(j){return j.replace(/"name"\s*:\s*"(mcp_)?([^"]+)"/g,(W,J,N)=>{if(J)return`"name": "${mj(N)??VW(N)}"`;let Z=mj(N);return Z?`"name": "${Z}"`:W})}function bj(j,W=!1){if(W)return{ready:S4(j),pending:""};let J=j.length,N='"name"',Z=Math.max(0,j.length-N.length+1);for(let V=Z;V<j.length;V++)if(N.startsWith(j.slice(V))){J=Math.min(J,V);break}let G=j.lastIndexOf(N);if(G!==-1){let V=j.slice(G);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(V))J=Math.min(J,G)}if(J<j.length)return{ready:S4(j.slice(0,J)),pending:j.slice(J)};return{ready:S4(j),pending:""}}function f4(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function zW(j){let W=j?.trim();if(!W)return null;try{let J=new URL(W);if(J.protocol!=="http:"&&J.protocol!=="https:"||J.username||J.password)return null;return J}catch{return null}}function g3(){return zW(process.env.ANTHROPIC_BASE_URL)}function v4(j,W={}){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 N=J.href,Z=W.baseURL?zW(W.baseURL):g3();if(Z){if(J.protocol=Z.protocol,J.host=Z.host,W.baseURL)J.pathname=`${Z.pathname.replace(/\/$/,"")}${J.pathname}`}if(J.pathname.endsWith("/v1/messages")&&!J.searchParams.has("beta"))J.searchParams.set("beta","true");if(J.href===N)return{input:j,url:J};return{input:j instanceof Request?new Request(J.toString(),j):J,url:J}}function h3(j){let N=j.split(/\n\n+/).filter((Z)=>{if(Z.includes(sj))return!1;for(let G of aj)if(Z.includes(G))return!1;return!0}).join(`
|
|
10
|
+
|
|
11
|
+
`);for(let Z of ej)N=N.replace(Z.match,Z.replacement);return N.trim()}var y3=8388608;function m3(){return process.env.OPENCODE_ANTHROPIC_AUTH_MEMO!=="0"}var b3=hj(h3,{maxBytes:y3,enabled:m3});function n1(j){return b3.call(j)}function c(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function p3(j){let W={type:"text",text:_1};if(j==null)return[W];if(typeof j==="string"){let N=n1(j);if(N===_1)return[W];return[W,{type:"text",text:N}]}if(c(j)){let N=typeof j.type==="string"?j.type:"text",Z=typeof j.text==="string"?j.text:"";return[W,{...j,type:N,text:n1(Z)}]}if(!Array.isArray(j))return[W];let J=j.map((N)=>{if(typeof N==="string")return{type:"text",text:n1(N)};if(c(N)&&N.type==="text"&&typeof N.text==="string")return{...N,type:"text",text:n1(N.text)};return{type:"text",text:String(N)}});if(J[0]?.text===_1)return J;return[W,...J]}var KW={type:"ephemeral",ttl:"1h"},pj=20;function _W(j){if(c(j.cache_control))return j.cache_control;if(c(j.cacheControl))return j.cacheControl;return null}function S1(j,W){if(!c(j))return!1;return delete j.cacheControl,j.cache_control=W?{...KW}:{type:"ephemeral"},!0}function ij(j){if(!c(j))return;delete j.cache_control,delete j.cacheControl}function R4(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function A4(j){if(Array.isArray(j))return j.map(A4);if(!c(j))return j;let W={};for(let J of Object.keys(j).sort()){if(J==="cache_control"||J==="cacheControl")continue;W[J]=A4(j[J])}return W}function UW(j){if(!c(j))return;let W=R4(j.content);if(!W?.length)return;let J=A4({...j,content:W});return v3("sha256").update(JSON.stringify(J)).digest("hex")}function i3(j){if(!c(j))return!1;let W=R4(j.content);return Boolean(W?.some((J)=>c(J)&&_W(J)?.type==="ephemeral"))}function PW(j){try{let W=JSON.parse(j);if(!Array.isArray(W.messages))return;for(let J=W.messages.length-1;J>1;J--){let N=W.messages[J];if(!c(N)||N.role!=="user"||!i3(N))continue;let Z=UW(N);if(!Z)return;return{fingerprint:Z,messageIndex:J,messageCount:W.messages.length}}return}catch{return}}function o1(j,W){if(!c(j))return;let J=_W(j);if(J?.type!=="ephemeral")return;if(W)J.ttl="1h";else delete J.ttl}function cj(j,W){if(Array.isArray(j.system))for(let J of j.system)o1(J,W);else o1(j.system,W);if(!Array.isArray(j.messages))return;for(let J of j.messages)if(o1(J,W),c(J)&&Array.isArray(J.content))for(let N of J.content)o1(N,W)}function c3(j,W){if(Array.isArray(j.system))for(let J of j.system)W(J);else W(j.system);if(!Array.isArray(j.messages))return;for(let J of j.messages)if(W(J),c(J)&&Array.isArray(J.content))for(let N of J.content)W(N)}function QW(j){ij(j),c3(j,ij)}function l3(j){QW(j),j.cache_control={...KW}}function d3(j){return c(j)&&j.type!=="thinking"&&j.type!=="redacted_thinking"}function e1(j){let W=R4(j.content);if(!W?.length)return;let J=W.filter(d3);if(!J.length)return;return{content:W,cacheableBlocks:J}}function u3(j){if(!c(j))return!1;let W=e1(j);if(!W)return!1;return j.content=W.content,S1(W.cacheableBlocks[0],!0)}function n3(j){if(!c(j))return!1;let W=e1(j);if(!W||W.cacheableBlocks.length<2)return!1;return j.content=W.content,S1(W.cacheableBlocks[1],!0)}function r1(j){if(!c(j))return!1;let W=e1(j);if(!W)return!1;let J=W.cacheableBlocks[W.cacheableBlocks.length-1];return j.content=W.content,S1(J,!0)}function o3(j){if(!c(j))return!1;return(e1(j)?.cacheableBlocks.length??0)>1}function r3(j){if(!c(j))return 0;let W=j.content;if(Array.isArray(W))return W.length;if(W==null)return 0;return 1}function s3(j){let W=[],J=0;return j.forEach((N,Z)=>{let G=r3(N);if(c(N)&&N.role==="user"&&G>0)W.push({index:Z,blockPosition:J+G-1});J+=G}),W}function t3(j,W,J,N){if(!N)return;let Z=[],G=W.find((V)=>V.index===N.messageIndex&&V.index>1&&V.index<J.index);if(G)Z.push(G);for(let V of[...W].reverse()){if(V.index<=1||V.index>=J.index||V.index===G?.index)continue;Z.push(V)}for(let V of Z)if(UW(j[V.index])===N.fingerprint)return V;return}function a3(j,W){let J=s3(j),N=[...J].reverse().find((E)=>E.index>1);if(!N)return{latest:void 0,bridge:void 0,standbyAnchorMatched:!1,standbyBridgeApplied:!1};let Z=t3(j,J,N,W),G=Z?N.blockPosition-Z.blockPosition+1:void 0,V=Z&&G!=null&&G>pj?Z:void 0,B=[...J].reverse().find((E)=>E.index<N.index),f=B?N.blockPosition-B.blockPosition+1:0,r=B&&B.index>1&&f>pj?B:void 0;return{latest:N,bridge:V??r,standbyAnchorMatched:Boolean(Z),standbyDistanceBlocks:G,standbyBridgeApplied:Boolean(V)}}function q4(j){return c(j)&&typeof j.text==="string"?j.text:""}function e3(j){if(!Array.isArray(j.system))return;let W=j.system,J=0;if(q4(W[J]).startsWith("x-anthropic-billing-header:"))J++;if(q4(W[J])===_1)J++;let N=J+1;if(N>=W.length-1)return;let Z=W[N];if(!c(Z))return;let G=W.slice(N).map(q4).join(`
|
|
12
|
+
`);W.splice(N,W.length-N,{...Z,type:"text",text:G})}function lj(j){if(Array.isArray(j.system)){let W=j.system.findIndex((Z)=>c(Z)&&Z.text===_1),J=j.system.slice(W>=0?W+1:0).filter(c),N=J[J.length-1];S1(N,!0)}else S1(j.system,!0)}function j7(j,W){if(QW(j),e3(j),!Array.isArray(j.messages))return lj(j),{standbyAnchorMatched:!1,standbyBridgeApplied:!1};let{latest:J,bridge:N,standbyAnchorMatched:Z,standbyDistanceBlocks:G,standbyBridgeApplied:V}=a3(j.messages,W);if(!N)lj(j);if(o3(j.messages[0]))u3(j.messages[0]),n3(j.messages[0]);else r1(j.messages[0]),r1(j.messages[1]);if(N)r1(j.messages[N.index]);if(J)r1(j.messages[J.index]);return{standbyAnchorMatched:Z,standbyDistanceBlocks:G,standbyBridgeApplied:V,...V&&N?{standbyBridgeMessageIndex:N.index}:{}}}function W7(j){if(!Array.isArray(j.messages))return 0;let W=0;return j.messages=j.messages.filter((J)=>{if(!c(J)||!Array.isArray(J.content))return!0;if(J.role!=="assistant")return!0;let N=J.content.filter((Z)=>{if(!c(Z)||Z.type!=="thinking")return!0;if(!XW(Z.signature))return!0;return W+=1,!1});if(N.length===J.content.length)return!0;return J.content=N,N.length>0}),W}function wW(j){if(!ZW(j.model))return null;let W=Object.hasOwn(j,"thinking");return j.thinking={...$W},{replacedExisting:W}}function J7(j){if(!DW(j.model))return null;let W=Object.hasOwn(j,"thinking"),J=j.thinking;if(c(J)&&J.type==="disabled")return j.thinking={type:"disabled"},{replacedExisting:W,display:"disabled"};return j.thinking={...YW},{replacedExisting:W,display:"summarized"}}function HW(j){if(!A0(j.model))return null;let W=Object.hasOwn(j,"thinking"),J=j.thinking;if(c(J)&&J.type==="disabled"){j.thinking={type:"disabled"};let N=j.output_config;if(c(N)&&N.effort==="xhigh")N.effort="high";else if(c(N)&&N.effort==="max")N.effort="high";return{replacedExisting:W,display:"disabled"}}return j.thinking={...GW},{replacedExisting:W,display:"summarized"}}function CW(j,W=E1){try{let J=JSON.parse(j);return J.model=W,delete J.speed,wW(J),HW(J),{ok:!0,bodyText:JSON.stringify(J)}}catch{return{ok:!1,reason:"body is not valid JSON"}}}function N7(j,W){if(!W.enabled)return cj(j,!1),delete j.cache_control,delete j.cacheControl,{};if(W.mode==="automatic")return l3(j),{};if(W.mode==="hybrid")return j7(j,W.hybridStandbyAnchor);return cj(j,!0),delete j.cacheControl,{}}function O7(j){if(!Array.isArray(j.messages))return;while(j.messages.length){let W=j.messages[j.messages.length-1];if(!c(W)||W.role!=="assistant")break;j.messages.pop()}}function $7(j){if(!Array.isArray(j.messages))return 0;for(let W=j.messages.length-1;W>=0;W--){let J=j.messages[W];if(!c(J)||J.role!=="assistant")continue;if(!Array.isArray(J.content))return 0;if(!J.content.some((Z)=>c(Z)&&Z.type==="tool_use"))return 0;let N=0;while(J.content.length){let Z=J.content[J.content.length-1];if(!c(Z)||Z.type!=="text"||typeof Z.text!=="string"||Z.text.trim())break;J.content.pop(),N++}return N}return 0}function a(){return performance.now()}function q0(j){return Math.round(j*10)/10}function dj(j){let W=0,J=0,N=0,Z=Array.isArray(j.messages)?j.messages:[];W=Z.length;for(let G of Z){if(!G||typeof G!=="object")continue;let V=G.content;if(!Array.isArray(V))continue;J+=V.length;for(let B of V)if(B&&typeof B==="object"&&B.type==="tool_use")N++}return{messageCount:W,contentBlockCount:J,toolDefinitionCount:Array.isArray(j.tools)?j.tools.length:0,toolUseCount:N,systemBlockCount:Array.isArray(j.system)?j.system.length:0}}async function k4(j,W={}){try{let J=a(),N=JSON.parse(j);W.perf?.("parse",{ms:q0(a()-J),inputBytes:j.length,...dj(N)});let Z=a(),G=Array.isArray(N.messages)?N.messages.length:void 0;O7(N);let V=$7(N),B=Array.isArray(N.messages)?N.messages.length:void 0;W.perf?.("strip_trailing_assistant",{ms:q0(a()-Z),removedMessages:typeof G==="number"&&typeof B==="number"?G-B:void 0,removedWhitespaceBlocks:V});let f=a(),r=W7(N),E=kj(N,W.serverSideFallbackEnabled===!0),v=wW(N),n=J7(N),l=HW(N);W.perf?.("model_normalize",{ms:q0(a()-f),model:typeof N.model==="string"?N.model:void 0,fableMythosThinkingDisplay:v?"summarized":void 0,replacedFableMythosThinking:v?.replacedExisting??!1,sonnet5ThinkingDisplay:n?.display,replacedSonnet5Thinking:n?.replacedExisting??!1,opus5ThinkingDisplay:l?.display,replacedOpus5Thinking:l?.replacedExisting??!1,removedNonAnthropicThinking:r,serverSideFallbackEnabled:E.enabled,serverFallbackMarkersRestored:E.restoredMarkers,serverFallbackMarkersDropped:E.droppedMarkers,hasOutputConfig:Object.hasOwn(N,"output_config")});let Y0=a(),t=Array.isArray(N.messages)&&N.messages.some((L1)=>L1.role==="user")?WW(N.messages,void 0,tj):null;W.perf?.("billing_header",{ms:q0(a()-Y0),hasBillingHeader:Boolean(t)});let w0=a();if(N.system=p3(N.system),W.perf?.("system_identity",{ms:q0(a()-w0),systemBlockCount:Array.isArray(N.system)?N.system.length:0}),t&&Array.isArray(N.system))N.system.unshift({type:"text",text:t});let F=a(),x0=N7(N,{enabled:W.cache1hEnabled??!1,mode:W.cache1hMode??"explicit",hybridStandbyAnchor:W.hybridStandbyAnchor});if(W.perf?.("cache_strategy",{ms:q0(a()-F),enabled:W.cache1hEnabled??!1,mode:W.cache1hMode??"explicit",...x0}),W.fastModeEnabled&&A1(N.model))N.speed="fast";else if(N.speed==="fast")delete N.speed;let n0=a();if(W.identity)JW(N,W.identity);W.perf?.("metadata",{ms:q0(a()-n0),hasAccountUuid:Boolean(W.identity?.accountUuid)});let F0=a(),i0=k3(N);W.perf?.("prefix_tools_stringify",{ms:q0(a()-F0),outputBytesBeforeSign:i0.length,...dj(N)});let Y1=a(),E0=await jW(i0);return W.perf?.("cch_sign",{ms:q0(a()-Y1),outputBytes:E0.length}),E0}catch{return j}}var Z7=new TextEncoder;function Y7(){return{pending:"",events:0,parseErrors:0,eventCounts:{},typeCounts:{},deltaTypeCounts:{},contentBlockTypeCounts:{},textDeltaBytes:0,thinkingDeltaBytes:0,inputJsonDeltaBytes:0,signatureDeltaBytes:0,redactedThinkingBytes:0}}function s1(j,W){if(!W)return;j[W]=(j[W]??0)+1}function J1(j){return Z7.encode(j).byteLength}function u0(j){return j&&typeof j==="object"&&!Array.isArray(j)?j:void 0}function L0(j,W){let J=j?.[W];return typeof J==="string"?J:void 0}function D7(j,W){let J=j?.[W];return typeof J==="number"?J:void 0}function LW(j){if(!j.trim())return null;let W,J=[];for(let v of j.split(/\r?\n/)){if(v.startsWith("event:")){W=v.slice(6).trim();continue}if(v.startsWith("data:")){let n=v.slice(5);J.push(n.startsWith(" ")?n.slice(1):n)}}let N=J.join(`
|
|
13
|
+
`),Z={event:W,rawBytes:J1(j),dataBytes:J1(N)};if(!N||N==="[DONE]")return Z.type=N==="[DONE]"?"done":void 0,Z.event??=Z.type,Z;let G;try{G=JSON.parse(N)}catch{return Z}let V=u0(G),B=u0(V?.delta),f=u0(V?.content_block),r=u0(V?.message),E=u0(V?.usage)??u0(r?.usage);if(Z.type=L0(V,"type"),Z.event??=Z.type,Z.index=D7(V,"index"),Z.contentBlockType=L0(f,"type"),Z.deltaType=L0(B,"type"),Z.stopReason=L0(B,"stop_reason")??L0(V,"stop_reason"),Z.deltaType==="text_delta")Z.textDeltaBytes=J1(L0(B,"text")??"");if(Z.deltaType==="thinking_delta")Z.thinkingDeltaBytes=J1(L0(B,"thinking")??"");if(Z.deltaType==="input_json_delta")Z.inputJsonDeltaBytes=J1(L0(B,"partial_json")??"");if(Z.deltaType==="signature_delta")Z.signatureDeltaBytes=J1(L0(B,"signature")??"");if(Z.contentBlockType==="redacted_thinking")Z.redactedThinkingBytes=J1(L0(f,"data")??"");if(E)Z.stopReason??=L0(r,"stop_reason");return Z}function g4(j){let W=j.indexOf(`
|
|
6
14
|
|
|
7
|
-
`),
|
|
15
|
+
`),J=j.indexOf(`\r
|
|
8
16
|
\r
|
|
9
|
-
`);if(
|
|
10
|
-
`);if(!J||J==="[DONE]")return null;let Y;try{Y=JSON.parse(J)}catch{return null}let D=d0(Y);if(j!=="error"&&P0(D,"type")!=="error")return null;let K=d0(D?.error),M=P0(K,"type")??P0(K,"code")??void 0,y=P0(K,"message")??P0(D,"message")??M??"Anthropic stream error";if(!SJ(M,y))return null;return fJ(M,y)}function x4(W,j){if(!j)return null;W.pending+=j;while(!0){let N=MW(W.pending);if(!N)break;let J=W.pending.slice(0,N.index);W.pending=W.pending.slice(N.index+N.length);let Y=AJ(J);if(Y)return Y}return null}function RJ(W){return{sseEvents:W.events,ssePendingChars:W.pending.length,sseParseErrors:W.parseErrors,sseEventCounts:{...W.eventCounts},sseTypeCounts:{...W.typeCounts},sseDeltaTypeCounts:{...W.deltaTypeCounts},sseContentBlockTypeCounts:{...W.contentBlockTypeCounts},sseTextDeltaBytes:W.textDeltaBytes,sseThinkingDeltaBytes:W.thinkingDeltaBytes,sseInputJsonDeltaBytes:W.inputJsonDeltaBytes,sseSignatureDeltaBytes:W.signatureDeltaBytes,sseRedactedThinkingBytes:W.redactedThinkingBytes,sseLastEvent:W.last?{...W.last}:void 0}}function Wj(W,j={}){if(!W.body)return W;let N=W.body.getReader(),J=new TextDecoder,Y=new TextEncoder,D="",K=0,M=0,y=0,r=0,i=0,l=!1,$0=!1,F=o(),T0=o(),U0=j.perf?IJ():void 0,x0=vJ(),m0=j.onContentFilter||j.onComplete?xJ():void 0,b0=(O0)=>{if(!m0)return null;let E0=EJ(m0,O0);if(E0?.type==="content-filter"&&j.onContentFilter)return j.onContentFilter()===!1?null:qJ();if(E0?.type==="complete")j.onComplete?.(E0.finishReason);return null},k0=()=>{if($0)return;$0=!0,N.releaseLock()},W1=async(O0)=>{try{await N.cancel(O0)}catch{}finally{k0()}},K1=(O0={})=>({chunks:K,pulls:M,inputBytes:y,outputBytes:r,pendingChars:D.length,rewriteMs:I0(i),totalMs:I0(o()-T0),...U0?RJ(U0):{},...O0}),v0=(O0,E0={})=>{j.perf?.(O0,K1(E0))};j.perf?.("stream_tool_prefix_wrapper_created",{status:W.status,hasBody:!0});let S0=new ReadableStream({async pull(O0){if(M++,!l)l=!0,v0("stream_tool_prefix_first_pull");let E0=o();try{let{done:L0,value:g0}=await N.read(),y0=I0(o()-E0);if(L0){let h0=J.decode();if(U0)T4(U0,h0);let p0=x4(x0,h0)??b0(h0);if(p0)throw v0("stream_tool_prefix_retryable_error",{error:p0.message,providerErrorType:p0.providerErrorType}),await W1(p0),p0;let B0=o(),c0=H4(`${D}${h0}`,!0);if(i+=o()-B0,c0.ready){let v1=Y.encode(c0.ready);r+=v1.byteLength,O0.enqueue(v1)}v0("stream_tool_prefix_rewrite",{readMs:y0}),k0(),O0.close();return}K++,y+=g0.byteLength;let j1=J.decode(g0,{stream:!0});if(U0)T4(U0,j1);let N1=x4(x0,j1)??b0(j1);if(N1)throw v0("stream_tool_prefix_retryable_error",{error:N1.message,providerErrorType:N1.providerErrorType,readMs:y0,lastChunkBytes:g0.byteLength}),k0(),N1;let E1=D+j1,D0=o(),_1=H4(E1);if(i+=o()-D0,D=_1.pending,_1.ready){let h0=Y.encode(_1.ready);r+=h0.byteLength,O0.enqueue(h0)}let M0=o();if(K===1||K%25===0||M0-F>5000)F=M0,v0("stream_tool_prefix_progress",{readMs:y0,lastChunkBytes:g0.byteLength})}catch(L0){throw v0("stream_tool_prefix_error",{error:L0 instanceof Error?L0.message:String(L0)}),k0(),L0}},async cancel(O0){v0("stream_tool_prefix_cancel",{reason:O0 instanceof Error?O0.message:String(O0)});try{await N.cancel(O0)}finally{k0()}}});return new Response(S0,{status:W.status,statusText:W.statusText,headers:W.headers})}var kJ="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",jj="~effect/http/HttpServerResponse",Nj="~effect/http/Cookies",Jj="~effect/http/HttpBody",gJ="~effect/ErrorReporter/ignore",yJ=60000,hJ=60000,mJ=5000,Oj=200,HN=240,bJ=HN,pJ=600000;function iJ(W,j){return(W?.accounts??[]).some((N)=>N.id===j&&N.enabled!==!1&&W0(N))}function lJ(W){let j=(W?.accounts??[]).find((N)=>N.enabled!==!1&&W0(N));if(D1(W)==="fallback-first"&&j)return{activeId:j.id,route:"fallback-first"};return{activeId:"main",route:"main"}}function $j(W,j){if(W?.activeId==="main"||W?.activeId&&iJ(j,W.activeId))return W;return lJ(j)}function LN(W,j,N){let J=Date.now()-W.lastUpdated;if(!W.activeId||J<0||J>pJ)return $j(N,j);return $j(W,j)}async function dJ(W,j,N){let J;try{J=await j()}catch(Y){return k.warn("sidebar","account storage reload failed; routing preserved",{message:Y instanceof Error?Y.message:String(Y)}),{...W.activeId?{activeId:W.activeId,route:W.route}:N??{activeId:"main",route:"main"},freshStorage:null}}return{...LN(W,J,N),freshStorage:J}}async function cJ(W){await YW()?.beforeStorageLoad?.();let j;try{j=await f(W)}catch{return{activeId:"main",route:"main",freshStorage:null}}finally{await YW()?.afterStorageLoad?.()}await YW()?.beforeSidebarRead?.();let N=await CN();return{...LN(N,j),freshStorage:j}}function uJ(W){let j=Math.floor(W.retryAfterSeconds/60),N=W.retryAfterSeconds%60,J=`Retry in ${j}m ${N}s.`;return W.modelName?`${W.modelName} weekly limit reached, no routable accounts. ${J}`:`Killswitch: no routable accounts. ${J}`}function nJ(W){if(!W.requestModelId)return{isScopedDriven:!1};if(!e0(W.mainQuota,W.storage))return{isScopedDriven:!1};let j=Sj(W.mainQuota,W.requestModelId);if(!j)return{isScopedDriven:!1};if(!Number.isFinite(j.remainingPercent))return{isScopedDriven:!1};let N=fj(W.storage);if(j.remainingPercent<=N.scoped)return{isScopedDriven:!0,modelName:j.modelName,modelId:W.requestModelId};return{isScopedDriven:!1}}var oJ=1,Yj=!1;function ZW(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function A(){return performance.now()}function s(W){return Math.round(W*10)/10}function Zj(W){return Math.floor(Math.random()*Math.max(0,W))}function i1(W){if(typeof W==="string")return W;if(W instanceof URL)return W.toString();return W.url}function l1(W,j){return j?.method??(W instanceof Request?W.method:void 0)}function Gj(W){return W instanceof Error?W.message:String(W)}function rJ(){if(Yj||!1||!ZW())return;Yj=!0;let W=100,j=250,N=A()+W;setInterval(()=>{let J=A(),Y=J-N;if(N=J+W,Y<j)return;a("[perf] opencode event_loop_lag",{lagMs:s(Y),thresholdMs:j})},W).unref?.()}function sJ(W){let j=A(),N={requestId:String(oJ++),start:j,last:j,mark(J,Y){let D=A();if(ZW())a("[perf] opencode request stage",{requestId:N.requestId,stage:J,deltaMs:s(D-N.last),totalMs:s(D-N.start),...Y});N.last=D},done(J,Y){let D=A();if(ZW())a("[perf] opencode request done",{requestId:N.requestId,stage:J,deltaMs:s(D-N.last),totalMs:s(D-N.start),...Y});N.last=D}};if(ZW())a("[perf] opencode request start",{requestId:N.requestId,...W});return N}function aJ(W,j){let N=/^msg_([0-9a-fA-F]{12})/.exec(W);if(!N)return;let J=BigInt(`0x${N[1]}`);if(J<=0n)return;let D=`msg_${(J-1n).toString(16).padStart(12,"0")}${"z".repeat(14)}`;if(j&&D<=j)return;return D}async function Xj(W,j,N,J={}){let Y=W.client.session,D=await D4(W.client,j),K={path:{id:j},body:{noReply:J.noReply??!0,parts:[{type:"text",text:N,ignored:!0}]}};if(J.beforeActiveAssistant){let M=D?.latestAssistantMessageId?aJ(D.latestAssistantMessageId,D.latestUserMessageId):void 0;if(!M)throw Error("OpenCode active assistant ordering is unavailable for an immediate notification.");K.body.messageID=M}if(D?.agent)K.body.agent=D.agent;if(D?.model)K.body.model=D.model;if(D?.variant)K.body.variant=D.variant;if(typeof Y?.promptAsync==="function"){await Y.promptAsync(K);return}if(typeof Y?.prompt==="function"){await Promise.resolve(Y.prompt(K));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function tJ(){let W=Error(kJ);throw W[jj]=jj,W[gJ]=!0,W.status=204,W.statusText=void 0,W.headers={},W.cookies={[Nj]:Nj,cookies:{}},W.body={[Jj]:Jj,_tag:"Empty"},W}function eJ(W){if(W.sessionID==null)return!1;let j=W.model;return j?.providerID==="anthropic"||j?.api?.npm==="@ai-sdk/anthropic"||j?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function W3(W){if(W.some((j)=>j.includes("<use_parallel_tool_calls>")))return!1;return W.push(Vj),!0}var j3={input:0,output:0,cache:{read:0,write:0}},N3="Fable content filter detected. Switched to Opus 4.8 for a 10-response recovery window while keeping the Fable cache warm.",J3="Fable recovery window complete. Returning to Fable 5.";function O3(W){let j=W["claude-opus-4-8"]??W["claude-opus-4-5"]??Object.values(W)[0];if(!j)return W;return{...W,...Object.fromEntries(Object.values(YN).map((N)=>[N.id,{...j,id:N.id,name:N.name,api:j.api?{...j.api,id:N.id}:void 0,cost:{input:x1.input,output:x1.output,cache:{read:x1.cacheRead,write:x1.cacheWrite5m}},limit:{...j.limit??{},context:JN,output:ON},capabilities:{...j.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:$N}]))}}function $3(W){return Object.fromEntries(Object.entries(W).map(([j,N])=>[j,{...N,cost:j3}]))}var f3=async(W)=>{rJ();let{client:j}=W,N=globalThis.fetch,J=zj(),Y=600000,D=50,K=new Map;function M(){let O=Date.now();for(let[$,G]of K)if(O-G.createdAt>Y)K.delete($)}function y(O,$){if(M(),K.size>=D){let G="",z=1/0;for(let[Z,w]of K)if(w.createdAt<z)z=w.createdAt,G=Z;if(G)K.delete(G)}K.set(O,$)}function r(O){M();let $=K.get(O);if(!$)return;if(Date.now()-$.createdAt>Y){K.delete(O);return}return $}let i;try{i=await f(J)}catch(O){let $=O instanceof Error?O.message:String(O);throw Error(`Failed to load account store: ${$}`,{cause:O instanceof Error?O:void 0})}let l=new KW,$0=new wN({path:process.env.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE||_N(J)}),F=new rj({storage:i,onMainQuotaFetched:async(O,$,G,z)=>{try{let Z=await f(J)??H0(),w=vj(Z);if(w&&w.checkedAt>=z&&yj(w.quota,Z,w.checkedAt)>Date.now()){F.seedMainFromStorage(Z);return}Z.quota=Z.quota??{},Z.quota.mainQuota=O,Z.quota.mainQuotaCheckedAt=$,Z.quota.mainQuotaToken=G,Z.quota.mainLastQuotaApiError=void 0,await s0(Z,J,{mainQuota:!0})}catch(Z){k.warn("quota","failed to persist main quota",{error:Z instanceof Error?Z.message:String(Z)})}},onApiError:async(O)=>{try{let $=await f(J)??H0();$.quota=$.quota??{},$.quota.mainLastQuotaApiError=O,await s0($,J,{mainQuota:!0})}catch($){k.warn("quota","failed to persist backoff state",{error:$ instanceof Error?$.message:String($)})}}}),T0=new Map;async function U0(O,$,G){if(G?.aborted)return;let z=`${O}:${u1($)}`,Z=T0.get(z);if(!Z){let w=sj({accessToken:$,fetchImpl:N,signal:G}).catch((I)=>{k.debug("quota","failed to hydrate account profile",{account:O,error:I instanceof Error?I.message:String(I)});return}).finally(()=>{if(T0.get(z)===w)T0.delete(z)});Z=w,T0.set(z,Z)}if(!G)return Z;return new Promise((w)=>{let I=!1,_=(u)=>{if(I)return;I=!0,G.removeEventListener("abort",B),w(u)},B=()=>_(void 0);if(G.addEventListener("abort",B,{once:!0}),G.aborted)B();Z.then(_)})}async function x0(O){try{if(O.accountId==="main"){let $=await Y0?.();if($?.type!=="oauth"||$.access!==O.accessToken)return!1}return await wj({accountId:O.accountId,profile:O.profile,expectedTokenFingerprint:u1(O.accessToken)},J)}catch($){k.debug("quota","failed to persist account profile",{account:O.accountId,error:$ instanceof Error?$.message:String($)});return}}async function m0(O,$,G){if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return O;let z=Date.now();if($&&O.main?.profile&&!WW(O.main.profile,$))O.main.profile=void 0,x0({accountId:"main",accessToken:$,profile:void 0}).catch(()=>{});if($&&!kW(O.main?.profile,z)){let Z=await U0("main",$,G);if(Z)O.main={type:"opencode",provider:"anthropic",profile:Z},x0({accountId:"main",accessToken:$,profile:Z}).catch(()=>{})}for(let Z of O.accounts){if(G?.aborted)break;if(!W0(Z)||!Z.access)continue;let w=Z.access;if(Z.profile&&!WW(Z.profile,w))Z.profile=void 0,x0({accountId:Z.id,accessToken:w,profile:void 0}).catch(()=>{});if(kW(Z.profile,z))continue;let I=await U0(Z.id,w,G);if(I)Z.profile=I,x0({accountId:Z.id,accessToken:w,profile:I}).catch(()=>{})}return O}let b0=new Set;async function k0(O,$){let G=await f(J)??H0();if(O.accountId==="main"){let Z;try{let w=await Y0?.();if(w?.type==="oauth")Z=w.access}catch{}if(Z!==O.accessToken){k.trace("quota","skipped stale main response quota persistence");return}G.quota=G.quota??{},G.quota.mainQuota=$.quota,G.quota.mainQuotaCheckedAt=$.checkedAt,G.quota.mainQuotaToken=u1(O.accessToken),await s0(G,J,{mainQuota:!0});return}let z=G.accounts.find((Z)=>Z.id===O.accountId&&W0(Z)&&Z.access===O.accessToken);if(!z)return;z.quota=$.quota,await s0(G,J,{accounts:[O.accountId]})}function W1(O){k.warn("quota","failed to persist harvested response quota",{error:O instanceof Error?O.message:String(O)})}function K1(O){let $=O instanceof Error?O.name:typeof O,G=O instanceof Error?O.message:String(O),z=`${$}:${G}`;if(b0.has(z))return;b0.add(z),k.warn("quota","failed to normalize response quota headers",{error:G})}function v0(O,$){try{if(!nj(O)){k.trace("quota","skipped non-quota response headers",{account:$.accountId});return}let G=oj(O),z=$.accountId==="main"?F.pushMainFromHeaders($.accessToken,G):F.pushFallbackFromHeaders($.accountId,$.accessToken,G);k0($,z).catch(W1),c0().catch(()=>{}),k.debug("quota","harvested response quota",{account:$.accountId,fiveHourPercent:z.quota.five_hour?.usedPercent,sevenDayPercent:z.quota.seven_day?.usedPercent,source:"headers"})}catch(G){K1(G)}}let S0=new hj({quotaManager:F,onFallbackStorageChanged:()=>{c0().catch(()=>{})}});S0.startBackgroundRefresh();let O0=null,E0=new uj({directory:process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||cj("opencode")}),L0=[],g0=new dj({loadStorage:()=>f(J),onTrackedSessionsChanged:async(O)=>{await E0.publish(O),L0=await E0.list(O)},prepareHeaders:async(O,$)=>{let G,z=$.oauthAccountId;if(z&&z!=="main"){let Z=await f(J),w=Z?.accounts.find((_)=>_.id===z&&_.enabled!==!1&&W0(_));if(!w||!Z)throw Error(`OAuth account ${z} is unavailable for cache prewarm`);let I=w;try{I=await S0.refreshAccount(w,Z)}catch(_){k.warn("cachekeep","fallback token refresh failed",{accountId:z,error:_ instanceof Error?_.message:String(_)})}if(G=I.access,!G)throw Error(`OAuth account ${z} has no access token for cache prewarm`)}else{if(!Y0)return O;let Z=await Y0();if(Z.type!=="oauth")return O;if(!Z.access||Z.expires&&Z.expires<Date.now()){if(!O0)return O;Z.access=await O0()}G=Z.access}if(!G)return O;try{let Z=JSON.parse($.bodyText),w=await SW(G,typeof Z.model==="string"?Z.model:void 0);if(O.delete("anthropic-beta"),L1(O,G,{body:Z,identity:w}),O.set("anthropic-beta",Q1(O.get("anthropic-beta"),[bj])),Z.speed==="fast")b1(O)}catch{L1(O,G)}return O}}),y0=new Map;function j1(O){let $=O.plan.sessionId,G=async()=>{let w=O.warmTarget;if(!w){k.debug("fable-fallback","cache warm skipped",{session:$,reason:"Opus response was not served by an OAuth route"});return}let I=t4(w.bodyText,O.plan.requestedModel);if(!I.ok){k.warn("fable-fallback","cache warm skipped",{session:$,reason:I.reason});return}try{let _=await g0.prewarmNow({sessionId:$,url:w.url,headers:w.headers,bodyText:I.bodyText,oauthAccountId:l.recoveryAccount(O.plan)??w.oauthAccountId});if(_.ok){k.debug("fable-fallback","Fable cache warmed",{session:$,remaining:l.remaining($),..._.usage&&{usage:_.usage}});return}k.warn("fable-fallback","Fable cache warm skipped",{session:$,status:_.status,reason:_.reason})}catch(_){k.warn("fable-fallback","Fable cache warm failed",{session:$,error:_ instanceof Error?_.message:String(_)})}},Z=(y0.get($)??Promise.resolve()).then(G,G);return y0.set($,Z),Z.finally(()=>{if(y0.get($)===Z)y0.delete($)}),Z}async function N1(){return L0=await E0.list(g0.trackedSessions()),L0}if(I1({enabled:M1(i),mode:B1(i)}),NW(o1(i)),OW(r1(i)),!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)Kj(t1(i)??"info");let E1=null;if(W.directory){let O=globalThis;if(O.__anthropicAuthRpcServer)await O.__anthropicAuthRpcServer.stop().catch(()=>{}),O.__anthropicAuthRpcServer=void 0;try{E1=await P4({dir:PN(W.directory),drain:z4,apply:AN}),O.__anthropicAuthRpcServer=E1}catch($){k.warn("rpc","failed to start",{error:$ instanceof Error?$.message:String($)})}}let D0={activeId:"main",route:"main"},_1=UN(),M0=new Map;function h0(O,$,G){if(!O||!$)return O;let z={...O,accounts:O.accounts.map((I)=>{let _=$.accounts.find((B)=>B.id===I.id);if(!W0(I)||!_||!W0(_)||!I.access||_.access!==I.access)return I;return{...I,profile:_.profile}})},Z=O.main?.profile,w=O.main??$.main;if(G&&w&&(!Z||WW(Z,G)))z.main={...w,profile:$.main?.profile};return z}function p0(O,$){F.updateStorage(O),F.seedMainFromStorage(O,$.mainAccessToken),F.seedFallbacksFromAccounts((O?.accounts??[]).filter(W0));let G=F.getMain($.mainAccessToken),z=F.getLastApiError(),Z=O?.refresh?.mainLastRefreshError;return{main:{quota:G?.quota??null,tierLabel:jW(O?.main?.profile),quotaBackedOff:F.isBackedOff(),quotaBackoffUntil:z?.nextRetryAt,refreshBackedOff:Z?a0(Z,$.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:Z?.nextRetryAt},fallbacks:(O?.accounts??[]).filter((w)=>w.enabled!==!1&&W0(w)).map((w)=>({id:w.id,label:w.label,tierLabel:jW(w.profile),quota:w.access?F.getFallback(w.id,w.access)?.quota??null:null,needsReauth:w.lastRefreshError!=null&&a0(w.lastRefreshError,w.refresh,Date.now())&&Z1(w.lastRefreshError),enabled:w.enabled!==!1})),activeId:$.activeId,route:$.route,relay:(()=>{let w=cW(O);return w?{enabled:!0,transport:w.transport??"http"}:null})(),fastMode:JW(),cacheKeep:{enabled:RW(O),window:AW(O)?"always":O?.cacheKeep?.startHour!=null&&O?.cacheKeep?.endHour!=null?`${O.cacheKeep.startHour}-${O.cacheKeep.endHour}`:void 0,trackedSessions:L0.length},fableRecoveries:M0.size>0?[...M0.values()]:void 0,lastUpdated:Date.now()}}function B0(O,$){let G=$.routingAuthoritative!==!1;if(G)D0={activeId:$.activeId,route:$.route};let z=p0(O,$);return QN(z,_1,{routingAuthoritative:G,resolvePreservedRouting:G?void 0:async(Z)=>{let w=await dJ(Z,()=>f(J),{activeId:z.activeId,route:z.route}),I=$.useHydratedProfiles?h0(w.freshStorage,O,$.mainAccessToken):w.freshStorage;return{activeId:w.activeId,route:w.route,state:p0(I,{...$,activeId:w.activeId,route:w.route})}},onRoutingResolved:G?void 0:(Z)=>{D0=Z}}).catch((Z)=>k.warn("sidebar","state write failed",{error:Z instanceof Error?Z.message:String(Z)}))}async function c0(){let O=await f(J),$,G;if(Y0)try{let z=await Y0();$=z.access,G=z.refresh}catch{}B0(O,{activeId:D0.activeId,route:D0.route,mainAccessToken:$,mainRefreshToken:G,routingAuthoritative:!1})}function v1(O,$){if(!$)return;if(O?.quota?.enabled!==!0)return;if(F.getMain($))return;if(GW)return;GW=!0,F.refreshMain($).then(()=>c0()).catch(()=>{}).finally(()=>{GW=!1})}let Y0=null,GW=!1,J1=null,S1=0;function MN(O){let $=O?.refresh?.refreshBeforeExpiryMinutes??bJ;return Math.max(HN,$)*60000}function BN(O){return O?.refresh?.enabled!==!1}async function oW(O){if(!O)return;let $=await f(J),G=$?.refresh?.mainLastRefreshError;if(!$?.refresh||!G?.tokenHash)return;let z=a1(O);if(G.tokenHash===z)return;if(G.nextRetryAt&&G.nextRetryAt>Date.now()){a("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:G.nextRetryAt,retryCount:G.retryCount,remainingMs:G.nextRetryAt-Date.now()});return}$.refresh.mainLastRefreshError=void 0,await s0($,J,{mainRefresh:!0}),a("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:G.checkedAt,previousNextRetryAt:G.nextRetryAt,previousRetryCount:G.retryCount})}async function FN(){let O=[],$;if(Y0)try{let _=await Y0();if(_.type==="oauth"&&_.access){$=_.access;let B=await F.refreshMain(_.access);O.push({name:"OpenCode anthropic",role:"main",quota:B})}else if(_.type==="oauth")O.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(_){let B=_ instanceof Error?_.message:String(_);O.push({name:"OpenCode anthropic",role:"main",error:B.includes("429")?"Usage API rate limited — try again in a moment":B})}let{storage:G,errors:z}=await S0.refreshQuotaForAllAccounts({force:!0}),Z=await m0(G??H0(),$,AbortSignal.timeout(3000)),w=O.find((_)=>_.role==="main");if(w)w.tierLabel=jW(Z.main?.profile);let I=new Map(z.map((_)=>[_.accountId,_.message]));if(O.push(...ZN(Z,I)),!Y0)O.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return GN({accounts:O,refreshedAt:Date.now()})}async function rW(O){if(Y0)try{let $=await Y0();B0(O,{activeId:D0.activeId,route:D0.route,mainAccessToken:$.access,mainRefreshToken:$.refresh,routingAuthoritative:!1})}catch{}}function XW(O,$,G,z){if(M0.delete(O.sessionId),M0.set(O.sessionId,{...O,changedAt:Date.now()}),M0.size>128){let Z=M0.keys().next().value;if(Z)M0.delete(Z)}if(B0($,{activeId:D0.activeId,route:D0.route,mainAccessToken:G.access,mainRefreshToken:G.refresh,routingAuthoritative:!1}),!z||zW(O.sessionId))return;Xj(W,O.sessionId,z,{noReply:!0,beforeActiveAssistant:!0}).catch((Z)=>{k.warn("fable-fallback","Desktop notification failed",{session:O.sessionId,error:Z instanceof Error?Z.message:String(Z)})})}function IN(O,$,G){if(!O||!M0.delete(O))return;B0($,{activeId:D0.activeId,route:D0.route,mainAccessToken:G.access,mainRefreshToken:G.refresh,routingAuthoritative:!1})}async function TN(O){let $=mj(O);if($.type==="enable"||$.type==="disable"){let w=$.type==="enable",I=await Uj(w),_=B1(I);return I1({enabled:w,mode:_}),k.info("commands","cache enabled changed",{enabled:w}),e1({argumentsText:O,enabled:w,mode:_})}if($.type==="mode"){let w=await Cj($.mode),I=M1(w);return I1({enabled:I,mode:$.mode}),k.info("commands","cache mode changed",{mode:$.mode}),e1({argumentsText:O,enabled:I,mode:$.mode})}let G=await f(J),z=M1(G),Z=B1(G);return I1({enabled:z,mode:Z}),e1({argumentsText:O,enabled:z,mode:Z})}async function xN(O){let $=pj(O),G=await f(J);if($.type==="window")G=await Lj($.startHour,$.endHour),k.info("commands","cachekeep schedule changed",{schedule:`${$.startHour}-${$.endHour}`});else if($.type==="always")G=await Mj(),k.info("commands","cachekeep schedule changed",{schedule:"always"});else if($.type==="disable")G=await Bj(!1),k.info("commands","cachekeep enabled changed",{enabled:!1});else if($.type==="subagents")G=await Ij($.enabled),k.info("commands","cachekeep subagents changed",{subagents:$.enabled});let z=qW(G),Z=await N1(),w=Z.length?Math.min(...Z.map((I)=>I.nextPrewarmAt)):void 0;return lj({argumentsText:O,enabled:ij(G),always:AW(G),window:z,hybridActive:RW(G),trackedSessions:Z.length,trackedSessionDetails:Z,nextPrewarmAt:w})}async function EN(O){let $=ej(O);if($.type==="enable"||$.type==="disable"){let Z=$.type==="enable";return await Qj(Z),NW(Z),k.info("commands","dump changed",{enabled:Z}),hW({argumentsText:O,enabled:Z})}let G=await f(J),z=o1(G);return NW(z),hW({argumentsText:O,enabled:z})}async function vN(O){let $=WN(O);if($.type==="enable"||$.type==="disable"){let Z=$.type==="enable";return await Hj(Z),OW(Z),k.info("commands","fast mode changed",{enabled:Z}),bW({argumentsText:O,enabled:Z})}let G=await f(J),z=r1(G);return OW(z),bW({argumentsText:O,enabled:z})}async function SN(O,$){let G=DN(O);if(G.type==="mode")return await VN(G.mode,J),k.info("commands","routing mode changed",{mode:G.mode}),nW({argumentsText:O,mode:G.mode});if(G.type==="reset"&&$)await $0.clear($),k.info("commands","sticky routing assignment reset");let z=await f(J);return nW({argumentsText:O,mode:D1(z)})}async function fN(O){let $=NN(O);if($.type==="level")return await Ej($.level),k.info("commands","log level changed",{level:$.level}),lW({argumentsText:O,level:$.level});let G=await f(J),z=t1(G)??"info";return lW({argumentsText:O,level:z})}async function qN(O,$){let G=aj(O);if(G.type==="add-apikey"){if(!G.apiKey)return{text:"API key is required",accounts:A0(await f(J)??H0())};let _=G.label?.trim()||void 0,B=Date.now(),u=G.baseURL?.trim()||"https://api.kie.ai/claude";if(!n1(u))return{text:"Invalid base URL. Must be an http(s) URL without embedded credentials.",accounts:A0(await f(J)??H0())};let j0=G.authHeader??"authorization-bearer",Z0={id:_||BW(),label:_||void 0,type:"api",apiKey:G.apiKey,baseURL:u,authHeader:j0,enabled:!0,addedAt:B,lastUsed:B};await EW(Z0,J),k.info("commands","account added",{id:Z0.id,label:Z0.label,type:"apikey"});let C0=await f(J);await rW(C0);let u0=A0(C0??{version:1,accounts:[]});return{text:`API key account "${Z0.label??Z0.id}" added.`,accounts:u0}}if(G.type==="add-oauth-start"){let _=await d1("max"),B={state:_.state,verifier:_.verifier,redirectUri:_.redirectUri,createdAt:Date.now()};return y($??"default",B),{text:`Open this URL in your browser:
|
|
11
|
-
${_.url}`,knobs:{oauthUrl:_.url},accounts:
|
|
12
|
-
`))}}if($?.length)for(let _ of $){let
|
|
13
|
-
`))}if(!
|
|
17
|
+
`);if(W===-1)return J===-1?null:{index:J,length:4};if(J===-1||W<J)return{index:W,length:2};return{index:J,length:4}}function uj(j,W){if(!W)return;j.pending+=W;while(!0){let J=g4(j.pending);if(!J)break;let N=j.pending.slice(0,J.index);j.pending=j.pending.slice(J.index+J.length);let Z=LW(N);if(!Z)continue;if(j.events++,s1(j.eventCounts,Z.event??"unknown"),s1(j.typeCounts,Z.type),s1(j.deltaTypeCounts,Z.deltaType),s1(j.contentBlockTypeCounts,Z.contentBlockType),j.textDeltaBytes+=Z.textDeltaBytes??0,j.thinkingDeltaBytes+=Z.thinkingDeltaBytes??0,j.inputJsonDeltaBytes+=Z.inputJsonDeltaBytes??0,j.signatureDeltaBytes+=Z.signatureDeltaBytes??0,j.redactedThinkingBytes+=Z.redactedThinkingBytes??0,j.last=Z,Z.dataBytes>0&&!Z.type&&!Z.event)j.parseErrors++}}function G7(){return{pending:"",completed:!1}}function X7(j,W){if(!W||j.completed)return null;j.pending+=W;while(!0){let J=g4(j.pending);if(!J)return null;let N=j.pending.slice(0,J.index);j.pending=j.pending.slice(J.index+J.length);let Z=LW(N);if(Z?.type!=="message_delta"||!Z.stopReason)continue;return j.completed=!0,Z.stopReason==="refusal"?{type:"content-filter"}:{type:"complete",finishReason:Z.stopReason}}}function V7(){return{pending:""}}function z7(j,W){let J=j?.toLowerCase(),N=W.toLowerCase();return J==="api_error"||J==="overloaded_error"||J==="server_error"||J==="internal_server_error"||N.includes("internal server error")||N.includes("server overloaded")}function K7(j,W){let J=j?`${j}: ${W}`:W,N=Error(`Anthropic stream error: ${J}`);if(N.code="ECONNRESET",N.syscall="anthropic-sse",j)N.providerErrorType=j;return N}function _7(j){let W=A0(j)?"Opus 5":"Fable",J=Error(`${W} response was blocked by the provider content filter; retrying with Opus 4.8`);return J.code="ECONNRESET",J.syscall="anthropic-sse",J.providerErrorType="refusal",J}function U7(j){if(!j.includes("error"))return null;let W,J=[];for(let r of j.split(/\r?\n/)){if(r.startsWith("event:")){W=r.slice(6).trim();continue}if(r.startsWith("data:")){let E=r.slice(5);J.push(E.startsWith(" ")?E.slice(1):E)}}let N=J.join(`
|
|
18
|
+
`);if(!N||N==="[DONE]")return null;let Z;try{Z=JSON.parse(N)}catch{return null}let G=u0(Z);if(W!=="error"&&L0(G,"type")!=="error")return null;let V=u0(G?.error),B=L0(V,"type")??L0(V,"code")??void 0,f=L0(V,"message")??L0(G,"message")??B??"Anthropic stream error";if(!z7(B,f))return null;return K7(B,f)}function nj(j,W){if(!W)return null;j.pending+=W;while(!0){let J=g4(j.pending);if(!J)break;let N=j.pending.slice(0,J.index);j.pending=j.pending.slice(J.index+J.length);let Z=U7(N);if(Z)return Z}return null}function P7(j){return{sseEvents:j.events,ssePendingChars:j.pending.length,sseParseErrors:j.parseErrors,sseEventCounts:{...j.eventCounts},sseTypeCounts:{...j.typeCounts},sseDeltaTypeCounts:{...j.deltaTypeCounts},sseContentBlockTypeCounts:{...j.contentBlockTypeCounts},sseTextDeltaBytes:j.textDeltaBytes,sseThinkingDeltaBytes:j.thinkingDeltaBytes,sseInputJsonDeltaBytes:j.inputJsonDeltaBytes,sseSignatureDeltaBytes:j.signatureDeltaBytes,sseRedactedThinkingBytes:j.redactedThinkingBytes,sseLastEvent:j.last?{...j.last}:void 0}}function BW(j,W={}){if(!j.body)return j;let J=j.body.getReader(),N=new TextDecoder,Z=new TextEncoder,G="",V=0,B=0,f=0,r=0,E=0,v=!1,n=!1,l=a(),Y0=a(),t=W.perf?Y7():void 0,w0=V7(),F=W.onContentFilter||W.onComplete?G7():void 0,x0=W.serverSideFallbackModel?gj({requestedModel:W.serverSideFallbackModel,onOutcome:W.onServerSideFallbackOutcome}):void 0,n0=(G0)=>{if(!F)return null;let v0=X7(F,G0);if(v0?.type==="content-filter"&&W.onContentFilter)return W.onContentFilter()===!1?null:_7(W.contentFilterModel);if(v0?.type==="complete")W.onComplete?.(v0.finishReason);return null},F0=()=>{if(n)return;n=!0,J.releaseLock()},i0=async(G0)=>{try{await J.cancel(G0)}catch{}finally{F0()}},Y1=(G0={})=>({chunks:V,pulls:B,inputBytes:f,outputBytes:r,pendingChars:G.length,rewriteMs:q0(E),totalMs:q0(a()-Y0),...t?P7(t):{},...G0}),E0=(G0,v0={})=>{W.perf?.(G0,Y1(v0))};W.perf?.("stream_tool_prefix_wrapper_created",{status:j.status,hasBody:!0});let L1=new ReadableStream({async pull(G0){if(B++,!v)v=!0,E0("stream_tool_prefix_first_pull");while(!0){let v0=a();try{let{done:H0,value:c0}=await J.read(),o0=q0(a()-v0);if(H0){let k0=N.decode();if(t)uj(t,k0);let P0=nj(w0,k0)??n0(k0);if(P0)throw E0("stream_tool_prefix_retryable_error",{error:P0.message,providerErrorType:P0.providerErrorType}),await i0(P0),P0;let B4=a(),m1=x0?x0.push(k0)+x0.flush():k0,M0=bj(`${G}${m1}`,!0);if(E+=a()-B4,M0.ready){let t0=Z.encode(M0.ready);r+=t0.byteLength,G0.enqueue(t0)}E0("stream_tool_prefix_rewrite",{readMs:o0}),F0(),G0.close();return}V++,f+=c0.byteLength;let R0=N.decode(c0,{stream:!0});if(t)uj(t,R0);let p0=nj(w0,R0)??n0(R0);if(p0)throw E0("stream_tool_prefix_retryable_error",{error:p0.message,providerErrorType:p0.providerErrorType,readMs:o0,lastChunkBytes:c0.byteLength}),F0(),p0;let r0=x0?x0.push(R0):R0,C4=G+r0,L4=a(),s0=bj(C4);if(E+=a()-L4,G=s0.pending,s0.ready){let k0=Z.encode(s0.ready);r+=k0.byteLength,G0.enqueue(k0)}let U0=a();if(V===1||V%25===0||U0-l>5000)l=U0,E0("stream_tool_prefix_progress",{readMs:o0,lastChunkBytes:c0.byteLength});if(s0.ready)return}catch(H0){throw E0("stream_tool_prefix_error",{error:H0 instanceof Error?H0.message:String(H0)}),F0(),H0}}},async cancel(G0){E0("stream_tool_prefix_cancel",{reason:G0 instanceof Error?G0.message:String(G0)});try{await J.cancel(G0)}finally{F0()}}});return new Response(L1,{status:j.status,statusText:j.statusText,headers:j.headers})}var Q7="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",IW="~effect/http/HttpServerResponse",TW="~effect/http/Cookies",MW="~effect/http/HttpBody",w7="~effect/ErrorReporter/ignore",H7=60000,C7=60000,L7=5000,xW=200,iJ=240,B7=iJ,I7=600000;function T7(j,W){return(j?.accounts??[]).some((J)=>J.id===W&&J.enabled!==!1&&$0(J))}function M7(j){let W=(j?.accounts??[]).find((J)=>J.enabled!==!1&&$0(J));if(C1(j)==="fallback-first"&&W)return{activeId:W.id,route:"fallback-first"};return{activeId:"main",route:"main"}}function FW(j,W){if(j?.activeId==="main"||j?.activeId&&T7(W,j.activeId))return j;return M7(W)}function cJ(j,W,J){let N=Date.now()-j.lastUpdated;if(!j.activeId||N<0||N>I7)return FW(J,W);return FW(j,W)}async function x7(j,W,J){let N;try{N=await W()}catch(Z){return h.warn("sidebar","account storage reload failed; routing preserved",{message:Z instanceof Error?Z.message:String(Z)}),{...j.activeId?{activeId:j.activeId,route:j.route}:J??{activeId:"main",route:"main"},freshStorage:null}}return{...cJ(j,N,J),freshStorage:N}}async function F7(j){await w4()?.beforeStorageLoad?.();let W;try{W=await k(j)}catch{return{activeId:"main",route:"main",freshStorage:null}}finally{await w4()?.afterStorageLoad?.()}await w4()?.beforeSidebarRead?.();let J=await bJ();return{...cJ(J,W),freshStorage:W}}function E7(j){let W=Math.floor(j.retryAfterSeconds/60),J=j.retryAfterSeconds%60,N=`Retry in ${W}m ${J}s.`;return j.modelName?`${j.modelName} weekly limit reached, no routable accounts. ${N}`:`Killswitch: no routable accounts. ${N}`}function S7(j){if(!j.requestModelId)return{isScopedDriven:!1};if(!Z1(j.mainQuota,j.storage))return{isScopedDriven:!1};let W=aW(j.mainQuota,j.requestModelId);if(!W)return{isScopedDriven:!1};if(!Number.isFinite(W.remainingPercent))return{isScopedDriven:!1};let J=eW(j.storage);if(W.remainingPercent<=J.scoped)return{isScopedDriven:!0,modelName:W.modelName,modelId:j.requestModelId};return{isScopedDriven:!1}}var q7=1,EW=!1;function H4(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function y(){return performance.now()}function j0(j){return Math.round(j*10)/10}function SW(j){return Math.floor(Math.random()*Math.max(0,j))}function j4(j){if(typeof j==="string")return j;if(j instanceof URL)return j.toString();return j.url}function W4(j,W){return W?.method??(j instanceof Request?j.method:void 0)}function qW(j){return j instanceof Error?j.message:String(j)}function A7(){if(EW||!1||!H4())return;EW=!0;let j=100,W=250,J=y()+j;setInterval(()=>{let N=y(),Z=N-J;if(J=N+j,Z<W)return;N0("[perf] opencode event_loop_lag",{lagMs:j0(Z),thresholdMs:W})},j).unref?.()}function f7(j){let W=y(),J={requestId:String(q7++),start:W,last:W,mark(N,Z){let G=y();if(H4())N0("[perf] opencode request stage",{requestId:J.requestId,stage:N,deltaMs:j0(G-J.last),totalMs:j0(G-J.start),...Z});J.last=G},done(N,Z){let G=y();if(H4())N0("[perf] opencode request done",{requestId:J.requestId,stage:N,deltaMs:j0(G-J.last),totalMs:j0(G-J.start),...Z});J.last=G}};if(H4())N0("[perf] opencode request start",{requestId:J.requestId,...j});return J}function v7(j,W){let J=/^msg_([0-9a-fA-F]{12})/.exec(j);if(!J)return;let N=BigInt(`0x${J[1]}`);if(N<=0n)return;let G=`msg_${(N-1n).toString(16).padStart(12,"0")}${"z".repeat(14)}`;if(W&&G<=W)return;return G}async function AW(j,W,J,N={}){let Z=j.client.session,G=await Mj(j.client,W),V={path:{id:W},body:{noReply:N.noReply??!0,parts:[{type:"text",text:J,ignored:!0}]}};if(N.beforeActiveAssistant){let B=G?.latestAssistantMessageId?v7(G.latestAssistantMessageId,G.latestUserMessageId):void 0;if(!B)throw Error("OpenCode assistant ordering is unavailable for the fallback notification.");V.body.messageID=B}if(G?.agent)V.body.agent=G.agent;if(G?.model)V.body.model=G.model;if(G?.variant)V.body.variant=G.variant;if(typeof Z?.promptAsync==="function"){await Z.promptAsync(V);return}if(typeof Z?.prompt==="function"){await Promise.resolve(Z.prompt(V));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function R7(){let j=Error(Q7);throw j[IW]=IW,j[w7]=!0,j.status=204,j.statusText=void 0,j.headers={},j.cookies={[TW]:TW,cookies:{}},j.body={[MW]:MW,_tag:"Empty"},j}function k7(j){if(j.sessionID==null)return!1;let W=j.model;return W?.providerID==="anthropic"||W?.api?.npm==="@ai-sdk/anthropic"||W?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function g7(j){if(j.some((W)=>W.includes("<use_parallel_tool_calls>")))return!1;return j.push(fW),!0}var h7={input:0,output:0,cache:{read:0,write:0}},y7="Fable content filter detected. Switched to Opus 4.8 for a 10-response recovery window while keeping the Fable cache warm.",m7="Fable recovery window complete. Returning to Fable 5.";function b7(j){if(A0(j))return"Opus 5 content filter detected. Switched to Opus 4.8 for a 10-response recovery window while keeping the Opus 5 cache warm.";return y7}function p7(j){if(A0(j))return"Opus 5 recovery window complete. Returning to Opus 5.";return m7}function Dj(j){if(A0(j))return"Opus 5";if(j==="claude-fable-5"||j.startsWith("claude-fable-5-"))return"Fable 5";if(j==="claude-opus-4-8"||j.startsWith("claude-opus-4-8-"))return"Opus 4.8";return j}function i7(j,W){return`Anthropic safety fallback active: ${Dj(j)} → ${Dj(W)}. Follow-up requests may remain on the fallback model for about one hour.`}function c7(j){return`Anthropic safety fallback ended. Returning to ${Dj(j)}.`}function l7(j){let W=j["claude-opus-4-8"]??j["claude-opus-4-5"]??Object.values(j)[0];if(!W)return j;return{...j,...Object.fromEntries(Object.values(EJ).map((J)=>[J.id,{...W,id:J.id,name:J.name,api:W.api?{...W.api,id:J.id}:void 0,cost:{input:y1.input,output:y1.output,cache:{read:y1.cacheRead,write:y1.cacheWrite5m}},limit:{...W.limit??{},context:MJ,output:xJ},capabilities:{...W.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:FJ}]))}}var d7=["low","medium","high","xhigh","max"];function u7(){return Object.fromEntries(d7.map((j)=>[j,{thinking:{type:"adaptive",display:"summarized"},effort:j}]))}function n7(j){return Object.fromEntries(Object.entries(j).map(([W,J])=>{let N=J.api?.id??J.id??W;return[W,A0(N)?{...J,variants:u7()}:J]}))}function o7(j){return Object.fromEntries(Object.entries(j).map(([W,J])=>[W,{...J,cost:h7}]))}var TN=async(j)=>{A7();let{client:W}=j,J=globalThis.fetch,N=gW(),Z=600000,G=50,V=new Map;function B(){let O=Date.now();for(let[$,D]of V)if(O-D.createdAt>Z)V.delete($)}function f(O,$){if(B(),V.size>=G){let D="",X=1/0;for(let[Y,K]of V)if(K.createdAt<X)X=K.createdAt,D=Y;if(D)V.delete(D)}V.set(O,$)}function r(O){B();let $=V.get(O);if(!$)return;if(Date.now()-$.createdAt>Z){V.delete(O);return}return $}let E;try{E=await k(N)}catch(O){let $=O instanceof Error?O.message:String(O);throw Error(`Failed to load account store: ${$}`,{cause:O instanceof Error?O:void 0})}let v=Rj(process.env.OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE),n=new x4,l=new Map,Y0=new Map,t=new Map,w0=new hJ({path:process.env.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE||kJ(N)}),F=new QJ({storage:E,onMainQuotaFetched:async(O,$,D,X)=>{try{let Y=await k(N)??T0(),K=tW(Y);if(K&&K.checkedAt>=X&&$J(K.quota,Y,K.checkedAt)>Date.now()){F.seedMainFromStorage(Y);return}Y.quota=Y.quota??{},Y.quota.mainQuota=O,Y.quota.mainQuotaCheckedAt=$,Y.quota.mainQuotaToken=D,Y.quota.mainLastQuotaApiError=void 0,await N1(Y,N,{mainQuota:!0})}catch(Y){h.warn("quota","failed to persist main quota",{error:Y instanceof Error?Y.message:String(Y)})}},onApiError:async(O)=>{try{let $=await k(N)??T0();$.quota=$.quota??{},$.quota.mainLastQuotaApiError=O,await N1($,N,{mainQuota:!0})}catch($){h.warn("quota","failed to persist backoff state",{error:$ instanceof Error?$.message:String($)})}}}),x0=new Map;async function n0(O,$,D){if(D?.aborted)return;let X=`${O}:${O4($)}`,Y=x0.get(X);if(!Y){let K=wJ({accessToken:$,fetchImpl:J,signal:D}).catch((M)=>{h.debug("quota","failed to hydrate account profile",{account:O,error:M instanceof Error?M.message:String(M)});return}).finally(()=>{if(x0.get(X)===K)x0.delete(X)});Y=K,x0.set(X,Y)}if(!D)return Y;return new Promise((K)=>{let M=!1,_=(b)=>{if(M)return;M=!0,D.removeEventListener("abort",I),K(b)},I=()=>_(void 0);if(D.addEventListener("abort",I,{once:!0}),D.aborted)I();Y.then(_)})}async function F0(O){try{if(O.accountId==="main"){let $=await X0?.();if($?.type!=="oauth"||$.access!==O.accessToken)return!1}return await hW({accountId:O.accountId,profile:O.profile,expectedTokenFingerprint:O4(O.accessToken)},N)}catch($){h.debug("quota","failed to persist account profile",{account:O.accountId,error:$ instanceof Error?$.message:String($)});return}}async function i0(O,$,D){if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return O;let X=Date.now();if($&&O.main?.profile&&!z4(O.main.profile,$))O.main.profile=void 0,F0({accountId:"main",accessToken:$,profile:void 0}).catch(()=>{});if($&&!r4(O.main?.profile,X)){let Y=await n0("main",$,D);if(Y)O.main={type:"opencode",provider:"anthropic",profile:Y},F0({accountId:"main",accessToken:$,profile:Y}).catch(()=>{})}for(let Y of O.accounts){if(D?.aborted)break;if(!$0(Y)||!Y.access)continue;let K=Y.access;if(Y.profile&&!z4(Y.profile,K))Y.profile=void 0,F0({accountId:Y.id,accessToken:K,profile:void 0}).catch(()=>{});if(r4(Y.profile,X))continue;let M=await n0(Y.id,K,D);if(M)Y.profile=M,F0({accountId:Y.id,accessToken:K,profile:M}).catch(()=>{})}return O}let Y1=new Set;async function E0(O,$){let D=await k(N)??T0();if(O.accountId==="main"){let Y;try{let K=await X0?.();if(K?.type==="oauth")Y=K.access}catch{}if(Y!==O.accessToken){h.trace("quota","skipped stale main response quota persistence");return}D.quota=D.quota??{},D.quota.mainQuota=$.quota,D.quota.mainQuotaCheckedAt=$.checkedAt,D.quota.mainQuotaToken=O4(O.accessToken),await N1(D,N,{mainQuota:!0});return}let X=D.accounts.find((Y)=>Y.id===O.accountId&&$0(Y)&&Y.access===O.accessToken);if(!X)return;X.quota=$.quota,await N1(D,N,{accounts:[O.accountId]})}function L1(O){h.warn("quota","failed to persist harvested response quota",{error:O instanceof Error?O.message:String(O)})}function G0(O){let $=O instanceof Error?O.name:typeof O,D=O instanceof Error?O.message:String(O),X=`${$}:${D}`;if(Y1.has(X))return;Y1.add(X),h.warn("quota","failed to normalize response quota headers",{error:D})}function v0(O,$){try{if(!UJ(O)){h.trace("quota","skipped non-quota response headers",{account:$.accountId});return}let D=PJ(O),X=$.accountId==="main"?F.pushMainFromHeaders($.accessToken,D):F.pushFallbackFromHeaders($.accountId,$.accessToken,D);E0($,X).catch(L1),t0().catch(()=>{}),h.debug("quota","harvested response quota",{account:$.accountId,fiveHourPercent:X.quota.five_hour?.usedPercent,sevenDayPercent:X.quota.seven_day?.usedPercent,source:"headers"})}catch(D){G0(D)}}let H0=new ZJ({quotaManager:F,onFallbackStorageChanged:()=>{t0().catch(()=>{})}});H0.startBackgroundRefresh();let c0=null,o0=new _J({directory:process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||KJ("opencode")}),R0=[],p0=new zJ({loadStorage:()=>k(N),onTrackedSessionsChanged:async(O)=>{await o0.publish(O),R0=await o0.list(O)},prepareHeaders:async(O,$)=>{let D,X=$.oauthAccountId;if(X&&X!=="main"){let Y=await k(N),K=Y?.accounts.find((_)=>_.id===X&&_.enabled!==!1&&$0(_));if(!K||!Y)throw Error(`OAuth account ${X} is unavailable for cache prewarm`);let M=K;try{M=await H0.refreshAccount(K,Y)}catch(_){h.warn("cachekeep","fallback token refresh failed",{accountId:X,error:_ instanceof Error?_.message:String(_)})}if(D=M.access,!D)throw Error(`OAuth account ${X} has no access token for cache prewarm`)}else{if(!X0)return O;let Y=await X0();if(Y.type!=="oauth")return O;if(!Y.access||Y.expires&&Y.expires<Date.now()){if(!c0)return O;Y.access=await c0()}D=Y.access}if(!D)return O;try{let Y=JSON.parse($.bodyText),K=await l4(D,typeof Y.model==="string"?Y.model:void 0);if(O.delete("anthropic-beta"),f1(O,D,{body:Y,identity:K}),O.set("anthropic-beta",q1(O.get("anthropic-beta"),[DJ])),Y.speed==="fast")a1(O)}catch{f1(O,D)}return O}}),r0=new Map;function C4(O){let $=O.plan.sessionId,D=A0(O.plan.requestedModel)?"Opus 5":"Fable",X=async()=>{let _=O.warmTarget;if(!_){h.debug("fable-fallback","cache warm skipped",{session:$,reason:"Opus response was not served by an OAuth route"});return}let I=CW(_.bodyText,O.plan.requestedModel);if(!I.ok){h.warn("fable-fallback","cache warm skipped",{session:$,reason:I.reason});return}try{let b=await p0.prewarmNow({sessionId:$,url:_.url,headers:_.headers,bodyText:I.bodyText,oauthAccountId:n.recoveryAccount(O.plan)??_.oauthAccountId});if(b.ok){h.debug("fable-fallback",`${D} cache warmed`,{session:$,remaining:n.remaining(O.plan),...b.usage&&{usage:b.usage}});return}h.warn("fable-fallback",`${D} cache warm skipped`,{session:$,status:b.status,reason:b.reason})}catch(b){h.warn("fable-fallback",`${D} cache warm failed`,{session:$,error:b instanceof Error?b.message:String(b)})}},{recoveryKey:Y}=O.plan,M=(r0.get(Y)??Promise.resolve()).then(X,X);return r0.set(Y,M),M.finally(()=>{if(r0.get(Y)===M)r0.delete(Y)}),M}async function L4(){return R0=await o0.list(p0.trackedSessions()),R0}if(g1({enabled:v1(E),mode:R1(E)}),_4(Z4(E)),P4(Y4(E)),!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)RW(X4(E)??"info");let s0=null;if(j.directory){let O=globalThis;if(O.__anthropicAuthRpcServer)await O.__anthropicAuthRpcServer.stop().catch(()=>{}),O.__anthropicAuthRpcServer=void 0;try{s0=await qj({dir:yJ(j.directory),drain:Ej,apply:O3}),O.__anthropicAuthRpcServer=s0}catch($){h.warn("rpc","failed to start",{error:$ instanceof Error?$.message:String($)})}}let U0={activeId:"main",route:"main"},k0=mJ(),P0=new Map;function B4(O,$,D){if(!O||!$)return O;let X={...O,accounts:O.accounts.map((M)=>{let _=$.accounts.find((I)=>I.id===M.id);if(!$0(M)||!_||!$0(_)||!M.access||_.access!==M.access)return M;return{...M,profile:_.profile}})},Y=O.main?.profile,K=O.main??$.main;if(D&&K&&(!Y||z4(Y,D)))X.main={...K,profile:$.main?.profile};return X}function m1(O,$){F.updateStorage(O),F.seedMainFromStorage(O,$.mainAccessToken),F.seedFallbacksFromAccounts((O?.accounts??[]).filter($0));let D=F.getMain($.mainAccessToken),X=F.getLastApiError(),Y=O?.refresh?.mainLastRefreshError;return{main:{quota:D?.quota??null,tierLabel:K4(O?.main?.profile),quotaBackedOff:F.isBackedOff(),quotaBackoffUntil:X?.nextRetryAt,refreshBackedOff:Y?O1(Y,$.mainRefreshToken,Date.now()):!1,refreshBackoffUntil:Y?.nextRetryAt},fallbacks:(O?.accounts??[]).filter((K)=>K.enabled!==!1&&$0(K)).map((K)=>({id:K.id,label:K.label,tierLabel:K4(K.profile),quota:K.access?F.getFallback(K.id,K.access)?.quota??null:null,needsReauth:K.lastRefreshError!=null&&O1(K.lastRefreshError,K.refresh,Date.now())&&P1(K.lastRefreshError),enabled:K.enabled!==!1})),activeId:$.activeId,route:$.route,relay:(()=>{let K=$j(O);return K?{enabled:!0,transport:K.transport??"http"}:null})(),fastMode:U4(),cacheKeep:{enabled:o4(O),window:n4(O)?"always":O?.cacheKeep?.startHour!=null&&O?.cacheKeep?.endHour!=null?`${O.cacheKeep.startHour}-${O.cacheKeep.endHour}`:void 0,trackedSessions:R0.length},fableRecoveries:P0.size>0?[...P0.values()]:void 0,lastUpdated:Date.now()}}function M0(O,$){let D=$.routingAuthoritative!==!1;if(D)U0={activeId:$.activeId,route:$.route};let X=m1(O,$);return pJ(X,k0,{routingAuthoritative:D,resolvePreservedRouting:D?void 0:async(Y)=>{let K=await x7(Y,()=>k(N),{activeId:X.activeId,route:X.route}),M=$.useHydratedProfiles?B4(K.freshStorage,O,$.mainAccessToken):K.freshStorage;return{activeId:K.activeId,route:K.route,state:m1(M,{...$,activeId:K.activeId,route:K.route})}},onRoutingResolved:D?void 0:(Y)=>{U0=Y}}).catch((Y)=>h.warn("sidebar","state write failed",{error:Y instanceof Error?Y.message:String(Y)}))}async function t0(){let O=await k(N),$,D;if(X0)try{let X=await X0();$=X.access,D=X.refresh}catch{}M0(O,{activeId:U0.activeId,route:U0.route,mainAccessToken:$,mainRefreshToken:D,routingAuthoritative:!1})}function lJ(O,$){if(!$)return;if(O?.quota?.enabled!==!0)return;if(F.getMain($))return;if(I4)return;I4=!0,F.refreshMain($).then(()=>t0()).catch(()=>{}).finally(()=>{I4=!1})}let X0=null,I4=!1,D1=null,b1=0;function dJ(O){let $=O?.refresh?.refreshBeforeExpiryMinutes??B7;return Math.max(iJ,$)*60000}function uJ(O){return O?.refresh?.enabled!==!1}async function Gj(O){if(!O)return;let $=await k(N),D=$?.refresh?.mainLastRefreshError;if(!$?.refresh||!D?.tokenHash)return;let X=G4(O);if(D.tokenHash===X)return;if(D.nextRetryAt&&D.nextRetryAt>Date.now()){N0("[refresh] opencode main oauth keeping backoff despite token rotation",{nextRetryAt:D.nextRetryAt,retryCount:D.retryCount,remainingMs:D.nextRetryAt-Date.now()});return}$.refresh.mainLastRefreshError=void 0,await N1($,N,{mainRefresh:!0}),N0("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:D.checkedAt,previousNextRetryAt:D.nextRetryAt,previousRetryCount:D.retryCount})}async function nJ(){let O=[],$;if(X0)try{let _=await X0();if(_.type==="oauth"&&_.access){$=_.access;let I=await F.refreshMain(_.access);O.push({name:"OpenCode anthropic",role:"main",quota:I})}else if(_.type==="oauth")O.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(_){let I=_ instanceof Error?_.message:String(_);O.push({name:"OpenCode anthropic",role:"main",error:I.includes("429")?"Usage API rate limited — try again in a moment":I})}let{storage:D,errors:X}=await H0.refreshQuotaForAllAccounts({force:!0}),Y=await i0(D??T0(),$,AbortSignal.timeout(3000)),K=O.find((_)=>_.role==="main");if(K)K.tierLabel=K4(Y.main?.profile);let M=new Map(X.map((_)=>[_.accountId,_.message]));if(O.push(...SJ(Y,M)),!X0)O.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return qJ({accounts:O,refreshedAt:Date.now()})}async function Xj(O){if(X0)try{let $=await X0();M0(O,{activeId:U0.activeId,route:U0.route,mainAccessToken:$.access,mainRefreshToken:$.refresh,routingAuthoritative:!1})}catch{}}function B1(O,$,D,X){if(P0.delete(O.sessionId),P0.set(O.sessionId,{...O,changedAt:Date.now()}),P0.size>128){let K=P0.keys().next().value;if(K)P0.delete(K)}if(M0($,{activeId:U0.activeId,route:U0.route,mainAccessToken:D.access,mainRefreshToken:D.refresh,routingAuthoritative:!1}),!X||E4(O.sessionId))return;let Y=Y0.get(O.sessionId)??[];if(Y.push(X),Y.length>4)Y.splice(0,Y.length-4);Y0.delete(O.sessionId),Y0.set(O.sessionId,Y);while(Y0.size>128){let K=Y0.keys().next().value;if(K)Y0.delete(K);else break}oJ(O.sessionId)}async function oJ(O){let $=j.client.session;if(typeof $?.status!=="function")return;try{let D=await Promise.resolve($.status()),X=D!==null&&typeof D==="object"?D:void 0,Y=X&&Object.hasOwn(X,"data")?X.data:X;if(Y===null||typeof Y!=="object"||Array.isArray(Y))return;let K=Y[O];if(K===void 0){await p1(O);return}if(K!==null&&typeof K==="object"&&K.type==="idle")await p1(O)}catch{}}function p1(O){let $=t.get(O);if($)return $;let D=(async()=>{while(!0){let Y=Y0.get(O)?.shift();if(!Y){Y0.delete(O);return}try{await AW(j,O,Y,{noReply:!0,beforeActiveAssistant:!0})}catch(K){h.warn("fable-fallback","Desktop notification failed",{session:O,error:K instanceof Error?K.message:String(K)})}}})();return t.set(O,D),D.finally(()=>{if(t.get(O)===D)t.delete(O)}),D}function rJ(O,$,D,X){if($.fallback&&$.targetModel){let Y=l.get(O.recoveryKey);l.delete(O.recoveryKey),l.set(O.recoveryKey,$.targetModel);while(l.size>128){let M=l.keys().next().value;if(M)l.delete(M);else break}let K=P0.get(O.sessionId);if(Y===$.targetModel&&K?.mode==="server"&&y0(K.requestedModelId)===y0(O.requestedModel)&&K.targetModelId===$.targetModel)return;h.info("fable-fallback","Anthropic server-side safety fallback active",{session:O.sessionId,requestedModel:O.requestedModel,targetModel:$.targetModel,handoff:$.handoff}),B1({sessionId:O.sessionId,mode:"server",remaining:0,requestedModelId:O.requestedModel,targetModelId:$.targetModel},D,X,i7(O.requestedModel,$.targetModel));return}if($.stopReason==="refusal"||!l.delete(O.recoveryKey))return;h.info("fable-fallback","Anthropic server-side safety fallback ended",{session:O.sessionId,requestedModel:O.requestedModel}),B1({sessionId:O.sessionId,mode:"fable",remaining:0,requestedModelId:O.requestedModel},D,X,c7(O.requestedModel))}function sJ(O,$,D){if(!O)return;for(let X of l.keys())if(X.startsWith(`${O}\x00`))l.delete(X);if(!P0.delete(O))return;M0($,{activeId:U0.activeId,route:U0.route,mainAccessToken:D.access,mainRefreshToken:D.refresh,routingAuthoritative:!1})}async function tJ(O){let $=YJ(O);if($.type==="enable"||$.type==="disable"){let K=$.type==="enable",M=await mW(K),_=R1(M);return g1({enabled:K,mode:_}),h.info("commands","cache enabled changed",{enabled:K}),V4({argumentsText:O,enabled:K,mode:_})}if($.type==="mode"){let K=await bW($.mode),M=v1(K);return g1({enabled:M,mode:$.mode}),h.info("commands","cache mode changed",{mode:$.mode}),V4({argumentsText:O,enabled:M,mode:$.mode})}let D=await k(N),X=v1(D),Y=R1(D);return g1({enabled:X,mode:Y}),V4({argumentsText:O,enabled:X,mode:Y})}async function aJ(O){let $=GJ(O),D=await k(N);if($.type==="window")D=await cW($.startHour,$.endHour),h.info("commands","cachekeep schedule changed",{schedule:`${$.startHour}-${$.endHour}`});else if($.type==="always")D=await lW(),h.info("commands","cachekeep schedule changed",{schedule:"always"});else if($.type==="disable")D=await dW(!1),h.info("commands","cachekeep enabled changed",{enabled:!1});else if($.type==="subagents")D=await nW($.enabled),h.info("commands","cachekeep subagents changed",{subagents:$.enabled});let X=u4(D),Y=await L4(),K=Y.length?Math.min(...Y.map((M)=>M.nextPrewarmAt)):void 0;return VJ({argumentsText:O,enabled:XJ(D),always:n4(D),window:X,hybridActive:o4(D),trackedSessions:Y.length,trackedSessionDetails:Y,nextPrewarmAt:K})}async function eJ(O){let $=LJ(O);if($.type==="enable"||$.type==="disable"){let Y=$.type==="enable";return await pW(Y),_4(Y),h.info("commands","dump changed",{enabled:Y}),a4({argumentsText:O,enabled:Y})}let D=await k(N),X=Z4(D);return _4(X),a4({argumentsText:O,enabled:X})}async function j3(O){let $=BJ(O);if($.type==="enable"||$.type==="disable"){let Y=$.type==="enable";return await iW(Y),P4(Y),h.info("commands","fast mode changed",{enabled:Y}),jj({argumentsText:O,enabled:Y})}let D=await k(N),X=Y4(D);return P4(X),jj({argumentsText:O,enabled:X})}async function W3(O,$){let D=vJ(O);if(D.type==="mode")return await fJ(D.mode,N),h.info("commands","routing mode changed",{mode:D.mode}),Yj({argumentsText:O,mode:D.mode});if(D.type==="reset"&&$)await w0.clear($),h.info("commands","sticky routing assignment reset");let X=await k(N);return Yj({argumentsText:O,mode:C1(X)})}async function J3(O){let $=TJ(O);if($.type==="level")return await sW($.level),h.info("commands","log level changed",{level:$.level}),Nj({argumentsText:O,level:$.level});let D=await k(N),X=X4(D)??"info";return Nj({argumentsText:O,level:X})}async function N3(O,$){let D=HJ(O);if(D.type==="add-apikey"){if(!D.apiKey)return{text:"API key is required",accounts:m0(await k(N)??T0())};let _=D.label?.trim()||void 0,I=Date.now(),b=D.baseURL?.trim()||"https://api.kie.ai/claude";if(!$4(b))return{text:"Invalid base URL. Must be an http(s) URL without embedded credentials.",accounts:m0(await k(N)??T0())};let Z0=D.authHeader??"authorization-bearer",V0={id:_||h4(),label:_||void 0,type:"api",apiKey:D.apiKey,baseURL:b,authHeader:Z0,enabled:!0,addedAt:I,lastUsed:I};await i4(V0,N),h.info("commands","account added",{id:V0.id,label:V0.label,type:"apikey"});let B0=await k(N);await Xj(B0);let a0=m0(B0??{version:1,accounts:[]});return{text:`API key account "${V0.label??V0.id}" added.`,accounts:a0}}if(D.type==="add-oauth-start"){let _=await J4("max"),I={state:_.state,verifier:_.verifier,redirectUri:_.redirectUri,createdAt:Date.now()};return f($??"default",I),{text:`Open this URL in your browser:
|
|
19
|
+
${_.url}`,knobs:{oauthUrl:_.url},accounts:m0(await k(N)??T0())}}if(D.type==="add-oauth-finish"){let _=$??"default",I=r(_);if(!I)return{text:"OAuth session expired. Please start again.",accounts:m0(await k(N)??T0())};try{let b=await N4(D.code,I.verifier,I.redirectUri,I.state);if(b.type==="failed")return{text:"OAuth authentication failed. Please check the code and try again.",accounts:m0(await k(N)??T0())};let Z0=Date.now(),V0={id:h4(),type:"oauth",label:D.label||void 0,access:b.access,refresh:b.refresh,expires:b.expires,enabled:!0,addedAt:Z0,lastUsed:Z0,lastRefreshedAt:Z0};await i4(V0,N),h.info("commands","account added",{id:V0.id,label:V0.label,type:"oauth"});let B0=await k(N);return await Xj(B0),{text:"OAuth account added.",accounts:m0(B0??T0())}}catch{return{text:"OAuth exchange failed due to a network error. Please try again.",accounts:m0(await k(N)??T0())}}finally{V.delete(_)}}let X=await k(N);if(D.type==="status"&&X){let _;if(X0)try{let I=await X0();if(I.type==="oauth")_=I.access}catch{}X=await i0(X,_,AbortSignal.timeout(3000))}let Y=CJ({argumentsText:O,storage:X??{version:1,accounts:[]}});if(Y.updated){if(Y.updated.action==="enable"||Y.updated.action==="disable"){let I=Y.updated.action==="enable";await OJ(Y.updated.id,I,N);let b=Y.updated.id,Z0=X?.accounts.find((V0)=>V0.id===b);h.info("commands",`account ${Y.updated.action}d`,{id:b,label:Z0?.label,enabled:I})}else if(Y.updated.action==="remove"){await JJ(Y.updated.id,N);let I=Y.updated.id,b=X?.accounts.find((Z0)=>Z0.id===I);h.info("commands","account removed",{id:I,label:b?.label})}else if(Y.updated.action==="reorder"){await NJ(Y.updated.newOrder??Y.updated.previousOrder??[],N);let I=Y.updated.id,b=X?.accounts.find((Z0)=>Z0.id===I);h.info("commands","account reordered",{id:I,label:b?.label})}let _=await k(N);if(X0)try{let I=await X0();M0(_,{activeId:U0.activeId,route:U0.route,mainAccessToken:I.access,mainRefreshToken:I.refresh,routingAuthoritative:!1})}catch{}}let K=await k(N),M=m0(K??{version:1,accounts:[]});return{text:Y.text,accounts:M}}async function Vj(O,$,D){if(O==="claude-quota")return{command:O,text:await nJ(),knobs:{}};if(O==="claude-logging"){let _=await J3($),I=await k(N);return{command:O,text:_,knobs:{level:X4(I)??"info"}}}if(O==="claude-account"){let _=await N3($,D),I={accounts:_.accounts};if("knobs"in _&&_.knobs)Object.assign(I,_.knobs);return{command:O,text:_.text,knobs:I}}if(O==="claude-routing"){let _=await W3($,D),I=await k(N);return{command:O,text:_,knobs:{mode:C1(I)}}}if(O==="claude-fast"){let _=await j3($),I=await k(N);return{command:O,text:_,knobs:{enabled:Y4(I)}}}if(O==="claude-dump"){let _=await eJ($),I=await k(N);return{command:O,text:_,knobs:{enabled:Z4(I)}}}if(O==="claude-cache"){let _=await tJ($),I=await k(N);return{command:O,text:_,knobs:{enabled:v1(I),mode:R1(I)}}}if(O==="claude-cachekeep"){let _=await aJ($),I=await k(N);return{command:O,text:_,knobs:{window:u4(I)}}}let X=await k(),Y=p4(X),K=(X?.accounts??[]).filter((_)=>_.enabled!==!1).map((_)=>_.id),M=IJ({argumentsText:$,config:Y,accountIds:K});if(M.updatedConfig){if(await WJ(M.updatedConfig),Y.enabled!==M.updatedConfig.enabled)h.info("commands","killswitch changed",{enabled:M.updatedConfig.enabled===!0});if(JSON.stringify(Y.main)!==JSON.stringify(M.updatedConfig.main)||JSON.stringify(Y.accounts)!==JSON.stringify(M.updatedConfig.accounts))h.info("commands","killswitch thresholds changed",{thresholds:M.updatedConfig.main??M.updatedConfig.accounts})}return{command:O,text:M.text,knobs:{config:p4(await k()),accountIds:K}}}async function O3(O){let $=await Vj(O.command,O.arguments,O.sessionId);return{text:$.text,knobs:$.knobs}}function $3(O,$=10){let D=Math.max(0,Math.min(Math.round(O/100*$),$));return"█".repeat(D)+"░".repeat($-D)}function i1(O,$){return`${O} ${$3($)} ${String(Math.round($)).padStart(3)}%`}function zj(O){if(!O)return"";let $=new Date(O).getTime();if(Number.isNaN($))return"";let D=$-Date.now();if(D<=0)return"resets now";let X=Math.floor(D/60000);if(X<1)return"resets <1m";if(X<60)return`resets ${X}m`;let Y=Math.floor(X/60),K=X%60;return K>0?`resets ${Y}h${K}m`:`resets ${Y}h`}function Z3(O,$,D){let X=[],Y=0;if(O){let{five_hour:_,seven_day:I}=O;if(_||I){let Z0=D==="main"?"active":"idle",V0=zj(_?.resetsAt),B0=[`main · ${Z0}${V0?` (${V0})`:""}`];if(_)B0.push(i1("5h",_.usedPercent)),Y=Math.max(Y,_.usedPercent);if(I)B0.push(i1("7d",I.usedPercent)),Y=Math.max(Y,I.usedPercent);X.push(B0.join(`
|
|
20
|
+
`))}}if($?.length)for(let _ of $){let I=_.quota;if(!I)continue;let{five_hour:b,seven_day:Z0}=I;if(!b&&!Z0)continue;let V0=_.label||"alt",a0=D===_.id?"active":"idle",e0=zj(b?.resetsAt),j1=[`${V0} · ${a0}${e0?` (${e0})`:""}`];if(b)j1.push(i1("5h",b.usedPercent)),Y=Math.max(Y,b.usedPercent);if(Z0)j1.push(i1("7d",Z0.usedPercent)),Y=Math.max(Y,Z0.usedPercent);X.push(j1.join(`
|
|
21
|
+
`))}if(!X.length)return;let K=X.join(`
|
|
14
22
|
|
|
15
|
-
`),
|
|
23
|
+
`),M=Y>=90?"error":Y>=70?"warning":"info";W.tui?.showToast?.({body:{title:"Claude Quota",message:K,variant:M,duration:M==="error"?8000:5000}})?.catch?.(()=>{})}return{event:async({event:O})=>{let $=O,D=$.properties?.info,X=$.properties?.sessionID??D?.sessionID??D?.id;if(!X)return;if($.type==="session.status"&&$.properties?.status?.type==="idle")await p1(X);if($.type==="message.updated"&&D?.role==="assistant"&&typeof D.time?.completed==="number")await p1(X);if($.type==="session.deleted")P0.delete(X),Y0.delete(X)},config:async(O)=>{O.command={...O.command??{},[c4]:{template:c4,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[s4]:{template:s4,description:"Manage fallback accounts — list, enable/disable, reorder, remove, or add (API key or OAuth)."},[d4]:{template:d4,description:"Keep hybrid Claude cache warm always or during a local time window."},[Oj]:{template:Oj,description:"Show current Claude OAuth quota usage for all accounts."},[t4]:{template:t4,description:"Show or toggle Anthropic request dump capture for debugging."},[e4]:{template:e4,description:"Show or toggle Anthropic fast mode for supported Opus models."},[Jj]:{template:Jj,description:"Show or set the plugin log level (error, warn, info, debug, trace)."},[Zj]:{template:Zj,description:"Show or change Claude account routing: main-first, fallback-first, or sticky-balanced."},[Wj]:{template:Wj,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."}}},"experimental.chat.system.transform":async(O,$)=>{if(!k7(O))return;g7($.system)},provider:{id:"anthropic",async models(O,$){let D=n7(l7(O.models));if($.auth?.type!=="oauth"||!kW(E??{}))return D;return o7(D)}},"command.execute.before":async(O)=>{if(!["claude-account","claude-cache","claude-cachekeep","claude-quota","claude-dump","claude-fast","claude-routing","claude-killswitch","claude-logging"].includes(O.command))return;let D=O.command,X=await Vj(D,O.arguments,O.sessionID);if(D==="claude-quota"){let Y=await k(),K=X0?await X0().catch(()=>{return}):void 0;M0(Y,{activeId:U0.activeId,route:U0.route,mainAccessToken:K?.access,mainRefreshToken:K?.refresh,routingAuthoritative:!1})}if(E4(O.sessionID))Fj(X,O.sessionID);else await AW(j,O.sessionID,X.text);R7()},auth:{provider:"anthropic",async loader(O,$){X0=O;let D=await O();if(D.type==="oauth"){let K=function(){if(D1)clearInterval(D1),D1=null;let z=async()=>{try{let Q=await k(N);if(!uJ(Q))return;let g=await O();if(g.type!=="oauth")return;if(await Gj(g.refresh),!g.expires)return;let q=g.expires-Date.now(),T=dJ(Q);if(q>T)return;if(N0("[refresh] opencode main oauth background due",{expiresInMs:q,refreshBeforeMs:T}),g.refresh&&O1(Q?.refresh?.mainLastRefreshError,g.refresh,Date.now())){N0("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:Q?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:Q?.refresh?.mainLastRefreshError?.retryCount,expiresInMs:q});return}if(g.refresh&&Q?.refresh?.mainRefreshLeaseUntil&&Q.refresh.mainRefreshLeaseUntil>Date.now()&&Q.refresh.mainRefreshLeaseTokenHash===G4(g.refresh))return;await Y();let m=await O();N0("[refresh] opencode main oauth refreshed in background",{newExpiresInMs:m.expires?m.expires-Date.now():void 0})}catch(Q){h.warn("refresh","opencode main oauth refresh failed",{message:Q instanceof Error?Q.message:String(Q)})}};if(D1=setInterval(()=>{z()},H7+SW(C7)),"unref"in D1)D1.unref()},_=function(z,Q){if(z instanceof Request&&z.body)return!1;return Q==null||typeof Q==="string"},I=function(z){if(typeof z!=="string")return;try{let Q=JSON.parse(z);return typeof Q.model==="string"?Q.model:void 0}catch{return}},b=function(z){return z.has("x-parent-session-id")},Z0=function(z){return z.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(z)},V0=function(z){return z?.quota?.enabled===!0},a0=function(z,Q){if(z.delete("authorization"),z.delete("x-api-key"),Q.authHeader==="x-api-key")z.set("x-api-key",Q.apiKey??"");else z.set("Authorization",`Bearer ${Q.apiKey??""}`);z.set("Content-Type","application/json")},c1=function(z){return F.getFallback(z.id,z.access)?.quota??z.quota},T4=function(z){return["five_hour","seven_day"].some((Q)=>(z?.[Q]?.remainingPercent??1)<=0)},Kj=function(z,Q){return z.status===429||Q},l1=function(z){if(!z)return!1;let Q=F.getMain(z);return Boolean(Q&&Q.refreshAfter>Date.now()&&T4(Q.quota))},X=null;async function Y(){if(!X)X=(async()=>{let g=null,q=null,T=null;async function m(S){let R=await k(N)??T0();R.refresh=R.refresh??{},S(R),await N1(R,N,{mainRefresh:!0})}async function L(S){let R=Date.now()+L7;while(Date.now()<R){await new Promise((w)=>setTimeout(w,xW+SW(xW)));let U=await O();if(U.type!=="oauth"||!U.access)continue;if((U.access!==S.access||U.refresh!==S.refresh||(U.expires??0)>(S.expires??0)+60000)&&(!U.expires||U.expires>Date.now()))return N0("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:U.expires?U.expires-Date.now():void 0}),U.access}return null}for(let S=0;S<=2;S++){let R=null;try{if(S>0){let u=500*2**(S-1);await new Promise((z0)=>setTimeout(z0,u))}if(R=await O(),!R.refresh)throw Error("Token refresh failed: missing refresh token");let U=await k(N),H=G4(R.refresh),w=U?.refresh?.mainLastRefreshError;if(N0("[refresh] opencode main oauth refresh check",{attempt:S,expiresInMs:R.expires?R.expires-Date.now():void 0,hasBackoff:Boolean(w),backoffActive:w?O1(w,R.refresh,Date.now()):!1,retryCount:w?.retryCount,nextRetryAt:w?.nextRetryAt}),w&&O1(w,R.refresh,Date.now()))throw N0("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:w.nextRetryAt,retryCount:w.retryCount}),Error(y4(w,Date.now()));if(U?.refresh?.mainRefreshLeaseUntil&&U.refresh.mainRefreshLeaseUntil>Date.now()&&U.refresh.mainRefreshLeaseTokenHash===H){N0("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:U.refresh.mainRefreshLeaseUntil});let u=await L(R);if(u)return u;throw Error("Claude OAuth refresh is already in progress")}let P=await yW({name:"opencode-main-oauth-refresh",ttlMs:120000,renew:!0});if(!P){N0("[refresh] opencode main oauth refresh skipped file lock");let u=await L(R);if(u)return u;throw Error("Claude OAuth refresh is already in progress")}T=P.release,g=h4(),q=H,await m((u)=>{u.refresh=u.refresh??{},u.refresh.mainRefreshLeaseId=g??void 0,u.refresh.mainRefreshLeaseUntil=Date.now()+120000,u.refresh.mainRefreshLeaseTokenHash=H});let d=await k(N);if(N0("[refresh] opencode main oauth refresh lease acquired",{attempt:S,leaseUntil:Date.now()+120000}),d?.refresh?.mainRefreshLeaseId!==g||d.refresh.mainRefreshLeaseTokenHash!==H)throw Error("Claude OAuth refresh is already in progress");N0("[refresh] opencode main oauth refresh request start",{attempt:S});let C=await vW({refreshToken:R.refresh,maxRetries:0});return await W.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:C.refresh,access:C.access,expires:C.expires}}),await m((u)=>{if(!u?.refresh)return;if(u.refresh.mainLastRefreshError=void 0,u.refresh.mainRefreshLeaseId===g)u.refresh.mainRefreshLeaseId=void 0,u.refresh.mainRefreshLeaseUntil=void 0,u.refresh.mainRefreshLeaseTokenHash=void 0}),N0("[refresh] opencode main oauth refresh succeeded",{attempt:S,expiresInMs:C.expires-Date.now()}),C.access}catch(U){let H=U instanceof Error&&(U.message.includes("fetch failed")||("code"in U)&&(U.code==="ECONNRESET"||U.code==="ECONNREFUSED"||U.code==="ETIMEDOUT"||U.code==="UND_ERR_CONNECT_TIMEOUT"));if(S<2&&(H||(()=>{let P=U.status;return typeof P==="number"&&P>=500})()))continue;N0("[refresh] opencode main oauth refresh attempt failed",{attempt:S,error:U instanceof Error?U.message:String(U),transient:H});let w=R?.refresh;if(w&&U.isRefreshError)await m((P)=>{P.refresh=P.refresh??{},P.refresh.mainLastRefreshError=oW({error:U,now:Date.now(),refreshToken:w,previous:P.refresh.mainLastRefreshError})});throw U}finally{if(g)await m((U)=>{if(!U?.refresh)return;if(U.refresh.mainRefreshLeaseId===g&&U.refresh.mainRefreshLeaseTokenHash===q)U.refresh.mainRefreshLeaseId=void 0,U.refresh.mainRefreshLeaseUntil=void 0,U.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await T?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{X=null});return X}c0=Y,K(),F.seedFallbacksFromAccounts((E?.accounts??[]).filter($0));let M=await F7(N);if(await M0(M.freshStorage,{activeId:M.activeId,route:M.route,mainAccessToken:D.access,mainRefreshToken:D.refresh,routingAuthoritative:!1}),process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION!=="1")i0(E??T0(),D.access).then((z)=>{M0(z,{activeId:"main",route:"main",mainAccessToken:D.access,mainRefreshToken:D.refresh,routingAuthoritative:!1,useHydratedProfiles:!0})}).catch(()=>{});async function B0(z,Q){if(!z.body||z.status!==200)return Q?.mark("inspect_stream_skip",{status:z.status}),{response:z,rateLimited:!1};if(z.headers.get("x-cortexkit-relay-optimistic")==="true")return Q?.mark("inspect_stream_skip",{status:z.status,reason:"optimistic_relay"}),{response:z,rateLimited:!1};let g=y(),q=z.body.getReader(),T=[],m=new TextDecoder,L="",S=0;while(!L.includes(`
|
|
16
24
|
|
|
17
|
-
`)&&m.length<65536){let{done:L,value:X}=await v.read();if(L)break;if(U.push(X),Q+=X.byteLength,m+=S.decode(X,{stream:!0}),j0(m))break}if(j0(m)){await v.cancel().catch(()=>{});try{v.releaseLock()}catch{}let L=new ReadableStream({start(X){for(let C of U)X.enqueue(C);X.close()}});return P?.mark("inspect_stream_first_event",{ms:s(A()-q),bytes:Q,rateLimited:!0}),{response:new Response(L,{status:V.status,statusText:V.statusText,headers:V.headers}),rateLimited:!0}}let T=new ReadableStream({start(L){for(let X of U)L.enqueue(X)},async pull(L){let{done:X,value:C}=await v.read();if(X){L.close();return}L.enqueue(C)},cancel(L){return v.cancel(L)}});return P?.mark("inspect_stream_first_event",{ms:s(A()-q),bytes:Q,rateLimited:!1}),{response:new Response(T,{status:V.status,statusText:V.statusText,headers:V.headers}),rateLimited:!1}}async function n0(V,P,q,v,U="api_fallback",S,m){if(m?.plan.downgraded)m.warmTarget=void 0,m.opusCacheAnchor=void 0;let Q=A(),T=m1(V,P),L=T.get("x-session-affinity")||T.get("x-opencode-session"),X=u(T);T.delete("x-parent-session-id"),T.delete("x-session-affinity"),T.delete("x-opencode-session");let C=P?.body,H=typeof C==="string"?C.length:void 0;if(C&&typeof C==="string"){let N0=A(),J0=(()=>{if(!JW())return!1;try{return H1(JSON.parse(C).model)}catch{return!1}})();if(C=await LW(C,{cache1hEnabled:!X&&G1(),cache1hMode:X1(),fastModeEnabled:J0,perf:(t,G0)=>v?.mark(`rewrite_body_${t}`,{route:U,...G0})}),u0(T,q),T.set("anthropic-beta",Q1(T.get("anthropic-beta"),[])),J0)b1(T);v?.mark("rewrite_body",{route:U,ms:s(A()-N0),originalBytes:H,rewrittenBytes:C.length,cacheEnabled:!X&&G1(),cacheMode:X1(),fastModeEnabled:J0,subagent:X})}else u0(T,q);let b=QW(V,{baseURL:q.baseURL}),x=A(),h;try{h=await fetch(b.input,{...P,body:C,headers:T,...CW()&&{tls:{rejectUnauthorized:!1}}})}catch(N0){if(typeof C==="string")await T1({affinity:L,route:U,error:Gj(N0),bodyText:C,url:b.url?.toString()??i1(b.input),method:l1(V,P),headers:T});throw N0}if(typeof C==="string")await T1({affinity:L,route:U,status:h.status,bodyText:C,url:b.url?.toString()??i1(b.input),method:l1(V,P),headers:T});return v?.mark("send_headers_received",{route:U,ms:s(A()-x),status:h.status,relayConfigured:!1,totalSendWithAccessMs:s(A()-Q),baseURL:q.baseURL}),h}async function o0(V,P,q,v,U="unknown",S,m="main",Q){let T=A(),L=S,X=async()=>{return L??=await f(J),L},C=m1(V,P),H=C.get("x-session-affinity")||C.get("x-opencode-session"),b=u(C);C.delete("x-parent-session-id"),C.delete("x-session-affinity"),C.delete("x-opencode-session");let x=P?.body,h;if(x&&typeof x==="string"){let p=A();try{let g=JSON.parse(x);if(typeof g.model==="string")h=g.model}catch{}v?.mark("model_parse_for_identity",{route:U,ms:s(A()-p),bodyBytes:x.length})}let N0=A(),J0=await SW(q,h);v?.mark("resolve_claude_code_identity",{route:U,ms:s(A()-N0),hasAccountUuid:Boolean(J0.accountUuid)});let t=typeof x==="string"?x.length:void 0;if(x&&typeof x==="string"){let p=A(),g=(()=>{if(!JW())return!1;try{return H1(JSON.parse(x).model)}catch{return!1}})(),_0=!b&&G1(),Q0=X1(),F0=Q?.plan.downgraded&&Q.plan.standbyCacheAnchor?.oauthAccountId===m?Q.plan.standbyCacheAnchor:void 0;if(x=await LW(x,{cache1hEnabled:_0,cache1hMode:Q0,fastModeEnabled:g,identity:J0,hybridStandbyAnchor:F0,perf:(z0,f0)=>{if(v?.mark(`rewrite_body_${z0}`,{route:U,...f0}),z0==="cache_strategy"&&f0?.standbyBridgeApplied===!0&&Q&&!Q.standbyBridgeLogged)Q.standbyBridgeLogged=!0,k.info("fable-fallback","restored standby Opus cache bridge",{session:Q.plan.sessionId,distanceBlocks:f0?.standbyDistanceBlocks})}}),Q?.plan.downgraded&&_0&&Q0==="hybrid"){let z0=r4(x);Q.opusCacheAnchor=z0?{...z0,oauthAccountId:m}:void 0}let c=A();try{L1(C,q,{body:JSON.parse(x),identity:J0}),v?.mark("set_oauth_headers_body_parse",{route:U,ms:s(A()-c),bodyBytes:x.length,parsed:!0})}catch{L1(C,q,{identity:J0}),v?.mark("set_oauth_headers_body_parse",{route:U,ms:s(A()-c),bodyBytes:x.length,parsed:!1})}if(g)b1(C);v?.mark("rewrite_body",{route:U,ms:s(A()-p),originalBytes:t,rewrittenBytes:x.length,cacheEnabled:!b&&G1(),cacheMode:X1(),fastModeEnabled:g,subagent:b})}let G0=QW(V);if(Q&&typeof x==="string")Q.warmTarget={url:G0.url?.toString()??G0.input.toString(),headers:new Headers(C),bodyText:x,oauthAccountId:m};if(typeof x==="string"&&G1()&&X1()==="hybrid"){let p=await X();if(!b||Fj(p)){let g=A(),_0=g0.track({sessionId:H,url:G0.url?.toString()??G0.input.toString(),headers:C,bodyText:x,storage:p,cacheMode:"hybrid",oauthAccountId:m});v?.mark("cachekeep_track",{session:H,ms:s(A()-g),tracked:_0.tracked,reason:_0.tracked?void 0:_0.reason,bodyBytes:x.length})}}let P1=!1,R1=async()=>{P1=!0;try{let p=await fetch(G0.input,{...P,body:x,headers:C,...CW()&&{tls:{rejectUnauthorized:!1}}});if(typeof x==="string")await T1({affinity:H,route:U,status:p.status,bodyText:x,url:G0.url?.toString()??i1(G0.input),method:l1(V,P),headers:C});return p}catch(p){if(typeof x==="string")await T1({affinity:H,route:U,error:Gj(p),bodyText:x,url:G0.url?.toString()??i1(G0.input),method:l1(V,P),headers:C});throw p}},E=cW(await X()),R={accountId:m,accessToken:q},d=A(),K0=await XN({config:E,input:G0.input,init:P,headers:C,body:x,fallback:R1,affinity:H,optimisticResponse:E?.transport==="websocket",onResponseHeaders:(p)=>v0(p,R)});if(v?.mark("send_headers_received",{route:U,ms:s(A()-d),status:K0.status,relayConfigured:E!=null,totalSendWithAccessMs:s(A()-T)}),P1)v0(K0.headers,R);return K0}async function gN(V){if(!V)return!1;try{return await F.refreshMain(V),A1(V)}catch{return!1}}async function z1(V,P={}){let q=await S0.getUsableFallbackAccounts(V,{modelId:P.modelId}),v=new Map(q.map((S)=>[S.id,S])),U=[];for(let S of V?.accounts??[]){if(W0(S)){let m=v.get(S.id);if(m)U.push(m);continue}if(P.includeApiRoutes===!0&&Y1(S)&&S.enabled!==!1&&S.apiKey&&n1(S.baseURL))U.push(S)}if(!t0(V))return U;return U.filter((S)=>W0(S)?e0(q1(S),V,S.id,P.modelId):!0)}async function eW(V){let P=F.getMain(V.mainAccessToken),q=P?.quota;if(!V1(P?.quota,V.storage,Date.now(),V.requestedModelId))try{q=await F.refreshMain(V.mainAccessToken)}catch{}let v=await S0.getUsableFallbackAccounts(V.storage,{modelId:V.requestedModelId}),U=await f(J)??V.storage,S=new Map(v.map((X)=>[X.id,X])),m=[];if(!Z1(U?.refresh?.mainLastRefreshError))m.push({id:R0,access:V.mainAccessToken,quota:q,order:0});for(let[X,C]of(U?.accounts??[]).entries()){if(C.enabled===!1||!W0(C))continue;let H=S.get(C.id)??C;if(!H.access||Z1(H.lastRefreshError))continue;let b=q1(H);if(!V1(b,U,Date.now(),V.requestedModelId))try{b=await F.refreshFallback(H.id,H.access)}catch{}m.push({id:H.id,access:H.access,quota:b,order:X+1,account:H})}let Q=new Set(m.flatMap((X)=>{let C=X.id===R0?U?.refresh?.mainLastRefreshError:X.account?.lastRefreshError;if(Z1(C))return[];if(V1(X.quota,U,Date.now(),V.requestedModelId)&&$W({quota:X.quota,modelId:V.requestedModelId}).action==="migrate")return[];if(t0(U)&&!e0(X.quota,U,X.id===R0?void 0:X.id,V.requestedModelId))return[];return[X.id]})),T=new Set(v.map((X)=>X.id)),L=m.flatMap((X)=>{if(!X.quota)return[];let C=X.id===R0?void 0:X.id;return F1(X.quota,U)&&TW(X.quota,V.requestedModelId)&&(!t0(U)||e0(X.quota,U,C,V.requestedModelId))&&(X.id===R0||T.has(X.id))?[{accountId:X.id,quota:X.quota,order:X.order}]:[]});return{storage:U,allRoutes:m,candidates:L,retainAccountIds:Q}}async function W4(V,P,q,v=!1){let U=new Headers(V.headers);if(U.set("retry-after",String(zN(P,q))),v)return await V.body?.cancel().catch(()=>{}),U.set("content-type","application/json"),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account five-hour quota resets shortly; retaining session affinity."}}),{status:429,headers:U});return new Response(V.body,{status:V.status,statusText:V.statusText,headers:U})}async function w1(V,P,q,v,U,S,m){if(!q.length)return U??null;let Q=m?.returnLastOnExhausted??!0;await U?.body?.cancel().catch(()=>{});let T=U??null;for(let[L,X]of q.entries()){let C;if(Y1(X)){if(!X.apiKey)continue;C=await n0(V,P,X,S,`api_fallback_${L}`,v,m?.fableRequest)}else{let b=X.access;if(!b)continue;C=await o0(V,P,b,S,`fallback_${L}`,v,X.id,m?.fableRequest)}T=C;let H=s1(C.status,v);if(!H){let b=await C0(C,S);C=b.response,T=C,H=b.rateLimited}if(!H){if(await S0.markUsed(X),await m?.onSuccess?.(X),W0(X)&&X.access&&F.shouldRefreshOnRequestCount(S1))F.refreshFallback(X.id,X.access).then(()=>m?.onSuccess?.(X)).catch(()=>{});return C}if(L<q.length-1||!Q)await C.body?.cancel().catch(()=>{})}return Q?T:null}async function yN(V,P,q,v,U,S,m,Q,T,L){if(!_(V,P?.body))return q;let X=A(),C=S??await f(J);if(U?.mark("fallback_load_storage",{ms:s(A()-X),cached:!!S}),!(C?.accounts??[]).some((t)=>t.enabled!==!1&&(W0(t)||Y1(t)&&Boolean(t.apiKey)&&n1(t.baseURL))))return q;let b=q,x=s1(b.status,C),h=tW(b,!1);if(!x){let t=await C0(b,U);b=t.response,x=t.rateLimited,h=tW(b,t.rateLimited)}if(!x)return b;let N0=!1;if(v)N0=v.some(Y1);else if(h)N0=await gN(m);let J0=v;if(!J0){let t=A();J0=await z1(C,{includeApiRoutes:N0,modelId:T}),U?.mark("fallback_get_accounts",{ms:s(A()-t),accounts:J0.length})}if(t0(C)){let t=J0.length;if(J0=J0.filter((G0)=>W0(G0)?e0(q1(G0),C,G0.id,T):!0),J0.length<t)a("[killswitch] filtered fallbacks",{before:t,after:J0.length})}return await w1(V,P,J0,C,b,U,{onSuccess:Q,fableRequest:L})??b}return{apiKey:"",async fetch(V,P){let q=m1(V,P),v=q.get("x-session-affinity")||q.get("x-opencode-session"),U=l.plan(v,P?.body);if(U&&!U.downgraded){let E=y0.get(U.sessionId);if(E)await E,U=l.plan(v,P?.body)}let S=U?{plan:U}:void 0;if(U?.downgraded)P={...P,body:U.bodyText};let m=P?.body,Q=sJ({bodyBytes:typeof m==="string"?m.length:void 0}),T=(E)=>Wj(E,{perf:(R,d)=>Q.mark(R,d),...!U?.downgraded&&U?{onContentFilter:()=>{if(!S?.warmTarget)return k.debug("fable-fallback","content filter recovery unavailable for non-OAuth route",{session:U.sessionId}),!1;let R=l.activate(U,S.warmTarget.oauthAccountId);k.info("fable-fallback","content filter detected; switching session to Opus 4.8",{session:U.sessionId,remaining:R}),XW({sessionId:U.sessionId,mode:"opus",remaining:R},H,X,N3)}}:{},...U?.downgraded&&S?{onComplete:(R)=>{let d=l.complete(U,S.opusCacheAnchor);if(!d.counted)return;k.info("fable-fallback","Opus 4.8 turn completed",{session:U.sessionId,finishReason:R,remaining:d.remaining}),XW({sessionId:U.sessionId,mode:"opus",remaining:d.remaining},H,X);let K0=j1(S);if(d.remaining===0){let p=()=>{if(l.remaining(U.sessionId)!==0)return;XW({sessionId:U.sessionId,mode:"fable",remaining:0},H,X,J3)};K0.then(p,p)}}}:{}}),L=A(),X=await O();if(Q.mark("get_auth",{ms:s(A()-L),authType:X.type,hasAccess:Boolean(X.access)}),X.type!=="oauth"){let E=await fetch(V,P);return Q.done("non_oauth_passthrough",{status:E.status}),E}await oW(X.refresh);let C=A(),H=await f();if(Q.mark("load_storage",{ms:s(A()-C)}),F.updateStorage(H),F.seedMainFromStorage(H,X.access),F.seedFallbacksFromAccounts((H?.accounts??[]).filter(W0)),!U)IN(v,H,X);let b=_(V,P?.body),x=B(P?.body);if(b)S1++;if(b&&X.access&&(!X.expires||X.expires>Date.now()))v1(H,X.access);let h=(E,R)=>B0(H,{activeId:E,route:R,mainAccessToken:X.access,mainRefreshToken:X.refresh}),N0;if(b&&v&&D1(H)==="sticky-balanced"&&X.access){let E=U?.effectiveModel??x,R=KN(E),d=g0.trackedOAuthRoute(v),K0=U?.cacheAccountId??(d?d.oauthAccountId??R0:void 0),p=!1;try{let g=await eW({storage:H,mainAccessToken:X.access,requestedModelId:E}),_0=(z0)=>$0.resolve({sessionId:v,family:R,modelId:E,candidates:g.candidates,retainAccountIds:g.retainAccountIds,storage:g.storage,inputBytes:typeof P?.body==="string"?Buffer.byteLength(P.body):1,preferredAccountId:K0,excludeAccountIds:z0}),Q0=g.allRoutes.length===0||g.allRoutes.some((z0)=>!z0.quota||!V1(z0.quota,g.storage,Date.now(),E)),F0=await _0();if(!F0&&Q0)throw Error("Sticky-balanced routing is waiting for current OAuth quota snapshots");let c=g.allRoutes.find((z0)=>z0.id===F0?.accountId);if(F0&&c){if(p=!0,U?.downgraded&&l.bindRecoveryAccount(U,c.id))k.info("fable-fallback","rebound recovery to migrated sticky account",{accountId:c.id});let z0=(e)=>o0(V,P,e.access,Q,`sticky:${e.id}`,g.storage,e.id,S),f0=async(e,V0,w0=!0)=>{if(w0&&e.account)await S0.markUsed(e.account);return h(e.id,"sticky-balanced"),Q.done("return_sticky_balanced",{status:V0.status,accountId:e.id,created:F0?.created,migrated:F0?.migrated}),T(V0)},j4=async(e)=>{let V0=e,w0=s1(e.status,g.storage),q0=!1;if(!w0){let i0=await C0(e,Q);V0=i0.response,q0=i0.rateLimited,w0=i0.rateLimited}return{response:V0,routeFailure:w0,streamingRateLimit:q0}},N4=V1(c.quota,g.storage,Date.now(),E)?$W({quota:c.quota,modelId:E}):void 0;if(N4?.action==="hold")return f0(c,await W4(new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account five-hour quota resets shortly; retaining session affinity."}}),{status:429,headers:{"content-type":"application/json"}}),v,N4.retryAfterSeconds),!1);let X0=await j4(await z0(c)),DW=!1;if(!X0.routeFailure)return f0(c,X0.response);if(X0.response.status===401){let e=c.id;try{if(e===R0)X.access=await Z(),c={...c,access:X.access};else if(c.account&&g.storage){let V0=await S0.refreshAccount(c.account,g.storage,{force:!0});if(V0.access)c={...c,access:V0.access,account:V0}}if(await X0.response.body?.cancel().catch(()=>{}),X0=await j4(await z0(c)),!X0.routeFailure)return f0(c,X0.response);DW=X0.response.status===401}catch(V0){let w0=await f(J),q0=e===R0?w0?.refresh?.mainLastRefreshError:w0?.accounts.find((i0)=>i0.id===e&&W0(i0))?.lastRefreshError;if(!Z1(q0))throw V0;DW=!0}}let J4=X0.response.status===403||DW;if(X0.response.status===429||X0.streamingRateLimit){let e;try{e=c.id===R0?await F.refreshMain(c.access):await F.refreshFallback(c.id,c.access)}catch{e=void 0}let V0=$W({quota:e,modelId:E});if(Q.mark("sticky_quota_failure",{accountId:c.id,action:V0.action,reason:V0.reason}),V0.action==="hold")return f0(c,await W4(X0.response,v,V0.retryAfterSeconds,X0.streamingRateLimit));J4=V0.action==="migrate"}if(J4){let e=c.id;if(g=await eW({storage:g.storage,mainAccessToken:X.access,requestedModelId:E}),g.candidates.filter((w0)=>w0.accountId!==e).length>0){await X0.response.body?.cancel().catch(()=>{}),F0=await _0(new Set([e]));let w0=g.allRoutes.find((q0)=>q0.id===F0?.accountId);if(F0&&w0){if(c=w0,U?.downgraded)l.bindRecoveryAccount(U,c.id);return f0(c,await z0(c))}}else if((X0.response.status===429||X0.streamingRateLimit)&&A1(X.access)){let w0=(await z1(g.storage,{includeApiRoutes:!0,modelId:E})).filter(Y1);if(w0.length>0){let q0=await w1(V,P,w0,g.storage,X0.response,Q,{onSuccess:(i0)=>h(i0.id,"sticky-balanced"),fableRequest:S});if(q0)return Q.done("return_sticky_api_fallback",{status:q0.status}),T(q0)}}}return f0(c,X0.response)}}catch(g){if(Q.mark("sticky_balanced_error",{error:g instanceof Error?g.message:String(g)}),p)throw g;let _0=g instanceof Error?g:Error(String(g));throw Object.assign(_0,{code:"ECONNRESET",syscall:"sticky-routing"}),_0}}if(b&&D1(H)==="fallback-first")try{let E=A();N0=await z1(H,{includeApiRoutes:A1(X.access),modelId:x}),Q.mark("fallback_first_get_accounts",{ms:s(A()-E),accounts:N0.length});let R=await w1(V,P,N0,H,void 0,Q,{returnLastOnExhausted:!1,onSuccess:(d)=>h(d.id,"fallback-first"),fableRequest:S});if(R)return Q.done("return_fallback_first",{status:R.status}),T(R);N0=void 0}catch(E){Q.mark("fallback_first_error",{error:E instanceof Error?E.message:String(E)})}if(!X.access||!X.expires||X.expires<Date.now()){let R=(await f())?.refresh?.mainLastRefreshError;if(X.refresh&&R&&a0(R,X.refresh,Date.now()))throw a("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:R.nextRetryAt,retryCount:R.retryCount,expiresInMs:X.expires?X.expires-Date.now():void 0}),Error(FW(R,Date.now()));a("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(X.access),expiresInMs:X.expires?X.expires-Date.now():void 0,expiredAgoMs:X.expires&&X.expires<Date.now()?Date.now()-X.expires:void 0});let d=A();X.access=await Z(),Q.mark("refresh_main_access",{ms:s(A()-d)})}if(!X.access)throw Q.done("missing_access_error"),Error("OAuth access token is missing after refresh");function J0(){if(H?.quota?.showToasts!==!0)return;let E=F.getMain();if(!E)return;let R=(H?.accounts??[]).filter((p)=>p.enabled!==!1&&W0(p)).map((p)=>({...p,quota:F.getFallback(p.id,p.access)?.quota??p.quota})),d=F1(E.quota,H),K0;if(d)K0="main";else K0=R.find((p)=>F1(p.quota,H))?.id??"main";kN(E.quota,R,K0)}if(b&&Z0(H))try{let E=A(),R=F.getMain(X.access),d=R?.quota;if(!d)d=await F.refreshMain(X.access),R=F.getMain(X.access),J0();else if(F.needsRefresh(S1,x))if(VW(d)||IW(d,x))d=await F.refreshMain(X.access),R=F.getMain(X.access);else F.refreshMain(X.access).then(()=>{c0().catch(()=>{}),J0()}).catch(()=>{});B0(H,{activeId:"main",route:"main",mainAccessToken:X.access,mainRefreshToken:X.refresh});let K0=F1(d,H)&&TW(d,x);if(Q.mark("main_quota_for_routing",{ms:s(A()-E),passes:K0,model:x,modelScopedExhausted:IW(d,x)}),!K0){let p=A();N0=await z1(H,{includeApiRoutes:Boolean(R&&R.refreshAfter>Date.now()&&VW(R.quota)),modelId:x}),Q.mark("preselect_fallback_accounts",{ms:s(A()-p),accounts:N0.length});let g=await w1(V,P,N0,H,void 0,Q,{onSuccess:(_0)=>h(_0.id,"fallback"),fableRequest:S});if(g)return Q.done("return_preselected_fallback",{status:g.status}),T(g)}}catch(E){Q.mark("main_quota_for_routing_error",{error:E instanceof Error?E.message:String(E)})}let t=F.getMain(X.access)?.quota;if(H?.quota?.failClosedOnUnknownQuota&&!t&&F.isBackedOff()){let E=F.getLastApiError(),R=E?xj(E,Date.now()):"Quota API unavailable";return a("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:E?.nextRetryAt,retryCount:E?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:R}}),{status:429,headers:{"content-type":"application/json","retry-after":String(E?.nextRetryAt?Math.max(1,Math.ceil((E.nextRetryAt-Date.now())/1000)):60)}})}if(t0(H)){if(F.needsRefresh(S1,x))try{let R=(H?.accounts??[]).filter((d)=>d.enabled!==!1&&W0(d)&&Boolean(d.access));await Promise.all([F.refreshMain(X.access),F.refreshAllFallbacks(R)])}catch(R){a("[quota] killswitch refresh failed",{error:R instanceof Error?R.message:String(R),backedOff:F.isBackedOff()})}t=F.getMain(X.access)?.quota}if(t0(H)&&!e0(t,H,void 0,x)){let R=_(V,P?.body)?await z1(H,{includeApiRoutes:A1(X.access),modelId:x}):[];if(R.length>0){a("[route] skipping main (killswitch), trying fallbacks");let Q0=await w1(V,P,R,H,void 0,Q,{onSuccess:(F0)=>h(F0.id,"fallback")});if(Q0)return Q.done("return_killswitch_fallback",{status:Q0.status}),T(Q0)}let d=Date.now(),K0=(H?.accounts??[]).filter((Q0)=>Q0.enabled!==!1&&W0(Q0)).map((Q0)=>({...Q0,quota:q1(Q0)})),p=nJ({mainQuota:t,requestModelId:x,storage:H}),g=qj(t,K0,d,p.isScopedDriven?p.modelId:void 0),_0=uJ({retryAfterSeconds:g,...p.isScopedDriven&&{modelName:p.modelName}});return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:_0}}),{status:429,headers:{"content-type":"application/json","retry-after":String(g)}})}let G0=await o0(V,P,X.access,Q,"main",H,"main",S),P1=!1,R1=await yN(V,P,G0,N0,Q,H,X.access,(E)=>{P1=!0,h(E.id,"fallback")},x,S);if(!P1)h("main","main");return Q.done("return_response",{status:R1.status}),T(R1)}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let O=await d1("max");return{url:O.url,instructions:"Paste the authorization code here:",method:"code",callback:async($)=>{return c1($,O.verifier,O.redirectUri,O.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let O=await d1("console");return{url:O.url,instructions:"Paste the authorization code here:",method:"code",callback:async($)=>{let G=await c1($,O.verifier,O.redirectUri,O.state);if(G.type==="failed")return G;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${G.access}`}}).then((Z)=>Z.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{nJ as resolveScopedDrivenBlock,uJ as formatKillswitchBlockMessage,f3 as AnthropicAuthPlugin};
|
|
25
|
+
`)&&L.length<65536){let{done:U,value:H}=await q.read();if(U)break;if(T.push(H),S+=H.byteLength,L+=m.decode(H,{stream:!0}),Z0(L))break}if(Z0(L)){await q.cancel().catch(()=>{});try{q.releaseLock()}catch{}let U=new ReadableStream({start(H){for(let w of T)H.enqueue(w);H.close()}});return Q?.mark("inspect_stream_first_event",{ms:j0(y()-g),bytes:S,rateLimited:!0}),{response:new Response(U,{status:z.status,statusText:z.statusText,headers:z.headers}),rateLimited:!0}}let R=new ReadableStream({start(U){for(let H of T)U.enqueue(H)},async pull(U){let{done:H,value:w}=await q.read();if(H){U.close();return}U.enqueue(w)},cancel(U){return q.cancel(U)}});return Q?.mark("inspect_stream_first_event",{ms:j0(y()-g),bytes:S,rateLimited:!1}),{response:new Response(R,{status:z.status,statusText:z.statusText,headers:z.headers}),rateLimited:!1}}async function e0(z,Q,g,q,T="api_fallback",m,L){if(L?.plan.downgraded)L.warmTarget=void 0,L.opusCacheAnchor=void 0;let S=y(),R=t1(z,Q),U=R.get("x-session-affinity")||R.get("x-opencode-session"),H=b(R);R.delete("x-parent-session-id"),R.delete("x-session-affinity"),R.delete("x-opencode-session");let w=Q?.body,P=typeof w==="string"?w.length:void 0;if(w&&typeof w==="string"){let z0=y(),o=(()=>{if(!U4())return!1;try{return A1(JSON.parse(w).model)}catch{return!1}})();if(w=await k4(w,{cache1hEnabled:!H&&Q1(),cache1hMode:w1(),fastModeEnabled:o,perf:(e,W0)=>q?.mark(`rewrite_body_${e}`,{route:T,...W0})}),a0(R,g),R.set("anthropic-beta",q1(R.get("anthropic-beta"),[])),o)a1(R);q?.mark("rewrite_body",{route:T,ms:j0(y()-z0),originalBytes:P,rewrittenBytes:w.length,cacheEnabled:!H&&Q1(),cacheMode:w1(),fastModeEnabled:o,subagent:H})}else a0(R,g);let d=v4(z,{baseURL:g.baseURL}),C=y(),u;try{u=await fetch(d.input,{...Q,body:w,headers:R,...f4()&&{tls:{rejectUnauthorized:!1}}})}catch(z0){if(typeof w==="string")await h1({affinity:U,route:T,error:qW(z0),bodyText:w,url:d.url?.toString()??j4(d.input),method:W4(z,Q),headers:R});throw z0}if(typeof w==="string")await h1({affinity:U,route:T,status:u.status,bodyText:w,url:d.url?.toString()??j4(d.input),method:W4(z,Q),headers:R});return q?.mark("send_headers_received",{route:T,ms:j0(y()-C),status:u.status,relayConfigured:!1,totalSendWithAccessMs:j0(y()-S),baseURL:g.baseURL}),u}async function j1(z,Q,g,q,T="unknown",m,L="main",S){let R=y(),U=m,H=async()=>{return U??=await k(N),U},w=t1(z,Q),P=w.get("x-session-affinity")||w.get("x-opencode-session"),d=b(w);w.delete("x-parent-session-id"),w.delete("x-session-affinity"),w.delete("x-opencode-session");let C=Q?.body,u;if(C&&typeof C==="string"){let x=y();try{let p=JSON.parse(C);if(typeof p.model==="string")u=p.model}catch{}q?.mark("model_parse_for_identity",{route:T,ms:j0(y()-x),bodyBytes:C.length})}let z0=y(),o=await l4(g,u);q?.mark("resolve_claude_code_identity",{route:T,ms:j0(y()-z0),hasAccountUuid:Boolean(o.accountUuid)});let e=typeof C==="string"?C.length:void 0;if(C&&typeof C==="string"){let x=y(),p=(()=>{if(!U4())return!1;try{return A1(JSON.parse(C).model)}catch{return!1}})(),D0=!d&&Q1(),J0=w1(),i=S?.plan.downgraded&&S.plan.standbyCacheAnchor?.oauthAccountId===L?S.plan.standbyCacheAnchor:void 0;if(C=await k4(C,{cache1hEnabled:D0,cache1hMode:J0,fastModeEnabled:p,identity:o,hybridStandbyAnchor:i,serverSideFallbackEnabled:v==="server",perf:(Q0,I0)=>{if(q?.mark(`rewrite_body_${Q0}`,{route:T,...I0}),Q0==="cache_strategy"&&I0?.standbyBridgeApplied===!0&&S&&!S.standbyBridgeLogged)S.standbyBridgeLogged=!0,h.info("fable-fallback","restored standby Opus cache bridge",{session:S.plan.sessionId,distanceBlocks:I0?.standbyDistanceBlocks})}}),S?.plan.downgraded&&D0&&J0==="hybrid"){let Q0=PW(C);S.opusCacheAnchor=Q0?{...Q0,oauthAccountId:L}:void 0}let S0=y();try{f1(w,g,{body:JSON.parse(C),identity:o}),q?.mark("set_oauth_headers_body_parse",{route:T,ms:j0(y()-S0),bodyBytes:C.length,parsed:!0})}catch{f1(w,g,{identity:o}),q?.mark("set_oauth_headers_body_parse",{route:T,ms:j0(y()-S0),bodyBytes:C.length,parsed:!1})}if(p)a1(w);q?.mark("rewrite_body",{route:T,ms:j0(y()-x),originalBytes:e,rewrittenBytes:C.length,cacheEnabled:!d&&Q1(),cacheMode:w1(),fastModeEnabled:p,subagent:d})}let W0=v4(z);if(S&&typeof C==="string")S.warmTarget={url:W0.url?.toString()??W0.input.toString(),headers:new Headers(w),bodyText:C,oauthAccountId:L};if(typeof C==="string"&&Q1()&&w1()==="hybrid"){let x=await H();if(!d||uW(x)){let p=y(),D0=p0.track({sessionId:P,url:W0.url?.toString()??W0.input.toString(),headers:w,bodyText:C,storage:x,cacheMode:"hybrid",oauthAccountId:L});q?.mark("cachekeep_track",{session:P,ms:j0(y()-p),tracked:D0.tracked,reason:D0.tracked?void 0:D0.reason,bodyBytes:C.length})}}let M1=!1,W1=async()=>{M1=!0;try{let x=await fetch(W0.input,{...Q,body:C,headers:w,...f4()&&{tls:{rejectUnauthorized:!1}}});if(typeof C==="string")await h1({affinity:P,route:T,status:x.status,bodyText:C,url:W0.url?.toString()??j4(W0.input),method:W4(z,Q),headers:w});return x}catch(x){if(typeof C==="string")await h1({affinity:P,route:T,error:qW(x),bodyText:C,url:W0.url?.toString()??j4(W0.input),method:W4(z,Q),headers:w});throw x}},x1=$j(await H()),F1={accountId:L,accessToken:g},d1=y(),A=await AJ({config:x1,input:W0.input,init:Q,headers:w,body:C,fallback:W1,affinity:P,optimisticResponse:x1?.transport==="websocket",onResponseHeaders:(x)=>v0(x,F1)});if(q?.mark("send_headers_received",{route:T,ms:j0(y()-d1),status:A.status,relayConfigured:x1!=null,totalSendWithAccessMs:j0(y()-R)}),M1)v0(A.headers,F1);return A}async function Y3(z){if(!z)return!1;try{return await F.refreshMain(z),l1(z)}catch{return!1}}async function I1(z,Q={}){let g=await H0.getUsableFallbackAccounts(z,{modelId:Q.modelId}),q=new Map(g.map((m)=>[m.id,m])),T=[];for(let m of z?.accounts??[]){if($0(m)){let L=q.get(m.id);if(L)T.push(L);continue}if(Q.includeApiRoutes===!0&&U1(m)&&m.enabled!==!1&&m.apiKey&&$4(m.baseURL))T.push(m)}if(!$1(z))return T;return T.filter((m)=>$0(m)?Z1(c1(m),z,m.id,Q.modelId):!0)}async function _j(z){let Q=F.getMain(z.mainAccessToken),g=Q?.quota;if(!H1(Q?.quota,z.storage,Date.now(),z.requestedModelId))try{g=await F.refreshMain(z.mainAccessToken)}catch{}let q=await H0.getUsableFallbackAccounts(z.storage,{modelId:z.requestedModelId}),T=await k(N)??z.storage,m=new Map(q.map((H)=>[H.id,H])),L=[];if(!P1(T?.refresh?.mainLastRefreshError))L.push({id:b0,access:z.mainAccessToken,quota:g,order:0});for(let[H,w]of(T?.accounts??[]).entries()){if(w.enabled===!1||!$0(w))continue;let P=m.get(w.id)??w;if(!P.access||P1(P.lastRefreshError))continue;let d=c1(P);if(!H1(d,T,Date.now(),z.requestedModelId))try{d=await F.refreshFallback(P.id,P.access)}catch{}L.push({id:P.id,access:P.access,quota:d,order:H+1,account:P})}let S=new Set(L.flatMap((H)=>{let w=H.id===b0?T?.refresh?.mainLastRefreshError:H.account?.lastRefreshError;if(P1(w))return[];if(H1(H.quota,T,Date.now(),z.requestedModelId)&&Q4({quota:H.quota,modelId:z.requestedModelId}).action==="migrate")return[];if($1(T)&&!Z1(H.quota,T,H.id===b0?void 0:H.id,z.requestedModelId))return[];return[H.id]})),R=new Set(q.map((H)=>H.id)),U=L.flatMap((H)=>{if(!H.quota)return[];let w=H.id===b0?void 0:H.id;return k1(H.quota,T)&&b4(H.quota,z.requestedModelId)&&(!$1(T)||Z1(H.quota,T,w,z.requestedModelId))&&(H.id===b0||R.has(H.id))?[{accountId:H.id,quota:H.quota,order:H.order}]:[]});return{storage:T,allRoutes:L,candidates:U,retainAccountIds:S}}async function Uj(z,Q,g,q=!1){let T=new Headers(z.headers);if(T.set("retry-after",String(gJ(Q,g))),q)return await z.body?.cancel().catch(()=>{}),T.set("content-type","application/json"),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account five-hour quota resets shortly; retaining session affinity."}}),{status:429,headers:T});return new Response(z.body,{status:z.status,statusText:z.statusText,headers:T})}async function T1(z,Q,g,q,T,m,L){if(!g.length)return T??null;let S=L?.returnLastOnExhausted??!0;await T?.body?.cancel().catch(()=>{});let R=T??null;for(let[U,H]of g.entries()){let w;if(U1(H)){if(!H.apiKey)continue;w=await e0(z,Q,H,m,`api_fallback_${U}`,q,L?.fableRequest)}else{let d=H.access;if(!d)continue;w=await j1(z,Q,d,m,`fallback_${U}`,q,H.id,L?.fableRequest)}R=w;let P=D4(w.status,q);if(!P){let d=await B0(w,m);w=d.response,R=w,P=d.rateLimited}if(!P){if(await H0.markUsed(H),await L?.onSuccess?.(H),$0(H)&&H.access&&F.shouldRefreshOnRequestCount(b1))F.refreshFallback(H.id,H.access).then(()=>L?.onSuccess?.(H)).catch(()=>{});return w}if(U<g.length-1||!S)await w.body?.cancel().catch(()=>{})}return S?R:null}async function D3(z,Q,g,q,T,m,L,S,R,U){if(!_(z,Q?.body))return g;let H=y(),w=m??await k(N);if(T?.mark("fallback_load_storage",{ms:j0(y()-H),cached:!!m}),!(w?.accounts??[]).some((e)=>e.enabled!==!1&&($0(e)||U1(e)&&Boolean(e.apiKey)&&$4(e.baseURL))))return g;let d=g,C=D4(d.status,w),u=Kj(d,!1);if(!C){let e=await B0(d,T);d=e.response,C=e.rateLimited,u=Kj(d,e.rateLimited)}if(!C)return d;let z0=!1;if(q)z0=q.some(U1);else if(u)z0=await Y3(L);let o=q;if(!o){let e=y();o=await I1(w,{includeApiRoutes:z0,modelId:R}),T?.mark("fallback_get_accounts",{ms:j0(y()-e),accounts:o.length})}if($1(w)){let e=o.length;if(o=o.filter((W0)=>$0(W0)?Z1(c1(W0),w,W0.id,R):!0),o.length<e)N0("[killswitch] filtered fallbacks",{before:e,after:o.length})}return await T1(z,Q,o,w,d,T,{onSuccess:S,fableRequest:U})??d}return{apiKey:"",async fetch(z,Q){let g=t1(z,Q),q=g.get("x-session-affinity")||g.get("x-opencode-session"),T=I(Q?.body),m=v==="server"&&X1(T)?T:void 0,L=n.plan(q,Q?.body);if(v==="legacy"&&L&&!L.downgraded){let A=r0.get(L.recoveryKey);if(A)await A,L=n.plan(q,Q?.body)}let S=L?{plan:L}:void 0;if(v==="legacy"&&L?.downgraded)Q={...Q,body:L.bodyText};let R=Q?.body,U=f7({bodyBytes:typeof R==="string"?R.length:void 0}),H=(A)=>BW(A,{perf:(x,p)=>U.mark(x,p),contentFilterModel:L?.requestedModel,...v==="legacy"&&!L?.downgraded&&L?{onContentFilter:()=>{if(!S?.warmTarget)return h.debug("fable-fallback","content filter recovery unavailable for non-OAuth route",{session:L.sessionId}),!1;let x=n.activate(L,S.warmTarget.oauthAccountId);h.info("fable-fallback","content filter detected; switching session to Opus 4.8",{session:L.sessionId,requestedModel:L.requestedModel,remaining:x}),B1({sessionId:L.sessionId,mode:"opus",remaining:x,requestedModelId:L.requestedModel},C,P,b7(L.requestedModel))}}:{},...v==="legacy"&&L?.downgraded&&S?{onComplete:(x)=>{let p=n.complete(L,S.opusCacheAnchor);if(!p.counted)return;h.info("fable-fallback","Opus 4.8 turn completed",{session:L.sessionId,requestedModel:L.requestedModel,finishReason:x,remaining:p.remaining}),B1({sessionId:L.sessionId,mode:"opus",remaining:p.remaining,requestedModelId:L.requestedModel},C,P);let D0=C4(S);if(p.remaining===0){let J0=()=>{if(n.remaining(L)!==0)return;B1({sessionId:L.sessionId,mode:"fable",remaining:0,requestedModelId:L.requestedModel},C,P,p7(L.requestedModel))};D0.then(J0,J0)}}}:{},...m?{serverSideFallbackModel:m,...L?{onServerSideFallbackOutcome:(x)=>rJ(L,x,C,P)}:{}}:{}}),w=y(),P=await O();if(U.mark("get_auth",{ms:j0(y()-w),authType:P.type,hasAccess:Boolean(P.access)}),P.type!=="oauth"){let A=await fetch(z,Q);return U.done("non_oauth_passthrough",{status:A.status}),A}await Gj(P.refresh);let d=y(),C=await k();U.mark("load_storage",{ms:j0(y()-d)}),F.updateStorage(C),F.seedMainFromStorage(C,P.access),F.seedFallbacksFromAccounts((C?.accounts??[]).filter($0));let u=q?P0.get(q):void 0;if(!L||v==="server"&&u?.requestedModelId&&y0(u.requestedModelId)!==y0(L.requestedModel))sJ(q,C,P);let z0=_(z,Q?.body),o=I(Q?.body);if(z0)b1++;if(z0&&P.access&&(!P.expires||P.expires>Date.now()))lJ(C,P.access);let e=(A,x)=>M0(C,{activeId:A,route:x,mainAccessToken:P.access,mainRefreshToken:P.refresh}),W0;if(z0&&q&&C1(C)==="sticky-balanced"&&P.access){let A=L?.effectiveModel??o,x=RJ(A),p=p0.trackedOAuthRoute(q),D0=L?.cacheAccountId??(p?p.oauthAccountId??b0:void 0),J0=!1;try{let i=await _j({storage:C,mainAccessToken:P.access,requestedModelId:A}),S0=(g0)=>w0.resolve({sessionId:q,family:x,modelId:A,candidates:i.candidates,retainAccountIds:i.retainAccountIds,storage:i.storage,inputBytes:typeof Q?.body==="string"?Buffer.byteLength(Q.body):1,preferredAccountId:D0,excludeAccountIds:g0}),Q0=i.allRoutes.length===0||i.allRoutes.some((g0)=>!g0.quota||!H1(g0.quota,i.storage,Date.now(),A)),I0=await S0();if(!I0&&Q0)throw Error("Sticky-balanced routing is waiting for current OAuth quota snapshots");let s=i.allRoutes.find((g0)=>g0.id===I0?.accountId);if(I0&&s){if(J0=!0,L?.downgraded&&n.bindRecoveryAccount(L,s.id))h.info("fable-fallback","rebound recovery to migrated sticky account",{accountId:s.id});let g0=(O0)=>j1(z,Q,O0.access,U,`sticky:${O0.id}`,i.storage,O0.id,S),G1=async(O0,_0,C0=!0)=>{if(C0&&O0.account)await H0.markUsed(O0.account);return e(O0.id,"sticky-balanced"),U.done("return_sticky_balanced",{status:_0.status,accountId:O0.id,created:I0?.created,migrated:I0?.migrated}),H(_0)},Pj=async(O0)=>{let _0=O0,C0=D4(O0.status,i.storage),h0=!1;if(!C0){let l0=await B0(O0,U);_0=l0.response,h0=l0.rateLimited,C0=l0.rateLimited}return{response:_0,routeFailure:C0,streamingRateLimit:h0}},Qj=H1(s.quota,i.storage,Date.now(),A)?Q4({quota:s.quota,modelId:A}):void 0;if(Qj?.action==="hold")return G1(s,await Uj(new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account five-hour quota resets shortly; retaining session affinity."}}),{status:429,headers:{"content-type":"application/json"}}),q,Qj.retryAfterSeconds),!1);let K0=await Pj(await g0(s)),M4=!1;if(!K0.routeFailure)return G1(s,K0.response);if(K0.response.status===401){let O0=s.id;try{if(O0===b0)P.access=await Y(),s={...s,access:P.access};else if(s.account&&i.storage){let _0=await H0.refreshAccount(s.account,i.storage,{force:!0});if(_0.access)s={...s,access:_0.access,account:_0}}if(await K0.response.body?.cancel().catch(()=>{}),K0=await Pj(await g0(s)),!K0.routeFailure)return G1(s,K0.response);M4=K0.response.status===401}catch(_0){let C0=await k(N),h0=O0===b0?C0?.refresh?.mainLastRefreshError:C0?.accounts.find((l0)=>l0.id===O0&&$0(l0))?.lastRefreshError;if(!P1(h0))throw _0;M4=!0}}let wj=K0.response.status===403||M4;if(K0.response.status===429||K0.streamingRateLimit){let O0;try{O0=s.id===b0?await F.refreshMain(s.access):await F.refreshFallback(s.id,s.access)}catch{O0=void 0}let _0=Q4({quota:O0,modelId:A});if(U.mark("sticky_quota_failure",{accountId:s.id,action:_0.action,reason:_0.reason}),_0.action==="hold")return G1(s,await Uj(K0.response,q,_0.retryAfterSeconds,K0.streamingRateLimit));wj=_0.action==="migrate"}if(wj){let O0=s.id;if(i=await _j({storage:i.storage,mainAccessToken:P.access,requestedModelId:A}),i.candidates.filter((C0)=>C0.accountId!==O0).length>0){await K0.response.body?.cancel().catch(()=>{}),I0=await S0(new Set([O0]));let C0=i.allRoutes.find((h0)=>h0.id===I0?.accountId);if(I0&&C0){if(s=C0,L?.downgraded)n.bindRecoveryAccount(L,s.id);return G1(s,await g0(s))}}else if((K0.response.status===429||K0.streamingRateLimit)&&l1(P.access)){let C0=(await I1(i.storage,{includeApiRoutes:!0,modelId:A})).filter(U1);if(C0.length>0){let h0=await T1(z,Q,C0,i.storage,K0.response,U,{onSuccess:(l0)=>e(l0.id,"sticky-balanced"),fableRequest:S});if(h0)return U.done("return_sticky_api_fallback",{status:h0.status}),H(h0)}}}return G1(s,K0.response)}}catch(i){if(U.mark("sticky_balanced_error",{error:i instanceof Error?i.message:String(i)}),J0)throw i;let S0=i instanceof Error?i:Error(String(i));throw Object.assign(S0,{code:"ECONNRESET",syscall:"sticky-routing"}),S0}}if(z0&&C1(C)==="fallback-first")try{let A=y();W0=await I1(C,{includeApiRoutes:l1(P.access),modelId:o}),U.mark("fallback_first_get_accounts",{ms:j0(y()-A),accounts:W0.length});let x=await T1(z,Q,W0,C,void 0,U,{returnLastOnExhausted:!1,onSuccess:(p)=>e(p.id,"fallback-first"),fableRequest:S});if(x)return U.done("return_fallback_first",{status:x.status}),H(x);W0=void 0}catch(A){U.mark("fallback_first_error",{error:A instanceof Error?A.message:String(A)})}if(!P.access||!P.expires||P.expires<Date.now()){let x=(await k())?.refresh?.mainLastRefreshError;if(P.refresh&&x&&O1(x,P.refresh,Date.now()))throw N0("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:x.nextRetryAt,retryCount:x.retryCount,expiresInMs:P.expires?P.expires-Date.now():void 0}),Error(y4(x,Date.now()));N0("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(P.access),expiresInMs:P.expires?P.expires-Date.now():void 0,expiredAgoMs:P.expires&&P.expires<Date.now()?Date.now()-P.expires:void 0});let p=y();P.access=await Y(),U.mark("refresh_main_access",{ms:j0(y()-p)})}if(!P.access)throw U.done("missing_access_error"),Error("OAuth access token is missing after refresh");function M1(){if(C?.quota?.showToasts!==!0)return;let A=F.getMain();if(!A)return;let x=(C?.accounts??[]).filter((J0)=>J0.enabled!==!1&&$0(J0)).map((J0)=>({...J0,quota:F.getFallback(J0.id,J0.access)?.quota??J0.quota})),p=k1(A.quota,C),D0;if(p)D0="main";else D0=x.find((J0)=>k1(J0.quota,C))?.id??"main";Z3(A.quota,x,D0)}if(z0&&V0(C))try{let A=y(),x=F.getMain(P.access),p=x?.quota;if(!p)p=await F.refreshMain(P.access),x=F.getMain(P.access),M1();else if(F.needsRefresh(b1,o))if(T4(p)||m4(p,o))p=await F.refreshMain(P.access),x=F.getMain(P.access);else F.refreshMain(P.access).then(()=>{t0().catch(()=>{}),M1()}).catch(()=>{});M0(C,{activeId:"main",route:"main",mainAccessToken:P.access,mainRefreshToken:P.refresh});let D0=k1(p,C)&&b4(p,o);if(U.mark("main_quota_for_routing",{ms:j0(y()-A),passes:D0,model:o,modelScopedExhausted:m4(p,o)}),!D0){let J0=y();W0=await I1(C,{includeApiRoutes:Boolean(x&&x.refreshAfter>Date.now()&&T4(x.quota)),modelId:o}),U.mark("preselect_fallback_accounts",{ms:j0(y()-J0),accounts:W0.length});let i=await T1(z,Q,W0,C,void 0,U,{onSuccess:(S0)=>e(S0.id,"fallback"),fableRequest:S});if(i)return U.done("return_preselected_fallback",{status:i.status}),H(i)}}catch(A){U.mark("main_quota_for_routing_error",{error:A instanceof Error?A.message:String(A)})}let W1=F.getMain(P.access)?.quota;if(C?.quota?.failClosedOnUnknownQuota&&!W1&&F.isBackedOff()){let A=F.getLastApiError(),x=A?rW(A,Date.now()):"Quota API unavailable";return N0("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:A?.nextRetryAt,retryCount:A?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:x}}),{status:429,headers:{"content-type":"application/json","retry-after":String(A?.nextRetryAt?Math.max(1,Math.ceil((A.nextRetryAt-Date.now())/1000)):60)}})}if($1(C)){if(F.needsRefresh(b1,o))try{let x=(C?.accounts??[]).filter((p)=>p.enabled!==!1&&$0(p)&&Boolean(p.access));await Promise.all([F.refreshMain(P.access),F.refreshAllFallbacks(x)])}catch(x){N0("[quota] killswitch refresh failed",{error:x instanceof Error?x.message:String(x),backedOff:F.isBackedOff()})}W1=F.getMain(P.access)?.quota}if($1(C)&&!Z1(W1,C,void 0,o)){let x=_(z,Q?.body)?await I1(C,{includeApiRoutes:l1(P.access),modelId:o}):[];if(x.length>0){N0("[route] skipping main (killswitch), trying fallbacks");let Q0=await T1(z,Q,x,C,void 0,U,{onSuccess:(I0)=>e(I0.id,"fallback")});if(Q0)return U.done("return_killswitch_fallback",{status:Q0.status}),H(Q0)}let p=Date.now(),D0=(C?.accounts??[]).filter((Q0)=>Q0.enabled!==!1&&$0(Q0)).map((Q0)=>({...Q0,quota:c1(Q0)})),J0=S7({mainQuota:W1,requestModelId:o,storage:C}),i=jJ(W1,D0,p,J0.isScopedDriven?J0.modelId:void 0),S0=E7({retryAfterSeconds:i,...J0.isScopedDriven&&{modelName:J0.modelName}});return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:S0}}),{status:429,headers:{"content-type":"application/json","retry-after":String(i)}})}let x1=await j1(z,Q,P.access,U,"main",C,"main",S),F1=!1,d1=await D3(z,Q,x1,W0,U,C,P.access,(A)=>{F1=!0,e(A.id,"fallback")},o,S);if(!F1)e("main","main");return U.done("return_response",{status:d1.status}),H(d1)}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let O=await J4("max");return{url:O.url,instructions:"Paste the authorization code here:",method:"code",callback:async($)=>{return N4($,O.verifier,O.redirectUri,O.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let O=await J4("console");return{url:O.url,instructions:"Paste the authorization code here:",method:"code",callback:async($)=>{let D=await N4($,O.verifier,O.redirectUri,O.state);if(D.type==="failed")return D;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${D.access}`}}).then((Y)=>Y.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{S7 as resolveScopedDrivenBlock,E7 as formatKillswitchBlockMessage,TN as AnthropicAuthPlugin};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{bc as a,cc as b,dc as c,ec as d,fc as e,gc as f,hc as g,ic as h,jc as i,kc as j,lc as k,mc as l,nc as m}from"./index-1ets4bf8.js";import"./index-9aeag0wm.js";export{d as shouldEmit,b as setLogLevel,m as relayLog,h as redactPayload,a as parseLogLevel,k as logger,l as log,g as isSecretKey,c as getLogLevel,e as getLogFilePath,i as formatLogLine,j as __setLogTestSink,f as SECRET_KEY_EXACT};
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{oc as a,pc as b}from"../index-kckdabb4.js";import"../index-9aeag0wm.js";export{a as writePortFile,b as discoverPortFile};
|
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{pc as l}from"../index-kckdabb4.js";import"../index-9aeag0wm.js";async function a(n,e,t,o){let r=await l(n,o);if(!r)return null;let i=new AbortController,p=setTimeout(()=>i.abort(),2000);try{let s=await fetch(`http://127.0.0.1:${r.port}/rpc/${e}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r.token}`},body:JSON.stringify(t),signal:i.signal});if(!s.ok)return null;return await s.json()}catch{return null}finally{clearTimeout(p)}}function u(n,e){return{async pending(t,o){return(await a(n,"pending-notifications",{lastReceivedId:t,sessionId:o},e))?.messages??[]},async apply(t){return await a(n,"apply",{...t},e)??{text:"apply failed",knobs:{}}}}}export{u as createRpcClient};
|
package/dist/rpc/rpc-dir.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{qc as a,rc as b}from"../index-k5enth8h.js";import"../index-9aeag0wm.js";export{a as tmpdir,b as getRpcDir};
|