@cortexkit/opencode-anthropic-auth 2.5.2 → 2.5.4

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.
@@ -1,4 +1,4 @@
1
- import{u as o8}from"./index-2ra790fx.js";import{w as s8}from"./index-jc8zwxvw.js";import{G as a8}from"./index-a0jxsmac.js";import{K as t8,P as e9,R as e8,S as $Y}from"./index-d4e8qj37.js";import{ja as q7}from"./index-crx0xd9j.js";import{randomUUID as EZ}from"node:crypto";import{existsSync as Y6,readFileSync as X6}from"node:fs";import{dirname as G6,join as W6}from"node:path";import{fileURLToPath as z6}from"node:url";import{ANTHROPIC_OAUTH_ORIGIN_REFUSAL as V6,acquireNativeAccountRuntime as j6,applyCustomHeaders as W8,assertNotCustodyTombstone as K6,authorize as z8,buildAccountList as e$,buildClaudeQuotaSummary as _6,buildFallbackQuotaSummaries as L6,buildPrimeRequestBody as O6,CACHE_KEEP_EXTENDED_TTL_BETA as N6,CacheKeepManager as D6,CacheKeepSessionRegistry as H6,CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS as U6,CLAUDE_HAIKU_4_5_MODEL_ID as V8,CLAUDE_HAIKU_5_5_CONTEXT_WINDOW as Q6,CLAUDE_HAIKU_5_5_LONG_CONTEXT_PRICING as v9,CLAUDE_HAIKU_5_5_LONG_CONTEXT_THRESHOLD as B6,CLAUDE_HAIKU_5_5_MAX_OUTPUT_TOKENS as F6,CLAUDE_HAIKU_5_5_MODEL_ID as h9,CLAUDE_HAIKU_5_5_PRICING as b9,CLAUDE_HAIKU_5_5_RELEASE_DATE as T6,CLAUDE_OPUS_5_5_CONTEXT_WINDOW as w6,CLAUDE_OPUS_5_5_MAX_OUTPUT_TOKENS as S6,CLAUDE_OPUS_5_5_MODEL_ID as g9,CLAUDE_OPUS_5_5_PRICING as y9,CLAUDE_OPUS_5_5_RELEASE_DATE as E6,CLAUDE_SONNET_5_5_CONTEXT_WINDOW as C6,CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS as A6,CLAUDE_SONNET_5_5_MODEL_ID as m9,CLAUDE_SONNET_5_5_PRICING as p9,CLAUDE_SONNET_5_5_RELEASE_DATE as P6,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as CZ,cacheKeepSourceWarmIdleCap as q6,cacheWarmCacheablePrefixFingerprint as j8,computeXxhash64Hex as M6,configuredAnthropicOAuthAccountCount as R6,createEmptyStorage as _1,createNativeUsagePublisher as x6,createNativeVaultNoRouteResponse as K8,createProviderErrorResponseScope as c9,createQuotaRefusalResponse as I6,createSseFramer as f6,createStickyNoRouteResponse as k6,custodyTombstoneOAuth as AZ,decideOpenCodeStateLayoutOnce as v6,decideStickyQuotaFailure as PZ,decodeSseFrame as h6,detectClaustrumConnection as _8,dumpDirectRequest as l9,dumpResponseArtifact as qZ,effectiveRelayStatus as b6,effectiveRelayTransport as g6,exchange as MZ,executeAccountCommand as y6,executeCache1hCommand as RZ,executeCacheKeepCommand as m6,executeDumpCommand as L8,executeFastModeCommand as O8,executeKillswitchCommand as N8,executeLaneStartCommand as D8,executeLoggingCommand as H8,executePrimeCommand as p6,executeRoutingCommand as U8,FALLBACK_BACKGROUND_TICK_MS as c6,fallbackAccountUuidForLineage as l6,formatEnrollmentStatus as Q8,formatNativeAccountState as xZ,formatOAuthAccountTier as c4,formatQuotaBackoffMessage as B8,formatRefreshBackoffMessage as u6,getAccountStoragePath as d6,getCache1hMode as W4,getCache1hPersistentMode as l4,getCacheKeepWindow as F8,getClaudeCodeIdentityForVerifiedAccount as i6,getClaudeModelCatalogue as n6,getClaustrumMode as u4,getDefaultCacheKeepRegistryDirectory as r6,getFallbackReauthLabels as o6,getHostClaustrumEnrollmentPaths as u9,getKillswitchConfig as IZ,getMaxSameAccountWait as d9,getPersistedLogLevel as fZ,getQuotaCheckIntervalMs as T8,getQuotaNextRefreshAt as g1,getRequestGzipLatch as s6,getRequestGzipLatchPath as a6,getRoutingMode as $1,getScopedQuotaWindowForModel as t6,getThinkingPrefixMismatchBehavior as e6,inspectNativeHostAuthEntry as $G,isApiKeyAccount as z4,isCache1hEnabled as V4,isCache1hPersistentlyEnabled as i9,isCacheKeepAlways as w8,isCacheKeepHybridActive as S8,isCacheKeepPersistentlyEnabled as E8,isCacheKeepSubagentsEnabled as JG,isClaudeFableOrMythos51Model as ZG,isClaudeOpus5Model as YG,isClaudeOpus55Model as XG,isCostZeroingEnabled as GG,isCustodyTombstoneOAuth as kZ,isDumpPersistentlyEnabled as vZ,isFastModeEnabled as hZ,isFastModePersistentlyEnabled as bZ,isFastModeSupportedModel as C8,isKillswitchEnabled as L1,isNativeTransientAccountError as y1,isOAuthAccount as R0,isPermanentRefreshError as O1,isPrimePersistentlyEnabled as n9,isQuotaBearingHeaderFrame as WG,isValidApiBaseURL as gZ,killswitchPassesPolicy as N1,log as J1,logger as b,MessageThreadTracker as zG,mergeAnthropicBetas as A8,mergeHeaderQuotaForPersistence as P8,NativeAccountRefusal as m1,NativeCustodyError as VG,NativeRuntimeError as jG,NativeVaultNoAccountError as q8,nativeAccountCanServe as x0,nativeAccountPolicy as M8,nativeAccountRefusal as KG,nativeLocalAccountRefusal as _G,nativeLocalQuotaLineage as LG,nativeMigrationAuthorityPhase as R8,normalizeQuotaHeaders as OG,oauthProfileIsFresh as r9,oauthProfileMatchesIdentity as NG,PARALLEL_TOOL_CALLS_SYSTEM_PROMPT as DG,PROMPT_CACHE_1H_TTL_MS as HG,PROMPT_CACHE_DEFAULT_TTL_MS as x8,PrimeManager as UG,parseAccountCommandAction as QG,parseCache1hCommandAction as BG,parseCacheKeepCommandAction as FG,parseDumpCommandAction as TG,parseFastModeCommandAction as wG,parseLaneStartCommandAction as SG,parseLoggingCommandAction as EG,parsePrimeCommandAction as CG,parseRoutingCommandAction as AG,parseSseFrame as PG,prepareMessageThreadRequest as qG,QUOTA_HEADER_FEED_SCHEMA_VERSION as o9,QuotaHeaderFeedRegistry as MG,QuotaManager as RG,quotaExhaustionFromHeaders as xG,quotaRefusalTiming as IG,quotaSnapshotCheckedAt as p1,quotaSnapshotHasStandardWindows as yZ,quotaSnapshotModelScopeIsExhausted as s9,quotaSnapshotPassesModelScope as a9,quotaSnapshotPassesPolicy as j4,readClaustrumEnrollmentStatus as I8,readNativeAccountsForRequest as fG,readNativeEnrollmentMode as c1,readNativeHostAuthKind as kG,readNativeMigrationJournal as f8,refreshBackoffActive as l1,remapRequestBodyModel as vG,resetClaustrumEnrollmentState as hG,resolveClaudeModelCapabilities as bG,resolveNativePoolPaths as gG,STICKY_ROUTING_MAIN_ACCOUNT_ID as V$,StickyQuotaRetryCounter as yG,StickySessionRouter as mG,sendViaRelay as pG,sendWithRequestGzip as cG,sessionCacheActivity as u1,setCache1hState as t9,setDumpEnabled as mZ,setFastModeEnabled as pZ,setLogLevel as lG,shouldFallbackStatus as uG,signRequestBody as dG,snapshotHasServableLocalOAuth as k8,stateRefusalPublicMessage as iG,stickyQuotaSnapshotIsFresh as d1,stickyRouteFamilyForModel as nG,TrailingAssistantHistoryError as v8,tokenFingerprint as D1,withAbortableFetch as rG}from"@cortexkit/anthropic-auth-core";import{randomUUID as R3}from"node:crypto";import{isValidAnthropicRequestId as x3,isValidBillingPromptId as dY}from"@cortexkit/anthropic-auth-core";var e1="x-cortexkit-billing-lineage",iY=4096,nY=4096,rY=1024,I3=new Set(["title","summary","compaction"]),oY="[lane start] — automated cache warm; no response needed.";function sY($){let J=$.info?.sessionID??$.info?.sessionId;return typeof J==="string"&&J.length>0?J:void 0}function aY($){if($.info?.synthetic===!0||$.info?.ignored===!0||typeof $.info?.agent==="string"&&I3.has($.info.agent))return!0;for(let J of $.parts??[]){if(J.type==="compaction"||J.synthetic===!0||J.ignored===!0)return!0;if(J.metadata?.compaction_continue===!0)return!0;if(J.type==="text"&&J.text===oY)return!0}return!1}function v1($,J){while($.size>J){let Y=$.keys().next().value;if(Y===void 0)return;$.delete(Y)}}function gJ($){let J=$.get("request-id")??$.get("x-request-id");return J&&x3(J)?J:void 0}class yJ{#$;#_;#j;#L;#X;#J=new Map;#Y=new Map;#Z=new Map;#G=new Map;#W=new Map;#z=new Map;#V=new Map;constructor($={}){this.#$=$.createPromptId??R3,this.#_=$.createRequestToken??R3,this.#j=$.maxPrompts??iY,this.#L=$.maxRequests??nY,this.#X=$.maxSessions??rY}observeMessages($){let J;for(let N=$.length-1;N>=0;N-=1)if($[N]?.info?.role==="user"){J=$[N];break}if(!J)return;let Y=sY(J),X=J.info?.id;if(!Y||typeof X!=="string"||X.length===0)return;let z=this.#K(Y,X);if(aY(J)){this.#Y.delete(z),this.#Y.set(z,!0),v1(this.#Y,this.#j),this.#J.delete(z);return}this.#Y.delete(z);let V=this.#J.get(z);if(V){this.#J.delete(z),this.#J.set(z,V);return}let j=this.#$();if(!dY(j))return;this.#J.set(z,j),v1(this.#J,this.#j)}markHeaders($){let J=this.#K($.sessionId,$.messageId);if(I3.has($.agent??"")||this.#Y.has(J))return!1;let Y=this.#J.get(J);if(!Y)return!1;let X=this.#_();if(!X||/[\r\n]/.test(X))return!1;let z={sessionId:$.sessionId,messageId:$.messageId,promptId:Y,requestToken:X,generation:this.#W.get($.sessionId)??0,sequence:0};return this.#Z.set(X,z),v1(this.#Z,this.#L),$.headers[e1]=X,!0}promptIdForHeader($){return $?this.#Z.get($)?.promptId:void 0}resolveHeader($){if(!$)return;let J=this.#Z.get($);if(!J)return;this.#Z.delete($),this.#Z.set($,J);let Y=(this.#z.get(J.sessionId)??0)+1;this.#z.delete(J.sessionId),this.#z.set(J.sessionId,Y),v1(this.#z,this.#X);let X={...J,previousRequestId:this.#G.get(J.sessionId),sequence:Y};if(X.previousRequestId===void 0)delete X.previousRequestId;return X}commit($,J){if(!$||!J||!x3(J))return!1;if((this.#W.get($.sessionId)??0)!==$.generation)return!1;let Y=this.#Z.get($.requestToken);if(!Y||Y.sessionId!==$.sessionId||Y.messageId!==$.messageId||Y.promptId!==$.promptId||Y.generation!==$.generation)return!1;if(this.#J.get(this.#K($.sessionId,$.messageId))!==$.promptId)return!1;if($.sequence<(this.#V.get($.sessionId)??0))return!1;return this.#V.delete($.sessionId),this.#V.set($.sessionId,$.sequence),v1(this.#V,this.#X),this.#G.delete($.sessionId),this.#G.set($.sessionId,J),v1(this.#G,this.#X),!0}clearSession($){this.#W.set($,(this.#W.get($)??0)+1),this.#G.delete($),this.#z.delete($),this.#V.delete($);let J=`${$}\x00`;for(let Y of this.#J.keys())if(Y.startsWith(J))this.#J.delete(Y);for(let Y of this.#Y.keys())if(Y.startsWith(J))this.#Y.delete(Y);for(let[Y,X]of this.#Z)if(X.sessionId===$)this.#Z.delete(Y);v1(this.#W,this.#X)}#K($,J){return`${$}\x00${J}`}}import{setBounded as k3,stickyRetainRetryHeaders as tY,stickyRetryAfterWithJitter as eY}from"@cortexkit/anthropic-auth-core";var q4="cache-diagnosis-2026-04-07",$5="MC-CACHE-DIAG ",J5=1000,Z5=300000,Y5={turn:!1,start:!0,prewarm_cachekeep:!0},X5=1000;class mJ{entries=new Map;previousFor($){return this.entries.get($)??null}capture($,J,Y){k3(this.entries,$,{messageId:J,receivedAt:Y},J5)}}class pJ{hashes=new Map;capture($,J){if(this.hashes.has($))return null;return k3(this.hashes,$,!0,X5),`MC-CACHE-DIAG-BETAS ${JSON.stringify({hash:$,betas:[...J].sort()})}`}}function _9($,J,Y){let X=$.get(J);if(X)$.set(Y,X)}async function L9($,J,Y,X,z,V=!1){let j=V?tY($.headers):new Headers($.headers);if(!V)j.set("retry-after",String(eY(J,Y)));if(X)return await $.body?.cancel().catch(()=>{}),j.set("content-type","application/json"),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:V?"Sticky OAuth account quota is unconfirmed; retrying shortly while retaining session affinity.":"Sticky OAuth account quota resets shortly; retaining session affinity."}}),{status:429,headers:j});let N=new Response($.body,{status:$.status,statusText:$.statusText,headers:j});return _9(z,$,N),N}function O9($,J){$.diagnostics={previous_message_id:J}}function j1($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function G5($){return j1($)&&$.type==="ephemeral"}function v3($,J){if(!G5($))return;J.push($.ttl==="1h"?"1h":"5m")}function f3($,J){if(!Array.isArray($))return;for(let Y of $)if(j1(Y))v3(Y.cache_control,J)}function N9($){if(!j1($))return null;let J=[];if(v3($.cache_control,J),f3($.system,J),Array.isArray($.messages)){for(let Y of $.messages)if(j1(Y))f3(Y.content,J)}return J.at(-1)??null}function W5($){if(!Object.hasOwn($,"diagnostics"))return{state:"absent"};let J=$.diagnostics;if(J===null)return{state:"server_null"};if(!j1(J))return null;if(!Object.hasOwn(J,"cache_miss_reason"))return null;let Y=J.cache_miss_reason;if(Y===null)return{state:"pending"};if(!j1(Y)||typeof Y.type!=="string"||!Y.type)return null;let X=Y.cache_missed_input_tokens;if(X!==void 0&&typeof X!=="number")return null;return{state:"populated",missReason:Y.type,cacheMissedInputTokens:X}}function P4($,J){let Y=$[J];return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function h3($){if(typeof $.source!=="string"||$.source.length===0||typeof $.accountId!=="string"||$.accountId.length===0||typeof $.synthetic!=="boolean"||typeof $.betasHash!=="string"||$.betasHash.length===0)return{};let J=Y5[$.source];if(J!==void 0&&J!==$.synthetic)$.onWarning?.(`cache diagnostics source/synthetic mismatch: source=${$.source} expected=${J} actual=${$.synthetic}`);let Y=Math.trunc($.receivedAt);if(!Number.isFinite($.receivedAt)||Y!==$.receivedAt)return{};if(!j1($.message))return{};let X=$.message.id,z=$.message.model,V=$.message.usage;if(typeof X!=="string"||X.length===0)return{};if(typeof z!=="string"||z.length===0||!j1(V))return{};let j=P4(V,"input_tokens"),N=P4(V,"cache_read_input_tokens"),F=P4(V,"cache_creation_input_tokens"),C=V.cache_creation;if(j===null||N===null||F===null||!j1(C))return{};let q=P4(C,"ephemeral_5m_input_tokens"),M=P4(C,"ephemeral_1h_input_tokens");if(q===null||M===null)return{};let c=W5($.message);if(!c)return{};let l={v:2,source:$.source,account_id:$.accountId,synthetic:$.synthetic,betas_hash:$.betasHash,session_id:$.request.sessionId,ts_ms_received:Y,model:z,is_subagent:$.request.isSubagent,ttl_sent:$.request.ttlSent,cache_read:N,cache_creation:F,input_tokens:j,ephemeral_5m_tokens:q,ephemeral_1h_tokens:M,message_id:X,previous_message_id:$.request.previousMessageId,diag_state:c.state};if(c.missReason!==void 0)l.miss_reason=c.missReason;if(c.cacheMissedInputTokens!==void 0)l.cache_missed_input_tokens=c.cacheMissedInputTokens;if($.requestedModel!==void 0&&$.requestedModel!==z)l.requested_model=$.requestedModel;let K0=c.missReason==="previous_message_not_found"&&$.request.previousMessageId!==null&&$.request.previousMessageReceivedAt!==void 0&&$.receivedAt-$.request.previousMessageReceivedAt<Z5&&$.receivedAt>=$.request.previousMessageReceivedAt?{messageId:X,previousMessageId:$.request.previousMessageId}:void 0;return{record:l,messageId:X,...K0?{canary:K0}:{}}}function b3($){return`${$5}${JSON.stringify($)}`}import{getClaustrumMode as D9,hasNoLocalCredential as cJ,isCustodyTombstoneOAuth as z5,isOAuthAccount as lJ,nativeAccountCanServe as uJ}from"@cortexkit/anthropic-auth-core";function M4($,J){if(D9(J)!=="claustrum"||!J?.claustrum?.scopedRoster)return!1;let Y=J.accounts.find((X)=>X.id===$);return Boolean(Y&&lJ(Y)&&uJ(Y)&&Y.claustrumScopedCredentialId&&Y.anthropicAccountUuid&&cJ(Y))}function g3($){if(D9($)!=="claustrum")return{fallbacks:"R",evidence:"V"};if(!$?.claustrum?.scopedRoster)return{fallbacks:"M",evidence:"N"};return{fallbacks:$.accounts.filter((Y)=>uJ(Y)&&lJ(Y)).every((Y)=>Boolean(Y.claustrumScopedCredentialId&&Y.anthropicAccountUuid&&cJ(Y)))?"T":"R",evidence:"V"}}function dJ($){if(z5($,"anthropic"))return"T";if($.type==="oauth"&&$.access&&$.refresh)return"R";return"X"}function iJ($,J){if($.role==="main"){if(D9(J)!=="claustrum")return"na";let X=J?.claustrum?.scopedRoster?J.claustrum.primaryAccount:void 0;if(!X)return"unknown-identity";if(X.state==="needs_reauth")return"on-vault-reauth";return uJ(X)?"on-vault-served":"on-cold"}if(D9(J)!=="claustrum")return"off";let Y=J?.accounts.find((X)=>X.id===$.id);if(!Y||!lJ(Y)||!Y.claustrumScopedCredentialId||!Y.anthropicAccountUuid||!cJ(Y))return"off";if(Y.claustrumScopedState==="needs_reauth")return"on-vault-reauth";return M4($.id,J)?"on-vault-served":"on-cold"}class R4 extends Error{verdict;dimensions;code="custody_state_mismatch";constructor($,J){super(`custody state mismatch: ${$}`);this.verdict=$;this.dimensions=J}toJSON(){return{code:this.code,verdict:this.verdict,dimensions:this.dimensions}}}function y3($){if($.authority!=="committed"&&$.authority!=="retired")throw new R4("MIGRATION_REQUIRED",$);if($.mode==="L"&&$.main==="R"&&$.evidence==="V"&&$.localOAuthServable===!0)return{verdict:"LOCAL_SERVE"};if($.mode==="L"&&$.main==="T"&&$.fallbacks==="R"&&$.evidence==="V")return{verdict:"LOCAL_SERVE"};if($.mode==="C"&&$.main==="T"&&$.fallbacks==="T"&&$.evidence==="V")return{verdict:"CLAUSTRUM_SERVE"};throw new R4("FAIL_CLOSED",$)}import{createHash as V5}from"node:crypto";import{defaultAdaptiveEffort as j5,logger as K5,normalizeAdaptiveEffort as _5,pinsEffortOnEveryRequest as m3,resolveClaudeModelCapabilities as L5,supportsPerMessageEffort as O5}from"@cortexkit/anthropic-auth-core";var d3=512,N5=1024,D5=4096,x4=32,I4=32,U9="[A-Za-z0-9_-]{1,128}",H5="<cortexkit-internal-effort ",U5="<cortexkit-internal-effort-plan ",i3=/^\s*(?:§[0-9]+§\s*)+$/,f4={low:"l",medium:"m",high:"h",xhigh:"x",max:"z"},sJ=Object.fromEntries(Object.entries(f4).map(([$,J])=>[J,$])),aJ="<cortexkit-internal-effort-v2 ",tJ="<cortexkit-internal-effort-anchor-v1 ",$4="x-cortexkit-effort-plan";class C0 extends Error{check;details;constructor($,J="unspecified",Y={}){super($);this.check=J;this.details=Y;this.name="EffortMarkerCorrelationError"}}function e0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Q5($){let J=L5($);if(!J||J.effortMarkers==="none")return;return J.id.replace(/^claude-/,"")}function nJ($){if($?.info?.role!=="user")return;if($.info.model?.providerID!=="anthropic")return;return Q5($.info.model.modelID)}function p3($){return _5($.info?.model?.variant)??j5($.info?.model?.modelID)}function c3($){return $.parts?.some((J)=>{if(J.type==="text")return J.ignored!==!0&&J.text!=="";if(J.type==="file")return J.mime!=="text/plain"&&J.mime!=="application/x-directory";return J.type==="compaction"||J.type==="subtask"})??!1}function a$($){return V5("sha256").update($).digest("hex")}function B5($){return a$(`scope:${$}`).slice(0,I4)}function Q9($){return a$(`cortexkit-effort-v2:${$}`).slice(0,x4)}function F5($,J,Y){let X=f4[Y],z=`transition:${$}:${J}:${X}`;return`${aJ}scope="${$}" boundary="${J}" effort="${X}" check="${Q9(z)}"/>`}function n3($){let J=$.match(new RegExp(`^${aJ}scope="([0-9a-f]{${I4}})" boundary="(${U9})" effort="([lmhxz])" check="([0-9a-f]{${x4}})"/>$`));if(!J)return null;let[,Y,X,z,V]=J,j=sJ[z??""];if(!Y||!X||!z||!V||!j)return null;let N=`transition:${Y}:${X}:${z}`;if(Q9(N)!==V)return null;return{scope:Y,boundary:X,effort:j,token:$}}function T5($,J,Y,X){let z=f4[Y],V=`anchor:${$}:${J}:${z}:${X}`;return`${tJ}scope="${$}" boundary="${J}" effort="${z}" digest="${X}" check="${Q9(V)}"/>`}function r3($){let J=$.match(new RegExp(`^${tJ}scope="([0-9a-f]{${I4}})" boundary="(${U9})" effort="([lmhxz])" digest="([0-9a-f]{64})" check="([0-9a-f]{${x4}})"/>$`));if(!J)return null;let[,Y,X,z,V,j]=J,N=sJ[z??""];if(!Y||!X||!z||!V||!j||!N)return null;let F=`anchor:${Y}:${X}:${z}:${V}`;if(Q9(F)!==j)return null;return{scope:Y,boundary:X,effort:N,digest:V,token:$}}function rJ($){return $.trim()===""||i3.test($)}function l3(){return new RegExp(`(?:${U5}nonce="[^"]+" baseline="[^"]+" count="[^"]+" sig="[0-9a-f]+"/>|${H5}nonce="[^"]+" effort="[^"]+" sig="[0-9a-f]+"/>)`,"g")}function w5(){return new RegExp(`${aJ}scope="[0-9a-f]{${I4}}" boundary="${U9}" effort="[lmhxz]" check="[0-9a-f]{${x4}}"/>`,"g")}function S5(){return new RegExp(`${tJ}scope="[0-9a-f]{${I4}}" boundary="${U9}" effort="[lmhxz]" digest="[0-9a-f]{64}" check="[0-9a-f]{${x4}}"/>`,"g")}function o3($,J,Y){let X=0,z=$,V=$.replace(l3(),"");if(V!==$&&i3.test(V))X+=[...$.matchAll(l3())].length,z=V;return z=z.replace(w5(),(j)=>{let N=n3(j);if(!N)return j;return J?.(N),X++,""}),z=z.replace(S5(),(j)=>{let N=r3(j);if(!N)return j;return Y?.(N),X++,""}),{text:z,removed:X}}function E5($){for(let J of $){if(!Array.isArray(J.parts))continue;J.parts=J.parts.flatMap((Y)=>{if(Y.type!=="text"||typeof Y.text!=="string"||!Y.text.includes("<cortexkit-internal-effort"))return[Y];let X=o3(Y.text);if(X.removed===0)return[Y];if(rJ(X.text))return[];return Y.text=X.text,[Y]})}}function H9($,J,Y,X,z){let V=z?`:${z}`:"",j=`plan:${$}:${f4[J]}:${Y.toString(36)}${V}`;return a$([j,...X].join(`
1
+ import{u as o8}from"./index-2ra790fx.js";import{w as s8}from"./index-jc8zwxvw.js";import{G as a8}from"./index-k6303ymz.js";import{K as t8,P as e9,R as e8,S as $Y}from"./index-d4e8qj37.js";import{ja as q7}from"./index-crx0xd9j.js";import{randomUUID as EZ}from"node:crypto";import{existsSync as Y6,readFileSync as X6}from"node:fs";import{dirname as G6,join as W6}from"node:path";import{fileURLToPath as z6}from"node:url";import{ANTHROPIC_OAUTH_ORIGIN_REFUSAL as V6,acquireNativeAccountRuntime as j6,applyCustomHeaders as W8,assertNotCustodyTombstone as K6,authorize as z8,buildAccountList as e$,buildClaudeQuotaSummary as _6,buildFallbackQuotaSummaries as L6,buildPrimeRequestBody as O6,CACHE_KEEP_EXTENDED_TTL_BETA as N6,CacheKeepManager as D6,CacheKeepSessionRegistry as H6,CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS as U6,CLAUDE_HAIKU_4_5_MODEL_ID as V8,CLAUDE_HAIKU_5_5_CONTEXT_WINDOW as Q6,CLAUDE_HAIKU_5_5_LONG_CONTEXT_PRICING as v9,CLAUDE_HAIKU_5_5_LONG_CONTEXT_THRESHOLD as B6,CLAUDE_HAIKU_5_5_MAX_OUTPUT_TOKENS as F6,CLAUDE_HAIKU_5_5_MODEL_ID as h9,CLAUDE_HAIKU_5_5_PRICING as b9,CLAUDE_HAIKU_5_5_RELEASE_DATE as T6,CLAUDE_OPUS_5_5_CONTEXT_WINDOW as w6,CLAUDE_OPUS_5_5_MAX_OUTPUT_TOKENS as S6,CLAUDE_OPUS_5_5_MODEL_ID as g9,CLAUDE_OPUS_5_5_PRICING as y9,CLAUDE_OPUS_5_5_RELEASE_DATE as E6,CLAUDE_SONNET_5_5_CONTEXT_WINDOW as C6,CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS as A6,CLAUDE_SONNET_5_5_MODEL_ID as m9,CLAUDE_SONNET_5_5_PRICING as p9,CLAUDE_SONNET_5_5_RELEASE_DATE as P6,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as CZ,cacheKeepSourceWarmIdleCap as q6,cacheWarmCacheablePrefixFingerprint as j8,computeXxhash64Hex as M6,configuredAnthropicOAuthAccountCount as R6,createEmptyStorage as _1,createNativeUsagePublisher as x6,createNativeVaultNoRouteResponse as K8,createProviderErrorResponseScope as c9,createQuotaRefusalResponse as I6,createSseFramer as f6,createStickyNoRouteResponse as k6,custodyTombstoneOAuth as AZ,decideOpenCodeStateLayoutOnce as v6,decideStickyQuotaFailure as PZ,decodeSseFrame as h6,detectClaustrumConnection as _8,dumpDirectRequest as l9,dumpResponseArtifact as qZ,effectiveRelayStatus as b6,effectiveRelayTransport as g6,exchange as MZ,executeAccountCommand as y6,executeCache1hCommand as RZ,executeCacheKeepCommand as m6,executeDumpCommand as L8,executeFastModeCommand as O8,executeKillswitchCommand as N8,executeLaneStartCommand as D8,executeLoggingCommand as H8,executePrimeCommand as p6,executeRoutingCommand as U8,FALLBACK_BACKGROUND_TICK_MS as c6,fallbackAccountUuidForLineage as l6,formatEnrollmentStatus as Q8,formatNativeAccountState as xZ,formatOAuthAccountTier as c4,formatQuotaBackoffMessage as B8,formatRefreshBackoffMessage as u6,getAccountStoragePath as d6,getCache1hMode as W4,getCache1hPersistentMode as l4,getCacheKeepRegistryDirectories as i6,getCacheKeepWindow as F8,getClaudeCodeIdentityForVerifiedAccount as n6,getClaudeModelCatalogue as r6,getClaustrumMode as u4,getFallbackReauthLabels as o6,getHostClaustrumEnrollmentPaths as u9,getKillswitchConfig as IZ,getMaxSameAccountWait as d9,getPersistedLogLevel as fZ,getQuotaCheckIntervalMs as T8,getQuotaNextRefreshAt as g1,getRequestGzipLatch as s6,getRequestGzipLatchPath as a6,getRoutingMode as $1,getScopedQuotaWindowForModel as t6,getThinkingPrefixMismatchBehavior as e6,inspectNativeHostAuthEntry as $G,isApiKeyAccount as z4,isCache1hEnabled as V4,isCache1hPersistentlyEnabled as i9,isCacheKeepAlways as w8,isCacheKeepHybridActive as S8,isCacheKeepPersistentlyEnabled as E8,isCacheKeepSubagentsEnabled as JG,isClaudeFableOrMythos51Model as ZG,isClaudeOpus5Model as YG,isClaudeOpus55Model as XG,isCostZeroingEnabled as GG,isCustodyTombstoneOAuth as kZ,isDumpPersistentlyEnabled as vZ,isFastModeEnabled as hZ,isFastModePersistentlyEnabled as bZ,isFastModeSupportedModel as C8,isKillswitchEnabled as L1,isNativeTransientAccountError as y1,isOAuthAccount as R0,isPermanentRefreshError as O1,isPrimePersistentlyEnabled as n9,isQuotaBearingHeaderFrame as WG,isValidApiBaseURL as gZ,killswitchPassesPolicy as N1,log as J1,logger as b,MessageThreadTracker as zG,mergeAnthropicBetas as A8,mergeHeaderQuotaForPersistence as P8,NativeAccountRefusal as m1,NativeCustodyError as VG,NativeRuntimeError as jG,NativeVaultNoAccountError as q8,nativeAccountCanServe as x0,nativeAccountPolicy as M8,nativeAccountRefusal as KG,nativeLocalAccountRefusal as _G,nativeLocalQuotaLineage as LG,nativeMigrationAuthorityPhase as R8,normalizeQuotaHeaders as OG,oauthProfileIsFresh as r9,oauthProfileMatchesIdentity as NG,PARALLEL_TOOL_CALLS_SYSTEM_PROMPT as DG,PROMPT_CACHE_1H_TTL_MS as HG,PROMPT_CACHE_DEFAULT_TTL_MS as x8,PrimeManager as UG,parseAccountCommandAction as QG,parseCache1hCommandAction as BG,parseCacheKeepCommandAction as FG,parseDumpCommandAction as TG,parseFastModeCommandAction as wG,parseLaneStartCommandAction as SG,parseLoggingCommandAction as EG,parsePrimeCommandAction as CG,parseRoutingCommandAction as AG,parseSseFrame as PG,prepareMessageThreadRequest as qG,QUOTA_HEADER_FEED_SCHEMA_VERSION as o9,QuotaHeaderFeedRegistry as MG,QuotaManager as RG,quotaExhaustionFromHeaders as xG,quotaRefusalTiming as IG,quotaSnapshotCheckedAt as p1,quotaSnapshotHasStandardWindows as yZ,quotaSnapshotModelScopeIsExhausted as s9,quotaSnapshotPassesModelScope as a9,quotaSnapshotPassesPolicy as j4,readClaustrumEnrollmentStatus as I8,readNativeAccountsForRequest as fG,readNativeEnrollmentMode as c1,readNativeHostAuthKind as kG,readNativeMigrationJournal as f8,refreshBackoffActive as l1,remapRequestBodyModel as vG,resetClaustrumEnrollmentState as hG,resolveClaudeModelCapabilities as bG,resolveNativePoolPaths as gG,STICKY_ROUTING_MAIN_ACCOUNT_ID as V$,StickyQuotaRetryCounter as yG,StickySessionRouter as mG,sendViaRelay as pG,sendWithRequestGzip as cG,sessionCacheActivity as u1,setCache1hState as t9,setDumpEnabled as mZ,setFastModeEnabled as pZ,setLogLevel as lG,shouldFallbackStatus as uG,signRequestBody as dG,snapshotHasServableLocalOAuth as k8,stateRefusalPublicMessage as iG,stickyQuotaSnapshotIsFresh as d1,stickyRouteFamilyForModel as nG,TrailingAssistantHistoryError as v8,tokenFingerprint as D1,withAbortableFetch as rG}from"@cortexkit/anthropic-auth-core";import{randomUUID as R3}from"node:crypto";import{isValidAnthropicRequestId as x3,isValidBillingPromptId as dY}from"@cortexkit/anthropic-auth-core";var e1="x-cortexkit-billing-lineage",iY=4096,nY=4096,rY=1024,I3=new Set(["title","summary","compaction"]),oY="[lane start] — automated cache warm; no response needed.";function sY($){let J=$.info?.sessionID??$.info?.sessionId;return typeof J==="string"&&J.length>0?J:void 0}function aY($){if($.info?.synthetic===!0||$.info?.ignored===!0||typeof $.info?.agent==="string"&&I3.has($.info.agent))return!0;for(let J of $.parts??[]){if(J.type==="compaction"||J.synthetic===!0||J.ignored===!0)return!0;if(J.metadata?.compaction_continue===!0)return!0;if(J.type==="text"&&J.text===oY)return!0}return!1}function v1($,J){while($.size>J){let Y=$.keys().next().value;if(Y===void 0)return;$.delete(Y)}}function gJ($){let J=$.get("request-id")??$.get("x-request-id");return J&&x3(J)?J:void 0}class yJ{#$;#_;#j;#L;#X;#J=new Map;#Y=new Map;#Z=new Map;#G=new Map;#W=new Map;#z=new Map;#V=new Map;constructor($={}){this.#$=$.createPromptId??R3,this.#_=$.createRequestToken??R3,this.#j=$.maxPrompts??iY,this.#L=$.maxRequests??nY,this.#X=$.maxSessions??rY}observeMessages($){let J;for(let N=$.length-1;N>=0;N-=1)if($[N]?.info?.role==="user"){J=$[N];break}if(!J)return;let Y=sY(J),X=J.info?.id;if(!Y||typeof X!=="string"||X.length===0)return;let z=this.#K(Y,X);if(aY(J)){this.#Y.delete(z),this.#Y.set(z,!0),v1(this.#Y,this.#j),this.#J.delete(z);return}this.#Y.delete(z);let V=this.#J.get(z);if(V){this.#J.delete(z),this.#J.set(z,V);return}let j=this.#$();if(!dY(j))return;this.#J.set(z,j),v1(this.#J,this.#j)}markHeaders($){let J=this.#K($.sessionId,$.messageId);if(I3.has($.agent??"")||this.#Y.has(J))return!1;let Y=this.#J.get(J);if(!Y)return!1;let X=this.#_();if(!X||/[\r\n]/.test(X))return!1;let z={sessionId:$.sessionId,messageId:$.messageId,promptId:Y,requestToken:X,generation:this.#W.get($.sessionId)??0,sequence:0};return this.#Z.set(X,z),v1(this.#Z,this.#L),$.headers[e1]=X,!0}promptIdForHeader($){return $?this.#Z.get($)?.promptId:void 0}resolveHeader($){if(!$)return;let J=this.#Z.get($);if(!J)return;this.#Z.delete($),this.#Z.set($,J);let Y=(this.#z.get(J.sessionId)??0)+1;this.#z.delete(J.sessionId),this.#z.set(J.sessionId,Y),v1(this.#z,this.#X);let X={...J,previousRequestId:this.#G.get(J.sessionId),sequence:Y};if(X.previousRequestId===void 0)delete X.previousRequestId;return X}commit($,J){if(!$||!J||!x3(J))return!1;if((this.#W.get($.sessionId)??0)!==$.generation)return!1;let Y=this.#Z.get($.requestToken);if(!Y||Y.sessionId!==$.sessionId||Y.messageId!==$.messageId||Y.promptId!==$.promptId||Y.generation!==$.generation)return!1;if(this.#J.get(this.#K($.sessionId,$.messageId))!==$.promptId)return!1;if($.sequence<(this.#V.get($.sessionId)??0))return!1;return this.#V.delete($.sessionId),this.#V.set($.sessionId,$.sequence),v1(this.#V,this.#X),this.#G.delete($.sessionId),this.#G.set($.sessionId,J),v1(this.#G,this.#X),!0}clearSession($){this.#W.set($,(this.#W.get($)??0)+1),this.#G.delete($),this.#z.delete($),this.#V.delete($);let J=`${$}\x00`;for(let Y of this.#J.keys())if(Y.startsWith(J))this.#J.delete(Y);for(let Y of this.#Y.keys())if(Y.startsWith(J))this.#Y.delete(Y);for(let[Y,X]of this.#Z)if(X.sessionId===$)this.#Z.delete(Y);v1(this.#W,this.#X)}#K($,J){return`${$}\x00${J}`}}import{setBounded as k3,stickyRetainRetryHeaders as tY,stickyRetryAfterWithJitter as eY}from"@cortexkit/anthropic-auth-core";var q4="cache-diagnosis-2026-04-07",$5="MC-CACHE-DIAG ",J5=1000,Z5=300000,Y5={turn:!1,start:!0,prewarm_cachekeep:!0},X5=1000;class mJ{entries=new Map;previousFor($){return this.entries.get($)??null}capture($,J,Y){k3(this.entries,$,{messageId:J,receivedAt:Y},J5)}}class pJ{hashes=new Map;capture($,J){if(this.hashes.has($))return null;return k3(this.hashes,$,!0,X5),`MC-CACHE-DIAG-BETAS ${JSON.stringify({hash:$,betas:[...J].sort()})}`}}function _9($,J,Y){let X=$.get(J);if(X)$.set(Y,X)}async function L9($,J,Y,X,z,V=!1){let j=V?tY($.headers):new Headers($.headers);if(!V)j.set("retry-after",String(eY(J,Y)));if(X)return await $.body?.cancel().catch(()=>{}),j.set("content-type","application/json"),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:V?"Sticky OAuth account quota is unconfirmed; retrying shortly while retaining session affinity.":"Sticky OAuth account quota resets shortly; retaining session affinity."}}),{status:429,headers:j});let N=new Response($.body,{status:$.status,statusText:$.statusText,headers:j});return _9(z,$,N),N}function O9($,J){$.diagnostics={previous_message_id:J}}function j1($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function G5($){return j1($)&&$.type==="ephemeral"}function v3($,J){if(!G5($))return;J.push($.ttl==="1h"?"1h":"5m")}function f3($,J){if(!Array.isArray($))return;for(let Y of $)if(j1(Y))v3(Y.cache_control,J)}function N9($){if(!j1($))return null;let J=[];if(v3($.cache_control,J),f3($.system,J),Array.isArray($.messages)){for(let Y of $.messages)if(j1(Y))f3(Y.content,J)}return J.at(-1)??null}function W5($){if(!Object.hasOwn($,"diagnostics"))return{state:"absent"};let J=$.diagnostics;if(J===null)return{state:"server_null"};if(!j1(J))return null;if(!Object.hasOwn(J,"cache_miss_reason"))return null;let Y=J.cache_miss_reason;if(Y===null)return{state:"pending"};if(!j1(Y)||typeof Y.type!=="string"||!Y.type)return null;let X=Y.cache_missed_input_tokens;if(X!==void 0&&typeof X!=="number")return null;return{state:"populated",missReason:Y.type,cacheMissedInputTokens:X}}function P4($,J){let Y=$[J];return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function h3($){if(typeof $.source!=="string"||$.source.length===0||typeof $.accountId!=="string"||$.accountId.length===0||typeof $.synthetic!=="boolean"||typeof $.betasHash!=="string"||$.betasHash.length===0)return{};let J=Y5[$.source];if(J!==void 0&&J!==$.synthetic)$.onWarning?.(`cache diagnostics source/synthetic mismatch: source=${$.source} expected=${J} actual=${$.synthetic}`);let Y=Math.trunc($.receivedAt);if(!Number.isFinite($.receivedAt)||Y!==$.receivedAt)return{};if(!j1($.message))return{};let X=$.message.id,z=$.message.model,V=$.message.usage;if(typeof X!=="string"||X.length===0)return{};if(typeof z!=="string"||z.length===0||!j1(V))return{};let j=P4(V,"input_tokens"),N=P4(V,"cache_read_input_tokens"),F=P4(V,"cache_creation_input_tokens"),C=V.cache_creation;if(j===null||N===null||F===null||!j1(C))return{};let q=P4(C,"ephemeral_5m_input_tokens"),M=P4(C,"ephemeral_1h_input_tokens");if(q===null||M===null)return{};let c=W5($.message);if(!c)return{};let l={v:2,source:$.source,account_id:$.accountId,synthetic:$.synthetic,betas_hash:$.betasHash,session_id:$.request.sessionId,ts_ms_received:Y,model:z,is_subagent:$.request.isSubagent,ttl_sent:$.request.ttlSent,cache_read:N,cache_creation:F,input_tokens:j,ephemeral_5m_tokens:q,ephemeral_1h_tokens:M,message_id:X,previous_message_id:$.request.previousMessageId,diag_state:c.state};if(c.missReason!==void 0)l.miss_reason=c.missReason;if(c.cacheMissedInputTokens!==void 0)l.cache_missed_input_tokens=c.cacheMissedInputTokens;if($.requestedModel!==void 0&&$.requestedModel!==z)l.requested_model=$.requestedModel;let K0=c.missReason==="previous_message_not_found"&&$.request.previousMessageId!==null&&$.request.previousMessageReceivedAt!==void 0&&$.receivedAt-$.request.previousMessageReceivedAt<Z5&&$.receivedAt>=$.request.previousMessageReceivedAt?{messageId:X,previousMessageId:$.request.previousMessageId}:void 0;return{record:l,messageId:X,...K0?{canary:K0}:{}}}function b3($){return`${$5}${JSON.stringify($)}`}import{getClaustrumMode as D9,hasNoLocalCredential as cJ,isCustodyTombstoneOAuth as z5,isOAuthAccount as lJ,nativeAccountCanServe as uJ}from"@cortexkit/anthropic-auth-core";function M4($,J){if(D9(J)!=="claustrum"||!J?.claustrum?.scopedRoster)return!1;let Y=J.accounts.find((X)=>X.id===$);return Boolean(Y&&lJ(Y)&&uJ(Y)&&Y.claustrumScopedCredentialId&&Y.anthropicAccountUuid&&cJ(Y))}function g3($){if(D9($)!=="claustrum")return{fallbacks:"R",evidence:"V"};if(!$?.claustrum?.scopedRoster)return{fallbacks:"M",evidence:"N"};return{fallbacks:$.accounts.filter((Y)=>uJ(Y)&&lJ(Y)).every((Y)=>Boolean(Y.claustrumScopedCredentialId&&Y.anthropicAccountUuid&&cJ(Y)))?"T":"R",evidence:"V"}}function dJ($){if(z5($,"anthropic"))return"T";if($.type==="oauth"&&$.access&&$.refresh)return"R";return"X"}function iJ($,J){if($.role==="main"){if(D9(J)!=="claustrum")return"na";let X=J?.claustrum?.scopedRoster?J.claustrum.primaryAccount:void 0;if(!X)return"unknown-identity";if(X.state==="needs_reauth")return"on-vault-reauth";return uJ(X)?"on-vault-served":"on-cold"}if(D9(J)!=="claustrum")return"off";let Y=J?.accounts.find((X)=>X.id===$.id);if(!Y||!lJ(Y)||!Y.claustrumScopedCredentialId||!Y.anthropicAccountUuid||!cJ(Y))return"off";if(Y.claustrumScopedState==="needs_reauth")return"on-vault-reauth";return M4($.id,J)?"on-vault-served":"on-cold"}class R4 extends Error{verdict;dimensions;code="custody_state_mismatch";constructor($,J){super(`custody state mismatch: ${$}`);this.verdict=$;this.dimensions=J}toJSON(){return{code:this.code,verdict:this.verdict,dimensions:this.dimensions}}}function y3($){if($.authority!=="committed"&&$.authority!=="retired")throw new R4("MIGRATION_REQUIRED",$);if($.mode==="L"&&$.main==="R"&&$.evidence==="V"&&$.localOAuthServable===!0)return{verdict:"LOCAL_SERVE"};if($.mode==="L"&&$.main==="T"&&$.fallbacks==="R"&&$.evidence==="V")return{verdict:"LOCAL_SERVE"};if($.mode==="C"&&$.main==="T"&&$.fallbacks==="T"&&$.evidence==="V")return{verdict:"CLAUSTRUM_SERVE"};throw new R4("FAIL_CLOSED",$)}import{createHash as V5}from"node:crypto";import{defaultAdaptiveEffort as j5,logger as K5,normalizeAdaptiveEffort as _5,pinsEffortOnEveryRequest as m3,resolveClaudeModelCapabilities as L5,supportsPerMessageEffort as O5}from"@cortexkit/anthropic-auth-core";var d3=512,N5=1024,D5=4096,x4=32,I4=32,U9="[A-Za-z0-9_-]{1,128}",H5="<cortexkit-internal-effort ",U5="<cortexkit-internal-effort-plan ",i3=/^\s*(?:§[0-9]+§\s*)+$/,f4={low:"l",medium:"m",high:"h",xhigh:"x",max:"z"},sJ=Object.fromEntries(Object.entries(f4).map(([$,J])=>[J,$])),aJ="<cortexkit-internal-effort-v2 ",tJ="<cortexkit-internal-effort-anchor-v1 ",$4="x-cortexkit-effort-plan";class C0 extends Error{check;details;constructor($,J="unspecified",Y={}){super($);this.check=J;this.details=Y;this.name="EffortMarkerCorrelationError"}}function e0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Q5($){let J=L5($);if(!J||J.effortMarkers==="none")return;return J.id.replace(/^claude-/,"")}function nJ($){if($?.info?.role!=="user")return;if($.info.model?.providerID!=="anthropic")return;return Q5($.info.model.modelID)}function p3($){return _5($.info?.model?.variant)??j5($.info?.model?.modelID)}function c3($){return $.parts?.some((J)=>{if(J.type==="text")return J.ignored!==!0&&J.text!=="";if(J.type==="file")return J.mime!=="text/plain"&&J.mime!=="application/x-directory";return J.type==="compaction"||J.type==="subtask"})??!1}function a$($){return V5("sha256").update($).digest("hex")}function B5($){return a$(`scope:${$}`).slice(0,I4)}function Q9($){return a$(`cortexkit-effort-v2:${$}`).slice(0,x4)}function F5($,J,Y){let X=f4[Y],z=`transition:${$}:${J}:${X}`;return`${aJ}scope="${$}" boundary="${J}" effort="${X}" check="${Q9(z)}"/>`}function n3($){let J=$.match(new RegExp(`^${aJ}scope="([0-9a-f]{${I4}})" boundary="(${U9})" effort="([lmhxz])" check="([0-9a-f]{${x4}})"/>$`));if(!J)return null;let[,Y,X,z,V]=J,j=sJ[z??""];if(!Y||!X||!z||!V||!j)return null;let N=`transition:${Y}:${X}:${z}`;if(Q9(N)!==V)return null;return{scope:Y,boundary:X,effort:j,token:$}}function T5($,J,Y,X){let z=f4[Y],V=`anchor:${$}:${J}:${z}:${X}`;return`${tJ}scope="${$}" boundary="${J}" effort="${z}" digest="${X}" check="${Q9(V)}"/>`}function r3($){let J=$.match(new RegExp(`^${tJ}scope="([0-9a-f]{${I4}})" boundary="(${U9})" effort="([lmhxz])" digest="([0-9a-f]{64})" check="([0-9a-f]{${x4}})"/>$`));if(!J)return null;let[,Y,X,z,V,j]=J,N=sJ[z??""];if(!Y||!X||!z||!V||!j||!N)return null;let F=`anchor:${Y}:${X}:${z}:${V}`;if(Q9(F)!==j)return null;return{scope:Y,boundary:X,effort:N,digest:V,token:$}}function rJ($){return $.trim()===""||i3.test($)}function l3(){return new RegExp(`(?:${U5}nonce="[^"]+" baseline="[^"]+" count="[^"]+" sig="[0-9a-f]+"/>|${H5}nonce="[^"]+" effort="[^"]+" sig="[0-9a-f]+"/>)`,"g")}function w5(){return new RegExp(`${aJ}scope="[0-9a-f]{${I4}}" boundary="${U9}" effort="[lmhxz]" check="[0-9a-f]{${x4}}"/>`,"g")}function S5(){return new RegExp(`${tJ}scope="[0-9a-f]{${I4}}" boundary="${U9}" effort="[lmhxz]" digest="[0-9a-f]{64}" check="[0-9a-f]{${x4}}"/>`,"g")}function o3($,J,Y){let X=0,z=$,V=$.replace(l3(),"");if(V!==$&&i3.test(V))X+=[...$.matchAll(l3())].length,z=V;return z=z.replace(w5(),(j)=>{let N=n3(j);if(!N)return j;return J?.(N),X++,""}),z=z.replace(S5(),(j)=>{let N=r3(j);if(!N)return j;return Y?.(N),X++,""}),{text:z,removed:X}}function E5($){for(let J of $){if(!Array.isArray(J.parts))continue;J.parts=J.parts.flatMap((Y)=>{if(Y.type!=="text"||typeof Y.text!=="string"||!Y.text.includes("<cortexkit-internal-effort"))return[Y];let X=o3(Y.text);if(X.removed===0)return[Y];if(rJ(X.text))return[];return Y.text=X.text,[Y]})}}function H9($,J,Y,X,z){let V=z?`:${z}`:"",j=`plan:${$}:${f4[J]}:${Y.toString(36)}${V}`;return a$([j,...X].join(`
2
2
  `))}function C5($){return["v2",$.scope,f4[$.baseline],$.markerCount.toString(36),$.digest].join(".")}function A5($){if(!$)return null;let J=$.match(/^v2\.([0-9a-f]{32})\.([lmhxz])\.([0-9a-z]+)\.([0-9a-f]{64})$/);if(!J)return null;let[,Y,X,z,V]=J,j=sJ[X??""],N=Number.parseInt(z??"",36);if(!Y||!j||!V||!Number.isSafeInteger(N)||N<0||N>d3)return null;return{scope:Y,baseline:j,markerCount:N,digest:V}}function s3($){let J=$.findLast((l)=>l.info?.role==="user"),Y=nJ(J);if(!J||!Y)return null;if(E5($),!Array.isArray(J.parts)||!c3(J))return null;let X=J.info?.sessionID,z=J.info?.id;if(typeof X!=="string"||typeof z!=="string")throw new C0("Cannot correlate per-message effort markers without session and message IDs");let V=B5(X),j=$.findLast((l)=>l.info?.role==="user"&&l.parts?.some((K0)=>K0.type==="compaction")),N=typeof j?.info?.id==="string"?j.info.id:void 0,F,C;if(j&&nJ(j)===Y)F=p3(j),C=F;let q=[];for(let l of $){let K0=l.info;if(K0?.role!=="user")continue;if(N&&typeof K0.id==="string"&&K0.id<=N)continue;if(nJ(l)!==Y||!c3(l))continue;let v=p3(l);if(!F){F=v,C=v;continue}if(v===C)continue;if(q.length>=d3)throw new C0("Too many per-message effort changes in the active context");if(!Array.isArray(l.parts)||typeof K0.id!=="string")throw new C0("Cannot mark a per-message effort change without message identity");let j0=F5(V,K0.id,v);l.parts.push({type:"text",text:j0}),q.push(j0),C=v}if(!F)return null;let M=H9(V,F,q.length,q,q.length>0?z:void 0),c=q.length>0?T5(V,z,C??F,M):void 0;if(c)J.parts.push({type:"text",text:c});return{scope:V,baseline:F,markerCount:q.length,digest:M,transitionTokens:q,anchorToken:c,sessionId:X,messageId:z}}function P5($){let J=Array.isArray($.messages)?$.messages:[],Y=[];for(let X of J){let z=[],V=[];if(!e0(X)||X.role!=="user"){Y.push({value:X,transitions:z,anchors:V});continue}let j=(N)=>o3(N,(F)=>z.push(F),(F)=>V.push(F));if(typeof X.content==="string"){let N=j(X.content);X.content=N.removed>0&&rJ(N.text)?"":N.text}else if(Array.isArray(X.content))X.content=X.content.flatMap((N)=>{if(!e0(N)||N.type!=="text"||typeof N.text!=="string")return[N];let F=j(N.text);if(F.removed>0&&rJ(F.text))return[];return[{...N,text:F.text}]});Y.push({value:X,transitions:z,anchors:V})}return $.messages=Y.map((X)=>X.value),{messages:Y}}function q5($,J){let Y=$[J]?.value,X=$[J-1]?.value;if(!e0(Y)||Y.role!=="user"||!Array.isArray(Y.content)||Y.content.length===0||!e0(X)||X.role!=="assistant"||!Array.isArray(X.content))return!1;let z=new Set(X.content.flatMap((V)=>e0(V)&&V.type==="tool_use"&&typeof V.id==="string"?[V.id]:[]));return Y.content.every((V)=>e0(V)&&V.type==="tool_result"&&typeof V.tool_use_id==="string"&&z.has(V.tool_use_id))}function M5($,J){if(J<0)return!1;let Y=$.flatMap((X,z)=>z>J&&e0(X.value)&&X.value.role==="user"?[z]:[]);return Y.length>0&&Y.every((X)=>q5($,X))}function u3($){if(!e0($))return null;if(typeof $.id==="string")return $.id;return typeof $.message_id==="string"?$.message_id:null}function a3($,J){if(!J)return null;if(J.scope!==$.scope||J.baseline!==$.baseline||J.markerCount!==$.markerCount||J.digest!==$.digest||J.transitionTokens.length!==$.markerCount)throw new C0("Per-message effort marker request plan mismatch");let Y=J.transitionTokens.map((V)=>n3(V)),X=J.anchorToken?r3(J.anchorToken):null,z=Y.at(-1)?.effort??$.baseline;if(Y.some((V)=>V===null)||Y.some((V)=>V?.scope!==$.scope)||$.markerCount>0&&(!X||X.scope!==$.scope||X.boundary!==J.messageId||X.effort!==z||X.digest!==$.digest)||$.markerCount===0&&X!==null||$.digest!==H9($.scope,$.baseline,$.markerCount,J.transitionTokens,J.markerCount>0?J.messageId:void 0))throw new C0("Per-message effort marker request plan mismatch");return{transitions:Y,anchor:X}}function oJ($,J,Y,X){let z=Y.flatMap((M)=>M.transitions),V=z.length,j=$.length-V;if(j<0)throw new C0(`Per-message effort marker correlation failed: expected ${$.length}, found ${V}`);let N=$.slice(j);if(z.some((M,c)=>M.token!==N[c]?.token))throw new C0("Per-message effort marker non-prefix loss");let F=$.slice(0,j);if(X&&F.some((M)=>M.boundary===X.boundary))throw new C0("Per-message effort marker non-prefix loss");let C=[],q=0;return Y.forEach((M,c)=>{if(M.transitions.length===0)return;q+=M.transitions.length,C.push(`${c}:${N[q-1]?.effort}`)}),{effectiveBaseline:F.at(-1)?.effort??J,systemMarkers:C}}function R5($,J){let[Y,X]=$.transitions.length>=J.transitions.length?[$,J]:[J,$],z=Y.transitions.length-X.transitions.length;if(X.transitions.some((j,N)=>j.token!==Y.transitions[z+N]?.token))return!1;let V=z>0?Y.transitions[z-1]?.effort:Y.baseline;return X.baseline===V}function x5($){let{anchor:J,headerPlan:Y,headerAnchor:X}=$;if($.anchorCount!==1||J.scope!==X.scope||J.boundary!==X.boundary)return null;let z=$.recordedVersions.find((V)=>V.sessionId===Y.sessionId&&V.messageId===Y.messageId&&V.digest!==Y.digest&&V.anchorToken===J.token);if(!z)return null;try{let V=a3({scope:z.scope,baseline:z.baseline,markerCount:z.markerCount,digest:z.digest},z);if(!V?.anchor||V.anchor.token!==J.token||V.anchor.effort!==X.effort||!R5({baseline:Y.baseline,transitions:$.headerTransitions},{baseline:z.baseline,transitions:V.transitions}))return null;let j=oJ($.headerTransitions,Y.baseline,$.messages,J),N=oJ(V.transitions,z.baseline,$.messages,J);if(j.effectiveBaseline!==N.effectiveBaseline||j.systemMarkers.join(`
3
3
  `)!==N.systemMarkers.join(`
4
4
  `))return null}catch(V){if(V instanceof C0)return null;throw V}return z}function t3($,J,Y,X,z=[]){if(!Array.isArray($.messages))return{found:0,inserted:0};let V=A5(Y);if(Y&&!V)throw new C0("Missing or invalid internal per-message effort request plan");let j=V?a3(V,X):null,N=j?.transitions??null;if(!$.messages.some((s)=>{if(!e0(s)||s.role!=="user")return!1;if(typeof s.content==="string"&&s.content.includes("<cortexkit-internal-effort"))return!0;return Array.isArray(s.content)&&s.content.some((w0)=>e0(w0)&&w0.type==="text"&&typeof w0.text==="string"&&w0.text.includes("<cortexkit-internal-effort"))})){if(!V)return{found:0,inserted:0};if(V.markerCount!==0){let s=$.messages.findLastIndex((i0)=>e0(i0)&&i0.role==="user"),w0=$.messages[s],D$=e0(w0)&&Array.isArray(w0.content)?w0.content:[];throw new C0(`Per-message effort marker correlation failed: expected ${V.markerCount}, found 0`,"missing_all_markers",{markerCount:V.markerCount,resolvedPlan:j!==null,plannedBoundaryId:j?.anchor?.boundary??null,expectedAnchorHash:j?.anchor?a$(j.anchor.token):null,retainedMessageCount:$.messages.length,retainedUserMessageCount:$.messages.filter((i0)=>e0(i0)&&i0.role==="user").length,lastUserMessageIndex:s,lastUserTextBlockCount:D$.filter((i0)=>e0(i0)&&i0.type==="text").length,lastUserToolResultBlockCount:D$.filter((i0)=>e0(i0)&&i0.type==="tool_result").length})}if(!N&&V.digest!==H9(V.scope,V.baseline,0,[]))throw new C0("Per-message effort marker request plan mismatch");if(J&&m3($.model)){let s=e0($.output_config)?{...$.output_config}:{};s.effort=N?.at(-1)?.effort??V.baseline,$.output_config=s}return{found:0,inserted:0}}let C=P5($),q=C.messages.flatMap((s)=>s.transitions),M=C.messages.flatMap((s)=>s.anchors),c=q.length;if(!V){if(c===0)return{found:0,inserted:0};throw new C0("Missing or invalid internal per-message effort request plan")}for(let s of C.messages){for(let w0 of s.transitions)if(w0.scope!==V.scope)throw new C0("Per-message effort marker scope mismatch");if(s.anchors.length>1)throw new C0("Multiple internal per-message effort anchors on one user boundary")}let l=C.messages.findIndex((s)=>s.anchors.length===1),K0=C.messages.findLastIndex((s)=>e0(s.value)&&s.value.role==="user"),v=M[0],j0=C.messages[K0]?.value,n0=M5(C.messages,l);if(V.markerCount>0&&(M.length!==1||l!==K0&&!n0||!v||v.scope!==V.scope))throw new C0("Missing or invalid internal per-message effort anchor placement","anchor_placement",{anchorBoundaryId:v?.boundary??null,plannedBoundaryId:j?.anchor?.boundary??null,lastUserMessageId:u3(j0),anchorMessageIndex:l,lastUserMessageIndex:K0,validToolContinuationSuffix:n0,anchorsFound:M.length,markerCount:V.markerCount,scope:V.scope,foundScope:v?.scope??null,expectedAnchorHash:j?.anchor?a$(j.anchor.token):null,foundAnchorHash:v?a$(v.token):null,anchorMatchesExpected:j?.anchor!=null&&v?.token===j.anchor.token});if(V.markerCount===0&&M.length!==0)throw new C0("Unexpected internal per-message effort anchor");if(j?.anchor&&v?.token!==j.anchor.token){let s=v&&X&&N?x5({anchor:v,anchorCount:M.length,headerPlan:X,headerTransitions:N,headerAnchor:j.anchor,recordedVersions:z,messages:C.messages}):null;if(!s)throw new C0("Mismatched internal per-message effort anchor token","anchor_token",{anchorBoundaryId:v?.boundary??null,plannedBoundaryId:j.anchor.boundary,lastUserMessageId:u3(j0),anchorMessageIndex:l,lastUserMessageIndex:K0,anchorsFound:M.length,markerCount:V.markerCount,scope:V.scope,foundScope:v?.scope??null,expectedAnchorHash:a$(j.anchor.token),foundAnchorHash:v?a$(v.token):null,anchorMatchesExpected:!1});K5.warn("effort-history","accepted an earlier effort anchor whose plan gives the same efforts",{check:"anchor_token_equivalent_plan",plannedBoundaryId:j.anchor.boundary,markerCount:V.markerCount,foundPlanMarkerCount:s.markerCount,markersFound:c,expectedAnchorHash:a$(j.anchor.token),foundAnchorHash:v?a$(v.token):null})}let w=V.baseline;if(N)w=oJ(N,V.baseline,C.messages,v).effectiveBaseline;else{if(c!==V.markerCount)throw new C0(`Per-message effort marker correlation failed: expected ${V.markerCount}, found ${c}`);let s=H9(V.scope,V.baseline,V.markerCount,q.map((D$)=>D$.token),v?.boundary);if(V.digest!==s)throw new C0("Per-message effort marker request plan mismatch");let w0=q.at(-1)?.effort??V.baseline;if(v&&(v.effort!==w0||v.digest!==V.digest))throw new C0("Missing or invalid internal per-message effort anchor")}let B0=J&&O5($),D0=0,H0=[];for(let s of C.messages){let w0=s.transitions.at(-1);if(w0&&B0)H0.push({role:"system",content:[],output_config:{effort:w0.effort}}),D0++;H0.push(s.value)}if($.messages=H0,B0&&(D0>0||m3($.model))){let s=e0($.output_config)?{...$.output_config}:{};s.effort=w,$.output_config=s}return{found:c,inserted:D0}}class eJ{plans=new Map;history=new Map;historyByMessage=new Map;record($){let J=this.key($.sessionId,$.messageId),Y={...$,transitionTokens:[...$.transitionTokens]};this.remember(J,Y),this.plans.delete(J),this.plans.set(J,Y);while(this.plans.size>N5){let X=this.plans.keys().next().value;if(typeof X!=="string")break;this.plans.delete(X)}}clear($,J){let Y=this.key($,J);this.plans.delete(Y);for(let X of this.historyByMessage.get(Y)??[])this.history.delete(X);this.historyByMessage.delete(Y)}markHeaders($){let J=this.key($.sessionId,$.messageId),Y=this.plans.get(J);if(!Y)return!1;return $.headers[$4]=this.remember(J,Y),this.plans.delete(J),this.plans.set(J,Y),!0}resolveHeader($){return $?this.history.get($):void 0}versionsFor($,J){return[...this.historyByMessage.get(this.key($,J))??[]].flatMap((X)=>{let z=this.history.get(X);return z?[z]:[]})}remember($,J){let Y=C5(J),X=this.history.get(Y);if(X&&this.key(X.sessionId,X.messageId)!==$){if(X.markerCount!==0||J.markerCount!==0||X.sessionId!==J.sessionId)throw new C0("Per-message effort plan header collision");let V=this.key(X.sessionId,X.messageId),j=this.historyByMessage.get(V);if(j?.delete(Y),j?.size===0)this.historyByMessage.delete(V)}this.history.delete(Y),this.history.set(Y,J);let z=this.historyByMessage.get($)??new Set;z.add(Y),this.historyByMessage.set($,z);while(this.history.size>D5){let V=this.history.entries().next().value;if(!V)break;let[j,N]=V;this.history.delete(j);let F=this.key(N.sessionId,N.messageId),C=this.historyByMessage.get(F);if(C?.delete(j),C?.size===0)this.historyByMessage.delete(F)}return Y}key($,J){return`${$}\x00${J}`}}import{resolveClaudeModelCapabilities as I5}from"@cortexkit/anthropic-auth-core";var e3="claude-opus-4-8",$Z=10,ZZ="source-warm:";function J4($,J){return`${ZZ}${$}:${J}`}function k4($){if(!$.startsWith(ZZ))return null;let J=$.slice(ZZ.length),Y=J.lastIndexOf(":");if(Y<=0)return null;let X=J.slice(0,Y),z=J.slice(Y+1);if(z!=="fable-5"&&z!=="fable-5-1"&&z!=="opus-5"&&z!=="opus-5-5")return null;return{sessionId:X,family:z}}function JZ($,J){return`${$}\x00${J}`}var $7=128,f5=86400000;function X$($){return I5($)?.refusalRecoveryFamily??null}function B9($){return X$($)!==null}function k5($,J){let Y=X$(J);return Y?`${$}\x00${Y}`:null}function v5($){try{let J=JSON.parse($);return typeof J.model==="string"?{body:J,model:J.model}:null}catch{return null}}class YZ{now;recoveries=new Map;selectedModels=new Map;nextCycle=1;constructor($=Date.now){this.now=$}prune(){let $=this.now();for(let[J,Y]of this.recoveries)if($-Y.updatedAt>=f5)this.recoveries.delete(J);while(this.recoveries.size>$7){let J=this.recoveries.keys().next().value;if(typeof J!=="string")break;this.recoveries.delete(J)}}clearSession($){this.selectedModels.delete($);for(let J of this.recoveries.keys())if(J.startsWith(`${$}\x00`))this.recoveries.delete(J)}resetForModelChange($,J){let Y=this.selectedModels.get($),X=Y!==void 0&&Y!==J;if(X)this.clearSession($);this.selectedModels.delete($),this.selectedModels.set($,J);while(this.selectedModels.size>$7){let z=this.selectedModels.keys().next().value;if(z===void 0)break;this.selectedModels.delete(z)}return X}plan($,J){if(!$||typeof J!=="string")return null;this.prune();for(let[V,j]of[...this.recoveries]){if(!V.startsWith(`${$}\x00`))continue;j.updatedAt=this.now(),this.recoveries.delete(V),this.recoveries.set(V,j)}let Y=v5(J);if(!Y||!B9(Y.model))return null;let X=k5($,Y.model);if(!X)return null;let z=this.recoveries.get(X);if(z)z.nextRequestSequence++;if(!z||z.remaining<=0)return{sessionId:$,recoveryKey:X,requestedModel:Y.model,effectiveModel:Y.model,bodyText:J,downgraded:!1,cycle:z?.cycle,standbyCacheAnchor:z?.standbyCacheAnchor};return z.updatedAt=this.now(),this.recoveries.delete(X),this.recoveries.set(X,z),Y.body.model=e3,{sessionId:$,recoveryKey:X,requestedModel:z.model,effectiveModel:e3,bodyText:JSON.stringify(Y.body),downgraded:!0,cycle:z.cycle,cacheAccountId:z.cacheAccountId,standbyCacheAnchor:z.standbyCacheAnchor,requestSequence:z.nextRequestSequence}}recoveryAccount($){if($.cycle===void 0)return $.cacheAccountId;let J=this.recoveries.get($.recoveryKey);return J?.cycle===$.cycle?J.cacheAccountId:$.cacheAccountId}bindRecoveryAccount($,J){if(!$.downgraded||$.cycle===void 0)return!1;let Y=this.recoveries.get($.recoveryKey);if(!Y||Y.cycle!==$.cycle)return!1;if(Y.cacheAccountId===J)return!1;return Y.cacheAccountId=J,Y.standbyCacheAnchor=void 0,Y.standbyAnchorSequence=0,Y.sourceWarm=void 0,Y.updatedAt=this.now(),$.cacheAccountId=J,$.standbyCacheAnchor=void 0,!0}activate($,J,Y){if($.downgraded||!B9($.requestedModel))return this.remaining($);let X=this.recoveries.get($.recoveryKey),z=X&&X.sourceSuccesses<$Z?X.reRefusals+1:0,V={model:$.requestedModel,remaining:$Z*2**Math.min(z,2),reRefusals:z,sourceSuccesses:0,cycle:this.nextCycle++,cacheAccountId:J,standbyCacheAnchor:$.standbyCacheAnchor,sourceWarm:Y?{...Y,warmsSinceUserTurn:0}:void 0,nextRequestSequence:0,standbyAnchorSequence:0,updatedAt:this.now()};return this.recoveries.delete($.recoveryKey),this.recoveries.set($.recoveryKey,V),this.prune(),V.remaining}sourceWarmFor($){return this.recoveries.get($)?.sourceWarm}sourceWarmForTarget($){let J=k4($);if(!J)return;return this.sourceWarmFor(JZ(J.sessionId,J.family))}hasSourceWarmForSession($){for(let J of this.recoveries.keys())if(J.startsWith(`${$}\x00`)&&this.recoveries.get(J)?.sourceWarm)return!0;return!1}sourceWarmsForSession($){let J=[];for(let[Y,X]of this.recoveries)if(Y.startsWith(`${$}\x00`)&&X.sourceWarm)J.push({recoveryKey:Y,warm:X.sourceWarm});return J}dropSourceWarm($){let J=this.recoveries.get($);if(!J?.sourceWarm)return!1;return J.sourceWarm=void 0,J.updatedAt=this.now(),!0}dropSourceWarmForTarget($){let J=k4($);if(!J)return!1;return this.dropSourceWarm(JZ(J.sessionId,J.family))}noteSourceWarmSent($){let J=this.recoveries.get($)?.sourceWarm;if(!J)return;return J.warmsSinceUserTurn++,J.warmsSinceUserTurn}noteSourceWarmSentForTarget($){let J=k4($);if(!J)return;return this.noteSourceWarmSent(JZ(J.sessionId,J.family))}noteSourceWarmUserTurn($,J){let Y=!1;for(let[X,z]of this.recoveries){let V=X.startsWith(`${$}\x00`)?z.sourceWarm:void 0;if(!V)continue;if(V.lastUserTurnKey===void 0){V.lastUserTurnKey=J;continue}if(V.lastUserTurnKey!==J)V.lastUserTurnKey=J,V.warmsSinceUserTurn=0,Y=!0}return Y}completeSource($,J=!0){if($.downgraded||$.cycle==null||$.completed)return!1;$.completed=!0;let Y=this.recoveries.get($.recoveryKey);if(!Y||Y.cycle!==$.cycle||Y.remaining>0)return!1;if(!J)return Y.sourceSuccesses=0,!1;return Y.sourceSuccesses=Math.min(Y.sourceSuccesses+1,$Z),Y.updatedAt=this.now(),Y.sourceWarm=void 0,!0}complete($,J){if(!$.downgraded||$.cycle==null||$.completed)return{counted:!1,remaining:this.remaining($)};$.completed=!0;let Y=this.recoveries.get($.recoveryKey);if(!Y||Y.cycle!==$.cycle||Y.remaining<=0)return{counted:!1,remaining:Y?.remaining??0};if(Y.remaining--,J&&(!Y.cacheAccountId||J.oauthAccountId===Y.cacheAccountId)&&$.requestSequence!=null&&$.requestSequence>=Y.standbyAnchorSequence)Y.standbyCacheAnchor=J,Y.standbyAnchorSequence=$.requestSequence;return Y.updatedAt=this.now(),this.recoveries.delete($.recoveryKey),this.recoveries.set($.recoveryKey,Y),{counted:!0,remaining:Y.remaining}}remaining($){return this.prune(),this.recoveries.get($.recoveryKey)?.remaining??0}}function K1($){return typeof $==="object"&&$!==null}function h5($){if(Array.isArray($))return $;if(K1($)&&Array.isArray($.data))return $.data;return[]}function Y7($){if(!K1($)||!K1($.info))return;return $.info}function J7($){let J=Y7($);return typeof J?.role==="string"?J.role:void 0}function b5($){let J=Y7($);return typeof J?.id==="string"?J.id:void 0}function XZ($){if(!K1($)||!K1($.info))return null;let J=$.info,Y=K1(J.model)?J.model:void 0,X=typeof J.agent==="string"?J.agent:void 0,z=typeof Y?.providerID==="string"?Y.providerID:typeof J.providerID==="string"?J.providerID:void 0,V=typeof Y?.modelID==="string"?Y.modelID:typeof Y?.id==="string"?Y.id:typeof J.modelID==="string"?J.modelID:void 0,j=typeof Y?.variant==="string"?Y.variant:typeof J.variant==="string"?J.variant:void 0;if(!X&&(!z||!V)&&!j)return null;let N={};if(X)N.agent=X;if(z&&V)N.model={providerID:z,modelID:V};if(j)N.variant=j;return N}function GZ($,J){return{agent:$.agent??J.agent,model:$.model??J.model,variant:$.variant??J.variant,latestAssistantMessageId:$.latestAssistantMessageId??J.latestAssistantMessageId,latestUserMessageId:$.latestUserMessageId??J.latestUserMessageId}}function Z7($){return Boolean($.agent&&$.model&&$.variant)}async function F9($,J){if(!$||!J)return null;let Y=$,X=[];if(typeof Y.session?.messages==="function")try{X=h5(await Promise.resolve(Y.session.messages({path:{id:J},query:{limit:100}})))}catch{X=[]}let z,V;for(let N of X){let F=b5(N);if(!F)continue;let C=J7(N);if(C==="assistant"&&(!z||F>z))z=F;if(C==="user"&&(!V||F>V))V=F}let j={latestAssistantMessageId:z,latestUserMessageId:V};for(let N=X.length-1;N>=0;N--){if(J7(X[N])!=="assistant")continue;let F=XZ(X[N]);if(!F)continue;if(j=GZ(j,F),Z7(j))return j}for(let N=X.length-1;N>=0;N--){let F=XZ(X[N]);if(!F)continue;if(j=GZ(j,F),Z7(j))return j}if(typeof Y.session?.get==="function")try{let N=await Promise.resolve(Y.session.get({path:{id:J}})),F=K1(N)&&K1(N.data)?N.data:K1(N)?N:void 0,C=F?XZ({info:F}):null;if(C)j=GZ(j,C)}catch{}if(!j.agent&&!j.model&&!j.variant&&!j.latestAssistantMessageId&&!j.latestUserMessageId)return null;return j}var X7="[lane start] — automated cache warm; no response needed.",T9="x-cortexkit-lane-start",g5=1000;function y5($){if(!$||typeof $!=="object")return!1;let J=$;return J.type==="text"&&J.text===X7&&J.synthetic===!0}async function G7($,J){let Y=$?.session;if(typeof Y?.promptAsync!=="function")throw Error("OpenCode plugin client does not support session.promptAsync");let X=await F9($,J),z={noReply:!1,parts:[{type:"text",text:X7,synthetic:!0}]};if(X?.agent)z.agent=X.agent;if(X?.model)z.model=X.model;if(X?.variant)z.variant=X.variant;await Promise.resolve(Y.promptAsync({path:{id:J},body:z}))}class WZ{#$=new Map;observeSyntheticMessage($){if(!$.parts.some(y5))return!1;let J=`${$.sessionId}\x00${$.messageId}`;if(!this.#$.has(J)&&this.#$.size>=g5){let Y=this.#$.keys().next().value;if(Y!==void 0)this.#$.delete(Y)}return this.#$.set(J,$.sessionId),!0}markHeaders($){let J=`${$.sessionId}\x00${$.messageId}`;if(!this.#$.has(J))return!1;return this.#$.delete(J),$.headers[T9]="1",!0}clearSession($){for(let[J,Y]of this.#$)if(Y===$)this.#$.delete(J)}}import{createNativeUi as m5,disconnectNativeVaultForHost as p5,readNativeEnrollmentMode as c5}from"@cortexkit/anthropic-auth-core";function W7($){if(!$?.trim())throw TypeError("sessionId is required");return $}function z7($){if($.host!=="opencode")throw TypeError("OpenCode host is required");let J=m5({...$,readMode:$.readMode??(()=>c5("opencode",process.env)),disconnectVault:$.disconnectVault??(()=>p5({host:"opencode",env:process.env}))});return{menu:J,open(Y){return J.open({sessionId:W7(Y),notify(){}})},apply(Y){return J.apply(Y,{sessionId:W7(Y.sessionId),notify(){}})}}}import{createAnthropicOAuthFetch as l5,logger as V7,requireAnthropicOAuthOrigin as u5}from"@cortexkit/anthropic-auth-core";var zZ="ANTHROPIC_AUTH_TEST_OAUTH_LOOPBACK_ORIGIN",d5=new Set(["127.0.0.1","[::1]","localhost"]),j7;function i5(){let $=process.env[zZ];if(!$)return;let J=n5($);if(j7!==$)if(j7=$,J)V7.warn("oauth-destination","test-only loopback origin is allowed for Claude OAuth requests",{env:zZ});else V7.warn("oauth-destination","ignored an invalid test-only loopback origin; Claude OAuth requests stay limited to https://api.anthropic.com",{env:zZ});return J}function n5($){let J;try{J=new URL($)}catch{return}if(J.protocol!=="http:"&&J.protocol!=="https:")return;if(J.username||J.password||J.search||J.hash)return;if(!d5.has(J.hostname))return;if(!J.port)return;if($!==J.origin)return;return J.origin}function K7(){let $=i5();return $?{extraOrigin:$}:{}}function w9($){return u5($,K7())}function VZ($){try{return w9($),!0}catch{return!1}}var v4=l5(K7);var _7;import{primeStorageFingerprint as r5}from"@cortexkit/anthropic-auth-core";var S9=new Map,E9=new Map;function L7($,J){let Y=E9.get($);if(Y?.fingerprint!==J.fingerprint||Y.marker!==J.marker)return;let X=S9.get(J.fingerprint);if(X?.slots.delete($),X?.slots.size===0)X.manager.stop(),S9.delete(J.fingerprint);E9.delete($)}function O7($,J,Y){let X=r5($),z=S9.get(X),V=z?.manager??J();if(z)Y.rebind(V);let j=E9.get(Y.slot);if(j&&j.fingerprint!==X)L7(Y.slot,j);let N=z??{manager:V,slots:new Set};if(!z)S9.set(X,N);let F={fingerprint:X,marker:Symbol(Y.slot)};return N.slots.add(Y.slot),E9.set(Y.slot,F),{manager:V,release:()=>L7(Y.slot,F)}}import{classifySafeErrorForLog as o5,logger as s5}from"@cortexkit/anthropic-auth-core";function N7($,J,Y){s5.warn("quota","fallback quota preflight could not obtain a reading",{accountId:$,requiredByPolicy:J,...o5(Y)})}var jZ="x-cortexkit-request-class",a5=new Set(["title","summary","compaction","prime"]);function D7($){return typeof $==="string"&&a5.has($)}function H7($){let J=$.get("x-cortexkit-request-class");return $.delete("x-cortexkit-request-class"),J==="auxiliary"?"auxiliary":"main"}import{getKillswitchThresholdsForAccount as t5,getScopedQuotaWindowForModel as e5,killswitchPassesPolicy as $X}from"@cortexkit/anthropic-auth-core";function U7($){let J=$.retryAfterSeconds,Y=J===void 0?"":` Retry in ${Math.floor(J/60)}m ${J%60}s.`;return $.modelName?`${$.modelName} weekly limit reached, no routable accounts.${Y}`:`Killswitch: no routable accounts.${Y}`}function Q7($){if(!$.requestModelId)return{isScopedDriven:!1};if(!$X($.mainQuota,$.storage))return{isScopedDriven:!1};let J=e5($.mainQuota,$.requestModelId);if(!J)return{isScopedDriven:!1};if(!Number.isFinite(J.remainingPercent))return{isScopedDriven:!1};let Y=t5($.storage);if(J.remainingPercent<=Y.scoped)return{isScopedDriven:!0,modelName:J.modelName,modelId:$.requestModelId};return{isScopedDriven:!1}}import{askRouting as JX,getScopedQuotaWindowForModel as ZX,logger as YX,quotaExhaustionFromHeaders as XX,reportRouting as B7,stickyRouteFamilyForModel as GX,stickyRouteKnownFableExhausted as WX}from"@cortexkit/anthropic-auth-core";var zX=920000;function F7($,J){return J.accountIdentity===$.account_id&&(!J.credentialId||J.credentialId===$.credential_id)}function T7($,J,Y,X){if(GX(X)!=="opus")return!0;let z=J.filter((V)=>WX(V,Y));return!z.length||z.some((V)=>V.accountId===$)}var VX=/^[a-z0-9._-]{1,64}$/;function w7($){let J=new Set,Y=(X,z)=>{if(J.has(X))return;if(J.size>=512){let V=J.values().next();if(!V.done)J.delete(V.value)}J.add(X),YX.debug("routing-relay","Using local account choice",{sessionId:X,reason:z})};return{override:Y,async accountFor(X,z,V){let j=await JX({sessionId:X,provider:"anthropic",modelId:z,deadlineMs:2000,candidates:V.flatMap((N)=>N.accountIdentity?[{accountId:N.accountIdentity,credentialId:N.credentialId??"local"}]:[])});if(!j)return Y(X,"no valid answer within routing deadline"),null;return{account_id:j.candidate.accountId,credential_id:j.candidate.credentialId,...j.hold&&j.hold.retry_after_ms>0?{hold:{retry_after_ms:Math.min(j.hold.retry_after_ms,zX)}}:{}}},report(X,z,V,j,N,F=j<400){if(!z.accountIdentity)return;let C={sessionId:X,accountId:z.accountIdentity,...z.credentialId?{credentialId:z.credentialId}:{}},q=[];if(F&&j<400){let c={};V.forEach((l,K0)=>{if(K0.toLowerCase().startsWith("anthropic-ratelimit-"))c[K0.toLowerCase()]=l}),q.push({...C,outcome:"served",headers:c})}let M=j===429?XX(V,N):void 0;if(M){for(let[c,l]of[["5h",M.five_hour],["7d",M.seven_day]])if(l)q.push({...C,outcome:"exhausted",window:c,...l.resetsAt?{resetsAt:Date.parse(l.resetsAt)}:{}});if(!q.length&&!M.scoped?.length)q.push({...C,outcome:"exhausted",window:"7d"})}Promise.resolve().then(async()=>{for(let c of q)B7(c);if(M?.scoped?.length){let c=await $?.(z),l=ZX({scoped:c?.scoped?.filter((v)=>v.id.startsWith("claude-weekly-scoped-"))},N),K0=(l?.modelId??l?.modelName)?.trim().toLowerCase();if(!K0||!VX.test(K0))return;for(let v of M.scoped)B7({...C,outcome:"exhausted",window:"7d",pool:K0,...v.resetsAt?{resetsAt:Date.parse(v.resetsAt)}:{}})}}).catch(()=>{})}}}var l$=[],jX=1,S7=new Map,C9=new Map,h1=new Set,KX=1000;function E7($){if(typeof $!=="string"||$.length===0)throw TypeError("sessionId is required")}function KZ($,J){E7(J);let Y=jX++;if("menu"in $){if($.command!=="claude"||$.menu.command!=="claude")throw TypeError("Only the claude menu is supported");l$.push({id:Y,type:"open-menu",payload:$,sessionId:J})}else l$.push({id:Y,type:"open-dialog",payload:$,sessionId:J});if(l$.length>100)l$=l$.slice(l$.length-100);return Y}function C7($,J,Y){let X=KZ($,J);return new Promise((z)=>{let V;C9.set(X,{picked(){if(V!==void 0)Y.clearTimeout(V);z(!0)},cancel(){if(V!==void 0)Y.clearTimeout(V);z(!1)}}),V=Y.setTimeout(()=>{if(!C9.delete(X))return;if(l$=l$.filter((j)=>j.id!==X),h1.delete(J),h1.add(J),h1.size>KX){let j=h1.values().next().value;if(j!==void 0)h1.delete(j)}z(!1)},Y.timeoutMs)})}function A7($){return h1.has($)}function P7($,J){if(E7(J),S7.set(J,Date.now()),h1.delete(J),$>0)l$=l$.filter((X)=>X.id>$||X.sessionId!==J);let Y=l$.filter((X)=>X.id>$&&X.sessionId===J);for(let X of Y){let z=C9.get(X.id);if(!z)continue;C9.delete(X.id),z.picked()}return Y}function A9($){let J=Date.now(),Y=S7.get($)??0;return Y>0&&J-Y<3000}import{randomBytes as _X,timingSafeEqual as LX}from"node:crypto";import{readFile as OX,unlink as NX}from"node:fs/promises";import{createServer as DX}from"node:http";import{join as HX}from"node:path";import{parseApplyRequest as UX}from"@cortexkit/anthropic-auth-core";function QX($){return new Promise((J,Y)=>{let X=[],z=0;$.on("data",(V)=>{if(z+=V.length,z>1e6){$.destroy(),Y(Error("body too large"));return}X.push(V)}),$.on("end",()=>J(Buffer.concat(X).toString("utf8"))),$.on("error",Y)})}function BX($,J){if(!$?.startsWith("Bearer "))return!1;let Y=Buffer.from($.slice(7)),X=Buffer.from(J);return Y.length===X.length&&LX(Y,X)}async function M7($){let J=_X(32).toString("hex"),Y=DX((V,j)=>{X(V,j)});async function X(V,j){let N=(F,C)=>{j.writeHead(F,{"content-type":"application/json"}),j.end(JSON.stringify(C))};try{let F=V.url??"";if(V.method==="GET"&&F==="/health")return N(200,{ok:!0});if(V.method!=="POST"||!F.startsWith("/rpc/"))return N(404,{error:"not found"});if(!BX(V.headers.authorization,J))return N(401,{error:"unauthorized"});let C=F.slice(5),q=JSON.parse(await QX(V)||"{}");if(C==="pending-notifications"){if(typeof q.sessionId!=="string"||q.sessionId.length===0)return N(400,{error:"sessionId is required"});let M=$.drain(Number(q.lastReceivedId??0),q.sessionId);return N(200,{messages:M})}if(C==="apply"){if(!$.apply)return N(501,{error:"text apply unavailable"});let M=await $.apply(q);return N(200,M)}if(C==="apply-menu"){let M=UX(q);if(M?.command!=="claude"||!M.sessionId?.trim())return N(400,{error:"invalid menu request"});if(!$.applyMenu)return N(501,{error:"menu unavailable"});return N(200,await $.applyMenu(M))}return N(404,{error:"unknown method"})}catch{if(!j.headersSent&&!j.writableEnded&&!j.destroyed)N(500,{error:"RPC request failed"})}}let z=await new Promise((V,j)=>{Y.on("error",j),Y.listen(0,"127.0.0.1",()=>{let N=Y.address();if(N&&typeof N==="object")V(N.port);else j(Error("no port"))})});Y.unref();try{await q7($.dir,{port:z,token:J,pid:process.pid})}catch(V){throw await new Promise((j)=>Y.close(()=>j())),V}return{port:z,token:J,async stop(){await new Promise((V)=>Y.close(()=>V()));try{let V=HX($.dir,`port-${process.pid}.json`),j=JSON.parse(await OX(V,"utf8"));if(j.port===z&&j.pid===process.pid)await NX(V)}catch{}}}}async function R7($,J){let Y=globalThis,X=Y.__anthropicAuthRpcServers??new Map,z=Y.__anthropicAuthRpcServersPending??new Map;Y.__anthropicAuthRpcServers=X,Y.__anthropicAuthRpcServersPending=z;let V=z.get($)??Promise.resolve(),j,N=V.catch(()=>{}).then(async()=>{let C=X.get($);if(C){if(await C.stop(),X.get($)===C)X.delete($)}j=await J(),X.set($,j)});z.set($,N);try{await N}finally{if(z.get($)===N)z.delete($)}let F=j;if(!F)throw Error("RPC server failed to start");return{server:F,release:async()=>{if(X.get($)!==F)return;if(await F.stop(),X.get($)===F)X.delete($)}}}import{resolveClaudeModelCapabilities as FX}from"@cortexkit/anthropic-auth-core";var f7="server-side-fallback-2026-07-01",k7="⁠",P9="cortexkit-server-fallback-v1:";function u$($){return $!==null&&typeof $==="object"&&!Array.isArray($)?$:void 0}function Z4($,J){let Y=$?.[J];return typeof Y==="string"?Y:void 0}function Y4($){return typeof $==="string"&&$.length>0&&$.length<=128&&/^claude-[a-z0-9-]+$/i.test($)}function TX($){return`${P9}${$.fromModel}|${$.toModel}`}function wX($){if(typeof $!=="string"||!$.startsWith(P9))return null;let J=$.slice(P9.length),Y=J.indexOf("|");if(Y<=0||Y!==J.lastIndexOf("|"))return null;let X=J.slice(0,Y),z=J.slice(Y+1);if(!Y4(X)||!Y4(z))return null;return{fromModel:X,toModel:z}}function SX($){if($.type!=="fallback")return null;let J=Z4(u$($.from),"model"),Y=Z4(u$($.to),"model");if(!Y4(J)||!Y4(Y))return null;return{fromModel:J,toModel:Y}}function EX($){return{type:"fallback",from:{model:$.fromModel},to:{model:$.toModel}}}function CX($,J){let Y=0,X=0;if(!Array.isArray($.messages))return{restoredMarkers:Y,droppedMarkers:X};for(let z of $.messages){let V=u$(z);if(V?.role!=="assistant"||!Array.isArray(V.content))continue;let j=[];for(let N of V.content){let F=u$(N);if(!(F?.type==="thinking"&&(F.thinking===k7||F.thinking==="")&&typeof F.signature==="string"&&F.signature.startsWith(P9))){j.push(N);continue}let q=wX(F.signature);if(J&&q)j.push(EX(q)),Y++;else X++}V.content=j}return{restoredMarkers:Y,droppedMarkers:X}}function v7($){return $?.trim().toLowerCase()==="legacy"?"legacy":"server"}function h7($,J){let Y=J&&FX($.model)?.serverSideFallback===!0,X=CX($,Y);if(Y)$.fallbacks="default";else if($.fallbacks==="default")delete $.fallbacks;return{enabled:Y,...X}}function AX($){let J,Y=[];for(let z of $.split(/\r?\n/))if(z.startsWith("event:"))J=z.slice(6).trim();else if(z.startsWith("data:")){let V=z.slice(5);Y.push(V.startsWith(" ")?V.slice(1):V)}let X=Y.join(`
@@ -21,8 +21,8 @@ data: ${JSON.stringify(J)}
21
21
  \r
22
22
  `);if(J===-1)return Y===-1?null:{index:Y,length:4};if(Y===-1||J<Y)return{index:J,length:2};return{index:Y,length:4}}function l7($,J,Y,X){if(!J||$.disabled)return;$.pending+=J;while(!0){let z=X4($.pending);if(!z)break;let V=$.pending.slice(0,z.index);$.pending=$.pending.slice(z.index+z.length);let j=SZ(V);if(!j)continue;if($.events++,R9($.eventCounts,j.event??"unknown"),R9($.typeCounts,j.type),R9($.deltaTypeCounts,j.deltaType),R9($.contentBlockTypeCounts,j.contentBlockType),$.textDeltaBytes+=j.textDeltaBytes??0,$.thinkingDeltaBytes+=j.thinkingDeltaBytes??0,$.inputJsonDeltaBytes+=j.inputJsonDeltaBytes??0,$.signatureDeltaBytes+=j.signatureDeltaBytes??0,$.redactedThinkingBytes+=j.redactedThinkingBytes??0,$.last=j,X?.(j),j.dataBytes>0&&!j.type&&!j.event)$.parseErrors++}if(X8.encode($.pending).byteLength>Y)$.pending="",$.disabled=!0,$.pendingOverflowCount++}function i2(){return{pending:"",completed:!1,disabled:!1,resyncCarry:""}}function n2($,J,Y){if(!J||$.completed)return null;if($.disabled){let z=$.resyncCarry+J,V=X4(z);if(!V)return $.resyncCarry=z.slice(-3),null;if($.disabled=!1,$.resyncCarry="",J=z.slice(V.index+V.length),!J)return null}$.pending+=J;let X=null;while(!0){let z=X4($.pending);if(!z)break;let V=$.pending.slice(0,z.index);$.pending=$.pending.slice(z.index+z.length);let j=SZ(V);if(j?.type!=="message_delta"||!j.stopReason)continue;$.completed=!0,X??=j.stopReason==="refusal"?{type:"content-filter"}:{type:"complete",finishReason:j.stopReason}}if(new TextEncoder().encode($.pending).byteLength>Y){let z=$.pending;$.pending="",$.disabled=!0,$.resyncCarry=z.slice(-3)}return X}function r2(){return{pending:"",disabled:!1}}function u7($){let J=SZ($);if(J?.type!=="message_delta"||J.stopReason!=="max_tokens")return $;return $.replace(/("stop_reason"\s*:\s*)"max_tokens"/,'$1"end_turn"')}function o2($,J,Y,X=!1){if(!J&&!X)return"";if($.disabled)return J;if(new TextEncoder().encode($.pending+J).byteLength>Y){let V=$.pending+J;return $.pending="",$.disabled=!0,V}$.pending+=J;let z="";while(!0){let V=X4($.pending);if(!V)break;let j=$.pending.slice(0,V.index),N=$.pending.slice(V.index,V.index+V.length);$.pending=$.pending.slice(V.index+V.length),z+=u7(j),z+=N}if(X&&$.pending)z+=u7($.pending),$.pending="";return z}function s2(){return{pending:"",disabled:!1,resyncCarry:""}}function a2($,J){let Y=$?.toLowerCase(),X=J.toLowerCase();return Y==="api_error"||Y==="overloaded_error"||Y==="server_error"||Y==="internal_server_error"||X.includes("internal server error")||X.includes("server overloaded")}function t2($,J){let Y=$?`${$}: ${J}`:J,X=Error(`Anthropic stream error: ${Y}`);if(X.code="ECONNRESET",X.syscall="anthropic-sse",$)X.providerErrorType=$;return X}function e2($){let J=i7($)?"Opus 5":"Fable",Y=Error(`${J} response was blocked by the provider content filter; retrying with Opus 4.8`);return Y.code="ECONNRESET",Y.syscall="anthropic-sse",Y.providerErrorType="refusal",Y}function $6($){if(!$.includes("error"))return null;let J,Y=[];for(let C of $.split(/\r?\n/)){if(C.startsWith("event:")){J=C.slice(6).trim();continue}if(C.startsWith("data:")){let q=C.slice(5);Y.push(q.startsWith(" ")?q.slice(1):q)}}let X=Y.join(`
23
23
  `);if(!X||X==="[DONE]")return null;let z;try{z=JSON.parse(X)}catch{return null}let V=t$(z);if(J!=="error"&&$$(V,"type")!=="error")return null;let j=t$(V?.error),N=$$(j,"type")??$$(j,"code")??void 0,F=$$(j,"message")??$$(V,"message")??N??"Anthropic stream error";if(!a2(N,F))return null;return t2(N,F)}function J6($){if(!$.includes("relay_upstream_error"))return;let J=[];for(let Y of $.split(/\r?\n/))if(Y.startsWith("data:")){let X=Y.slice(5);J.push(X.startsWith(" ")?X.slice(1):X)}if(!J.length)return;try{let Y=t$(JSON.parse(J.join(`
24
- `))),X=t$(Y?.error);if($$(X,"type")!=="relay_upstream_error")return;let z=X?.status;if(typeof z==="number"&&Number.isInteger(z))return{status:z,source:"relay_status_field"};let j=$$(X,"message")?.match(/HTTP\s+(\d{3})\b/i);return j?{status:Number(j[1]),source:"relay_message_parse"}:void 0}catch{return}}function d7($,J,Y,X){if(!J)return null;if($.disabled){let V=$.resyncCarry+J,j=X4(V);if(!j)return $.resyncCarry=V.slice(-3),null;if($.disabled=!1,$.resyncCarry="",J=V.slice(j.index+j.length),!J)return null}$.pending+=J;let z=null;while(!0){let V=X4($.pending);if(!V)break;let j=$.pending.slice(0,V.index);$.pending=$.pending.slice(V.index+V.length);let N=J6(j);if(N!==void 0)X?.(N);let F=$6(j);z??=F}if(new TextEncoder().encode($.pending).byteLength>Y){let V=$.pending;$.pending="",$.disabled=!0,$.resyncCarry=V.slice(-3)}return z}function Z6($){return{sseEvents:$.events,ssePendingChars:$.pending.length,ssePendingOverflowCount:$.pendingOverflowCount,sseParseErrors:$.parseErrors,sseEventCounts:{...$.eventCounts},sseTypeCounts:{...$.typeCounts},sseDeltaTypeCounts:{...$.deltaTypeCounts},sseContentBlockTypeCounts:{...$.contentBlockTypeCounts},sseTextDeltaBytes:$.textDeltaBytes,sseThinkingDeltaBytes:$.thinkingDeltaBytes,sseInputJsonDeltaBytes:$.inputJsonDeltaBytes,sseSignatureDeltaBytes:$.signatureDeltaBytes,sseRedactedThinkingBytes:$.redactedThinkingBytes,sseLastEvent:$.last?{...$.last}:void 0}}function G8($,J={}){if(!$.body)return $;let Y=$.body.getReader(),X=new TextDecoder("utf-8",{ignoreBOM:!0}),z=new TextEncoder,V=J.responseMode==="json",j=Q2(J.toolNameMap,V),N=!0,F="",C=0,q=0,M=0,c=0,l=0,K0=!1,v=!1,j0=A0(),n0=A0(),w=J.perf||J.onMessageStart||J.onMessageDelta?u2():void 0,B0="",D0=0,H0=!1,s=(y0)=>{if(!y0)return;try{y0()}catch{}},w0=s2(),D$=J.onContentFilter||J.onComplete?i2():void 0,i0=J.laneStart&&J.laneStartOAuthServed!==!1?r2():void 0,v$=!1,r=!1,B$=(y0=!1)=>{if(!J.onContentFilter)return!1;if(!v$)v$=!0,r=J.onContentFilter({completedToolUse:y0})!==!1;return r},H1=J.serverSideFallbackModel?b7({requestedModel:J.serverSideFallbackModel,maxPendingBytes:d$,onOutcome:J.onServerSideFallbackOutcome,onRefusalAfterToolUse:J.onContentFilter?()=>B$(!0):void 0}):void 0,n1=(y0)=>{if(!D$)return null;let E$=n2(D$,y0,d$);if(E$?.type==="content-filter"&&J.onContentFilter)return B$()?e2(J.contentFilterModel):null;if(E$?.type==="complete")J.onComplete?.(E$.finishReason);return null},r4=(y0,E$=!1)=>i0?o2(i0,y0,d$,E$):y0,C1=()=>{if(v)return;v=!0,Y.releaseLock()},YJ=async(y0)=>{try{await Y.cancel(y0)}catch{}finally{C1()}},XJ=(y0={})=>({chunks:C,pulls:q,inputBytes:M,outputBytes:c,pendingChars:j.pendingLength(),sseErrorPending:w0.pending.length,sseFinishPending:D$?.pending.length??0,sseFinishDisabled:D$?.disabled??!1,serverFallbackPending:H1?.pendingLength()??0,rewriteMs:f$(l),totalMs:f$(A0()-n0),...w?Z6(w):{},...y0}),Z1=(y0,E$={})=>{J.perf?.(y0,XJ(E$))};J.perf?.("stream_tool_prefix_wrapper_created",{status:$.status,hasBody:!0});let GJ=new ReadableStream({async pull(y0){if(q++,!K0)K0=!0,Z1("stream_tool_prefix_first_pull");while(!0){let E$=A0();try{let{done:_4,value:h$}=await Y.read(),L4=f$(A0()-E$);if(_4){let f0=X.decode();if(w&&!V)l7(w,f0,d$,(b0)=>{let b$=b0.message;if(b0.type==="message_start"&&b$)s(()=>J.onMessageStart?.(b$));if(b0.type==="message_delta"&&(b0.usage||b0.stopReason))s(()=>J.onMessageDelta?.({...b0.usage?{usage:b0.usage}:{},...b0.stopReason?{stopReason:b0.stopReason}:{}}))});if(V){let b0=z.encode(f0).byteLength;if(D0+b0<=d$)B0+=f0,D0+=b0;else H0=!0}if(V&&!H0)try{let b0=JSON.parse(B0);if(b0&&typeof b0==="object"&&!Array.isArray(b0))s(()=>J.onMessageResponse?.(b0))}catch{}let q1=A0(),zJ=H1?H1.push(f0)+H1.flush():f0,H$=r4(zJ,!0),Y1=V?n1(H$):d7(w0,f0,d$,J.onRelayUpstreamError)??n1(H$);if(Y1)throw Z1("stream_tool_prefix_retryable_error",{providerErrorType:Y1.providerErrorType}),await YJ(Y1),Y1;let U1=j.push(H$,!0);if(l+=A0()-q1,U1||F){let b0=z.encode(F+U1);F="",c+=b0.byteLength,y0.enqueue(b0)}if(Z1("stream_tool_prefix_rewrite",{readMs:L4}),C1(),J.onStreamEnd)try{await J.onStreamEnd()}catch{}y0.close();return}C++,M+=h$.byteLength;let C$=X.decode(h$,{stream:!0});if(N&&C$){if(N=!1,C$.charCodeAt(0)===65279)F=C$[0]??"",C$=C$.slice(1)}if(V){let f0=h$.byteLength;if(D0+f0<=d$)B0+=C$,D0+=f0;else H0=!0}if(w&&!V)l7(w,C$,d$,(f0)=>{let q1=f0.message;if(f0.type==="message_start"&&q1)s(()=>J.onMessageStart?.(q1));if(f0.type==="message_delta"&&(f0.usage||f0.stopReason))s(()=>J.onMessageDelta?.({...f0.usage?{usage:f0.usage}:{},...f0.stopReason?{stopReason:f0.stopReason}:{}}))});let WJ=A0(),j$=H1?H1.push(C$):C$,G$=r4(j$),O4=V?n1(G$):d7(w0,C$,d$,J.onRelayUpstreamError)??n1(G$);if(O4)throw Z1("stream_tool_prefix_retryable_error",{providerErrorType:O4.providerErrorType,readMs:L4,lastChunkBytes:h$.byteLength}),C1(),O4;let A1=j.push(G$);if(l+=A0()-WJ,A1){let f0=z.encode(F+A1);F="",c+=f0.byteLength,y0.enqueue(f0)}let P1=A0();if(C===1||C%25===0||P1-j0>5000)j0=P1,Z1("stream_tool_prefix_progress",{readMs:L4,lastChunkBytes:h$.byteLength});if(A1)return}catch(_4){s(J.onResponseFailure);let h$=NZ(_4,J.toolNameMap);if(Z1("stream_tool_prefix_error"),h$ instanceof y4)await DZ(Y,h$),v=!0,s(J.onToolNameRefusal);else C1();throw h$}}},async cancel(y0){s(J.onResponseFailure),Z1("stream_tool_prefix_cancel");try{await Y.cancel(y0)}finally{C1()}}});return new Response(GJ,{status:$.status,statusText:$.statusText,headers:$.headers})}import{mergeNativeSettingsSection as MW,nativeCacheKeepAlways as RW,nativeSettingsRecord as xW}from"@cortexkit/anthropic-auth-core";var h8="physical send failed before a response",oG="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",b8="~effect/http/HttpServerResponse",g8="~effect/http/Cookies",y8="~effect/http/HttpBody",sG="~effect/ErrorReporter/ignore",aG="https://api.anthropic.com/v1/messages",JY=new WeakSet;function ZJ($){let J=new Response(JSON.stringify({type:"error",error:{type:"invalid_request_error",message:$}}),{status:400,headers:{"content-type":"application/json"}});return JY.add(J),J}async function m8($,J){if(!J?.aborted)return;await $.body?.cancel().catch(()=>{}),J.throwIfAborted()}function cZ($,J){return($.status!==400||!JY.has($))&&uG($.status,J)}function p8($){return b.warn("effort-history","refused uncorrelated per-message effort request",{check:$.check,...$.details}),ZJ($.message)}function c8($){return b.warn("transform","refused request ending on assistant history",{check:$.check,...$.details}),ZJ($.message)}var tG=60000,l8=60000,ZY=240,eG=ZY,$W=600000;function JW($,J){return($?.accounts??[]).some((Y)=>Y.id===J&&x0(Y)&&R0(Y))}function ZW($){let J=($?.accounts??[]).find((Y)=>x0(Y)&&R0(Y));if($1($)==="fallback-first"&&J)return{activeId:J.id,route:"fallback-first"};return{activeId:"main",route:"main"}}function u8($,J){if($?.activeId==="main"||$?.activeId&&JW(J,$.activeId))return{activeId:$.activeId,route:$.route};return ZW(J)}function YY($,J,Y){let X=Date.now()-$.lastUpdated;if(!$.activeId||X<0||X>$W)return u8(Y,J);return u8({activeId:$.activeId,route:$.route},J)}async function YW($,J,Y){let X;try{X=await J()}catch(z){return b.warn("sidebar","account storage reload failed; routing preserved",{message:z instanceof Error?z.message:String(z)}),{...$.activeId?{activeId:$.activeId,route:$.route}:Y??{activeId:"main",route:"main"},freshStorage:null}}return{...YY($,X,Y),freshStorage:X}}async function XW($){await e9()?.beforeStorageLoad?.();let J;try{J=await $()}catch{return{activeId:"main",route:"main",freshStorage:null}}finally{await e9()?.afterStorageLoad?.()}await e9()?.beforeSidebarRead?.();let Y=await e8();return{...YY(Y,J),freshStorage:J}}var GW=4,WW=25,zW=1,d8=!1;function $J(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function X0(){return performance.now()}function I0($){return Math.round($*10)/10}function i8($){return Math.floor(Math.random()*Math.max(0,$))}function K4($){if(typeof $==="string")return $;if($ instanceof URL)return $.toString();return $.url}function i1($,J){return J?.method??($ instanceof Request?$.method:void 0)}async function d4($,J){if(J?.body!==void 0)return J.body;if(!($ instanceof Request)||$.body===null)return;try{return await $.clone().text()}catch{return}}function VW(){if(d8||!1||!$J())return;d8=!0;let $=100,J=250,Y=X0()+$;setInterval(()=>{let X=X0(),z=X-Y;if(Y=X+$,z<J)return;J1("[perf] opencode event_loop_lag",{lagMs:I0(z),thresholdMs:J})},$).unref?.()}function jW($){let J=X0(),Y={requestId:String(zW++),start:J,last:J,mark(X,z){let V=X0();if($J())J1("[perf] opencode request stage",{requestId:Y.requestId,stage:X,deltaMs:I0(V-Y.last),totalMs:I0(V-Y.start),...z});Y.last=V},done(X,z){let V=X0();if($J())J1("[perf] opencode request done",{requestId:Y.requestId,stage:X,deltaMs:I0(V-Y.last),totalMs:I0(V-Y.start),...z});Y.last=V}};if($J())J1("[perf] opencode request start",{requestId:Y.requestId,...$});return Y}function XY($,J){let Y=/^msg_([0-9a-fA-F]{12})/.exec($);if(!Y)return;let X=BigInt(`0x${Y[1]}`);if(X<=0n)return;let V=`msg_${(X-1n).toString(16).padStart(12,"0")}${"z".repeat(14)}`,j=J&&V<=J?`${J}z`:V;if(j.length>128||j>=$)return;return j}async function n8($,J,Y,X={}){let z=$.client.session,V=await F9($.client,J),j={path:{id:J},body:{noReply:X.noReply??!0,parts:[{type:"text",text:Y,ignored:!0}]}};if(X.beforeActiveAssistant){let N=X.latestPreparedMessageId?.(),F=V?.latestUserMessageId,C=N&&(!F||N>F)?N:F,q=V?.latestAssistantMessageId?XY(V.latestAssistantMessageId,C):void 0;if(!q)return!1;j.body.messageID=q}if(V?.agent)j.body.agent=V.agent;if(V?.model)j.body.model=V.model;if(V?.variant)j.body.variant=V.variant;if(X.canSend&&!X.canSend())return!1;if(j.body.messageID)X.onPreparedMessageId?.(j.body.messageID);if(typeof z?.promptAsync==="function")return await z.promptAsync(j),!0;if(typeof z?.prompt==="function")return await Promise.resolve(z.prompt(j)),!0;throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function KW(){throw Object.assign(Error(oG),{[b8]:b8,[sG]:!0,status:204,statusText:void 0,headers:{},cookies:{[g8]:g8,cookies:{}},body:{[y8]:y8,_tag:"Empty"}})}function _W($){if($.sessionID==null)return!1;let J=$.model;return J?.providerID==="anthropic"||J?.api?.npm==="@ai-sdk/anthropic"||J?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function LW($){if($.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return $.push(DG),!0}var OW={input:0,output:0,cache:{read:0,write:0}},NW=1000;function k$($){return $}function DW($,J){let Y=n4($);return`${Y} content filter detected. Switched to Opus 4.8 for a ${J}-response recovery window before trying ${Y} again.`}function HW($){let J=n4($);return`${J} recovery window complete. Returning to ${J}.`}function n4($){if(XG($))return"Opus 5.5";if(YG($))return"Opus 5";if(ZG($)){if($.startsWith("claude-mythos-5-1"))return"Mythos 5.1";if($.startsWith("claude-fable-5-1"))return"Fable 5.1"}if($==="claude-fable-5"||$.startsWith("claude-fable-5-"))return"Fable 5";if($==="claude-opus-4-8"||$.startsWith("claude-opus-4-8-"))return"Opus 4.8";return $}function UW($,J){return`Anthropic safety fallback active: ${n4($)} → ${n4(J)}. Follow-up requests may remain on the fallback model for about one hour.`}function QW($){return`Anthropic safety fallback ended. Returning to ${n4($)}.`}function BW(){return{input:b9.input,output:b9.output,cache:{read:b9.cacheRead,write:b9.cacheWrite5m},tiers:[{tier:{type:"context",size:B6},input:v9.input,output:v9.output,cache:{read:v9.cacheRead,write:v9.cacheWrite5m}}]}}function FW($){let J=$["claude-opus-4-8"]??$["claude-opus-4-5"]??Object.values($)[0];if(!J)return $;return{...$,...Object.fromEntries(Object.values(U6).map((Y)=>{let X=n6(Y.id),z=X.pricing;return[Y.id,{...J,id:Y.id,name:Y.name,api:J.api?{...J.api,id:Y.id}:void 0,cost:{input:z.input,output:z.output,cache:{read:z.cacheRead,write:z.cacheWrite5m}},limit:{...J.limit??{},context:X.contextWindow,output:X.maxOutputTokens},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:X.releaseDate}]})),...$[h9]?{}:{[h9]:{...J,id:h9,name:"Claude Haiku 5.5",api:J.api?{...J.api,id:h9}:void 0,cost:BW(),limit:{...J.limit??{},context:Q6,output:F6},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:T6,variants:JJ()}},...$[m9]?{}:{[m9]:{...J,id:m9,name:"Claude Sonnet 5.5",api:J.api?{...J.api,id:m9}:void 0,cost:{input:p9.input,output:p9.output,cache:{read:p9.cacheRead,write:p9.cacheWrite5m}},limit:{...J.limit??{},context:C6,output:A6},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:P6,variants:JJ()}},...$[g9]?{}:{[g9]:{...J,id:g9,name:"Claude Opus 5.5",api:J.api?{...J.api,id:g9}:void 0,cost:{input:y9.input,output:y9.output,cache:{read:y9.cacheRead,write:y9.cacheWrite5m}},limit:{...J.limit??{},context:w6,output:S6},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:E6,variants:JJ()}}}}var TW=["low","medium","high","xhigh","max"];function JJ($=TW){return Object.fromEntries($.map((J)=>[J,{thinking:{type:"adaptive",display:"summarized"},effort:J}]))}function wW($){return Object.fromEntries(Object.entries($).map(([J,Y])=>{let X=Y.api?.id??Y.id??J,z=bG(X)?.efforts.variants;return[J,z?{...Y,variants:JJ(z)}:Y]}))}function SW($){return Object.fromEntries(Object.entries($).map(([J,Y])=>[J,{...Y,cost:OW}]))}var EW=2000,lZ="@cortexkit/opencode-anthropic-auth",i4;function CW(){if(i4!==void 0)return i4;i4=lZ;try{let $=JSON.parse(X6(W6(G6(z6(import.meta.url)),"..","package.json"),"utf8"));if($.name===lZ&&typeof $.version==="string"&&$.version.trim())i4=`${lZ}@${$.version.trim()}`}catch{}return i4}function AW(){return["The Claude menu opens in OpenCode's terminal window when the plugin's TUI part is loaded.",`In the terminal, add "${CW()}" to the plugin list in tui.json (or rerun setup), then restart OpenCode.`,"In OpenCode Desktop, use the text menu below."].join(`
25
- `)}function PW(){return process.env.OPENCODE_CLIENT==="desktop"}function r8(){return process.env.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||void 0}var qW=async($,J={})=>{let Y={setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,setInterval:globalThis.setInterval,clearInterval:globalThis.clearInterval,...J},X=J.authorize??z8;VW();let{client:z}=$,V=globalThis.fetch,j=d6(),N=new zG,F=s6(a6(j)),C=600000,q=50,M=new Map;function c(){let Z=Date.now();for(let[G,W]of M)if(Z-W.createdAt>C)M.delete(G)}function l(Z,G){if(c(),M.size>=q){let W="",K=1/0;for(let[_,L]of M)if(L.createdAt<K)K=L.createdAt,W=_;if(W)M.delete(W)}M.set(Z,G)}function K0(Z){c();let G=M.get(Z);if(!G)return;if(Date.now()-G.createdAt>C){M.delete(Z);return}return G}let v;try{v=await v6({role:"opencode1",onLockEvent:J.nativeLocal?.onLockEvent})}catch(Z){let G=iG(Z);if(G)throw Error(G,{cause:Z});throw Z}let j0=await gG(j,void 0,v.layout),n0=v.kind==="state-home"?void 0:v.registration,w=j6({paths:j0,host:"opencode",local:J.nativeLocal,vault:J.claustrumScopedConnect?{connect:J.claustrumScopedConnect}:void 0}),B0=w.quotaObservations,D0=null;function H0(Z){return LG(Z)}function s(Z,G){return Z?H0(Z.binding):G?JSON.stringify([G.credentialId,G.accountIdentity,G.recordVersion]):void 0}function w0(Z,G,W,K=D0){let _=B0.get(Z);if(!_||!G||_.lineage!==G||_.accountUuid!==W||g1(_.entry.quota,K,_.entry.checkedAt)<=Date.now())return;return _}function D$(Z,G,W,K,_=D0){let L=w0(Z,G,W,_);if(!L)return K;if(!K)return{...L.entry,refreshAfter:g1(L.entry.quota,_,L.entry.checkedAt)};let D=L.entry.quota.source!=="headers"&&p1(K.quota)>p1(L.entry.quota)?K.quota:P8(K.quota,L.entry.quota);return{...L.entry,quota:D,refreshAfter:g1(D,_,p1(D))}}function i0(Z,G,W){if(!B0.has(Z.id))return Z.quota;let K=Z.binding?H0(Z.binding):s(void 0,W),_=p1(Z.quota);return D$(Z.id,K,Z.accountIdentity,Z.quota?{quota:Z.quota,checkedAt:_,refreshAfter:g1(Z.quota,G,_)}:null,G)?.quota}let v$;async function r(Z=j){if(Z!==j)throw Error("Native account storage mismatch");let G=await w.read();if(D0=G.policyStorage,!v$){let _=G.accounts.find((L)=>L.id==="main")?.binding;if(_)v$={rowId:_.rowId,credentialEpoch:_.credentialEpoch}}if(G.mode!=="claustrum")return G.policyStorage;let W=G.accounts.find((_)=>_.id==="main"&&_.source==="vault"),K=k$(W?.accountIdentity);return{...G.policyStorage,claustrum:{...G.policyStorage.claustrum,mode:"claustrum",scopedRoster:!0,primaryAccount:W?.credentialId&&K?{credentialId:W.credentialId,accountId:K,state:W.state??"cold",enabled:W.enabled}:void 0}}}async function B$(Z,G){return await w.updateSettings((W)=>MW(W,Z,G)),r()}let H1=async(Z)=>{return await w.updateSettings((G)=>({...G,claudeCache:{...xW(G.claudeCache),enabled:Z,mode:l4({...G,version:1,accounts:[]})}})),r()},n1=(Z)=>B$("claudeCache",{mode:Z}),r4=(Z)=>B$("cacheKeep",{enabled:Z}),C1=async()=>{return await w.updateSettings(RW),r()},YJ=(Z,G)=>B$("cacheKeep",{enabled:!0,always:!1,startHour:Z,endHour:G}),XJ=(Z)=>B$("cacheKeep",{subagents:Z}),Z1=(Z)=>B$("dump",{enabled:Z}),GJ=(Z)=>B$("claudeFast",{enabled:Z}),y0=async(Z)=>{return await w.setLoggingLevel(Z),r()},E$=(Z,G=j)=>B$("prime",{enabled:Z}),_4=(Z,G=j)=>B$("routing",{mode:Z}),h$=(Z)=>B$("killswitch",Z),L4=(Z,G,W=j)=>w.setEnabled(Z,G),C$=(Z,G=j)=>w.remove(Z),WJ=(Z,G=j,W)=>w.reorder(Z,W),j$=null;try{j$=await r()}catch{}function G$(Z){return Boolean(Z&&u4(Z)==="claustrum"&&Z.claustrum?.scopedRoster===!0)}function O4(Z=j,G=$.directory){if(Z!==j)throw Error("Native vault storage mismatch");return w.vault}let A1=x6("native-auth"),P1=new Set;async function f0(Z){let G=Promise.resolve().then(Z);P1.add(G);try{return await G}finally{P1.delete(G)}}async function q1(){while(P1.size)await Promise.allSettled([...P1])}async function zJ(Z=j){TJ?.close(),await q1(),await A1.drain(),await w.drainQuotaPublications(),await Promise.all([...OJ.values()].map((G)=>G.drain())),await w.drainRoutingPublications(),await w.close()}function H$(){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native OAuth cannot serve while OPENCODE_AUTH_CONTENT is set")}function Y1(Z){let G=k$(Z);if(!G)throw Error("Native wire identity requires an admitted provider account");return i6(G,G)}class U1 extends Error{account;checkIntervalMs;constructor(Z,G){super("OAuth account cannot serve the requested model under current quota policy");this.account=Z;this.checkIntervalMs=G}}class b0 extends Error{constructor(){super("Native OAuth requires a Claude Pro/Max credential. An API key belongs in OpenCode stock Anthropic authentication.")}}class b$ extends Error{account;tokenRefreshFailed;failure;constructor(Z,G,W=!1,K){super(K?.kind==="provider"&&K.status!==void 0?`Claude OAuth refresh failed: ${K.status} — ${K.classification==="invalid-grant"?"invalid_grant":"OAuth operation failed"}`:`Native OAuth authorization refused: ${G}`);this.account=Z;this.tokenRefreshFailed=W;this.failure=K}}async function m0(Z,G,W,K,_="serve",L){H$(),G?.throwIfAborted();let D=L??await w.read(),O=D.accounts.find((i)=>i.id===Z);if(_==="cachekeep"&&(O?.type!=="oauth"||!x0(O)))throw new m1("account-unavailable");if(O?.state==="unsupported-access")throw new b0;if(O?.source==="vault"&&!x0(O))throw new b$(O,"not-active");if(O?.type!=="oauth"||!x0(O))throw Error("Native OAuth account is unavailable");let Q=(i,t,L0)=>{let p0=i0(i,t,L0),P0=_==="last-main"&&Z==="main"&&$1(t)!=="sticky-balanced";if(K&&(L1(t)&&!N1(p0,t,Z==="main"?void 0:Z,K)||!P0&&!a9(p0,K)))throw _==="cachekeep"?new m1("account-policy"):new U1(i,T8(t))};Q(O,D.policyStorage);let U;if(O.source==="vault"){let i=await w.authorizeVault(Z,G).catch((t)=>{if(G?.throwIfAborted(),_==="cachekeep"){let L0=KG(t);if(L0)throw L0}if(t instanceof VG&&["not-active","route-declined","route-unavailable"].includes(t.code))throw new b$(O,t.code);throw t});U={accessToken:i.accessToken,expires:i.expiresAtMs??void 0,accountIdentity:i.accountIdentity,scopedAttempt:i}}else{let i=await w.authorizeLocal(Z,{signal:G,rejectedAccessToken:W,intent:W?"refresh":_==="last-main"||_==="cachekeep"?"serve":_});if(i.status!=="usable"){if(_==="cachekeep"){let t=_G(i);if(t)throw t}throw new b$(O,i.status,i.status==="failed"&&i.failure.kind==="provider",i.status==="failed"?i.failure:void 0)}U={accessToken:i.access,expires:i.expires,accountIdentity:i.binding.identity,localSubject:i.subject,localSource:i.source}}let P=await w.read(),p=P.accounts.find((i)=>i.id===Z);if(G?.aborted)throw G.reason??Error("Request aborted");if(!p||!x0(p)||p.source!==O.source||p.accountIdentity!==U.accountIdentity)throw _==="cachekeep"?new m1("credential-changed"):Error("Native OAuth account changed before dispatch");if(U.localSubject&&(!p.binding||p.binding.storageId!==U.localSubject.binding.storageId||p.binding.rowId!==U.localSubject.binding.rowId||p.binding.credentialEpoch!==U.localSubject.binding.credentialEpoch||p.binding.identity!==U.localSubject.binding.identity))throw _==="cachekeep"?new m1("credential-changed"):Error("Native local account binding changed before dispatch");if(U.scopedAttempt&&p.credentialId!==U.scopedAttempt.credentialId)throw _==="cachekeep"?new m1("credential-changed"):Error("Native vault credential binding changed before dispatch");return Q(p,P.policyStorage,U.scopedAttempt),U}async function uZ(Z,G){let K=(await w.read()).accounts.find((L)=>L.id===Z);if(K?.type!=="oauth")throw Error("Native OAuth account is unavailable");let _=K.source==="vault"?await w.authorizeVault(Z,G):await w.captureLocalSubject(Z);if(!await w.resetBackoff(Z,_))throw Error("Native reset fence changed")}let dZ=new WeakMap,iZ=new WeakSet;async function VJ(Z,G){if(iZ.has(Z))return;iZ.add(Z),await f0(()=>w.vault.reportFailure(Z,401,G)).catch(()=>{b.warn("claustrum","native auth-failure report unavailable")})}async function o4(Z,G,W){let K=await w.vault.prepareRetry(Z,W,G);return K.retry?K.receipt:void 0}let jJ=v7(process.env.OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE),k0=new YZ,Q1=new Map;function KJ(Z){for(let{recoveryKey:G}of k0.sourceWarmsForSession(Z))k0.dropSourceWarm(G);for(let G of a0.trackedSessions()){let W=k4(G.id);if(W&&W.sessionId===Z)a0.untrack(G.id)}for(let G of[...Q1.keys()])if(G.startsWith(`${Z}\x00`))Q1.delete(G)}let _J=new WZ,M1=new eJ,R1=new yJ,r1=new yG,i$=new Map,A$=new Map,g$=new Map,s4=new Map,K$=new Set,LJ=new Map,a4=new Map,X1=new Map,N4=new Map,OJ=new Map,D4=w7(async(Z)=>{return(await w.read()).accounts.find((W)=>W.accountIdentity===Z.accountIdentity&&(!Z.credentialId||W.credentialId===Z.credentialId))?.quota}),nZ=new WeakSet,NJ=new WeakMap;async function rZ(){let Z=await w.read(),G=Z.routingPath;if(!G)throw Error(Z.mode==="claustrum"?"Vault routing storage is unavailable":"Native routing storage is unavailable");let W;if(Z.mode==="claustrum"){W=new Map;for(let _ of Z.accounts)if(_.source==="vault"&&_.accountIdentity)W.set(_.id,_.accountIdentity)}let K=OJ.get(G);if(!K)K=new mG({path:G,vaultSeed:Z.routingSeed,onLockEvent:w.onLockEvent,relocationGuard:w.relocationGuard,localRecoveryPath:Z.mode==="local"?Z.routingRecoveryPath:void 0}),OJ.set(G,K);return K.setVaultSeed(Z.routingSeed),{router:K,...W&&{accountIdentities:W}}}let y=new RG({storage:j$,pauseBetweenQuotaCalls:J.quotaCallPause,fetchQuotaSnapshot:(Z,G)=>{H$();let W=Z.kind==="main"?"main":Z.accountId;if(!W)throw Error("Quota request has no account identity");return w.fetchQuota(W,void 0,void 0,G,Z.purpose)}});function H4(Z){return["five_hour","seven_day"].some((G)=>(Z?.[G]?.remainingPercent??1)<=0)}function oZ(Z,G,W=!1){if(!Z||Z.quota?.enabled===!1||!G||$1(Z)==="sticky-balanced"||O1(Z.refresh?.mainLastRefreshError))return;let K=Date.now(),_=Z.quota?.mainLastQuotaApiError;if(_&&_.accountIdentity===G&&_.nextRetryAt!==void 0&&_.nextRetryAt>K)return{message:B8(_,K),retryAfter:Math.max(1,Math.ceil((_.nextRetryAt-K)/1000))};let L=Z.quota?.mainQuota,D=p1(L);if(L?.accountIdentity!==G||L.source==="headers"&&!W||!H4(L)||D<=0||D>K||g1(L,Z,D)<=K)return;let O=["five_hour","seven_day"].flatMap((Q)=>{let U=L[Q],P=U?.resetsAt?Date.parse(U.resetsAt):Number.NaN;return U&&U.remainingPercent<=0&&Number.isFinite(P)&&P>K?[P]:[]});return{message:"Claude OAuth quota is exhausted for this account.",retryAfter:Math.max(1,Math.ceil(((O.length?Math.max(...O):K+T8(Z))-K)/1000))}}async function sZ(Z,G,W){if(MJ===Z&&P$===G)return;let K=a1!==void 0&&W!==void 0&&a1!==W;MJ=Z,P$=G,y.setMainQuotaAccountIdentity(G,!0,K)}async function U4(Z,G,W,K){let _=Z,L=z9.get(_);if(L){let O=await L.promise;return K===L.recordVersion?O:{...O,stale:!0}}let D=(async()=>{let O=++N3,Q=B4,U=await w.read(),P=U.policyStorage,p=U.accounts.find((w1)=>w1.id==="main")?.accountIdentity,i=Y1(W??p),t=U.mode==="claustrum",L0=t?P?.claustrum?.primaryAccount?.accountId:void 0;if(W!==void 0&&W!==p||t&&W===void 0)return{quotaKey:void 0,providerAccountUuid:void 0,generation:y.getMainQuotaIdentityGeneration(),stale:!0,state:"on-identity-mismatch"};let p0=p??L0??Q,P0=P?.main?.profile?.providerAccountUuid??P?.main?.profile?.accountIdentity,c0=k$(W)??k$(i.accountUuid),U0=W?c0:Z.startsWith("sk-ant-oat")?c0??k$(P0):void 0,F$=u4(P)!=="claustrum"?"na":P0===void 0||c0===void 0?"unknown-identity":P0!==void 0&&c0!==void 0&&P0!==c0?"on-identity-mismatch":"on-vault-served";if(O!==N3){let w1=MJ!==Z||P$!==p0;return{quotaKey:p0,providerAccountUuid:U0,generation:y.getMainQuotaIdentityGeneration(),stale:w1,state:F$}}if(await sZ(Z,p0,U0),Z.startsWith("sk-ant-oat")&&U0===void 0)y.clearMain();if(a1=U0,Z.startsWith("sk-ant-oat"))F4=Z;return{quotaKey:p0,providerAccountUuid:U0,generation:y.getMainQuotaIdentityGeneration(),stale:!1,state:F$}})();z9.set(_,{promise:D,recordVersion:K});try{return await D}finally{if(z9.get(_)?.promise===D)z9.delete(_)}}let DJ=j$?.quotaHeaderFeed?.enabled===!0?new MG:null,G1=new Map,aZ=new Map,B1=new Set,F1=new AbortController,tZ=!1;function t4(Z,G){return JSON.stringify([Z,G??null])}function HJ(Z){let G=Z.binding;if(Z.source!=="local"||!G)return;return JSON.stringify([G.storageId,G.rowId,G.credentialEpoch])}function UJ(Z,G){return Z.lineage!==void 0&&Z.lineage===HJ(G)&&(!Z.profile||Z.profile.accountIdentity===G.accountIdentity)}async function e4(Z,G){if(!Z?.profile||!r9(Z.profile,G)||!await Z.isCurrent?.())return;return Z.persistence==="refused"?void 0:Z.profile}function eZ(Z){if(!Z)return[];let G=new Set([...Z.main?["main"]:[],...(Z.accounts??[]).filter((W)=>R0(W)&&(W.enabled!==!1||Boolean(W.claustrumScopedCredentialId))).map((W)=>W.id)]);return[...new Set(G1.values())].filter((W)=>W.persistence==="failed"&&W.profile!==void 0&&G.has(W.accountId))}async function GY(Z,G,W,K){let _=G.accountId,L=W.accounts.find((Q)=>Q.id===_),D=L?.source==="local"?UJ(G,L):L?.source==="vault"&&L.accountIdentity===K.accountIdentity;if(L?.type!=="oauth"||!x0(L)||L.accountIdentity!==K.accountIdentity||!D||await e4(G,Date.now())!==K)return Z;if(_==="main")return Z.main?{...Z,main:{...Z.main,profile:K}}:Z;let O=Z.accounts?.find((Q)=>Q.id===_);if(!O||!R0(O))return Z;return{...Z,accounts:Z.accounts.map((Q)=>Q.id===_&&R0(Q)?{...Q,profile:K}:Q)}}async function $3(Z,G,W=eZ(Z)){if(!Z||W.length===0)return Z;let K=[];for(let D of W){let O=await e4(D,Date.now());if(O)K.push({hydration:D,profile:O})}if(!K.length)return Z;let _=G??await w.read(),L=Z;for(let D of K)L=await GY(L,D.hydration,_,D.profile);return L}function WY(Z,G,W){H$();let K=!1,_=Object.assign((D,O)=>{return K=!0,V(D,O)},{preconnect:V.preconnect}),L={accountId:Z.id,fetched:Promise.resolve(),lineage:HJ(Z),...W&&{deadline:W}};return L.fetched=w.fetchProfileForDisplay(Z.id,_,AbortSignal.any([F1.signal,...W?[W]:[]])).then(({profile:D,persisted:O,isCurrent:Q})=>{if(L.settled=!0,D.accountIdentity!==void 0)aZ.set(t4(Z.id,D.accountIdentity),D);if(Z.accountIdentity===void 0||D.accountIdentity===Z.accountIdentity)L.profile=D,L.isCurrent=Q,L.persistence="pending";let U=O.then(async(P)=>{if(L.persistence=P,P==="failed")b.warn("quota","failed to persist account profile",{account:Z.id});else if(P==="refused")b.debug("quota","refused account profile publication",{account:Z.id});if((P==="saved"||P==="failed")&&!F1.signal.aborted){let p=P==="failed"&&await e4(L,Date.now());if(P==="saved"||p)try{let i=await w.read();if(!F1.signal.aborted)await m$(i.policyStorage,{...W$,routingAuthoritative:!1},i)}catch{b.debug("quota","failed to publish account profile to sidebar",{account:Z.id})}}});B1.add(U),U.then(()=>B1.delete(U))},(D)=>{if(L.settled=!0,L.failed=K,b.debug("quota","failed to hydrate account profile",{account:Z.id,error:D instanceof Error?D.message:String(D)}),!K&&G1.get(G)===L)G1.delete(G)}),B1.add(L.fetched),L.fetched.then(()=>B1.delete(L.fetched)),L}function zY(Z,G){let W=[G,Z.deadline].filter((_)=>_!==void 0);if(!W.length)return Z.fetched;let K=AbortSignal.any(W);if(K.aborted)return Promise.resolve();return new Promise((_)=>{let L=()=>{K.removeEventListener("abort",L),_()};K.addEventListener("abort",L,{once:!0}),Z.fetched.then(L)})}function J3(Z,G){return r9(Z.profile,G)&&NG(Z.profile,Z.accountIdentity)}async function $9(Z){let G=await w.read();if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return G;let W=Date.now(),K=[],_=new Map;for(let O of G.accounts){if(O.type!=="oauth"||!x0(O)||J3(O,W))continue;let Q=t4(O.id,O.accountIdentity),U=G1.get(Q);if(U&&O.accountIdentity===void 0&&(U.lineage===void 0||U.lineage!==HJ(O)))U=void 0;if(!U&&O.accountIdentity!==void 0){let P=G1.get(t4(O.id));if(P&&UJ(P,O))U=P,_.set(O.id,P)}if(U?.failed)continue;if(!U&&r9(aZ.get(Q),W))continue;if(!U||!U.profile&&(U.deadline?.aborted||U.settled)||U.profile&&!r9(U.profile,W)){if(Z?.aborted||F1.signal.aborted)continue;U=WY(O,Q,Z),G1.set(Q,U)}if(O.accountIdentity===void 0)_.set(O.id,U);K.push(zY(U,Z))}if(!K.length)return G;await Promise.all(K);let L=await w.read(),D=Date.now();for(let O of L.accounts){if(O.type!=="oauth"||!x0(O))continue;let Q=t4(O.id,O.accountIdentity),U=_.get(O.id);if(U&&O.accountIdentity!==void 0&&!G1.has(Q)&&UJ(U,O))G1.set(Q,U);if(J3(O,D))continue;let P=await e4(G1.get(Q),D);if(!P||P.accountIdentity!==O.accountIdentity)continue;if(O.profile=P,O.id==="main"){if(L.policyStorage.main)L.policyStorage.main.profile=P}else for(let p of L.policyStorage.accounts)if(p.id===O.id&&R0(p))p.profile=P}return L}async function VY(Z,G,W,K){if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return Z;return(await $9(W)).policyStorage}let Z3=new Set;async function jY(Z,G,W){let _=(await w.read()).accounts.find((U)=>U.id===Z.accountId);if(!_||!Z.anthropicAccountUuid||_.accountIdentity!==Z.anthropicAccountUuid)return null;let L={...P8(_.quota,G.quota),accountIdentity:_.accountIdentity};if(!(Z.scopedAttempt?await w.vault.publish(Z.scopedAttempt,{quota:L}):Z.localSubject?await w.publishLocal(Z.localSubject,{quota:L}):!1)){if(Z.accountId==="main"){if(y.getMain(Z.mainQuotaIdentity?.quotaKey)===W)y.clearMain()}else if(y.getAllFallbacks().get(Z.accountId)===W)y.clearFallback(Z.accountId);return b.debug("quota","native quota publication refused",{accountId:Z.accountId}),b.warn("quota","Quota publication discarded"),null}let O=await w.read(),Q=O.accounts.find((U)=>U.id===Z.accountId);if(!Q?.quota||Q.accountIdentity!==Z.anthropicAccountUuid||Q.source!==_.source)return null;if(Z.localSubject&&Q.binding?.credentialEpoch!==Z.localSubject.binding.credentialEpoch)return null;if(Z.scopedAttempt&&Q.credentialId!==Z.scopedAttempt.credentialId)return null;return{...G,quota:Q.quota,refreshAfter:g1(Q.quota,O.policyStorage,G.checkedAt)}}function KY(Z){b.warn("quota","failed to persist harvested response quota",{error:Z instanceof Error?Z.message:String(Z)})}function _Y(Z){let G=Z instanceof Error?Z.name:typeof Z,W=Z instanceof Error?Z.message:String(Z),K=`${G}:${W}`;if(Z3.has(K))return;Z3.add(K),b.warn("quota","failed to normalize response quota headers",{error:W})}function LY(Z){if(!Z||typeof Z!=="object")return;let G=Z,W=G.credential_id;if(typeof W==="string"&&W&&W!=="main")return W;let K=G.vault;if(K&&typeof K==="object"){let _=K.credential_id;if(typeof _==="string"&&_&&_!=="main")return _}return}async function OY(Z,G){if(!DJ)return;if(Z.accountId==="main"&&!Z.mainQuotaIdentity?.quotaKey)return;let W=await r(j)??_1(),_=(await T1?.())?.type==="oauth",L=Z.accountId==="main"?W.main:W.accounts.find((i)=>i.id===Z.accountId),D=LY(L),O=R6({storage:W,mainOAuthConfigured:_}),Q=G.checkedAt,U={five_hour:G.quota.five_hour,seven_day:G.quota.seven_day,bindingWindow:G.quota.bindingWindow,fallbackAdvised:G.quota.fallbackAdvised,scoped:G.quota.scoped,extraUsage:G.quota.extraUsage,fieldSources:G.quota.fieldSources},P=D??(Z.accountId==="main"?Z.mainQuotaIdentity?.quotaKey??"main":Z.accountId),p=D?{identity_source:"credential_id",credential_id:D,schema_version:o9,provider:"anthropic",configured_account_count:O,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:P}:Z.accountId==="main"&&Z.mainQuotaIdentity?.quotaKey?{identity_source:"account_ref",account_ref:Z.mainQuotaIdentity.quotaKey,schema_version:o9,provider:"anthropic",configured_account_count:O,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:P}:Z.accountId==="main"?{identity_source:"none",schema_version:o9,provider:"anthropic",configured_account_count:O,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:P}:{identity_source:"account_ref",account_ref:Z.accountId,schema_version:o9,provider:"anthropic",configured_account_count:O,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:P};await DJ.publish(p)}function NY(Z){b.debug("quota","failed to publish quota header feed",{error:Z instanceof Error?Z.message:String(Z)})}function Y3(Z,G){try{if(!WG(Z)){b.trace("quota","skipped non-quota response headers",{account:G.accountId});return}let W=OG(Z),K=G.accountId==="main"?G.mainQuotaIdentity:void 0;if(G.accountId==="main"){if(!K||y.getMainQuotaIdentityGeneration()!==K.generation){b.trace("quota","discarded stale main quota headers",{boundIdentity:K?.quotaKey,currentGeneration:y.getMainQuotaIdentityGeneration()});return}}let _=G.accountId==="main"?y.getMain(K?.quotaKey):y.getAllFallbacks().get(G.accountId),L=W.checkedAt??Date.now(),D=s(G.localSubject,G.scopedAttempt),O=D&&G.anthropicAccountUuid?{lineage:D,accountUuid:G.anthropicAccountUuid,entry:{quota:{...W,accountIdentity:G.anthropicAccountUuid},checkedAt:L,refreshAfter:L},generalExhausted:["five_hour","seven_day"].some((Q)=>{let U=Z.get(Q==="five_hour"?"anthropic-ratelimit-unified-5h-utilization":"anthropic-ratelimit-unified-7d-utilization");return W[Q]!==void 0&&U!==null&&Number.isFinite(Number(U))&&Number(U)>=1})}:void 0;if(O){if(B0.delete(G.accountId),B0.size>=NW){let Q=B0.keys().next().value;if(Q!==void 0)B0.delete(Q)}B0.set(G.accountId,O)}(async()=>{let Q=!1;try{let U;try{U=await jY(G,{quota:W,checkedAt:L,refreshAfter:L},_)}catch(p){KY(p);return}if(U===null)return;if(G.accountId==="main"&&y.getMainQuotaIdentityGeneration()!==K?.generation)return;let P=U;if(O&&B0.get(G.accountId)===O)O.entry=P,Q=!0;if(G.accountId==="main")y.setMain(K?.quotaKey,P);else y.setFallback(G.accountId,P,{authLineageId:G.authLineageId});s1().catch(()=>{}),await OY(G,P),b.debug("quota","harvested response quota",{account:G.accountId,fiveHourPercent:P.quota.five_hour?.usedPercent,sevenDayPercent:P.quota.seven_day?.usedPercent,source:"headers"})}finally{if(!Q&&O&&B0.get(G.accountId)===O)B0.delete(G.accountId),b.debug("quota","discarded pending response quota",{accountId:G.accountId})}})().catch(NY),b.trace("quota","response quota awaiting publication",{account:G.accountId})}catch(W){_Y(W)}}let X3=Promise.resolve();function x1(Z=!1,G=!1,W,K){let _=X3.then(()=>DY(Z,G,W,K));return X3=_.then(()=>{},()=>{}),_}async function DY(Z,G,W,K){let _=await w.read(),L=new Set;if(!Z&&!G&&_.policyStorage.quota?.enabled===!1)return L;for(let D of _.accounts){if(D.id==="main"||D.type!=="oauth")continue;if(!x0(D)){if(G)L.add(D.id);continue}if(!Z&&g1(D.quota,_.policyStorage,p1(D.quota))>Date.now()&&(!W||d1(D.quota,_.policyStorage,Date.now(),W)))continue;try{if(!await y.refreshFallback(D.id,"",_.policyStorage.accounts.find((Q)=>Q.id===D.id&&R0(Q)),Z?void 0:K))L.add(D.id),b.debug("quota","fallback quota preflight returned no reading",{accountId:D.id,requiredByPolicy:G})}catch(O){if(G&&y1(O))throw O;L.add(D.id),N7(D.id,G,O)}}return s1().catch(()=>{}),L}let QJ={refreshQuotaForDueAccounts:async()=>{await x1()},refreshQuotaForAllAccounts:async(Z)=>{await x1(!0)},refreshAccount:async(Z,G,W)=>{let K=await m0(Z.id,void 0,W?.force?Z.access:void 0);return{...Z,access:K.accessToken,expires:K.expires}},refreshAccountQuota:async(Z,G)=>{H$();let W=await w.fetchQuota(Z.id);return{account:{...Z,quota:W},fetched:!0}},getUsableFallbackAccounts:async(Z,G)=>{Z=Z??null;let W=[],K=Z?.accounts.some((_)=>R0(_)&&B0.has(_.id))?(await w.read()).accounts:[];for(let _ of Z?.accounts??[]){if(!R0(_)||!x0(_))continue;let L=K.find((Q)=>Q.id===_.id),D=y.getFallback(_.id,L?.binding?{authLineageId:JSON.stringify(L.binding)}:_)?.quota??L?.quota??_.quota,O=L&&Z?i0({...L,quota:D},Z):D;if(!j4(O,Z)||!a9(O,G?.modelId)||L1(Z)&&!N1(O,Z,_.id,G?.modelId))continue;if(G$(Z)){if(M4(_.id,Z))W.push(_);continue}try{let Q=await m0(_.id,void 0,void 0,G?.modelId);W.push({..._,access:Q.accessToken,expires:Q.expires})}catch(Q){if(y1(Q))throw Q}}return W}};async function BJ(){H$();let Z=await w.read();if(Z.mode==="local"&&Z.policyStorage.refresh?.enabled!==!1)for(let G of Z.accounts){if(G.id==="main"||G.type!=="oauth"||!x0(G))continue;try{let W=await m0(G.id);if(l1(G.lastRefreshError,G.accountIdentity,Date.now(),void 0))continue;if(W.localSource!=="rotated"&&W.localSource!=="adopted"&&(!W.expires||W.expires-Date.now()<=D3(Z.policyStorage)))await m0(G.id,void 0,void 0,void 0,"refresh")}catch{}}await x1(!1,!1,void 0,"background")}let FJ=j$!==null&&process.env.OPENCODE_AUTH_CONTENT===void 0,G3=new Set;async function HY(){let Z=await w.read(),G=new Set(Z.accounts.filter((K)=>K.id!=="main"&&K.source==="vault"&&K.type==="oauth"&&x0(K)).map((K)=>K.id)),W=[...G].some((K)=>!G3.has(K));if(G3=G,W)await x1(!1,!1,void 0,"background");await s1()}let TJ=FJ&&G$(j$)?w.vault.watch({intervalMs:J.scopedRosterPollIntervalMs??2000,shouldRefresh:()=>process.env.OPENCODE_AUTH_CONTENT===void 0,onRefresh:HY,setInterval:Y.setInterval,clearInterval:Y.clearInterval}):void 0,UY=FJ?(TJ?TJ.ready.then(()=>BJ()):BJ()).catch(()=>{}):Promise.resolve(),wJ=FJ?Y.setInterval(()=>{BJ().catch(()=>{})},c6+i8(l8)):null;wJ?.unref?.();let QY=(Z,G)=>{let W=iJ({id:Z,role:"fallback"},G);return W==="na"?"off":W},SJ=new mJ,BY=new pJ,n$=new WeakMap,Q4=new Map;async function EJ(Z){let G=(Z.get("anthropic-beta")??"").split(",").map((W)=>W.trim()).filter(Boolean).sort();return{betas:G,betasHash:await M6(G.join(","))}}function W3(Z){try{if(!Z.request)return;let G=h3({request:Z.request,source:Z.source,accountId:Z.accountId,synthetic:Z.synthetic,betasHash:Z.betasHash,requestedModel:Z.requestedModel,onWarning:(K)=>b.warn("cache-diagnostics",K),message:Z.message,receivedAt:Z.receivedAt});if(!G.record||!G.messageId){b.debug("cache-diagnostics","skipped invalid response envelope",{status:Z.status});return}b.debug("cache-diagnostics",b3(G.record));let W=BY.capture(Z.betasHash,Z.betas);if(W)b.debug("cache-diagnostics",W);if(G.canary)b.warn("cache-diagnostics","short-gap previous_message_not_found",{message_id:G.canary.messageId,previous_message_id:G.canary.previousMessageId});if(Z.trackSessionId)SJ.capture(Z.trackSessionId,G.messageId,Z.receivedAt)}catch(G){b.debug("cache-diagnostics","response observation failed",{status:Z.status,error:G instanceof Error?G.message:String(G)})}}function z3(Z,G,W=!0){let K=n$.get(Z);if(!K)return;if(G&&typeof G==="object"&&!Array.isArray(G)&&!W)K.messageStart=G;K.dumpWrite=K.dumpWrite.then(()=>qZ(K.dump,{status:K.status,message:G,complete:W})).catch(()=>{}),W3({...K,message:G,receivedAt:Date.now()})}function FY(Z,G){let W=n$.get(Z);if(!W)return;let K=W.messageStart??{},_=K.usage&&typeof K.usage==="object"&&!Array.isArray(K.usage)?K.usage:{},L={...K,...G.usage?{usage:{..._,...G.usage}}:{},...G.stopReason?{stop_reason:G.stopReason}:{}};W.dumpWrite=W.dumpWrite.then(()=>qZ(W.dump,{status:W.status,message:L,complete:!0})).catch(()=>{})}function V3(Z,G){let W=Promise.resolve(qZ(G.dump,{status:G.status,message:null,complete:!1})).catch(()=>{});n$.set(Z,{...G,dumpWrite:W})}let W1=null,J9=null;function Z9(Z){return Z!==null&&typeof Z==="object"&&dJ(Z)==="R"}function TY(Z){let G=AZ("anthropic");if(!Z||typeof Z!=="object")return!1;let W=Z;return W.type===G.type&&W.access===G.access&&W.refresh===G.refresh&&W.expires===G.expires}async function wY(){if(J9){let Z=await J9();return $G("opencode",Z===void 0?{}:{anthropic:Z}).kind}if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("OpenCode logins cannot be checked while OPENCODE_AUTH_CONTENT is set");return kG("opencode",a8())}async function j3(){if(await c1("opencode")!=="claustrum")throw Error("This host is not connected to the credential vault; run setup to connect it first");if(await wY()!=="absent")throw Error("OpenCode already holds an Anthropic login; remove it before choosing the vault login")}let SY={label:"Claude via credential vault",type:"oauth",authorize:async()=>{return await j3(),{url:"",instructions:"Claude requests use the credential vault this host is connected to. OpenCode stores only a placeholder, never a credential.",method:"auto",callback:async()=>{await j3();let Z=AZ("anthropic");return{type:"success",access:Z.access,refresh:Z.refresh,expires:Z.expires}}}}},CJ=new H6({directory:process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||r6("opencode")}),Y9=[],o1=new Map,a0=new D6({loadStorage:()=>r(j),fetchImpl:v4,setIntervalImpl:Y.setInterval,clearIntervalImpl:Y.clearInterval,onTrackedSessionsChanged:async(Z)=>{await CJ.publish(Z),Y9=await CJ.list(Z)},prepareBody:(Z,G)=>{if(!new Headers(G.headers).get("anthropic-beta")?.split(",").map((W)=>W.trim()).includes(q4))return Z;try{let W=JSON.parse(Z),K=SJ.previousFor(G.id),_=K?.messageId??null;return O9(W,_),Q4.set(G.id,{sessionId:G.id,previousMessageId:_,...K?{previousMessageReceivedAt:K.receivedAt}:{},isSubagent:G.isSubagent,ttlSent:N9(W),accountId:G.oauthAccountId??"main",synthetic:!0,requestedModel:typeof W.model==="string"?W.model:void 0}),JSON.stringify(W)}catch{return Z}},onResponse:async({target:Z,bodyText:G,status:W,data:K,receivedAt:_,attempt:L})=>{let D=o1.get(L.id);if(!Z.sourceWarm&&W>=200&&W<300&&!L.signal?.aborted)u1.recordPrewarm(Z.id,Z.oauthAccountId??"main",_);if(W===401&&D?.scopedAttempt)await VJ(D.scopedAttempt,"direct");if(Z.sourceWarm&&W>=200&&W<300)k0.noteSourceWarmSentForTarget(Z.id);let O=Q4.get(Z.id);if(!O?.betasHash||!O.betas){Q4.delete(Z.id);return}try{let Q=JSON.parse(G),U=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q.diagnostics:void 0,P=U&&typeof U==="object"&&!Array.isArray(U)&&U.previous_message_id===O.previousMessageId?O.previousMessageId:void 0;if(P===void 0)return;W3({source:"prewarm_cachekeep",accountId:O.accountId,synthetic:O.synthetic,betasHash:O.betasHash,betas:O.betas,requestedModel:O.requestedModel,request:{...O,previousMessageId:P,ttlSent:N9(Q)},trackSessionId:Z.id,status:W,message:K,receivedAt:_})}catch{}finally{Q4.delete(Z.id)}},onComplete:({attempt:Z})=>{o1.delete(Z.id)},retryOnUnauthorized:async({target:Z,headers:G,attempt:W})=>{let K=o1.get(W.id);if(!K)return;let _;try{let O=JSON.parse(Z.bodyText);if(typeof O.model==="string")_=O.model}catch{}if(K.scopedAttempt&&!await o4(K.scopedAttempt,"cachekeep",W.signal))return;let L=await m0(Z.oauthAccountId??"main",W.signal,K.scopedAttempt?void 0:K.accessToken,_,"cachekeep");if(L.accountIdentity!==K.accountIdentity||Boolean(L.scopedAttempt)!==Boolean(K.scopedAttempt))return;if(K.scopedAttempt&&(!L.scopedAttempt||L.scopedAttempt.credentialId!==K.scopedAttempt.credentialId||L.scopedAttempt.recordVersion<=K.scopedAttempt.recordVersion))return;if(!K.scopedAttempt&&L.accessToken===K.accessToken)return;let D=new Headers(G);return D.set("authorization",`Bearer ${L.accessToken}`),o1.set(W.id,L),D},prepareHeaders:async(Z,G,W)=>{if(!VZ(G.url))return;let K=G.oauthAccountId??"main",_;try{let Q=JSON.parse(G.bodyText);if(typeof Q.model==="string")_=Q.model}catch{}let L=await m0(K,W.signal,void 0,_,"cachekeep");if(G.oauthAccountIdentity&&L.accountIdentity!==G.oauthAccountIdentity)throw new m1("credential-changed");let D=L.accessToken;o1.set(W.id,L);try{let Q=JSON.parse(G.bodyText),U=Y1(L.accountIdentity);if(Z.delete("anthropic-beta"),G4(Z,D,{body:Q,identity:U}),Z.set("anthropic-beta",A8(Z.get("anthropic-beta"),[N6])),Q.speed==="fast")f9(Z);let P=Q4.get(G.id);if(P){let{betas:p,betasHash:i}=await EJ(Z);P.betas=p,P.betasHash=i}}catch{G4(Z,D)}let O=await m0(K,W.signal,void 0,_,"cachekeep");if(O.accountIdentity!==L.accountIdentity||Boolean(O.scopedAttempt)!==Boolean(L.scopedAttempt))throw new m1("credential-changed");if(Z.set("authorization",`Bearer ${O.accessToken}`),o1.set(W.id,O),G.sourceWarm){let Q=k0.sourceWarmForTarget(G.id);if(!Q||Q.oauthAccountId!==G.oauthAccountId||Q.accountIdentity!==void 0&&O.accountIdentity!==Q.accountIdentity){k0.dropSourceWarmForTarget(G.id),a0.untrack(G.id),b.warn("cachekeep","source warm refused: bound account changed",{session:G.id,reason:"source-warm-account-changed"});return}}return Z},validatePrewarm:({target:Z,warmBodyText:G})=>{if(!Z.sourceWarm)return{ok:!0};let W=k0.sourceWarmForTarget(Z.id);if(!W)return a0.untrack(Z.id),{ok:!1,reason:"source-round-ended"};if(W.warmsSinceUserTurn>=q6(W.model))return k0.dropSourceWarmForTarget(Z.id),{ok:!1,reason:"source-warm-idle-cap"};let K=j8(G),_=j8(W.bodyText);if(!K||!_||K!==_)return k0.dropSourceWarmForTarget(Z.id),{ok:!1,reason:"source-prefix-mismatch"};return{ok:!0}}});async function EY(Z){let G=X$(Z.requestedModel);if(!G)return;let W=J4(Z.sessionId,G),K=k0.sourceWarmFor(Z.recoveryKey);if(!K){a0.untrack(W);return}let _;try{_=await r()}catch{return}if(!a0.track({sessionId:W,url:K.url,headers:new Headers(K.headers),bodyText:K.bodyText,storage:_,cacheMode:"hybrid",oauthAccountId:K.oauthAccountId,...K.accountIdentity!==void 0&&{oauthAccountIdentity:K.accountIdentity},isSubagent:K.subagent??!1,sourceWarm:!0}).tracked)k0.dropSourceWarm(Z.recoveryKey)}async function CY(Z){if(!W1||!(await W1()).active)throw Error("Native main OAuth activation is not available");let G=await m0("main",Z);return{...G,credentialAccountId:k$(G.accountIdentity)}}async function AY(){let Z=await CY();if((await U4(Z.accessToken,void 0,Z.credentialAccountId)).stale&&Z.credentialAccountId!==void 0)throw Error("Main account identity changed before the prime refresh");let W=await y.refreshMainWithMetadata(P$,Z.accessToken);return{quota:W.quota,fresh:W.fetched}}async function PY(Z){H$();let G=await r(j),W=G?.accounts.find((_)=>_.id===Z&&x0(_)&&R0(_));if(!W||!G)throw Error(`prime: OAuth account ${Z} is unavailable`);let K=await QJ.refreshAccountQuota(W,G);return{quota:K.account.quota??{},fresh:K.fetched}}let AJ=new Map;async function qY(Z){let G=performance.now(),W,K,_,L="",D;try{if(Z==="main"&&(!W1||!(await W1()).active))throw Error("Native main OAuth activation is not available");let O=p4(aG,{baseURL:""}),Q=O.url?.toString()??O.input.toString();w9(Q);let U=await m0(Z,void 0,void 0,V8);if(W=U.accessToken,_=U.scopedAttempt,K=V8,!W)return{ok:!1,error:"prime: no access token available"};let P=O6(),p=Y1(U.accountIdentity),i=await k9(JSON.stringify(P),{identity:p}),t=new Headers({"content-type":"application/json"});G4(t,W,{body:JSON.parse(i),identity:p,requestClass:"auxiliary"}),t.delete("content-length"),t.delete("transfer-encoding");let L0=AbortSignal.timeout(30000),p0={method:"POST",headers:t,body:i,signal:L0},P0=await m0(Z,L0,void 0,K);if(P0.accountIdentity!==U.accountIdentity||Boolean(P0.scopedAttempt)!==Boolean(U.scopedAttempt))throw Error("Prime credential authority changed before dispatch");_=P0.scopedAttempt,L=P0.accessToken,t.set("authorization",`Bearer ${L}`);let c0=async()=>{let S0=c9([L],"http");return D=S0,S0.redactResponse(await v4(Q,p0))},U0=await c0();if(U0.status===401&&_&&!L0.aborted){let S0;try{S0=await o4(_,"prime",L0)}catch{}if(S0){D?.dispose(),await U0.body?.cancel().catch(()=>{}),b.info("claustrum","retrying Prime after scoped credential rotation",{accountId:Z,previousVersion:_.recordVersion,newVersion:S0.recordVersion}),P0=await m0(Z,L0,void 0,K);let l0=P0.scopedAttempt;if(!l0||l0.credentialId!==_.credentialId||l0.accountIdentity!==_.accountIdentity||l0.recordVersion<=_.recordVersion)throw Error("Prime vault retry lost its strict newer receipt");_=l0,L=l0.accessToken,t.set("authorization",`Bearer ${L}`),U0=await c0()}}if(U0.status===401&&!P0.scopedAttempt&&!L0.aborted){let S0=P0.accessToken,l0=await m0(Z,L0,S0,K).catch(()=>{return});if(l0&&l0.accessToken!==S0&&l0.accountIdentity===U.accountIdentity&&!l0.scopedAttempt){if(D?.dispose(),await U0.body?.cancel().catch(()=>{}),P0=await m0(Z,L0,void 0,K),P0.scopedAttempt||P0.accountIdentity!==U.accountIdentity)throw Error("Prime local authority changed before retry");L=P0.accessToken,t.set("authorization",`Bearer ${L}`),U0=await c0()}}let F$=Math.round(performance.now()-G);if(!U0.ok){let S0;try{S0=await U0.text().catch(()=>"")||`HTTP ${U0.status}`}finally{D?.dispose()}if(U0.status===401&&_)await VJ(_,"direct");return{ok:!1,status:U0.status,ms:F$,error:S0}}let q$=(await U0.json().catch(()=>null))?.usage,M$=q$&&(Number.isFinite(q$.input_tokens)||Number.isFinite(q$.output_tokens))?{inputTokens:Number.isFinite(q$.input_tokens)?q$.input_tokens:void 0,outputTokens:Number.isFinite(q$.output_tokens)?q$.output_tokens:void 0}:void 0;return AJ.set(Z,P0),{ok:!0,status:U0.status,ms:F$,...M$&&{usage:M$}}}catch(O){D?.dispose();let Q=c9([L],"http"),U=Q.redactError(O);return Q.dispose(),{ok:!1,...O instanceof b$&&O.tokenRefreshFailed&&{reason:"token-refresh"},ms:Math.round(performance.now()-G),error:U instanceof Error?U.message:String(U)}}}let K3={storagePath:j,loadStorage:()=>r(j),getAccountFingerprint:async(Z)=>{if(Z==="main"&&(!W1||!(await W1()).active))return;let G=await m0(Z),W=G.scopedAttempt??G.localSubject;if(!W)return;let K=await w.getOrCreateAuthLineage(Z,W);return K?D1(K):void 0},refreshQuota:async(Z)=>{if(Z==="main")return AY();return PY(Z)},sendPrime:qY,recordSuccess:async(Z,G)=>{let W=AJ.get(Z);AJ.delete(Z);let K=W?.scopedAttempt??W?.localSubject;if(!K||!await w.incrementPrimeUsage(Z,K,G))throw Error("Prime usage publication lost its native credential fence");let _=(await w.read()).accounts.find((L)=>L.id===Z)?.prime;if(!_)throw Error("Prime usage counters are unavailable after publication");return _},setIntervalImpl:Y.setInterval,clearIntervalImpl:Y.clearInterval,setTimeoutImpl:Y.setTimeout,clearTimeoutImpl:Y.clearTimeout},_3=O7(j,()=>new UG(K3),{slot:$.directory??"default",rebind:(Z)=>Z.updateOptions(K3)}),I1=_3.manager;if(n9(j$))I1.start();async function X9(){return Y9=await CJ.list(a0.trackedSessions()),Y9}let L3=J.cacheKeepAggregateRefreshIntervalMs??1e4,PJ=L3>0?Y.setInterval(()=>{X9().catch(()=>{})},L3):void 0;if(PJ?.unref?.(),t9({enabled:i9(j$),mode:l4(j$)}),mZ(vZ(j$)),pZ(bZ(j$)),!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)lG(fZ(j$)??"info");let qJ=null,MY=async()=>{n0?.close(),F1.abort();while(B1.size)await Promise.all([...B1]);try{await zJ(j)}catch(Z){b.warn("claustrum","failed to close scoped runtime",{error:Z instanceof Error?Z.message:String(Z)})}try{y.close()}catch{}try{await DJ?.dispose()}catch(Z){b.warn("quota-header-feed","failed to dispose",{error:Z instanceof Error?Z.message:String(Z)})}try{if(f1)Y.clearInterval(f1),f1=null}catch(Z){b.warn("main-background","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{if(wJ)Y.clearInterval(wJ)}catch(Z){b.warn("fallback-background","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{if(PJ!==void 0)Y.clearInterval(PJ)}catch(Z){b.warn("cachekeep","failed to stop aggregate refresh",{error:Z instanceof Error?Z.message:String(Z)})}try{a0.stop()}catch(Z){b.warn("cachekeep","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{_3.release()}catch(Z){b.warn("prime","failed to release slot",{error:Z instanceof Error?Z.message:String(Z)})}if(!qJ)return;try{await qJ.release()}catch(Z){b.warn("rpc","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}},W$={activeId:"main",route:"main"},RY=t8(),y$=new Map;function G9(Z,G){if(y.updateStorage(Z),y.seedMainFromStorage(Z,P$),!G.skipFallbackQuotaSeed)y.seedFallbacksFromAccounts((Z?.accounts??[]).filter(R0));let W=y.getMain(P$),K=y.getLastApiError(),_=Z?.refresh?.mainLastRefreshError,L=Z?.claustrum?.primaryAccount,D=G$(Z)&&!x0(L)?xZ({source:"vault",enabled:L?.enabled,state:L?.state}):void 0;return{main:{quota:W?.quota??null,enabled:L?.enabled,tierLabel:c4(Z?.main?.profile),quotaBackedOff:y.isBackedOff(),quotaBackoffUntil:K?.nextRetryAt,refreshBackedOff:_?l1(_,B4??Z?.mainAccountId,Date.now(),G.mainRefreshToken?D1(G.mainRefreshToken):void 0):!1,refreshBackoffUntil:_?.nextRetryAt,stateLine:D,quotaDated:Boolean(D)},fallbacks:(Z?.accounts??[]).filter((O)=>R0(O)&&(O.enabled!==!1||Boolean(O.claustrumScopedCredentialId))).map((O)=>{let Q=M4(O.id,Z),U=QY(O.id,Z),P=O.claustrumScopedCredentialId&&!Q?xZ({source:"vault",enabled:O.enabled!==!1,state:O.claustrumScopedState}):void 0;return{id:O.id,label:O.label,tierLabel:c4(O.profile),quota:G.skipFallbackQuotaSeed?null:y.getFallback(O.id,O)?.quota??O.quota??null,needsReauth:O.lastRefreshError!=null&&l1(O.lastRefreshError,O.id,Date.now(),D1(O.refresh))&&O1(O.lastRefreshError),vaultReauth:U==="on-vault-reauth",vaultServed:Q,custodyState:U,enabled:O.enabled!==!1,stateLine:P,quotaDated:Boolean(P)}}),activeId:G.activeId,route:G.route,relay:b6(Z?.relay),fastMode:hZ(),cacheKeep:{enabled:S8(Z),window:w8(Z)?"always":Z?.cacheKeep?.startHour!=null&&Z?.cacheKeep?.endHour!=null?`${Z.cacheKeep.startHour}-${Z.cacheKeep.endHour}`:void 0,trackedSessions:Y9.length},prime:n9(Z)?{enabled:!0,accounts:I1.stats(Z)}:void 0,fableRecoveries:y$.size>0?[...y$.values()]:void 0,lastUpdated:Date.now()}}function m$(Z,G,W){let K=G.routingAuthoritative!==!1;if(K)W$={activeId:G.activeId,route:G.route};function _(L){return $Y(L,RY,{routingAuthoritative:K,resolvePreservedRouting:K?void 0:async(D)=>{let O=await YW(D,()=>r(j),{activeId:L.activeId,route:L.route}),Q=await $3(O.freshStorage,W);return{activeId:O.activeId,route:O.route,state:G9(Q,{...G,activeId:O.activeId,route:O.route})}},onRoutingResolved:K?void 0:(D)=>{W$=D}}).catch((D)=>b.warn("sidebar","state write failed",{error:D instanceof Error?D.message:String(D)}))}if(K){let L=eZ(Z);if(L.length>0)return $3(Z,W,L).then((D)=>_(G9(D,G))).catch(()=>{return b.debug("quota","failed to recheck account profile for sidebar"),_(G9(Z,G))})}return _(G9(Z,G))}async function O3(){return{storage:await r(j),access:void 0}}async function s1(){await X9().catch(()=>{});let{storage:Z,access:G}=await O3();m$(Z,{activeId:W$.activeId,route:W$.route,mainAccessToken:G,mainRefreshToken:void 0,routingAuthoritative:!1})}function xY(Z,G,W){if(!G)return;if(Z?.quota?.enabled!==!0)return;let K=W?.quotaKey??P$;if(y.getMain(K))return;if(RJ)return;RJ=!0,y.refreshMain(K,G,W?.generation).then(()=>s1()).catch(()=>{}).finally(()=>{RJ=!1})}let T1=null,W9,B4,P$,F4,a1,MJ,N3=0,z9=new Map,RJ=!1,f1=null,V9=0;function D3(Z){let G=Z?.refresh?.refreshBeforeExpiryMinutes??eG;return Math.max(ZY,G)*60000}function IY(Z){return Z?.refresh?.enabled!==!1}async function H3(Z=!1){let G=new Map;if(Z){if(W1&&(await W1()).active)try{await w.fetchQuota("main")}catch{G.set("main","Native primary usage refresh unavailable")}await x1(!0)}let W=await $9(AbortSignal.timeout(3000));y.updateStorage(W.policyStorage),y.seedMainFromStorage(W.policyStorage,P$),y.seedFallbacksFromAccounts(W.policyStorage.accounts.filter(R0));let K=[],_=W.accounts.find((D)=>D.id==="main"&&D.type==="oauth");if(_)K.push({name:_.label??"OpenCode anthropic",role:"main",quota:_.quota,tierLabel:c4(_.profile),error:G.get("main")??_.lastQuotaRefreshError?.message});K.push(...L6(W.policyStorage,G));let L=Math.max(0,...W.accounts.map((D)=>p1(D.quota)));return _6({accounts:K,refreshedAt:L||void 0})}async function xJ(Z){await X9().catch(()=>{}),await m$(Z,{activeId:W$.activeId,route:W$.route,routingAuthoritative:!1})}function T4(Z,G,W,K){if(y$.delete(Z.sessionId),y$.set(Z.sessionId,{...Z,changedAt:Date.now()}),y$.size>128){let _=y$.keys().next().value;if(_)y$.delete(_)}if(m$(G,{activeId:W$.activeId,route:W$.route,mainAccessToken:W.access,mainRefreshToken:W.refresh,routingAuthoritative:!1}),K)B3(Z.sessionId,K)}function U3(Z,G){let W=X1.get(Z)??new Set;W.delete(G),W.add(G);while(W.size>4){let K=W.values().next().value;if(typeof K!=="string")break;W.delete(K)}X1.delete(Z),X1.set(Z,W);while(X1.size>128){let K=X1.keys().next().value;if(typeof K!=="string")break;X1.delete(K)}}function Q3(Z,G){return typeof G==="string"&&X1.get(Z)?.has(G)===!0}function B3(Z,G){if(A9(Z))return;A$.delete(Z),A$.set(Z,[G]);while(A$.size>128){let W=A$.keys().next().value;if(W)A$.delete(W);else break}if(K$.has(Z))IJ(Z)}function IJ(Z,G=0){if(!A$.has(Z)||N4.has(Z))return;N4.set(Z,G);let W=()=>{if(N4.get(Z)!==G)return;N4.delete(Z),fY(Z,G)};if(G===0)setImmediate(W);else setTimeout(W,WW*G)}function fJ(Z,G){if(G+1<GW)IJ(Z,G+1)}async function fY(Z,G){if(!K$.has(Z)||!A$.has(Z))return;let W=$.client.session;if(typeof W?.status==="function")try{let K=await Promise.resolve(W.status()),_=K!==null&&typeof K==="object"?K:void 0,L=_&&Object.hasOwn(_,"data")?_.data:_;if(L===null||typeof L!=="object"||Array.isArray(L)){fJ(Z,G);return}let D=L[Z];if(D!==void 0&&(!D||typeof D!=="object"||D.type!=="idle")){fJ(Z,G);return}}catch{fJ(Z,G);return}if(!K$.has(Z))return;await kY(Z)}function kY(Z){let G=s4.get(Z);if(G)return G;let W=(async()=>{while(!0){let K=A$.get(Z),_=K?.[0];if(!_){A$.delete(Z);return}try{let L=()=>A$.get(Z)===K&&K[0]===_;if(!await n8($,Z,_,{noReply:!0,beforeActiveAssistant:!0,canSend:()=>K$.has(Z)&&L(),onPreparedMessageId:(O)=>U3(Z,O),latestPreparedMessageId:()=>[...X1.get(Z)??[]].at(-1)})){if(K$.has(Z)&&!L())continue;return}if(L())K.shift()}catch(L){b.warn("fable-fallback","Desktop notification failed",{session:Z,error:L instanceof Error?L.message:String(L)})}}})();return s4.set(Z,W),W.finally(()=>{if(s4.get(Z)===W)s4.delete(Z)}),W}function vY(Z,G,W,K){if(G.fallback&&G.targetModel){let _=i$.get(Z.recoveryKey);i$.delete(Z.recoveryKey),i$.set(Z.recoveryKey,G.targetModel);while(i$.size>128){let D=i$.keys().next().value;if(D)i$.delete(D);else break}let L=y$.get(Z.sessionId);if(_===G.targetModel&&L?.mode==="server"&&X$(L.requestedModelId)===X$(Z.requestedModel)&&L.targetModelId===G.targetModel)return;b.info("fable-fallback","Anthropic server-side safety fallback active",{session:Z.sessionId,requestedModel:Z.requestedModel,targetModel:G.targetModel,handoff:G.handoff}),T4({sessionId:Z.sessionId,mode:"server",remaining:0,requestedModelId:Z.requestedModel,targetModelId:G.targetModel},W,K,UW(Z.requestedModel,G.targetModel));return}if(G.stopReason==="refusal"||!i$.delete(Z.recoveryKey))return;b.info("fable-fallback","Anthropic server-side safety fallback ended",{session:Z.sessionId,requestedModel:Z.requestedModel}),T4({sessionId:Z.sessionId,mode:"fable",remaining:0,requestedModelId:Z.requestedModel},W,K,QW(Z.requestedModel))}function hY(Z,G,W){if(!Z)return;for(let K of i$.keys())if(K.startsWith(`${Z}\x00`))i$.delete(K);if(!y$.delete(Z))return;m$(G,{activeId:W$.activeId,route:W$.route,mainAccessToken:W.access,mainRefreshToken:W.refresh,routingAuthoritative:!1})}async function kJ(Z){let G=BG(Z);if(G.type==="enable"||G.type==="disable"){let L=G.type==="enable",D=await H1(L),O=l4(D);return t9({enabled:L,mode:O}),b.info("commands","cache enabled changed",{enabled:L}),RZ({argumentsText:Z,enabled:L,mode:O,settingsPath:await w.getSettingsPath()})}if(G.type==="mode"){let L=await n1(G.mode),D=i9(L);return t9({enabled:D,mode:G.mode}),b.info("commands","cache mode changed",{mode:G.mode}),RZ({argumentsText:Z,enabled:D,mode:G.mode,settingsPath:await w.getSettingsPath()})}let W=await r(j),K=i9(W),_=l4(W);return t9({enabled:K,mode:_}),RZ({argumentsText:Z,enabled:K,mode:_})}async function w4(Z){let G=FG(Z),W=await r(j);if(G.type==="window")W=await YJ(G.startHour,G.endHour),b.info("commands","cachekeep schedule changed",{schedule:`${G.startHour}-${G.endHour}`});else if(G.type==="always")W=await C1(),b.info("commands","cachekeep schedule changed",{schedule:"always"});else if(G.type==="disable")W=await r4(!1),b.info("commands","cachekeep enabled changed",{enabled:!1});else if(G.type==="subagents")W=await XJ(G.enabled),b.info("commands","cachekeep subagents changed",{subagents:G.enabled});let K=F8(W),_=await X9(),L=_.length?Math.min(..._.map((D)=>D.nextPrewarmAt)):void 0;return m6({argumentsText:Z,enabled:E8(W),always:w8(W),window:K,hybridActive:S8(W),trackedSessions:_.length,trackedSessionDetails:_,nextPrewarmAt:L})}async function F3(Z){let G=TG(Z);if(G.type==="enable"||G.type==="disable"){let _=G.type==="enable";return await Z1(_),mZ(_),b.info("commands","dump changed",{enabled:_}),L8({argumentsText:Z,enabled:_,settingsPath:await w.getSettingsPath()})}let W=await r(j),K=vZ(W);return mZ(K),L8({argumentsText:Z,enabled:K})}async function T3(Z){let G=wG(Z);if(G.type==="enable"||G.type==="disable"){let _=G.type==="enable";return await GJ(_),pZ(_),b.info("commands","fast mode changed",{enabled:_}),O8({argumentsText:Z,enabled:_,settingsPath:await w.getSettingsPath()})}let W=await r(j),K=bZ(W);return pZ(K),O8({argumentsText:Z,enabled:K})}async function w3(Z,G){if(SG(Z).type==="fire"){if(!G)return`## Claude Start Failed
24
+ `))),X=t$(Y?.error);if($$(X,"type")!=="relay_upstream_error")return;let z=X?.status;if(typeof z==="number"&&Number.isInteger(z))return{status:z,source:"relay_status_field"};let j=$$(X,"message")?.match(/HTTP\s+(\d{3})\b/i);return j?{status:Number(j[1]),source:"relay_message_parse"}:void 0}catch{return}}function d7($,J,Y,X){if(!J)return null;if($.disabled){let V=$.resyncCarry+J,j=X4(V);if(!j)return $.resyncCarry=V.slice(-3),null;if($.disabled=!1,$.resyncCarry="",J=V.slice(j.index+j.length),!J)return null}$.pending+=J;let z=null;while(!0){let V=X4($.pending);if(!V)break;let j=$.pending.slice(0,V.index);$.pending=$.pending.slice(V.index+V.length);let N=J6(j);if(N!==void 0)X?.(N);let F=$6(j);z??=F}if(new TextEncoder().encode($.pending).byteLength>Y){let V=$.pending;$.pending="",$.disabled=!0,$.resyncCarry=V.slice(-3)}return z}function Z6($){return{sseEvents:$.events,ssePendingChars:$.pending.length,ssePendingOverflowCount:$.pendingOverflowCount,sseParseErrors:$.parseErrors,sseEventCounts:{...$.eventCounts},sseTypeCounts:{...$.typeCounts},sseDeltaTypeCounts:{...$.deltaTypeCounts},sseContentBlockTypeCounts:{...$.contentBlockTypeCounts},sseTextDeltaBytes:$.textDeltaBytes,sseThinkingDeltaBytes:$.thinkingDeltaBytes,sseInputJsonDeltaBytes:$.inputJsonDeltaBytes,sseSignatureDeltaBytes:$.signatureDeltaBytes,sseRedactedThinkingBytes:$.redactedThinkingBytes,sseLastEvent:$.last?{...$.last}:void 0}}function G8($,J={}){if(!$.body)return $;let Y=$.body.getReader(),X=new TextDecoder("utf-8",{ignoreBOM:!0}),z=new TextEncoder,V=J.responseMode==="json",j=Q2(J.toolNameMap,V),N=!0,F="",C=0,q=0,M=0,c=0,l=0,K0=!1,v=!1,j0=A0(),n0=A0(),w=J.perf||J.onMessageStart||J.onMessageDelta?u2():void 0,B0="",D0=0,H0=!1,s=(y0)=>{if(!y0)return;try{y0()}catch{}},w0=s2(),D$=J.onContentFilter||J.onComplete?i2():void 0,i0=J.laneStart&&J.laneStartOAuthServed!==!1?r2():void 0,v$=!1,r=!1,B$=(y0=!1)=>{if(!J.onContentFilter)return!1;if(!v$)v$=!0,r=J.onContentFilter({completedToolUse:y0})!==!1;return r},H1=J.serverSideFallbackModel?b7({requestedModel:J.serverSideFallbackModel,maxPendingBytes:d$,onOutcome:J.onServerSideFallbackOutcome,onRefusalAfterToolUse:J.onContentFilter?()=>B$(!0):void 0}):void 0,n1=(y0)=>{if(!D$)return null;let E$=n2(D$,y0,d$);if(E$?.type==="content-filter"&&J.onContentFilter)return B$()?e2(J.contentFilterModel):null;if(E$?.type==="complete")J.onComplete?.(E$.finishReason);return null},r4=(y0,E$=!1)=>i0?o2(i0,y0,d$,E$):y0,C1=()=>{if(v)return;v=!0,Y.releaseLock()},YJ=async(y0)=>{try{await Y.cancel(y0)}catch{}finally{C1()}},XJ=(y0={})=>({chunks:C,pulls:q,inputBytes:M,outputBytes:c,pendingChars:j.pendingLength(),sseErrorPending:w0.pending.length,sseFinishPending:D$?.pending.length??0,sseFinishDisabled:D$?.disabled??!1,serverFallbackPending:H1?.pendingLength()??0,rewriteMs:f$(l),totalMs:f$(A0()-n0),...w?Z6(w):{},...y0}),Z1=(y0,E$={})=>{J.perf?.(y0,XJ(E$))};J.perf?.("stream_tool_prefix_wrapper_created",{status:$.status,hasBody:!0});let GJ=new ReadableStream({async pull(y0){if(q++,!K0)K0=!0,Z1("stream_tool_prefix_first_pull");while(!0){let E$=A0();try{let{done:_4,value:h$}=await Y.read(),L4=f$(A0()-E$);if(_4){let f0=X.decode();if(w&&!V)l7(w,f0,d$,(b0)=>{let b$=b0.message;if(b0.type==="message_start"&&b$)s(()=>J.onMessageStart?.(b$));if(b0.type==="message_delta"&&(b0.usage||b0.stopReason))s(()=>J.onMessageDelta?.({...b0.usage?{usage:b0.usage}:{},...b0.stopReason?{stopReason:b0.stopReason}:{}}))});if(V){let b0=z.encode(f0).byteLength;if(D0+b0<=d$)B0+=f0,D0+=b0;else H0=!0}if(V&&!H0)try{let b0=JSON.parse(B0);if(b0&&typeof b0==="object"&&!Array.isArray(b0))s(()=>J.onMessageResponse?.(b0))}catch{}let q1=A0(),zJ=H1?H1.push(f0)+H1.flush():f0,H$=r4(zJ,!0),Y1=V?n1(H$):d7(w0,f0,d$,J.onRelayUpstreamError)??n1(H$);if(Y1)throw Z1("stream_tool_prefix_retryable_error",{providerErrorType:Y1.providerErrorType}),await YJ(Y1),Y1;let U1=j.push(H$,!0);if(l+=A0()-q1,U1||F){let b0=z.encode(F+U1);F="",c+=b0.byteLength,y0.enqueue(b0)}if(Z1("stream_tool_prefix_rewrite",{readMs:L4}),C1(),J.onStreamEnd)try{await J.onStreamEnd()}catch{}y0.close();return}C++,M+=h$.byteLength;let C$=X.decode(h$,{stream:!0});if(N&&C$){if(N=!1,C$.charCodeAt(0)===65279)F=C$[0]??"",C$=C$.slice(1)}if(V){let f0=h$.byteLength;if(D0+f0<=d$)B0+=C$,D0+=f0;else H0=!0}if(w&&!V)l7(w,C$,d$,(f0)=>{let q1=f0.message;if(f0.type==="message_start"&&q1)s(()=>J.onMessageStart?.(q1));if(f0.type==="message_delta"&&(f0.usage||f0.stopReason))s(()=>J.onMessageDelta?.({...f0.usage?{usage:f0.usage}:{},...f0.stopReason?{stopReason:f0.stopReason}:{}}))});let WJ=A0(),j$=H1?H1.push(C$):C$,G$=r4(j$),O4=V?n1(G$):d7(w0,C$,d$,J.onRelayUpstreamError)??n1(G$);if(O4)throw Z1("stream_tool_prefix_retryable_error",{providerErrorType:O4.providerErrorType,readMs:L4,lastChunkBytes:h$.byteLength}),C1(),O4;let A1=j.push(G$);if(l+=A0()-WJ,A1){let f0=z.encode(F+A1);F="",c+=f0.byteLength,y0.enqueue(f0)}let P1=A0();if(C===1||C%25===0||P1-j0>5000)j0=P1,Z1("stream_tool_prefix_progress",{readMs:L4,lastChunkBytes:h$.byteLength});if(A1)return}catch(_4){s(J.onResponseFailure);let h$=NZ(_4,J.toolNameMap);if(Z1("stream_tool_prefix_error"),h$ instanceof y4)await DZ(Y,h$),v=!0,s(J.onToolNameRefusal);else C1();throw h$}}},async cancel(y0){s(J.onResponseFailure),Z1("stream_tool_prefix_cancel");try{await Y.cancel(y0)}finally{C1()}}});return new Response(GJ,{status:$.status,statusText:$.statusText,headers:$.headers})}import{mergeNativeSettingsSection as MW,nativeCacheKeepAlways as RW,nativeSettingsRecord as xW}from"@cortexkit/anthropic-auth-core";var h8="physical send failed before a response",oG="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",b8="~effect/http/HttpServerResponse",g8="~effect/http/Cookies",y8="~effect/http/HttpBody",sG="~effect/ErrorReporter/ignore",aG="https://api.anthropic.com/v1/messages",JY=new WeakSet;function ZJ($){let J=new Response(JSON.stringify({type:"error",error:{type:"invalid_request_error",message:$}}),{status:400,headers:{"content-type":"application/json"}});return JY.add(J),J}async function m8($,J){if(!J?.aborted)return;await $.body?.cancel().catch(()=>{}),J.throwIfAborted()}function cZ($,J){return($.status!==400||!JY.has($))&&uG($.status,J)}function p8($){return b.warn("effort-history","refused uncorrelated per-message effort request",{check:$.check,...$.details}),ZJ($.message)}function c8($){return b.warn("transform","refused request ending on assistant history",{check:$.check,...$.details}),ZJ($.message)}var tG=60000,l8=60000,ZY=240,eG=ZY,$W=600000;function JW($,J){return($?.accounts??[]).some((Y)=>Y.id===J&&x0(Y)&&R0(Y))}function ZW($){let J=($?.accounts??[]).find((Y)=>x0(Y)&&R0(Y));if($1($)==="fallback-first"&&J)return{activeId:J.id,route:"fallback-first"};return{activeId:"main",route:"main"}}function u8($,J){if($?.activeId==="main"||$?.activeId&&JW(J,$.activeId))return{activeId:$.activeId,route:$.route};return ZW(J)}function YY($,J,Y){let X=Date.now()-$.lastUpdated;if(!$.activeId||X<0||X>$W)return u8(Y,J);return u8({activeId:$.activeId,route:$.route},J)}async function YW($,J,Y){let X;try{X=await J()}catch(z){return b.warn("sidebar","account storage reload failed; routing preserved",{message:z instanceof Error?z.message:String(z)}),{...$.activeId?{activeId:$.activeId,route:$.route}:Y??{activeId:"main",route:"main"},freshStorage:null}}return{...YY($,X,Y),freshStorage:X}}async function XW($){await e9()?.beforeStorageLoad?.();let J;try{J=await $()}catch{return{activeId:"main",route:"main",freshStorage:null}}finally{await e9()?.afterStorageLoad?.()}await e9()?.beforeSidebarRead?.();let Y=await e8();return{...YY(Y,J),freshStorage:J}}var GW=4,WW=25,zW=1,d8=!1;function $J(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function X0(){return performance.now()}function I0($){return Math.round($*10)/10}function i8($){return Math.floor(Math.random()*Math.max(0,$))}function K4($){if(typeof $==="string")return $;if($ instanceof URL)return $.toString();return $.url}function i1($,J){return J?.method??($ instanceof Request?$.method:void 0)}async function d4($,J){if(J?.body!==void 0)return J.body;if(!($ instanceof Request)||$.body===null)return;try{return await $.clone().text()}catch{return}}function VW(){if(d8||!1||!$J())return;d8=!0;let $=100,J=250,Y=X0()+$;setInterval(()=>{let X=X0(),z=X-Y;if(Y=X+$,z<J)return;J1("[perf] opencode event_loop_lag",{lagMs:I0(z),thresholdMs:J})},$).unref?.()}function jW($){let J=X0(),Y={requestId:String(zW++),start:J,last:J,mark(X,z){let V=X0();if($J())J1("[perf] opencode request stage",{requestId:Y.requestId,stage:X,deltaMs:I0(V-Y.last),totalMs:I0(V-Y.start),...z});Y.last=V},done(X,z){let V=X0();if($J())J1("[perf] opencode request done",{requestId:Y.requestId,stage:X,deltaMs:I0(V-Y.last),totalMs:I0(V-Y.start),...z});Y.last=V}};if($J())J1("[perf] opencode request start",{requestId:Y.requestId,...$});return Y}function XY($,J){let Y=/^msg_([0-9a-fA-F]{12})/.exec($);if(!Y)return;let X=BigInt(`0x${Y[1]}`);if(X<=0n)return;let V=`msg_${(X-1n).toString(16).padStart(12,"0")}${"z".repeat(14)}`,j=J&&V<=J?`${J}z`:V;if(j.length>128||j>=$)return;return j}async function n8($,J,Y,X={}){let z=$.client.session,V=await F9($.client,J),j={path:{id:J},body:{noReply:X.noReply??!0,parts:[{type:"text",text:Y,ignored:!0}]}};if(X.beforeActiveAssistant){let N=X.latestPreparedMessageId?.(),F=V?.latestUserMessageId,C=N&&(!F||N>F)?N:F,q=V?.latestAssistantMessageId?XY(V.latestAssistantMessageId,C):void 0;if(!q)return!1;j.body.messageID=q}if(V?.agent)j.body.agent=V.agent;if(V?.model)j.body.model=V.model;if(V?.variant)j.body.variant=V.variant;if(X.canSend&&!X.canSend())return!1;if(j.body.messageID)X.onPreparedMessageId?.(j.body.messageID);if(typeof z?.promptAsync==="function")return await z.promptAsync(j),!0;if(typeof z?.prompt==="function")return await Promise.resolve(z.prompt(j)),!0;throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function KW(){throw Object.assign(Error(oG),{[b8]:b8,[sG]:!0,status:204,statusText:void 0,headers:{},cookies:{[g8]:g8,cookies:{}},body:{[y8]:y8,_tag:"Empty"}})}function _W($){if($.sessionID==null)return!1;let J=$.model;return J?.providerID==="anthropic"||J?.api?.npm==="@ai-sdk/anthropic"||J?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function LW($){if($.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return $.push(DG),!0}var OW={input:0,output:0,cache:{read:0,write:0}},NW=1000;function k$($){return $}function DW($,J){let Y=n4($);return`${Y} content filter detected. Switched to Opus 4.8 for a ${J}-response recovery window before trying ${Y} again.`}function HW($){let J=n4($);return`${J} recovery window complete. Returning to ${J}.`}function n4($){if(XG($))return"Opus 5.5";if(YG($))return"Opus 5";if(ZG($)){if($.startsWith("claude-mythos-5-1"))return"Mythos 5.1";if($.startsWith("claude-fable-5-1"))return"Fable 5.1"}if($==="claude-fable-5"||$.startsWith("claude-fable-5-"))return"Fable 5";if($==="claude-opus-4-8"||$.startsWith("claude-opus-4-8-"))return"Opus 4.8";return $}function UW($,J){return`Anthropic safety fallback active: ${n4($)} → ${n4(J)}. Follow-up requests may remain on the fallback model for about one hour.`}function QW($){return`Anthropic safety fallback ended. Returning to ${n4($)}.`}function BW(){return{input:b9.input,output:b9.output,cache:{read:b9.cacheRead,write:b9.cacheWrite5m},tiers:[{tier:{type:"context",size:B6},input:v9.input,output:v9.output,cache:{read:v9.cacheRead,write:v9.cacheWrite5m}}]}}function FW($){let J=$["claude-opus-4-8"]??$["claude-opus-4-5"]??Object.values($)[0];if(!J)return $;return{...$,...Object.fromEntries(Object.values(U6).map((Y)=>{let X=r6(Y.id),z=X.pricing;return[Y.id,{...J,id:Y.id,name:Y.name,api:J.api?{...J.api,id:Y.id}:void 0,cost:{input:z.input,output:z.output,cache:{read:z.cacheRead,write:z.cacheWrite5m}},limit:{...J.limit??{},context:X.contextWindow,output:X.maxOutputTokens},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:X.releaseDate}]})),...$[h9]?{}:{[h9]:{...J,id:h9,name:"Claude Haiku 5.5",api:J.api?{...J.api,id:h9}:void 0,cost:BW(),limit:{...J.limit??{},context:Q6,output:F6},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:T6,variants:JJ()}},...$[m9]?{}:{[m9]:{...J,id:m9,name:"Claude Sonnet 5.5",api:J.api?{...J.api,id:m9}:void 0,cost:{input:p9.input,output:p9.output,cache:{read:p9.cacheRead,write:p9.cacheWrite5m}},limit:{...J.limit??{},context:C6,output:A6},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:P6,variants:JJ()}},...$[g9]?{}:{[g9]:{...J,id:g9,name:"Claude Opus 5.5",api:J.api?{...J.api,id:g9}:void 0,cost:{input:y9.input,output:y9.output,cache:{read:y9.cacheRead,write:y9.cacheWrite5m}},limit:{...J.limit??{},context:w6,output:S6},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:E6,variants:JJ()}}}}var TW=["low","medium","high","xhigh","max"];function JJ($=TW){return Object.fromEntries($.map((J)=>[J,{thinking:{type:"adaptive",display:"summarized"},effort:J}]))}function wW($){return Object.fromEntries(Object.entries($).map(([J,Y])=>{let X=Y.api?.id??Y.id??J,z=bG(X)?.efforts.variants;return[J,z?{...Y,variants:JJ(z)}:Y]}))}function SW($){return Object.fromEntries(Object.entries($).map(([J,Y])=>[J,{...Y,cost:OW}]))}var EW=2000,lZ="@cortexkit/opencode-anthropic-auth",i4;function CW(){if(i4!==void 0)return i4;i4=lZ;try{let $=JSON.parse(X6(W6(G6(z6(import.meta.url)),"..","package.json"),"utf8"));if($.name===lZ&&typeof $.version==="string"&&$.version.trim())i4=`${lZ}@${$.version.trim()}`}catch{}return i4}function AW(){return["The Claude menu opens in OpenCode's terminal window when the plugin's TUI part is loaded.",`In the terminal, add "${CW()}" to the plugin list in tui.json (or rerun setup), then restart OpenCode.`,"In OpenCode Desktop, use the text menu below."].join(`
25
+ `)}function PW(){return process.env.OPENCODE_CLIENT==="desktop"}function r8(){return process.env.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||void 0}var qW=async($,J={})=>{let Y={setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,setInterval:globalThis.setInterval,clearInterval:globalThis.clearInterval,...J},X=J.authorize??z8;VW();let{client:z}=$,V=globalThis.fetch,j=d6(),N=new zG,F=s6(a6(j)),C=600000,q=50,M=new Map;function c(){let Z=Date.now();for(let[G,W]of M)if(Z-W.createdAt>C)M.delete(G)}function l(Z,G){if(c(),M.size>=q){let W="",K=1/0;for(let[_,L]of M)if(L.createdAt<K)K=L.createdAt,W=_;if(W)M.delete(W)}M.set(Z,G)}function K0(Z){c();let G=M.get(Z);if(!G)return;if(Date.now()-G.createdAt>C){M.delete(Z);return}return G}let v;try{v=await v6({role:"opencode1",onLockEvent:J.nativeLocal?.onLockEvent})}catch(Z){let G=iG(Z);if(G)throw Error(G,{cause:Z});throw Z}let j0=await gG(j,void 0,v.layout),n0=v.kind==="state-home"?void 0:v.registration,w=j6({paths:j0,host:"opencode",local:J.nativeLocal,vault:J.claustrumScopedConnect?{connect:J.claustrumScopedConnect}:void 0}),B0=w.quotaObservations,D0=null;function H0(Z){return LG(Z)}function s(Z,G){return Z?H0(Z.binding):G?JSON.stringify([G.credentialId,G.accountIdentity,G.recordVersion]):void 0}function w0(Z,G,W,K=D0){let _=B0.get(Z);if(!_||!G||_.lineage!==G||_.accountUuid!==W||g1(_.entry.quota,K,_.entry.checkedAt)<=Date.now())return;return _}function D$(Z,G,W,K,_=D0){let L=w0(Z,G,W,_);if(!L)return K;if(!K)return{...L.entry,refreshAfter:g1(L.entry.quota,_,L.entry.checkedAt)};let D=L.entry.quota.source!=="headers"&&p1(K.quota)>p1(L.entry.quota)?K.quota:P8(K.quota,L.entry.quota);return{...L.entry,quota:D,refreshAfter:g1(D,_,p1(D))}}function i0(Z,G,W){if(!B0.has(Z.id))return Z.quota;let K=Z.binding?H0(Z.binding):s(void 0,W),_=p1(Z.quota);return D$(Z.id,K,Z.accountIdentity,Z.quota?{quota:Z.quota,checkedAt:_,refreshAfter:g1(Z.quota,G,_)}:null,G)?.quota}let v$;async function r(Z=j){if(Z!==j)throw Error("Native account storage mismatch");let G=await w.read();if(D0=G.policyStorage,!v$){let _=G.accounts.find((L)=>L.id==="main")?.binding;if(_)v$={rowId:_.rowId,credentialEpoch:_.credentialEpoch}}if(G.mode!=="claustrum")return G.policyStorage;let W=G.accounts.find((_)=>_.id==="main"&&_.source==="vault"),K=k$(W?.accountIdentity);return{...G.policyStorage,claustrum:{...G.policyStorage.claustrum,mode:"claustrum",scopedRoster:!0,primaryAccount:W?.credentialId&&K?{credentialId:W.credentialId,accountId:K,state:W.state??"cold",enabled:W.enabled}:void 0}}}async function B$(Z,G){return await w.updateSettings((W)=>MW(W,Z,G)),r()}let H1=async(Z)=>{return await w.updateSettings((G)=>({...G,claudeCache:{...xW(G.claudeCache),enabled:Z,mode:l4({...G,version:1,accounts:[]})}})),r()},n1=(Z)=>B$("claudeCache",{mode:Z}),r4=(Z)=>B$("cacheKeep",{enabled:Z}),C1=async()=>{return await w.updateSettings(RW),r()},YJ=(Z,G)=>B$("cacheKeep",{enabled:!0,always:!1,startHour:Z,endHour:G}),XJ=(Z)=>B$("cacheKeep",{subagents:Z}),Z1=(Z)=>B$("dump",{enabled:Z}),GJ=(Z)=>B$("claudeFast",{enabled:Z}),y0=async(Z)=>{return await w.setLoggingLevel(Z),r()},E$=(Z,G=j)=>B$("prime",{enabled:Z}),_4=(Z,G=j)=>B$("routing",{mode:Z}),h$=(Z)=>B$("killswitch",Z),L4=(Z,G,W=j)=>w.setEnabled(Z,G),C$=(Z,G=j)=>w.remove(Z),WJ=(Z,G=j,W)=>w.reorder(Z,W),j$=null;try{j$=await r()}catch{}function G$(Z){return Boolean(Z&&u4(Z)==="claustrum"&&Z.claustrum?.scopedRoster===!0)}function O4(Z=j,G=$.directory){if(Z!==j)throw Error("Native vault storage mismatch");return w.vault}let A1=x6("native-auth"),P1=new Set;async function f0(Z){let G=Promise.resolve().then(Z);P1.add(G);try{return await G}finally{P1.delete(G)}}async function q1(){while(P1.size)await Promise.allSettled([...P1])}async function zJ(Z=j){TJ?.close(),await q1(),await A1.drain(),await w.drainQuotaPublications(),await Promise.all([...OJ.values()].map((G)=>G.drain())),await w.drainRoutingPublications(),await w.close()}function H$(){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native OAuth cannot serve while OPENCODE_AUTH_CONTENT is set")}function Y1(Z){let G=k$(Z);if(!G)throw Error("Native wire identity requires an admitted provider account");return n6(G,G)}class U1 extends Error{account;checkIntervalMs;constructor(Z,G){super("OAuth account cannot serve the requested model under current quota policy");this.account=Z;this.checkIntervalMs=G}}class b0 extends Error{constructor(){super("Native OAuth requires a Claude Pro/Max credential. An API key belongs in OpenCode stock Anthropic authentication.")}}class b$ extends Error{account;tokenRefreshFailed;failure;constructor(Z,G,W=!1,K){super(K?.kind==="provider"&&K.status!==void 0?`Claude OAuth refresh failed: ${K.status} — ${K.classification==="invalid-grant"?"invalid_grant":"OAuth operation failed"}`:`Native OAuth authorization refused: ${G}`);this.account=Z;this.tokenRefreshFailed=W;this.failure=K}}async function m0(Z,G,W,K,_="serve",L){H$(),G?.throwIfAborted();let D=L??await w.read(),O=D.accounts.find((i)=>i.id===Z);if(_==="cachekeep"&&(O?.type!=="oauth"||!x0(O)))throw new m1("account-unavailable");if(O?.state==="unsupported-access")throw new b0;if(O?.source==="vault"&&!x0(O))throw new b$(O,"not-active");if(O?.type!=="oauth"||!x0(O))throw Error("Native OAuth account is unavailable");let Q=(i,t,L0)=>{let p0=i0(i,t,L0),P0=_==="last-main"&&Z==="main"&&$1(t)!=="sticky-balanced";if(K&&(L1(t)&&!N1(p0,t,Z==="main"?void 0:Z,K)||!P0&&!a9(p0,K)))throw _==="cachekeep"?new m1("account-policy"):new U1(i,T8(t))};Q(O,D.policyStorage);let U;if(O.source==="vault"){let i=await w.authorizeVault(Z,G).catch((t)=>{if(G?.throwIfAborted(),_==="cachekeep"){let L0=KG(t);if(L0)throw L0}if(t instanceof VG&&["not-active","route-declined","route-unavailable"].includes(t.code))throw new b$(O,t.code);throw t});U={accessToken:i.accessToken,expires:i.expiresAtMs??void 0,accountIdentity:i.accountIdentity,scopedAttempt:i}}else{let i=await w.authorizeLocal(Z,{signal:G,rejectedAccessToken:W,intent:W?"refresh":_==="last-main"||_==="cachekeep"?"serve":_});if(i.status!=="usable"){if(_==="cachekeep"){let t=_G(i);if(t)throw t}throw new b$(O,i.status,i.status==="failed"&&i.failure.kind==="provider",i.status==="failed"?i.failure:void 0)}U={accessToken:i.access,expires:i.expires,accountIdentity:i.binding.identity,localSubject:i.subject,localSource:i.source}}let P=await w.read(),p=P.accounts.find((i)=>i.id===Z);if(G?.aborted)throw G.reason??Error("Request aborted");if(!p||!x0(p)||p.source!==O.source||p.accountIdentity!==U.accountIdentity)throw _==="cachekeep"?new m1("credential-changed"):Error("Native OAuth account changed before dispatch");if(U.localSubject&&(!p.binding||p.binding.storageId!==U.localSubject.binding.storageId||p.binding.rowId!==U.localSubject.binding.rowId||p.binding.credentialEpoch!==U.localSubject.binding.credentialEpoch||p.binding.identity!==U.localSubject.binding.identity))throw _==="cachekeep"?new m1("credential-changed"):Error("Native local account binding changed before dispatch");if(U.scopedAttempt&&p.credentialId!==U.scopedAttempt.credentialId)throw _==="cachekeep"?new m1("credential-changed"):Error("Native vault credential binding changed before dispatch");return Q(p,P.policyStorage,U.scopedAttempt),U}async function uZ(Z,G){let K=(await w.read()).accounts.find((L)=>L.id===Z);if(K?.type!=="oauth")throw Error("Native OAuth account is unavailable");let _=K.source==="vault"?await w.authorizeVault(Z,G):await w.captureLocalSubject(Z);if(!await w.resetBackoff(Z,_))throw Error("Native reset fence changed")}let dZ=new WeakMap,iZ=new WeakSet;async function VJ(Z,G){if(iZ.has(Z))return;iZ.add(Z),await f0(()=>w.vault.reportFailure(Z,401,G)).catch(()=>{b.warn("claustrum","native auth-failure report unavailable")})}async function o4(Z,G,W){let K=await w.vault.prepareRetry(Z,W,G);return K.retry?K.receipt:void 0}let jJ=v7(process.env.OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE),k0=new YZ,Q1=new Map;function KJ(Z){for(let{recoveryKey:G}of k0.sourceWarmsForSession(Z))k0.dropSourceWarm(G);for(let G of a0.trackedSessions()){let W=k4(G.id);if(W&&W.sessionId===Z)a0.untrack(G.id)}for(let G of[...Q1.keys()])if(G.startsWith(`${Z}\x00`))Q1.delete(G)}let _J=new WZ,M1=new eJ,R1=new yJ,r1=new yG,i$=new Map,A$=new Map,g$=new Map,s4=new Map,K$=new Set,LJ=new Map,a4=new Map,X1=new Map,N4=new Map,OJ=new Map,D4=w7(async(Z)=>{return(await w.read()).accounts.find((W)=>W.accountIdentity===Z.accountIdentity&&(!Z.credentialId||W.credentialId===Z.credentialId))?.quota}),nZ=new WeakSet,NJ=new WeakMap;async function rZ(){let Z=await w.read(),G=Z.routingPath;if(!G)throw Error(Z.mode==="claustrum"?"Vault routing storage is unavailable":"Native routing storage is unavailable");let W;if(Z.mode==="claustrum"){W=new Map;for(let _ of Z.accounts)if(_.source==="vault"&&_.accountIdentity)W.set(_.id,_.accountIdentity)}let K=OJ.get(G);if(!K)K=new mG({path:G,vaultSeed:Z.routingSeed,onLockEvent:w.onLockEvent,relocationGuard:w.relocationGuard,localRecoveryPath:Z.mode==="local"?Z.routingRecoveryPath:void 0}),OJ.set(G,K);return K.setVaultSeed(Z.routingSeed),{router:K,...W&&{accountIdentities:W}}}let y=new RG({storage:j$,pauseBetweenQuotaCalls:J.quotaCallPause,fetchQuotaSnapshot:(Z,G)=>{H$();let W=Z.kind==="main"?"main":Z.accountId;if(!W)throw Error("Quota request has no account identity");return w.fetchQuota(W,void 0,void 0,G,Z.purpose)}});function H4(Z){return["five_hour","seven_day"].some((G)=>(Z?.[G]?.remainingPercent??1)<=0)}function oZ(Z,G,W=!1){if(!Z||Z.quota?.enabled===!1||!G||$1(Z)==="sticky-balanced"||O1(Z.refresh?.mainLastRefreshError))return;let K=Date.now(),_=Z.quota?.mainLastQuotaApiError;if(_&&_.accountIdentity===G&&_.nextRetryAt!==void 0&&_.nextRetryAt>K)return{message:B8(_,K),retryAfter:Math.max(1,Math.ceil((_.nextRetryAt-K)/1000))};let L=Z.quota?.mainQuota,D=p1(L);if(L?.accountIdentity!==G||L.source==="headers"&&!W||!H4(L)||D<=0||D>K||g1(L,Z,D)<=K)return;let O=["five_hour","seven_day"].flatMap((Q)=>{let U=L[Q],P=U?.resetsAt?Date.parse(U.resetsAt):Number.NaN;return U&&U.remainingPercent<=0&&Number.isFinite(P)&&P>K?[P]:[]});return{message:"Claude OAuth quota is exhausted for this account.",retryAfter:Math.max(1,Math.ceil(((O.length?Math.max(...O):K+T8(Z))-K)/1000))}}async function sZ(Z,G,W){if(MJ===Z&&P$===G)return;let K=a1!==void 0&&W!==void 0&&a1!==W;MJ=Z,P$=G,y.setMainQuotaAccountIdentity(G,!0,K)}async function U4(Z,G,W,K){let _=Z,L=z9.get(_);if(L){let O=await L.promise;return K===L.recordVersion?O:{...O,stale:!0}}let D=(async()=>{let O=++N3,Q=B4,U=await w.read(),P=U.policyStorage,p=U.accounts.find((w1)=>w1.id==="main")?.accountIdentity,i=Y1(W??p),t=U.mode==="claustrum",L0=t?P?.claustrum?.primaryAccount?.accountId:void 0;if(W!==void 0&&W!==p||t&&W===void 0)return{quotaKey:void 0,providerAccountUuid:void 0,generation:y.getMainQuotaIdentityGeneration(),stale:!0,state:"on-identity-mismatch"};let p0=p??L0??Q,P0=P?.main?.profile?.providerAccountUuid??P?.main?.profile?.accountIdentity,c0=k$(W)??k$(i.accountUuid),U0=W?c0:Z.startsWith("sk-ant-oat")?c0??k$(P0):void 0,F$=u4(P)!=="claustrum"?"na":P0===void 0||c0===void 0?"unknown-identity":P0!==void 0&&c0!==void 0&&P0!==c0?"on-identity-mismatch":"on-vault-served";if(O!==N3){let w1=MJ!==Z||P$!==p0;return{quotaKey:p0,providerAccountUuid:U0,generation:y.getMainQuotaIdentityGeneration(),stale:w1,state:F$}}if(await sZ(Z,p0,U0),Z.startsWith("sk-ant-oat")&&U0===void 0)y.clearMain();if(a1=U0,Z.startsWith("sk-ant-oat"))F4=Z;return{quotaKey:p0,providerAccountUuid:U0,generation:y.getMainQuotaIdentityGeneration(),stale:!1,state:F$}})();z9.set(_,{promise:D,recordVersion:K});try{return await D}finally{if(z9.get(_)?.promise===D)z9.delete(_)}}let DJ=j$?.quotaHeaderFeed?.enabled===!0?new MG:null,G1=new Map,aZ=new Map,B1=new Set,F1=new AbortController,tZ=!1;function t4(Z,G){return JSON.stringify([Z,G??null])}function HJ(Z){let G=Z.binding;if(Z.source!=="local"||!G)return;return JSON.stringify([G.storageId,G.rowId,G.credentialEpoch])}function UJ(Z,G){return Z.lineage!==void 0&&Z.lineage===HJ(G)&&(!Z.profile||Z.profile.accountIdentity===G.accountIdentity)}async function e4(Z,G){if(!Z?.profile||!r9(Z.profile,G)||!await Z.isCurrent?.())return;return Z.persistence==="refused"?void 0:Z.profile}function eZ(Z){if(!Z)return[];let G=new Set([...Z.main?["main"]:[],...(Z.accounts??[]).filter((W)=>R0(W)&&(W.enabled!==!1||Boolean(W.claustrumScopedCredentialId))).map((W)=>W.id)]);return[...new Set(G1.values())].filter((W)=>W.persistence==="failed"&&W.profile!==void 0&&G.has(W.accountId))}async function GY(Z,G,W,K){let _=G.accountId,L=W.accounts.find((Q)=>Q.id===_),D=L?.source==="local"?UJ(G,L):L?.source==="vault"&&L.accountIdentity===K.accountIdentity;if(L?.type!=="oauth"||!x0(L)||L.accountIdentity!==K.accountIdentity||!D||await e4(G,Date.now())!==K)return Z;if(_==="main")return Z.main?{...Z,main:{...Z.main,profile:K}}:Z;let O=Z.accounts?.find((Q)=>Q.id===_);if(!O||!R0(O))return Z;return{...Z,accounts:Z.accounts.map((Q)=>Q.id===_&&R0(Q)?{...Q,profile:K}:Q)}}async function $3(Z,G,W=eZ(Z)){if(!Z||W.length===0)return Z;let K=[];for(let D of W){let O=await e4(D,Date.now());if(O)K.push({hydration:D,profile:O})}if(!K.length)return Z;let _=G??await w.read(),L=Z;for(let D of K)L=await GY(L,D.hydration,_,D.profile);return L}function WY(Z,G,W){H$();let K=!1,_=Object.assign((D,O)=>{return K=!0,V(D,O)},{preconnect:V.preconnect}),L={accountId:Z.id,fetched:Promise.resolve(),lineage:HJ(Z),...W&&{deadline:W}};return L.fetched=w.fetchProfileForDisplay(Z.id,_,AbortSignal.any([F1.signal,...W?[W]:[]])).then(({profile:D,persisted:O,isCurrent:Q})=>{if(L.settled=!0,D.accountIdentity!==void 0)aZ.set(t4(Z.id,D.accountIdentity),D);if(Z.accountIdentity===void 0||D.accountIdentity===Z.accountIdentity)L.profile=D,L.isCurrent=Q,L.persistence="pending";let U=O.then(async(P)=>{if(L.persistence=P,P==="failed")b.warn("quota","failed to persist account profile",{account:Z.id});else if(P==="refused")b.debug("quota","refused account profile publication",{account:Z.id});if((P==="saved"||P==="failed")&&!F1.signal.aborted){let p=P==="failed"&&await e4(L,Date.now());if(P==="saved"||p)try{let i=await w.read();if(!F1.signal.aborted)await m$(i.policyStorage,{...W$,routingAuthoritative:!1},i)}catch{b.debug("quota","failed to publish account profile to sidebar",{account:Z.id})}}});B1.add(U),U.then(()=>B1.delete(U))},(D)=>{if(L.settled=!0,L.failed=K,b.debug("quota","failed to hydrate account profile",{account:Z.id,error:D instanceof Error?D.message:String(D)}),!K&&G1.get(G)===L)G1.delete(G)}),B1.add(L.fetched),L.fetched.then(()=>B1.delete(L.fetched)),L}function zY(Z,G){let W=[G,Z.deadline].filter((_)=>_!==void 0);if(!W.length)return Z.fetched;let K=AbortSignal.any(W);if(K.aborted)return Promise.resolve();return new Promise((_)=>{let L=()=>{K.removeEventListener("abort",L),_()};K.addEventListener("abort",L,{once:!0}),Z.fetched.then(L)})}function J3(Z,G){return r9(Z.profile,G)&&NG(Z.profile,Z.accountIdentity)}async function $9(Z){let G=await w.read();if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return G;let W=Date.now(),K=[],_=new Map;for(let O of G.accounts){if(O.type!=="oauth"||!x0(O)||J3(O,W))continue;let Q=t4(O.id,O.accountIdentity),U=G1.get(Q);if(U&&O.accountIdentity===void 0&&(U.lineage===void 0||U.lineage!==HJ(O)))U=void 0;if(!U&&O.accountIdentity!==void 0){let P=G1.get(t4(O.id));if(P&&UJ(P,O))U=P,_.set(O.id,P)}if(U?.failed)continue;if(!U&&r9(aZ.get(Q),W))continue;if(!U||!U.profile&&(U.deadline?.aborted||U.settled)||U.profile&&!r9(U.profile,W)){if(Z?.aborted||F1.signal.aborted)continue;U=WY(O,Q,Z),G1.set(Q,U)}if(O.accountIdentity===void 0)_.set(O.id,U);K.push(zY(U,Z))}if(!K.length)return G;await Promise.all(K);let L=await w.read(),D=Date.now();for(let O of L.accounts){if(O.type!=="oauth"||!x0(O))continue;let Q=t4(O.id,O.accountIdentity),U=_.get(O.id);if(U&&O.accountIdentity!==void 0&&!G1.has(Q)&&UJ(U,O))G1.set(Q,U);if(J3(O,D))continue;let P=await e4(G1.get(Q),D);if(!P||P.accountIdentity!==O.accountIdentity)continue;if(O.profile=P,O.id==="main"){if(L.policyStorage.main)L.policyStorage.main.profile=P}else for(let p of L.policyStorage.accounts)if(p.id===O.id&&R0(p))p.profile=P}return L}async function VY(Z,G,W,K){if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return Z;return(await $9(W)).policyStorage}let Z3=new Set;async function jY(Z,G,W){let _=(await w.read()).accounts.find((U)=>U.id===Z.accountId);if(!_||!Z.anthropicAccountUuid||_.accountIdentity!==Z.anthropicAccountUuid)return null;let L={...P8(_.quota,G.quota),accountIdentity:_.accountIdentity};if(!(Z.scopedAttempt?await w.vault.publish(Z.scopedAttempt,{quota:L}):Z.localSubject?await w.publishLocal(Z.localSubject,{quota:L}):!1)){if(Z.accountId==="main"){if(y.getMain(Z.mainQuotaIdentity?.quotaKey)===W)y.clearMain()}else if(y.getAllFallbacks().get(Z.accountId)===W)y.clearFallback(Z.accountId);return b.debug("quota","native quota publication refused",{accountId:Z.accountId}),b.warn("quota","Quota publication discarded"),null}let O=await w.read(),Q=O.accounts.find((U)=>U.id===Z.accountId);if(!Q?.quota||Q.accountIdentity!==Z.anthropicAccountUuid||Q.source!==_.source)return null;if(Z.localSubject&&Q.binding?.credentialEpoch!==Z.localSubject.binding.credentialEpoch)return null;if(Z.scopedAttempt&&Q.credentialId!==Z.scopedAttempt.credentialId)return null;return{...G,quota:Q.quota,refreshAfter:g1(Q.quota,O.policyStorage,G.checkedAt)}}function KY(Z){b.warn("quota","failed to persist harvested response quota",{error:Z instanceof Error?Z.message:String(Z)})}function _Y(Z){let G=Z instanceof Error?Z.name:typeof Z,W=Z instanceof Error?Z.message:String(Z),K=`${G}:${W}`;if(Z3.has(K))return;Z3.add(K),b.warn("quota","failed to normalize response quota headers",{error:W})}function LY(Z){if(!Z||typeof Z!=="object")return;let G=Z,W=G.credential_id;if(typeof W==="string"&&W&&W!=="main")return W;let K=G.vault;if(K&&typeof K==="object"){let _=K.credential_id;if(typeof _==="string"&&_&&_!=="main")return _}return}async function OY(Z,G){if(!DJ)return;if(Z.accountId==="main"&&!Z.mainQuotaIdentity?.quotaKey)return;let W=await r(j)??_1(),_=(await T1?.())?.type==="oauth",L=Z.accountId==="main"?W.main:W.accounts.find((i)=>i.id===Z.accountId),D=LY(L),O=R6({storage:W,mainOAuthConfigured:_}),Q=G.checkedAt,U={five_hour:G.quota.five_hour,seven_day:G.quota.seven_day,bindingWindow:G.quota.bindingWindow,fallbackAdvised:G.quota.fallbackAdvised,scoped:G.quota.scoped,extraUsage:G.quota.extraUsage,fieldSources:G.quota.fieldSources},P=D??(Z.accountId==="main"?Z.mainQuotaIdentity?.quotaKey??"main":Z.accountId),p=D?{identity_source:"credential_id",credential_id:D,schema_version:o9,provider:"anthropic",configured_account_count:O,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:P}:Z.accountId==="main"&&Z.mainQuotaIdentity?.quotaKey?{identity_source:"account_ref",account_ref:Z.mainQuotaIdentity.quotaKey,schema_version:o9,provider:"anthropic",configured_account_count:O,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:P}:Z.accountId==="main"?{identity_source:"none",schema_version:o9,provider:"anthropic",configured_account_count:O,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:P}:{identity_source:"account_ref",account_ref:Z.accountId,schema_version:o9,provider:"anthropic",configured_account_count:O,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:P};await DJ.publish(p)}function NY(Z){b.debug("quota","failed to publish quota header feed",{error:Z instanceof Error?Z.message:String(Z)})}function Y3(Z,G){try{if(!WG(Z)){b.trace("quota","skipped non-quota response headers",{account:G.accountId});return}let W=OG(Z),K=G.accountId==="main"?G.mainQuotaIdentity:void 0;if(G.accountId==="main"){if(!K||y.getMainQuotaIdentityGeneration()!==K.generation){b.trace("quota","discarded stale main quota headers",{boundIdentity:K?.quotaKey,currentGeneration:y.getMainQuotaIdentityGeneration()});return}}let _=G.accountId==="main"?y.getMain(K?.quotaKey):y.getAllFallbacks().get(G.accountId),L=W.checkedAt??Date.now(),D=s(G.localSubject,G.scopedAttempt),O=D&&G.anthropicAccountUuid?{lineage:D,accountUuid:G.anthropicAccountUuid,entry:{quota:{...W,accountIdentity:G.anthropicAccountUuid},checkedAt:L,refreshAfter:L},generalExhausted:["five_hour","seven_day"].some((Q)=>{let U=Z.get(Q==="five_hour"?"anthropic-ratelimit-unified-5h-utilization":"anthropic-ratelimit-unified-7d-utilization");return W[Q]!==void 0&&U!==null&&Number.isFinite(Number(U))&&Number(U)>=1})}:void 0;if(O){if(B0.delete(G.accountId),B0.size>=NW){let Q=B0.keys().next().value;if(Q!==void 0)B0.delete(Q)}B0.set(G.accountId,O)}(async()=>{let Q=!1;try{let U;try{U=await jY(G,{quota:W,checkedAt:L,refreshAfter:L},_)}catch(p){KY(p);return}if(U===null)return;if(G.accountId==="main"&&y.getMainQuotaIdentityGeneration()!==K?.generation)return;let P=U;if(O&&B0.get(G.accountId)===O)O.entry=P,Q=!0;if(G.accountId==="main")y.setMain(K?.quotaKey,P);else y.setFallback(G.accountId,P,{authLineageId:G.authLineageId});s1().catch(()=>{}),await OY(G,P),b.debug("quota","harvested response quota",{account:G.accountId,fiveHourPercent:P.quota.five_hour?.usedPercent,sevenDayPercent:P.quota.seven_day?.usedPercent,source:"headers"})}finally{if(!Q&&O&&B0.get(G.accountId)===O)B0.delete(G.accountId),b.debug("quota","discarded pending response quota",{accountId:G.accountId})}})().catch(NY),b.trace("quota","response quota awaiting publication",{account:G.accountId})}catch(W){_Y(W)}}let X3=Promise.resolve();function x1(Z=!1,G=!1,W,K){let _=X3.then(()=>DY(Z,G,W,K));return X3=_.then(()=>{},()=>{}),_}async function DY(Z,G,W,K){let _=await w.read(),L=new Set;if(!Z&&!G&&_.policyStorage.quota?.enabled===!1)return L;for(let D of _.accounts){if(D.id==="main"||D.type!=="oauth")continue;if(!x0(D)){if(G)L.add(D.id);continue}if(!Z&&g1(D.quota,_.policyStorage,p1(D.quota))>Date.now()&&(!W||d1(D.quota,_.policyStorage,Date.now(),W)))continue;try{if(!await y.refreshFallback(D.id,"",_.policyStorage.accounts.find((Q)=>Q.id===D.id&&R0(Q)),Z?void 0:K))L.add(D.id),b.debug("quota","fallback quota preflight returned no reading",{accountId:D.id,requiredByPolicy:G})}catch(O){if(G&&y1(O))throw O;L.add(D.id),N7(D.id,G,O)}}return s1().catch(()=>{}),L}let QJ={refreshQuotaForDueAccounts:async()=>{await x1()},refreshQuotaForAllAccounts:async(Z)=>{await x1(!0)},refreshAccount:async(Z,G,W)=>{let K=await m0(Z.id,void 0,W?.force?Z.access:void 0);return{...Z,access:K.accessToken,expires:K.expires}},refreshAccountQuota:async(Z,G)=>{H$();let W=await w.fetchQuota(Z.id);return{account:{...Z,quota:W},fetched:!0}},getUsableFallbackAccounts:async(Z,G)=>{Z=Z??null;let W=[],K=Z?.accounts.some((_)=>R0(_)&&B0.has(_.id))?(await w.read()).accounts:[];for(let _ of Z?.accounts??[]){if(!R0(_)||!x0(_))continue;let L=K.find((Q)=>Q.id===_.id),D=y.getFallback(_.id,L?.binding?{authLineageId:JSON.stringify(L.binding)}:_)?.quota??L?.quota??_.quota,O=L&&Z?i0({...L,quota:D},Z):D;if(!j4(O,Z)||!a9(O,G?.modelId)||L1(Z)&&!N1(O,Z,_.id,G?.modelId))continue;if(G$(Z)){if(M4(_.id,Z))W.push(_);continue}try{let Q=await m0(_.id,void 0,void 0,G?.modelId);W.push({..._,access:Q.accessToken,expires:Q.expires})}catch(Q){if(y1(Q))throw Q}}return W}};async function BJ(){H$();let Z=await w.read();if(Z.mode==="local"&&Z.policyStorage.refresh?.enabled!==!1)for(let G of Z.accounts){if(G.id==="main"||G.type!=="oauth"||!x0(G))continue;try{let W=await m0(G.id);if(l1(G.lastRefreshError,G.accountIdentity,Date.now(),void 0))continue;if(W.localSource!=="rotated"&&W.localSource!=="adopted"&&(!W.expires||W.expires-Date.now()<=D3(Z.policyStorage)))await m0(G.id,void 0,void 0,void 0,"refresh")}catch{}}await x1(!1,!1,void 0,"background")}let FJ=j$!==null&&process.env.OPENCODE_AUTH_CONTENT===void 0,G3=new Set;async function HY(){let Z=await w.read(),G=new Set(Z.accounts.filter((K)=>K.id!=="main"&&K.source==="vault"&&K.type==="oauth"&&x0(K)).map((K)=>K.id)),W=[...G].some((K)=>!G3.has(K));if(G3=G,W)await x1(!1,!1,void 0,"background");await s1()}let TJ=FJ&&G$(j$)?w.vault.watch({intervalMs:J.scopedRosterPollIntervalMs??2000,shouldRefresh:()=>process.env.OPENCODE_AUTH_CONTENT===void 0,onRefresh:HY,setInterval:Y.setInterval,clearInterval:Y.clearInterval}):void 0,UY=FJ?(TJ?TJ.ready.then(()=>BJ()):BJ()).catch(()=>{}):Promise.resolve(),wJ=FJ?Y.setInterval(()=>{BJ().catch(()=>{})},c6+i8(l8)):null;wJ?.unref?.();let QY=(Z,G)=>{let W=iJ({id:Z,role:"fallback"},G);return W==="na"?"off":W},SJ=new mJ,BY=new pJ,n$=new WeakMap,Q4=new Map;async function EJ(Z){let G=(Z.get("anthropic-beta")??"").split(",").map((W)=>W.trim()).filter(Boolean).sort();return{betas:G,betasHash:await M6(G.join(","))}}function W3(Z){try{if(!Z.request)return;let G=h3({request:Z.request,source:Z.source,accountId:Z.accountId,synthetic:Z.synthetic,betasHash:Z.betasHash,requestedModel:Z.requestedModel,onWarning:(K)=>b.warn("cache-diagnostics",K),message:Z.message,receivedAt:Z.receivedAt});if(!G.record||!G.messageId){b.debug("cache-diagnostics","skipped invalid response envelope",{status:Z.status});return}b.debug("cache-diagnostics",b3(G.record));let W=BY.capture(Z.betasHash,Z.betas);if(W)b.debug("cache-diagnostics",W);if(G.canary)b.warn("cache-diagnostics","short-gap previous_message_not_found",{message_id:G.canary.messageId,previous_message_id:G.canary.previousMessageId});if(Z.trackSessionId)SJ.capture(Z.trackSessionId,G.messageId,Z.receivedAt)}catch(G){b.debug("cache-diagnostics","response observation failed",{status:Z.status,error:G instanceof Error?G.message:String(G)})}}function z3(Z,G,W=!0){let K=n$.get(Z);if(!K)return;if(G&&typeof G==="object"&&!Array.isArray(G)&&!W)K.messageStart=G;K.dumpWrite=K.dumpWrite.then(()=>qZ(K.dump,{status:K.status,message:G,complete:W})).catch(()=>{}),W3({...K,message:G,receivedAt:Date.now()})}function FY(Z,G){let W=n$.get(Z);if(!W)return;let K=W.messageStart??{},_=K.usage&&typeof K.usage==="object"&&!Array.isArray(K.usage)?K.usage:{},L={...K,...G.usage?{usage:{..._,...G.usage}}:{},...G.stopReason?{stop_reason:G.stopReason}:{}};W.dumpWrite=W.dumpWrite.then(()=>qZ(W.dump,{status:W.status,message:L,complete:!0})).catch(()=>{})}function V3(Z,G){let W=Promise.resolve(qZ(G.dump,{status:G.status,message:null,complete:!1})).catch(()=>{});n$.set(Z,{...G,dumpWrite:W})}let W1=null,J9=null;function Z9(Z){return Z!==null&&typeof Z==="object"&&dJ(Z)==="R"}function TY(Z){let G=AZ("anthropic");if(!Z||typeof Z!=="object")return!1;let W=Z;return W.type===G.type&&W.access===G.access&&W.refresh===G.refresh&&W.expires===G.expires}async function wY(){if(J9){let Z=await J9();return $G("opencode",Z===void 0?{}:{anthropic:Z}).kind}if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("OpenCode logins cannot be checked while OPENCODE_AUTH_CONTENT is set");return kG("opencode",a8())}async function j3(){if(await c1("opencode")!=="claustrum")throw Error("This host is not connected to the credential vault; run setup to connect it first");if(await wY()!=="absent")throw Error("OpenCode already holds an Anthropic login; remove it before choosing the vault login")}let SY={label:"Claude via credential vault",type:"oauth",authorize:async()=>{return await j3(),{url:"",instructions:"Claude requests use the credential vault this host is connected to. OpenCode stores only a placeholder, never a credential.",method:"auto",callback:async()=>{await j3();let Z=AZ("anthropic");return{type:"success",access:Z.access,refresh:Z.refresh,expires:Z.expires}}}}},CJ=new H6({...i6("opencode")}),Y9=[],o1=new Map,a0=new D6({loadStorage:()=>r(j),fetchImpl:v4,setIntervalImpl:Y.setInterval,clearIntervalImpl:Y.clearInterval,onTrackedSessionsChanged:async(Z)=>{await CJ.publish(Z),Y9=await CJ.list(Z)},prepareBody:(Z,G)=>{if(!new Headers(G.headers).get("anthropic-beta")?.split(",").map((W)=>W.trim()).includes(q4))return Z;try{let W=JSON.parse(Z),K=SJ.previousFor(G.id),_=K?.messageId??null;return O9(W,_),Q4.set(G.id,{sessionId:G.id,previousMessageId:_,...K?{previousMessageReceivedAt:K.receivedAt}:{},isSubagent:G.isSubagent,ttlSent:N9(W),accountId:G.oauthAccountId??"main",synthetic:!0,requestedModel:typeof W.model==="string"?W.model:void 0}),JSON.stringify(W)}catch{return Z}},onResponse:async({target:Z,bodyText:G,status:W,data:K,receivedAt:_,attempt:L})=>{let D=o1.get(L.id);if(!Z.sourceWarm&&W>=200&&W<300&&!L.signal?.aborted)u1.recordPrewarm(Z.id,Z.oauthAccountId??"main",_);if(W===401&&D?.scopedAttempt)await VJ(D.scopedAttempt,"direct");if(Z.sourceWarm&&W>=200&&W<300)k0.noteSourceWarmSentForTarget(Z.id);let O=Q4.get(Z.id);if(!O?.betasHash||!O.betas){Q4.delete(Z.id);return}try{let Q=JSON.parse(G),U=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q.diagnostics:void 0,P=U&&typeof U==="object"&&!Array.isArray(U)&&U.previous_message_id===O.previousMessageId?O.previousMessageId:void 0;if(P===void 0)return;W3({source:"prewarm_cachekeep",accountId:O.accountId,synthetic:O.synthetic,betasHash:O.betasHash,betas:O.betas,requestedModel:O.requestedModel,request:{...O,previousMessageId:P,ttlSent:N9(Q)},trackSessionId:Z.id,status:W,message:K,receivedAt:_})}catch{}finally{Q4.delete(Z.id)}},onComplete:({attempt:Z})=>{o1.delete(Z.id)},retryOnUnauthorized:async({target:Z,headers:G,attempt:W})=>{let K=o1.get(W.id);if(!K)return;let _;try{let O=JSON.parse(Z.bodyText);if(typeof O.model==="string")_=O.model}catch{}if(K.scopedAttempt&&!await o4(K.scopedAttempt,"cachekeep",W.signal))return;let L=await m0(Z.oauthAccountId??"main",W.signal,K.scopedAttempt?void 0:K.accessToken,_,"cachekeep");if(L.accountIdentity!==K.accountIdentity||Boolean(L.scopedAttempt)!==Boolean(K.scopedAttempt))return;if(K.scopedAttempt&&(!L.scopedAttempt||L.scopedAttempt.credentialId!==K.scopedAttempt.credentialId||L.scopedAttempt.recordVersion<=K.scopedAttempt.recordVersion))return;if(!K.scopedAttempt&&L.accessToken===K.accessToken)return;let D=new Headers(G);return D.set("authorization",`Bearer ${L.accessToken}`),o1.set(W.id,L),D},prepareHeaders:async(Z,G,W)=>{if(!VZ(G.url))return;let K=G.oauthAccountId??"main",_;try{let Q=JSON.parse(G.bodyText);if(typeof Q.model==="string")_=Q.model}catch{}let L=await m0(K,W.signal,void 0,_,"cachekeep");if(G.oauthAccountIdentity&&L.accountIdentity!==G.oauthAccountIdentity)throw new m1("credential-changed");let D=L.accessToken;o1.set(W.id,L);try{let Q=JSON.parse(G.bodyText),U=Y1(L.accountIdentity);if(Z.delete("anthropic-beta"),G4(Z,D,{body:Q,identity:U}),Z.set("anthropic-beta",A8(Z.get("anthropic-beta"),[N6])),Q.speed==="fast")f9(Z);let P=Q4.get(G.id);if(P){let{betas:p,betasHash:i}=await EJ(Z);P.betas=p,P.betasHash=i}}catch{G4(Z,D)}let O=await m0(K,W.signal,void 0,_,"cachekeep");if(O.accountIdentity!==L.accountIdentity||Boolean(O.scopedAttempt)!==Boolean(L.scopedAttempt))throw new m1("credential-changed");if(Z.set("authorization",`Bearer ${O.accessToken}`),o1.set(W.id,O),G.sourceWarm){let Q=k0.sourceWarmForTarget(G.id);if(!Q||Q.oauthAccountId!==G.oauthAccountId||Q.accountIdentity!==void 0&&O.accountIdentity!==Q.accountIdentity){k0.dropSourceWarmForTarget(G.id),a0.untrack(G.id,"policy-refused"),b.warn("cachekeep","source warm refused: bound account changed",{session:G.id,reason:"source-warm-account-changed"});return}}return Z},validatePrewarm:({target:Z,warmBodyText:G})=>{if(!Z.sourceWarm)return{ok:!0};let W=k0.sourceWarmForTarget(Z.id);if(!W)return a0.untrack(Z.id),{ok:!1,reason:"source-round-ended"};if(W.warmsSinceUserTurn>=q6(W.model))return k0.dropSourceWarmForTarget(Z.id),{ok:!1,reason:"source-warm-idle-cap"};let K=j8(G),_=j8(W.bodyText);if(!K||!_||K!==_)return k0.dropSourceWarmForTarget(Z.id),{ok:!1,reason:"source-prefix-mismatch"};return{ok:!0}}});async function EY(Z){let G=X$(Z.requestedModel);if(!G)return;let W=J4(Z.sessionId,G),K=k0.sourceWarmFor(Z.recoveryKey);if(!K){a0.untrack(W);return}let _;try{_=await r()}catch{return}if(!a0.track({sessionId:W,url:K.url,headers:new Headers(K.headers),bodyText:K.bodyText,storage:_,cacheMode:"hybrid",oauthAccountId:K.oauthAccountId,...K.accountIdentity!==void 0&&{oauthAccountIdentity:K.accountIdentity},isSubagent:K.subagent??!1,sourceWarm:!0}).tracked)k0.dropSourceWarm(Z.recoveryKey)}async function CY(Z){if(!W1||!(await W1()).active)throw Error("Native main OAuth activation is not available");let G=await m0("main",Z);return{...G,credentialAccountId:k$(G.accountIdentity)}}async function AY(){let Z=await CY();if((await U4(Z.accessToken,void 0,Z.credentialAccountId)).stale&&Z.credentialAccountId!==void 0)throw Error("Main account identity changed before the prime refresh");let W=await y.refreshMainWithMetadata(P$,Z.accessToken);return{quota:W.quota,fresh:W.fetched}}async function PY(Z){H$();let G=await r(j),W=G?.accounts.find((_)=>_.id===Z&&x0(_)&&R0(_));if(!W||!G)throw Error(`prime: OAuth account ${Z} is unavailable`);let K=await QJ.refreshAccountQuota(W,G);return{quota:K.account.quota??{},fresh:K.fetched}}let AJ=new Map;async function qY(Z){let G=performance.now(),W,K,_,L="",D;try{if(Z==="main"&&(!W1||!(await W1()).active))throw Error("Native main OAuth activation is not available");let O=p4(aG,{baseURL:""}),Q=O.url?.toString()??O.input.toString();w9(Q);let U=await m0(Z,void 0,void 0,V8);if(W=U.accessToken,_=U.scopedAttempt,K=V8,!W)return{ok:!1,error:"prime: no access token available"};let P=O6(),p=Y1(U.accountIdentity),i=await k9(JSON.stringify(P),{identity:p}),t=new Headers({"content-type":"application/json"});G4(t,W,{body:JSON.parse(i),identity:p,requestClass:"auxiliary"}),t.delete("content-length"),t.delete("transfer-encoding");let L0=AbortSignal.timeout(30000),p0={method:"POST",headers:t,body:i,signal:L0},P0=await m0(Z,L0,void 0,K);if(P0.accountIdentity!==U.accountIdentity||Boolean(P0.scopedAttempt)!==Boolean(U.scopedAttempt))throw Error("Prime credential authority changed before dispatch");_=P0.scopedAttempt,L=P0.accessToken,t.set("authorization",`Bearer ${L}`);let c0=async()=>{let S0=c9([L],"http");return D=S0,S0.redactResponse(await v4(Q,p0))},U0=await c0();if(U0.status===401&&_&&!L0.aborted){let S0;try{S0=await o4(_,"prime",L0)}catch{}if(S0){D?.dispose(),await U0.body?.cancel().catch(()=>{}),b.info("claustrum","retrying Prime after scoped credential rotation",{accountId:Z,previousVersion:_.recordVersion,newVersion:S0.recordVersion}),P0=await m0(Z,L0,void 0,K);let l0=P0.scopedAttempt;if(!l0||l0.credentialId!==_.credentialId||l0.accountIdentity!==_.accountIdentity||l0.recordVersion<=_.recordVersion)throw Error("Prime vault retry lost its strict newer receipt");_=l0,L=l0.accessToken,t.set("authorization",`Bearer ${L}`),U0=await c0()}}if(U0.status===401&&!P0.scopedAttempt&&!L0.aborted){let S0=P0.accessToken,l0=await m0(Z,L0,S0,K).catch(()=>{return});if(l0&&l0.accessToken!==S0&&l0.accountIdentity===U.accountIdentity&&!l0.scopedAttempt){if(D?.dispose(),await U0.body?.cancel().catch(()=>{}),P0=await m0(Z,L0,void 0,K),P0.scopedAttempt||P0.accountIdentity!==U.accountIdentity)throw Error("Prime local authority changed before retry");L=P0.accessToken,t.set("authorization",`Bearer ${L}`),U0=await c0()}}let F$=Math.round(performance.now()-G);if(!U0.ok){let S0;try{S0=await U0.text().catch(()=>"")||`HTTP ${U0.status}`}finally{D?.dispose()}if(U0.status===401&&_)await VJ(_,"direct");return{ok:!1,status:U0.status,ms:F$,error:S0}}let q$=(await U0.json().catch(()=>null))?.usage,M$=q$&&(Number.isFinite(q$.input_tokens)||Number.isFinite(q$.output_tokens))?{inputTokens:Number.isFinite(q$.input_tokens)?q$.input_tokens:void 0,outputTokens:Number.isFinite(q$.output_tokens)?q$.output_tokens:void 0}:void 0;return AJ.set(Z,P0),{ok:!0,status:U0.status,ms:F$,...M$&&{usage:M$}}}catch(O){D?.dispose();let Q=c9([L],"http"),U=Q.redactError(O);return Q.dispose(),{ok:!1,...O instanceof b$&&O.tokenRefreshFailed&&{reason:"token-refresh"},ms:Math.round(performance.now()-G),error:U instanceof Error?U.message:String(U)}}}let K3={storagePath:j,loadStorage:()=>r(j),getAccountFingerprint:async(Z)=>{if(Z==="main"&&(!W1||!(await W1()).active))return;let G=await m0(Z),W=G.scopedAttempt??G.localSubject;if(!W)return;let K=await w.getOrCreateAuthLineage(Z,W);return K?D1(K):void 0},refreshQuota:async(Z)=>{if(Z==="main")return AY();return PY(Z)},sendPrime:qY,recordSuccess:async(Z,G)=>{let W=AJ.get(Z);AJ.delete(Z);let K=W?.scopedAttempt??W?.localSubject;if(!K||!await w.incrementPrimeUsage(Z,K,G))throw Error("Prime usage publication lost its native credential fence");let _=(await w.read()).accounts.find((L)=>L.id===Z)?.prime;if(!_)throw Error("Prime usage counters are unavailable after publication");return _},setIntervalImpl:Y.setInterval,clearIntervalImpl:Y.clearInterval,setTimeoutImpl:Y.setTimeout,clearTimeoutImpl:Y.clearTimeout},_3=O7(j,()=>new UG(K3),{slot:$.directory??"default",rebind:(Z)=>Z.updateOptions(K3)}),I1=_3.manager;if(n9(j$))I1.start();async function X9(){return Y9=await CJ.list(a0.trackedSessions()),Y9}let L3=J.cacheKeepAggregateRefreshIntervalMs??1e4,PJ=L3>0?Y.setInterval(()=>{X9().catch(()=>{})},L3):void 0;if(PJ?.unref?.(),t9({enabled:i9(j$),mode:l4(j$)}),mZ(vZ(j$)),pZ(bZ(j$)),!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)lG(fZ(j$)??"info");let qJ=null,MY=async()=>{n0?.close(),F1.abort();while(B1.size)await Promise.all([...B1]);try{await zJ(j)}catch(Z){b.warn("claustrum","failed to close scoped runtime",{error:Z instanceof Error?Z.message:String(Z)})}try{y.close()}catch{}try{await DJ?.dispose()}catch(Z){b.warn("quota-header-feed","failed to dispose",{error:Z instanceof Error?Z.message:String(Z)})}try{if(f1)Y.clearInterval(f1),f1=null}catch(Z){b.warn("main-background","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{if(wJ)Y.clearInterval(wJ)}catch(Z){b.warn("fallback-background","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{if(PJ!==void 0)Y.clearInterval(PJ)}catch(Z){b.warn("cachekeep","failed to stop aggregate refresh",{error:Z instanceof Error?Z.message:String(Z)})}try{a0.stop()}catch(Z){b.warn("cachekeep","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{_3.release()}catch(Z){b.warn("prime","failed to release slot",{error:Z instanceof Error?Z.message:String(Z)})}if(!qJ)return;try{await qJ.release()}catch(Z){b.warn("rpc","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}},W$={activeId:"main",route:"main"},RY=t8(),y$=new Map;function G9(Z,G){if(y.updateStorage(Z),y.seedMainFromStorage(Z,P$),!G.skipFallbackQuotaSeed)y.seedFallbacksFromAccounts((Z?.accounts??[]).filter(R0));let W=y.getMain(P$),K=y.getLastApiError(),_=Z?.refresh?.mainLastRefreshError,L=Z?.claustrum?.primaryAccount,D=G$(Z)&&!x0(L)?xZ({source:"vault",enabled:L?.enabled,state:L?.state}):void 0;return{main:{quota:W?.quota??null,enabled:L?.enabled,tierLabel:c4(Z?.main?.profile),quotaBackedOff:y.isBackedOff(),quotaBackoffUntil:K?.nextRetryAt,refreshBackedOff:_?l1(_,B4??Z?.mainAccountId,Date.now(),G.mainRefreshToken?D1(G.mainRefreshToken):void 0):!1,refreshBackoffUntil:_?.nextRetryAt,stateLine:D,quotaDated:Boolean(D)},fallbacks:(Z?.accounts??[]).filter((O)=>R0(O)&&(O.enabled!==!1||Boolean(O.claustrumScopedCredentialId))).map((O)=>{let Q=M4(O.id,Z),U=QY(O.id,Z),P=O.claustrumScopedCredentialId&&!Q?xZ({source:"vault",enabled:O.enabled!==!1,state:O.claustrumScopedState}):void 0;return{id:O.id,label:O.label,tierLabel:c4(O.profile),quota:G.skipFallbackQuotaSeed?null:y.getFallback(O.id,O)?.quota??O.quota??null,needsReauth:O.lastRefreshError!=null&&l1(O.lastRefreshError,O.id,Date.now(),D1(O.refresh))&&O1(O.lastRefreshError),vaultReauth:U==="on-vault-reauth",vaultServed:Q,custodyState:U,enabled:O.enabled!==!1,stateLine:P,quotaDated:Boolean(P)}}),activeId:G.activeId,route:G.route,relay:b6(Z?.relay),fastMode:hZ(),cacheKeep:{enabled:S8(Z),window:w8(Z)?"always":Z?.cacheKeep?.startHour!=null&&Z?.cacheKeep?.endHour!=null?`${Z.cacheKeep.startHour}-${Z.cacheKeep.endHour}`:void 0,trackedSessions:Y9.length},prime:n9(Z)?{enabled:!0,accounts:I1.stats(Z)}:void 0,fableRecoveries:y$.size>0?[...y$.values()]:void 0,lastUpdated:Date.now()}}function m$(Z,G,W){let K=G.routingAuthoritative!==!1;if(K)W$={activeId:G.activeId,route:G.route};function _(L){return $Y(L,RY,{routingAuthoritative:K,resolvePreservedRouting:K?void 0:async(D)=>{let O=await YW(D,()=>r(j),{activeId:L.activeId,route:L.route}),Q=await $3(O.freshStorage,W);return{activeId:O.activeId,route:O.route,state:G9(Q,{...G,activeId:O.activeId,route:O.route})}},onRoutingResolved:K?void 0:(D)=>{W$=D}}).catch((D)=>b.warn("sidebar","state write failed",{error:D instanceof Error?D.message:String(D)}))}if(K){let L=eZ(Z);if(L.length>0)return $3(Z,W,L).then((D)=>_(G9(D,G))).catch(()=>{return b.debug("quota","failed to recheck account profile for sidebar"),_(G9(Z,G))})}return _(G9(Z,G))}async function O3(){return{storage:await r(j),access:void 0}}async function s1(){await X9().catch(()=>{});let{storage:Z,access:G}=await O3();m$(Z,{activeId:W$.activeId,route:W$.route,mainAccessToken:G,mainRefreshToken:void 0,routingAuthoritative:!1})}function xY(Z,G,W){if(!G)return;if(Z?.quota?.enabled!==!0)return;let K=W?.quotaKey??P$;if(y.getMain(K))return;if(RJ)return;RJ=!0,y.refreshMain(K,G,W?.generation).then(()=>s1()).catch(()=>{}).finally(()=>{RJ=!1})}let T1=null,W9,B4,P$,F4,a1,MJ,N3=0,z9=new Map,RJ=!1,f1=null,V9=0;function D3(Z){let G=Z?.refresh?.refreshBeforeExpiryMinutes??eG;return Math.max(ZY,G)*60000}function IY(Z){return Z?.refresh?.enabled!==!1}async function H3(Z=!1){let G=new Map;if(Z){if(W1&&(await W1()).active)try{await w.fetchQuota("main")}catch{G.set("main","Native primary usage refresh unavailable")}await x1(!0)}let W=await $9(AbortSignal.timeout(3000));y.updateStorage(W.policyStorage),y.seedMainFromStorage(W.policyStorage,P$),y.seedFallbacksFromAccounts(W.policyStorage.accounts.filter(R0));let K=[],_=W.accounts.find((D)=>D.id==="main"&&D.type==="oauth");if(_)K.push({name:_.label??"OpenCode anthropic",role:"main",quota:_.quota,tierLabel:c4(_.profile),error:G.get("main")??_.lastQuotaRefreshError?.message});K.push(...L6(W.policyStorage,G));let L=Math.max(0,...W.accounts.map((D)=>p1(D.quota)));return _6({accounts:K,refreshedAt:L||void 0})}async function xJ(Z){await X9().catch(()=>{}),await m$(Z,{activeId:W$.activeId,route:W$.route,routingAuthoritative:!1})}function T4(Z,G,W,K){if(y$.delete(Z.sessionId),y$.set(Z.sessionId,{...Z,changedAt:Date.now()}),y$.size>128){let _=y$.keys().next().value;if(_)y$.delete(_)}if(m$(G,{activeId:W$.activeId,route:W$.route,mainAccessToken:W.access,mainRefreshToken:W.refresh,routingAuthoritative:!1}),K)B3(Z.sessionId,K)}function U3(Z,G){let W=X1.get(Z)??new Set;W.delete(G),W.add(G);while(W.size>4){let K=W.values().next().value;if(typeof K!=="string")break;W.delete(K)}X1.delete(Z),X1.set(Z,W);while(X1.size>128){let K=X1.keys().next().value;if(typeof K!=="string")break;X1.delete(K)}}function Q3(Z,G){return typeof G==="string"&&X1.get(Z)?.has(G)===!0}function B3(Z,G){if(A9(Z))return;A$.delete(Z),A$.set(Z,[G]);while(A$.size>128){let W=A$.keys().next().value;if(W)A$.delete(W);else break}if(K$.has(Z))IJ(Z)}function IJ(Z,G=0){if(!A$.has(Z)||N4.has(Z))return;N4.set(Z,G);let W=()=>{if(N4.get(Z)!==G)return;N4.delete(Z),fY(Z,G)};if(G===0)setImmediate(W);else setTimeout(W,WW*G)}function fJ(Z,G){if(G+1<GW)IJ(Z,G+1)}async function fY(Z,G){if(!K$.has(Z)||!A$.has(Z))return;let W=$.client.session;if(typeof W?.status==="function")try{let K=await Promise.resolve(W.status()),_=K!==null&&typeof K==="object"?K:void 0,L=_&&Object.hasOwn(_,"data")?_.data:_;if(L===null||typeof L!=="object"||Array.isArray(L)){fJ(Z,G);return}let D=L[Z];if(D!==void 0&&(!D||typeof D!=="object"||D.type!=="idle")){fJ(Z,G);return}}catch{fJ(Z,G);return}if(!K$.has(Z))return;await kY(Z)}function kY(Z){let G=s4.get(Z);if(G)return G;let W=(async()=>{while(!0){let K=A$.get(Z),_=K?.[0];if(!_){A$.delete(Z);return}try{let L=()=>A$.get(Z)===K&&K[0]===_;if(!await n8($,Z,_,{noReply:!0,beforeActiveAssistant:!0,canSend:()=>K$.has(Z)&&L(),onPreparedMessageId:(O)=>U3(Z,O),latestPreparedMessageId:()=>[...X1.get(Z)??[]].at(-1)})){if(K$.has(Z)&&!L())continue;return}if(L())K.shift()}catch(L){b.warn("fable-fallback","Desktop notification failed",{session:Z,error:L instanceof Error?L.message:String(L)})}}})();return s4.set(Z,W),W.finally(()=>{if(s4.get(Z)===W)s4.delete(Z)}),W}function vY(Z,G,W,K){if(G.fallback&&G.targetModel){let _=i$.get(Z.recoveryKey);i$.delete(Z.recoveryKey),i$.set(Z.recoveryKey,G.targetModel);while(i$.size>128){let D=i$.keys().next().value;if(D)i$.delete(D);else break}let L=y$.get(Z.sessionId);if(_===G.targetModel&&L?.mode==="server"&&X$(L.requestedModelId)===X$(Z.requestedModel)&&L.targetModelId===G.targetModel)return;b.info("fable-fallback","Anthropic server-side safety fallback active",{session:Z.sessionId,requestedModel:Z.requestedModel,targetModel:G.targetModel,handoff:G.handoff}),T4({sessionId:Z.sessionId,mode:"server",remaining:0,requestedModelId:Z.requestedModel,targetModelId:G.targetModel},W,K,UW(Z.requestedModel,G.targetModel));return}if(G.stopReason==="refusal"||!i$.delete(Z.recoveryKey))return;b.info("fable-fallback","Anthropic server-side safety fallback ended",{session:Z.sessionId,requestedModel:Z.requestedModel}),T4({sessionId:Z.sessionId,mode:"fable",remaining:0,requestedModelId:Z.requestedModel},W,K,QW(Z.requestedModel))}function hY(Z,G,W){if(!Z)return;for(let K of i$.keys())if(K.startsWith(`${Z}\x00`))i$.delete(K);if(!y$.delete(Z))return;m$(G,{activeId:W$.activeId,route:W$.route,mainAccessToken:W.access,mainRefreshToken:W.refresh,routingAuthoritative:!1})}async function kJ(Z){let G=BG(Z);if(G.type==="enable"||G.type==="disable"){let L=G.type==="enable",D=await H1(L),O=l4(D);return t9({enabled:L,mode:O}),b.info("commands","cache enabled changed",{enabled:L}),RZ({argumentsText:Z,enabled:L,mode:O,settingsPath:await w.getSettingsPath()})}if(G.type==="mode"){let L=await n1(G.mode),D=i9(L);return t9({enabled:D,mode:G.mode}),b.info("commands","cache mode changed",{mode:G.mode}),RZ({argumentsText:Z,enabled:D,mode:G.mode,settingsPath:await w.getSettingsPath()})}let W=await r(j),K=i9(W),_=l4(W);return t9({enabled:K,mode:_}),RZ({argumentsText:Z,enabled:K,mode:_})}async function w4(Z){let G=FG(Z),W=await r(j);if(G.type==="window")W=await YJ(G.startHour,G.endHour),b.info("commands","cachekeep schedule changed",{schedule:`${G.startHour}-${G.endHour}`});else if(G.type==="always")W=await C1(),b.info("commands","cachekeep schedule changed",{schedule:"always"});else if(G.type==="disable")W=await r4(!1),b.info("commands","cachekeep enabled changed",{enabled:!1});else if(G.type==="subagents")W=await XJ(G.enabled),b.info("commands","cachekeep subagents changed",{subagents:G.enabled});let K=F8(W),_=await X9(),L=_.length?Math.min(..._.map((D)=>D.nextPrewarmAt)):void 0;return m6({argumentsText:Z,enabled:E8(W),always:w8(W),window:K,hybridActive:S8(W),trackedSessions:_.length,trackedSessionDetails:_,nextPrewarmAt:L})}async function F3(Z){let G=TG(Z);if(G.type==="enable"||G.type==="disable"){let _=G.type==="enable";return await Z1(_),mZ(_),b.info("commands","dump changed",{enabled:_}),L8({argumentsText:Z,enabled:_,settingsPath:await w.getSettingsPath()})}let W=await r(j),K=vZ(W);return mZ(K),L8({argumentsText:Z,enabled:K})}async function T3(Z){let G=wG(Z);if(G.type==="enable"||G.type==="disable"){let _=G.type==="enable";return await GJ(_),pZ(_),b.info("commands","fast mode changed",{enabled:_}),O8({argumentsText:Z,enabled:_,settingsPath:await w.getSettingsPath()})}let W=await r(j),K=bZ(W);return pZ(K),O8({argumentsText:Z,enabled:K})}async function w3(Z,G){if(SG(Z).type==="fire"){if(!G)return`## Claude Start Failed
26
26
 
27
27
  - OpenCode did not provide a session ID.`;try{return await G7($.client,G),D8({argumentsText:Z}).text}catch(K){return`## Claude Start Failed
28
28
 
@@ -41,5 +41,5 @@ ${U.url}`,knobs:{oauthUrl:U.url},accounts:e$(await r(j)??_1())}}if(K.type==="add
41
41
 
42
42
  `),D=_>=90?"error":_>=70?"warning":"info";z.tui?.showToast?.({body:{title:"Claude Quota",message:L,variant:D,duration:D==="error"?8000:5000}})?.catch?.(()=>{})}if($.directory){let Z=s8($.directory);try{qJ=await R7(Z,()=>M7({dir:Z,drain:P7,apply:gY,applyMenu:(G)=>A3(G.sessionId??"").apply(G)}))}catch{b.warn("rpc","native menu server unavailable")}}let q3={"experimental.chat.messages.transform":async(Z,G)=>{let W=G.messages;R1.observeMessages(W);let K=s3(W);if(K){M1.record(K);return}let _=W.findLast((O)=>O.info?.role==="user"),L=_?.info?.sessionID,D=_?.info?.id;if(typeof L==="string"&&typeof D==="string")M1.clear(L,D)},"chat.message":async({sessionID:Z},G)=>{_J.observeSyntheticMessage({sessionId:Z,messageId:G.message.id,parts:G.parts})},"chat.headers":async({sessionID:Z,agent:G,message:W},K)=>{if(D7(G))K.headers[jZ]="auxiliary";_J.markHeaders({sessionId:Z,messageId:W.id,headers:K.headers}),M1.markHeaders({sessionId:Z,messageId:W.id,headers:K.headers}),R1.markHeaders({sessionId:Z,messageId:W.id,headers:K.headers})},event:async({event:Z})=>{let G=Z,W=G.properties?.info,K=G.properties?.sessionID??W?.sessionID??W?.id;if(!K)return;if(G.type==="message.updated"&&W?.role==="user"&&!Q3(K,W.id))if(typeof W.id==="string"){if(LJ.set(K,W.id),K$.has(K)&&a4.get(K)!==W.id)K$.delete(K)}else K$.delete(K);if(G.type==="session.status"&&G.properties?.status?.type!=="idle")K$.delete(K);if(G.type==="session.idle"){r1.clear(K);let _=LJ.get(K);if(_)a4.set(K,_);else a4.delete(K);K$.add(K);while(K$.size>128){let L=K$.values().next().value;if(L)K$.delete(L);else break}IJ(K)}if(G.type==="session.deleted"||G.type==="message.removed")R1.clearSession(K);if(G.type==="session.deleted"){r1.clear(K),u1.forget(K),N.forget(K),k0.clearSession(K),KJ(K),hJ.delete(K),M.delete(K),_J.clearSession(K),y$.delete(K),A$.delete(K),K$.delete(K),LJ.delete(K),a4.delete(K),X1.delete(K);for(let _ of g$.keys())if(_.startsWith(`${K}\x00`))g$.delete(_);N4.delete(K)}},config:async(Z)=>{let G={...Z.command??{}};for(let W of o8)delete G[W];Z.command={...G,claude:{template:"claude",description:"Manage Claude accounts, quotas, routing, and cache settings."}}},"experimental.chat.system.transform":async(Z,G)=>{if(!_W(Z))return;LW(G.system)},provider:{id:"anthropic",async models(Z,G){let W=wW(FW(Z.models));if(G.auth?.type!=="oauth"||!GG(j$??{}))return W;return SW(W)}},"command.execute.before":async(Z)=>{if(Z.command!=="claude")return;let G=await A3(Z.sessionID).open(Z.sessionID),W=A9(Z.sessionID),K=!1;if(W)KZ(G,Z.sessionID);else if(!PW()&&!A7(Z.sessionID))W=await C7(G,Z.sessionID,{timeoutMs:J.tuiPickupTimeoutMs??EW,setTimeout:Y.setTimeout,clearTimeout:Y.clearTimeout}),K=!W;if(!W){let _=[...K?[AW(),""]:[],G.menu.title,...G.menu.sections.flatMap((L)=>[`
43
43
  ## ${L.title}`,...L.lines,...L.items.map((D)=>`${D.label}${D.detail?` — ${D.detail}`:""}`)])].join(`
44
- `);await n8($,Z.sessionID,_)}KW()},auth:{provider:"anthropic",async loader(Z,G){W1=async()=>{let Q=await Z();return{type:Q.type,active:kZ(Q,"anthropic")}},J9=Z;let W=await Z();if(W.type!=="oauth")return{};let K=await c1("opencode").catch(()=>{return});if(!tZ&&kZ(W,"anthropic")&&process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION!=="1"){tZ=!0;let Q=$9(F1.signal).then((U)=>{if(!F1.signal.aborted)return m$(U.policyStorage,{...W$,routingAuthoritative:!1})}).catch(()=>{if(!F1.signal.aborted)b.debug("quota","startup account profile hydration failed")});B1.add(Q),Q.then(()=>B1.delete(Q))}function _(Q,U=!1){if(!kZ(Q,"anthropic")&&!(U&&Z9(Q)))throw Error("Native OAuth requires inert OpenCode activation; run offline setup")}async function L(Q){_(await Z(),Q&&await c1("opencode")==="local")}let D=async(Q,U,P=!1)=>{let p=await Z();if(p.type!=="oauth")return{type:p.type,access:"",expires:0,refresh:void 0,nativeAccountIdentity:void 0,nativeRoutingLineage:void 0,nativeLocalSource:void 0,nativeScopedAttempt:void 0,modelDenied:!1,credentialUnavailable:!1,credentialFailure:void 0,deferred:!1};let i=await c1("opencode");if(i==="claustrum"&&!TY(p))throw Error("This host uses the credential vault, but OpenCode holds a separate Anthropic login. Remove it and choose the vault login, or disconnect from the vault.");H$();let t=await fG(w,U),L0=i==="claustrum"?"committed":R8(await f8(j0)),p0=k8(t);if(_(p,i==="local"&&(L0==="committed"||L0==="retired")&&p0),i==="claustrum"&&!t.accounts.some((v0)=>v0.type==="oauth"&&x0(v0)))throw new q8;let P0=g3(t.policyStorage);try{y3({mode:i==="claustrum"?"C":"L",main:dJ(p),fallbacks:i==="claustrum"?"T":P0.fallbacks,evidence:"V",authority:L0,localOAuthServable:p0}),W9=void 0}catch(v0){if(v0 instanceof R4)W9=v0.verdict;throw v0}D0=t.policyStorage;let c0=t.accounts.find((v0)=>v0.id==="main"),U0=c0?.binding,F$=c0?i0(c0,t.policyStorage):void 0,w1=F$&&F$!==c0?.quota?{...t.policyStorage,quota:{...t.policyStorage.quota,mainQuota:F$}}:t.policyStorage,q$=w0("main",H0(U0),c0?.accountIdentity,t.policyStorage),M$=Boolean(U0&&q$?.lineage===H0(U0)&&q$?.generalExhausted===!0);if(c0&&U0&&(!v$||U0.rowId!==v$.rowId||U0.credentialEpoch>v$.credentialEpoch))y.clearMain(),y.setMainQuotaAccountIdentity(c0.accountIdentity),v$={rowId:U0.rowId,credentialEpoch:U0.credentialEpoch};if(P&&($1(t.policyStorage)==="fallback-first"||oZ(w1,c0?.accountIdentity,M$))){let v0=t.accounts.find((U$)=>U$.id==="main");return U?.throwIfAborted(),{type:"oauth",access:"",expires:0,refresh:void 0,nativeAccountIdentity:v0?.accountIdentity,nativeRoutingLineage:v0?.binding?H0(v0.binding):void 0,nativeLocalSource:void 0,nativeScopedAttempt:void 0,modelDenied:!1,credentialUnavailable:!1,credentialFailure:void 0,deferred:!0}}let S0,l0,T$,r$;try{S0=await m0("main",U,void 0,Q,"serve",t)}catch(v0){if(v0 instanceof b0)throw v0;if(y1(v0))throw v0;if(v0 instanceof U1){l0=v0.account;let U$=t6(l0.quota,Q);if(U$!==void 0&&(!Number.isFinite(U$.checkedAt)||(U$.checkedAt??0)+v0.checkIntervalMs<=Date.now())||!yZ(l0.quota)&&!s9(l0.quota,Q))try{await w.fetchQuota("main",void 0,U),S0=await m0("main",U,void 0,Q),l0=void 0}catch(o$){if(y1(o$))throw o$;if(o$ instanceof U1)l0=o$.account;else if(o$ instanceof b$)T$=o$.account,r$=o$}}else if(v0 instanceof b$)T$=v0.account,r$=v0}return U?.throwIfAborted(),{type:"oauth",access:S0?.accessToken??"",expires:S0?.expires??0,refresh:void 0,nativeRoutingLineage:s(S0?.localSubject,S0?.scopedAttempt)??(c0?.binding?H0(c0.binding):void 0),nativeAccountIdentity:S0?.accountIdentity??l0?.accountIdentity??T$?.accountIdentity,modelDenied:Boolean(l0),credentialUnavailable:Boolean(T$),credentialFailure:r$,deferred:!1,nativeLocalSource:S0?.localSource,nativeScopedAttempt:S0?.scopedAttempt}};T1=D;let O={type:"oauth",access:"",expires:0};if(O.type==="oauth"){let p=function(){if(f1)Y.clearInterval(f1);let H=async()=>{try{let B=await r(j);if(!IY(B))return;let f=await D();if(f.type!=="oauth")return;if(f.nativeLocalSource==="rotated"||f.nativeLocalSource==="adopted")return;if(f.expires&&f.expires-Date.now()>D3(B))return;await P()}catch{b.warn("refresh","native main OAuth background refresh unavailable")}};f1=Y.setInterval(()=>{H()},tG+i8(l8)),f1.unref?.()},t=function(H,B){if(H instanceof Request&&H.body)return!1;return B==null||typeof B==="string"},L0=function(H){if(typeof H!=="string")return;try{let B=JSON.parse(H);return typeof B.model==="string"?B.model:void 0}catch{return}},p0=function(H){return H.has("x-parent-session-id")},P0=function(H){let B;try{B=JSON.parse(H)}catch{return!1}if(typeof B!=="object"||B===null)return!1;let f=Reflect.get(B,"error");return Reflect.get(B,"type")==="error"&&typeof f==="object"&&f!==null&&Reflect.get(f,"type")==="rate_limit_error"},c0=function(H){return H?.quota?.enabled===!0},F$=function(H,B){if(H.delete("authorization"),H.delete("x-api-key"),B.authHeader==="x-api-key")H.set("x-api-key",B.apiKey??"");else H.set("Authorization",`Bearer ${B.apiKey??""}`);H.set("Content-Type","application/json"),W8(H)},S0=function(H){return y.getFallback(H.id,H)?.quota??H.quota},l0=function(H,B){return H.status===429||B},T$=function(H,B=D0){return D$("main",H?.routingLineage,H?.providerAccountUuid,y.getMain(H?.quotaKey??P$),B)},r$=function(H,B){if(!H&&!B?.providerAccountUuid)return!1;let f=T$(B);return Boolean(f&&(H||f.quota.accountIdentity===B?.providerAccountUuid)&&f.refreshAfter>Date.now()&&H4(f.quota)&&(f.quota.source!=="headers"||w0("main",B?.routingLineage,B?.providerAccountUuid)?.generalExhausted===!0||["five_hour","seven_day"].some((h)=>f.quota.fieldSources?.[h]==="poll"&&(f.quota[h]?.remainingPercent??1)<=0)))},U=(await w.read().catch(()=>{return}))?.accounts.find((H)=>H.id==="main");if(B4=U?.binding?.rowId??U?.accountIdentity,P$??=U?.accountIdentity??B4,O.access)await U4(O.access);async function P(H,B,f){let h=Z9(await Z());await L(h),f?.throwIfAborted();let I=await m0("main",f,H,B,"refresh");return await L(h),f?.throwIfAborted(),I.accessToken}if(K==="local")p();y.seedFallbacksFromAccounts((j$?.accounts??[]).filter(R0));let i=await XW(()=>r(j)).catch(()=>({freshStorage:null,activeId:void 0,route:"main"}));await m$(i.freshStorage,{activeId:i.activeId,route:i.route,mainAccessToken:O.access,routingAuthoritative:!1});async function U0(H,B){if(!H.body||H.status!==200)return B?.mark("inspect_stream_skip",{status:H.status}),{response:H,rateLimited:!1};if(H.headers.get("x-cortexkit-relay-optimistic")==="true")return B?.mark("inspect_stream_skip",{status:H.status,reason:"optimistic_relay"}),{response:H,rateLimited:!1};let f=X0(),h=H.body.getReader(),I=[],V0=0,g=f6({maxFrameBytes:65536}),e=!1,A=!1,q0=!0;while(!A&&V0<65536){let{done:E,value:m}=await h.read().catch(async(Z0)=>{let T=NZ(Z0,n$.get(H)?.toolNameMap);if(T!==Z0)await DZ(h,T);throw T});if(E)break;I.push(m),V0+=m.byteLength;let O0;try{O0=g.push(m)}catch{break}for(let Z0 of O0){let T=PG(h6(Z0,{streamStart:q0}));if(q0=!1,T.data===void 0)continue;e=P0(T.data),A=!0;break}}if(e){NJ.get(H)?.(),NJ.delete(H),await h.cancel().catch(()=>{});try{h.releaseLock()}catch{}let E=new ReadableStream({start(O0){for(let Z0 of I)O0.enqueue(Z0);O0.close()}});B?.mark("inspect_stream_first_event",{ms:I0(X0()-f),bytes:V0,rateLimited:!0});let m=new Response(E,{status:H.status,statusText:H.statusText,headers:H.headers});return _9(n$,H,m),{response:m,rateLimited:!0}}let d=new ReadableStream({start(E){for(let m of I)E.enqueue(m)},async pull(E){let{done:m,value:O0}=await h.read();if(m){E.close();return}E.enqueue(O0)},cancel(E){return h.cancel(E)}});B?.mark("inspect_stream_first_event",{ms:I0(X0()-f),bytes:V0,rateLimited:!1});let k=new Response(d,{status:H.status,statusText:H.statusText,headers:H.headers});return _9(n$,H,k),{response:k,rateLimited:!1}}async function w1(H,B,f,h){if(H$(),!B){let g=T$(f);if(!f?.providerAccountUuid||!g||g.refreshAfter<=Date.now()||!H4(g.quota))throw Error("API fallback requires fresh general primary OAuth exhaustion");let e=await m0("main",h);if(e.accountIdentity!==f.providerAccountUuid||f.routingLineage&&s(e.localSubject,e.scopedAttempt)!==f.routingLineage)throw Error("Primary identity changed before API fallback");B=e.accessToken}let I=await w.authorizeApi(H,h),V0=(await w.read()).accounts.find((g)=>g.id==="main");if(V0?.binding&&H0(V0.binding)!==f?.routingLineage)throw Error("Primary identity changed before API fallback");if(!r$(B,f))throw Error("API fallback requires fresh general primary OAuth exhaustion");return I}async function q$(H,B,f,h,I="api_fallback",V0,g,e,A){if(g)g.oauthAccountId=void 0,g.opusCacheAnchor=void 0;let q0=X0(),d=m4(H,B),k=d.get("x-session-affinity")||d.get("x-opencode-session"),E=p0(d),m=d.get($4)??void 0,O0=M1.resolveHeader(m),Z0=O0?M1.versionsFor(O0.sessionId,O0.messageId):void 0;d.delete("x-parent-session-id"),d.delete("x-session-affinity"),d.delete("x-opencode-session"),d.delete("x-opencode-session-id"),d.delete("x-opencode-parent-session-id"),d.delete($4),d.delete(e1),d.delete(jZ);let T=await d4(H,B),S=!1,G0=null,M0,u=typeof T==="string"?T.length:void 0;if(T&&typeof T==="string"){let J0=X0(),x$=(()=>{if(!hZ())return!1;try{return C8(JSON.parse(T).model)}catch{return!1}})();try{T=await k9(T,{onToolNameMap:(J$)=>{M0=J$},cache1hEnabled:!E&&V4(),cache1hMode:W4(),fastModeEnabled:x$,sessionId:k||void 0,midConversationEffortEnabled:!1,midConversationEffortPlan:m,midConversationEffortResolvedPlan:O0,midConversationEffortPlanVersions:Z0,modelRemapEnabled:!0,perf:(J$,_$)=>h?.mark(`rewrite_body_${J$}`,{route:I,..._$})})}catch(J$){if(J$ instanceof C0)return p8(J$);if(J$ instanceof v8)return c8(J$);throw J$}if(F$(d,f),d.set("anthropic-beta",A8(d.get("anthropic-beta"),[])),x$)f9(d);try{S=JSON.parse(T).stream===!0}catch{}h?.mark("rewrite_body",{route:I,ms:I0(X0()-J0),originalBytes:u,rewrittenBytes:T.length,cacheEnabled:!E&&V4(),cacheMode:W4(),fastModeEnabled:x$,subagent:E})}else F$(d,f);let R$=await EJ(d),k1=await w1(f.id,e,A,B?.signal??void 0);f={...f,...k1},F$(d,f);let z$=p4(H,{baseURL:f.baseURL}),o0=X0(),w$=c9([f.apiKey??""],S?"event-stream":"http"),Q$;try{Q$=w$.redactResponse(await fetch(z$.input,{...B,body:T,headers:d,...HZ()&&{tls:{rejectUnauthorized:!1}}}))}catch(J0){let x$=w$.redactError(J0);if(w$.dispose(),typeof T==="string")await l9({affinity:k,route:I,error:h8,bodyText:T,url:z$.url?.toString()??K4(z$.input),method:i1(H,B),headers:d});throw x$}if(typeof T==="string")G0=await l9({affinity:k,route:I,status:Q$.status,bodyText:T,url:z$.url?.toString()??K4(z$.input),method:i1(H,B),headers:d});if(V3(Q$,{source:"turn",toolNameMap:M0,accountId:f.id,synthetic:!1,...R$,requestedModel:L0(T),dump:G0,status:Q$.status,streaming:S}),h?.mark("send_headers_received",{route:I,ms:I0(X0()-o0),status:Q$.status,relayConfigured:!1,totalSendWithAccessMs:I0(X0()-q0),baseURL:f.baseURL}),Q$.ok)A1.publish(()=>w.publishApi(k1.subject,{lastUsed:Date.now()}));return Q$}async function M$(H,B,f,h,I="unknown",V0,g="main",e,A,q0=!1,d,k){K6(f,"anthropic");let E=p4(H);if(!VZ(E.url?.toString()??K4(E.input)))return b.warn("oauth-destination","refused a Claude OAuth request to a non-Anthropic origin; nothing was sent",{route:I}),ZJ(V6);let m=Z9(await Z()),O0=X0(),Z0=V0,T=async()=>{return Z0??=await r(j),Z0},S=m4(H,B),G0=S.get("x-session-affinity")||S.get("x-opencode-session"),M0=p0(S),u=S.get($4)??void 0,R$=M1.resolveHeader(u),k1=R$?M1.versionsFor(R$.sessionId,R$.messageId):void 0,z$=S.get(e1)??void 0,o0=R1.resolveHeader(z$),w$=!M0&&!q0?o0:void 0;S.delete("x-parent-session-id"),S.delete("x-session-affinity"),S.delete("x-opencode-session"),S.delete("x-opencode-session-id"),S.delete("x-opencode-parent-session-id"),S.delete($4),S.delete(e1);let Q$=H7(S),J0=await d4(H,B),x$=G0?SJ.previousFor(G0):null,J$=x$?.messageId??null,_$,I$=!1,E4=null,s$=null,C4,E1;if(J0&&typeof J0==="string"){let x=X0();try{let Y0=JSON.parse(J0);if(typeof Y0.model==="string")E1=Y0.model}catch{}h?.mark("model_parse_for_identity",{route:I,ms:I0(X0()-x),bodyBytes:J0.length})}let F0=await m0(g,B?.signal??void 0,void 0,E1,g==="main"?"last-main":"serve");if(f=F0.accessToken,g==="main"&&d?.providerAccountUuid&&F0.accountIdentity!==d.providerAccountUuid)throw Error("Main account identity changed after request routing");k=F0.scopedAttempt;let R=X0(),o=Y1(F0.accountIdentity);h?.mark("resolve_claude_code_identity",{route:I,ms:I0(X0()-R),hasAccountUuid:Boolean(o.accountUuid)});let a=x8,W0=typeof J0==="string"?J0.length:void 0;if(J0&&typeof J0==="string"){let x=X0(),Y0=(()=>{if(!hZ())return!1;try{return C8(JSON.parse(J0).model)}catch{return!1}})(),u0=!M0&&V4();a=u0?HG:x8;let g0=W4(),S$=A?.plan.downgraded&&A.plan.standbyCacheAnchor?.oauthAccountId===g?A.plan.standbyCacheAnchor:void 0;try{J0=await k9(J0,{deferSigning:!0,onToolNameMap:(h0)=>{C4=h0},cache1hEnabled:u0,cache1hMode:g0,fastModeEnabled:Y0,identity:o,sessionId:G0||void 0,thinkingPrefixMismatchBehavior:e6(await T()),midConversationEffortEnabled:!0,turnEndNoteEnabled:!0,turnEndNote:(await T())?.turnEndNote,midConversationEffortPlan:u,midConversationEffortResolvedPlan:R$,midConversationEffortPlanVersions:k1,hybridStandbyAnchor:S$,serverSideFallbackEnabled:jJ==="server",laneStart:q0,billingLineage:w$,cacheDiagnosticsPreviousMessageId:J$,perf:(h0,c$)=>{if(h?.mark(`rewrite_body_${h0}`,{route:I,...c$}),h0==="cache_strategy"&&c$?.standbyBridgeApplied===!0&&A&&!A.standbyBridgeLogged)A.standbyBridgeLogged=!0,b.info("fable-fallback","restored standby Opus cache bridge",{session:A.plan.sessionId,distanceBlocks:c$?.standbyDistanceBlocks})}})}catch(h0){if(h0 instanceof C0)return p8(h0);if(h0 instanceof v8)return c8(h0);throw h0}if(A?.plan.downgraded&&u0&&g0==="hybrid"){let h0=$8(J0);A.opusCacheAnchor=h0?{...h0,oauthAccountId:g}:void 0}let A4=X0();try{let h0=JSON.parse(J0);G4(S,f,{body:h0,identity:o,requestClass:Q$});let c$=h0.diagnostics,M3=c$&&typeof c$==="object"&&!Array.isArray(c$)&&c$.previous_message_id===J$?J$:void 0;if(M3!==void 0&&S.get("anthropic-beta")?.split(",").map((uY)=>uY.trim()).includes(q4))_$={sessionId:G0??"session-unknown",previousMessageId:M3,...x$?{previousMessageReceivedAt:x$.receivedAt}:{},isSubagent:M0,ttlSent:N9(h0)};I$=h0.stream===!0,h?.mark("set_oauth_headers_body_parse",{route:I,ms:I0(X0()-A4),bodyBytes:J0.length,parsed:!0})}catch{G4(S,f,{identity:o,requestClass:Q$}),h?.mark("set_oauth_headers_body_parse",{route:I,ms:I0(X0()-A4),bodyBytes:J0.length,parsed:!1})}if(Y0)f9(S);h?.mark("rewrite_body",{route:I,ms:I0(X0()-x),originalBytes:W0,rewrittenBytes:J0.length,cacheEnabled:!M0&&V4(),cacheMode:W4(),fastModeEnabled:Y0,subagent:M0})}let $0=await EJ(S);if(A)A.oauthAccountId=g;if(A)A.subagent=M0;let n,s0=()=>{if(B?.signal?.aborted)return;if(G0)u1.record(G0,g,a);n?.()};if(typeof J0==="string"){let x=await T();if(V4()&&W4()==="hybrid"&&(!M0||JG(x))){let Y0=J0;n=()=>{let u0=X0(),g0=a0.track({sessionId:G0,url:E.url?.toString()??E.input.toString(),headers:S,bodyText:Y0,storage:x,cacheMode:"hybrid",oauthAccountId:g,oauthAccountIdentity:F0?.accountIdentity,isSubagent:M0});if(h?.mark("cachekeep_track",{session:G0,ms:I0(X0()-u0),tracked:g0.tracked,reason:g0.tracked?void 0:g0.reason,bodyBytes:Y0.length}),G0&&A&&!A.plan.downgraded&&g0.tracked){Q1.set(A.plan.recoveryKey,{...F0.accountIdentity!==void 0&&{accountIdentity:F0.accountIdentity},sentAt:Date.now()});while(Q1.size>128){let S$=Q1.keys().next().value;if(S$===void 0)break;Q1.delete(S$)}}}}if(G0&&!M0&&k0.hasSourceWarmForSession(G0)){if(w$&&w$.sessionId===G0)k0.noteSourceWarmUserTurn(G0,w$.promptId);if(!E8(x)||!V4()||W4()!=="hybrid")KJ(G0);else{let Y0=FZ(J0),u0=new Set(a0.trackedSessions().map((g0)=>g0.id));for(let{recoveryKey:g0,warm:S$}of k0.sourceWarmsForSession(G0)){let A4=X$(S$.model),h0=A4?J4(G0,A4):void 0;if(h0!==void 0&&!u0.has(h0)&&Date.now()-S$.sentAt>30000){k0.dropSourceWarm(g0);continue}if(S$.oauthAccountId!=="main"&&!x?.accounts.some((c$)=>c$.id===S$.oauthAccountId&&x0(c$))){if(k0.dropSourceWarm(g0),h0!==void 0)a0.untrack(h0);b.info("fable-fallback","source warm stopped: bound account unavailable",{session:G0,reason:"account-unavailable"});continue}if(S$.firstAnchorFingerprint!==void 0&&!Y0.includes(S$.firstAnchorFingerprint)){if(k0.dropSourceWarm(g0),h0!==void 0)a0.untrack(h0);b.warn("fable-fallback","source warm stopped: history no longer starts with the kept prefix",{session:G0,reason:"source-prefix-changed"})}}}}}let z1=F0,Z$,V1=async(x)=>{await L(m),B?.signal?.throwIfAborted();let Y0=await m0(g,B?.signal??void 0,x,E1,g==="main"?"last-main":"serve");if(await L(m),B?.signal?.throwIfAborted(),Y0.accountIdentity!==z1.accountIdentity||Boolean(Y0.scopedAttempt)!==Boolean(z1.scopedAttempt))throw Error("Native credential authority changed during the request");if(Z$&&(!Y0.scopedAttempt||Y0.scopedAttempt.credentialId!==Z$.credentialId||Y0.scopedAttempt.accountIdentity!==Z$.accountIdentity||Y0.scopedAttempt.recordVersion<=Z$.recordVersion))throw Error("Native vault retry has no strict newer same-account receipt");return Y0},L$=!1,O$=k,Y$=async()=>{L$=!0,F0=await V1(),O$=F0.scopedAttempt,S.set("authorization",`Bearer ${F0.accessToken}`),Q0={...Q0,accessToken:F0.accessToken,anthropicAccountUuid:k$(F0.accountIdentity),localSubject:F0.localSubject,scopedAttempt:F0.scopedAttempt};let x=c9([F0.accessToken],I$?"event-stream":"http");try{let Y0=(g0,S$)=>v4(E.input,{...B,body:g0,headers:S$,...HZ()&&{tls:{rejectUnauthorized:!1}}}),u0=x.redactResponse(typeof J0==="string"?await cG({url:E.url?.toString()??K4(E.input),body:J0,headers:S,latch:F,send:Y0}):await Y0(J0,S));if(u0.ok&&!B?.signal?.aborted)s0?.();if(typeof J0==="string")E4=await l9({affinity:G0,route:I,status:u0.status,bodyText:J0,url:E.url?.toString()??K4(E.input),method:i1(H,B),headers:S,tag:q0?"start":void 0});return u0}catch(Y0){let u0=x.redactError(Y0);if(x.dispose(),typeof J0==="string")await l9({affinity:G0,route:I,error:h8,bodyText:J0,url:E.url?.toString()??K4(E.input),method:i1(H,B),headers:S,tag:q0?"start":void 0});throw u0}},T0=await T(),E0;try{E0=await w.getRelayConfig()}catch(x){if(x instanceof jG&&x.code==="relay-inconsistent")return ZJ(x.message);throw x}let _0;if(typeof J0==="string"&&Q$==="main"&&!M0&&!q0&&(!E0||g6(E0.transport,E0.url)!=="websocket"))_0=await qG(N,{session:G0??void 0,account:F0.accountIdentity??g,credential:F0.scopedAttempt?.credentialId??F0.accessToken,bodyText:J0,replyToolNames:C4,headers:S,signal:B?.signal??void 0}),J0=_0.bodyText;else if(typeof J0==="string")J0=await dG(J0);let N$=g==="main"?void 0:T0?.accounts.find((x)=>x.id===g&&R0(x)),t1=l6(N$,e),Q0={accountId:g,accessToken:f,authLineageId:e,anthropicAccountUuid:k$(k?.accountIdentity)??(g==="main"?d?.providerAccountUuid:k$(o.accountUuid)??k$(t1)),localSubject:F0.localSubject,scopedAttempt:F0.scopedAttempt,...g==="main"&&d?{mainQuotaIdentity:d}:{}},K9=X0(),p$,N0=!1,r0,d0=VJ,t0=()=>pG({config:E0,input:E.input,requireUpstreamUrl:w9,init:B,headers:S,body:J0,fallback:Y$,affinity:G0,optimisticResponse:E0?.transport==="websocket",authorizeAttempt:async()=>{let x=await V1(),Y0=x.scopedAttempt;F0=x,Q0={...Q0,accessToken:x.accessToken,anthropicAccountUuid:k$(x.accountIdentity),localSubject:x.localSubject,scopedAttempt:Y0};let u0=new Headers(S);return u0.set("authorization",`Bearer ${x.accessToken}`),{headers:u0,errorSecrets:[x.accessToken],onUpstreamStatus:(g0)=>{if(g0>=200&&g0<300&&!B?.signal?.aborted)s0?.();if(g0!==401||!Y0)return;if(p$=Y0,N0)d0(Y0,"relay_status_field")}}},onResponseHeaders:(x)=>{r0=x,Y3(x,Q0),R1.commit(w$,gJ(x))},onDumpCreated:(x)=>{s$=x},dumpTag:q0?"start":void 0});return f0(async()=>{let x=await t0();if(!L$&&p$&&x.status===401&&typeof J0==="string"&&(i1(H,B)??"").toUpperCase()==="POST"&&!B?.signal?.aborted){let Y0;try{Y0=await o4(p$,"model-relay",B?.signal??void 0)}catch{}if(Y0)await x.body?.cancel().catch(()=>{}),b.info("claustrum","retrying after scoped credential rotation",{accountId:g,previousVersion:p$.recordVersion,newVersion:Y0.recordVersion,transport:"relay"}),Z$=p$,p$=void 0,x=await t0()}if(L$&&O$&&x.status===401&&typeof J0==="string"&&(i1(H,B)??"").toUpperCase()==="POST"&&!B?.signal?.aborted){let Y0;try{Y0=await o4(O$,"model",B?.signal??void 0)}catch{}if(Y0)await x.body?.cancel().catch(()=>{}),b.info("claustrum","retrying after scoped credential rotation",{accountId:g,previousVersion:O$.recordVersion,newVersion:Y0.recordVersion,transport:"direct"}),Z$=O$,x=await Y$()}if(x.status===401&&!F0.scopedAttempt&&typeof J0==="string"&&(i1(H,B)??"").toUpperCase()==="POST"&&!B?.signal?.aborted){let Y0=F0.accessToken,u0;try{u0=await V1(Y0)}catch(g0){dZ.set(x,g0)}if(u0&&u0.accessToken!==Y0)await x.body?.cancel().catch(()=>{}),x=L$?await Y$():await t0()}if(_0)x=await _0.recover(x,async(Y0)=>{return J0=Y0,t0()}),x=_0.observe(x);if(h?.mark("send_headers_received",{route:I,ms:I0(X0()-K9),status:x.status,relayConfigured:E0!=null,totalSendWithAccessMs:I0(X0()-O0)}),L$)Y3(x.headers,Q0),R1.commit(w$,gJ(x.headers));if(G0&&!q0){let Y0=L$?x.headers:r0??x.headers,u0=x.status<400&&(!h||!nZ.has(h));if(u0&&h)nZ.add(h);let g0={accountIdentity:F0.accountIdentity,credentialId:F0.scopedAttempt?.credentialId};if(D4.report(G0,g0,Y0,x.status,E1,u0),x.status===200)NJ.set(x,()=>D4.report(G0,g0,Y0,429,E1,!1))}if(V3(x,{source:q0?"start":"turn",toolNameMap:C4,failThread:_0?.fail,accountId:g,synthetic:q0,...$0,requestedModel:L0(J0),request:_$,trackSessionId:G0??void 0,dump:L$?E4:s$,status:x.status,streaming:I$}),L$&&O$&&x.status===401)await d0(O$,"direct");if(N0=!0,!L$&&p$)await d0(p$,"relay_status_field");if(x.status===401)await m8(x,B?.signal);if(x.ok)A1.publish(async()=>{if(Q0.scopedAttempt)await w.vault.publish(Q0.scopedAttempt,{lastUsed:Date.now()});else if(Q0.localSubject)await w.publishLocal(Q0.localSubject,{lastUsed:Date.now()})});return x})}async function v0(H,B){if(!H)return!1;try{return await y.refreshMain(B?.quotaKey??P$,H,B?.generation),r$(H,B)}catch{return!1}}async function U$(H,B={}){let f=L1(H),h=await x1(!1,f,B.modelId,"admission");if(H=await r(j),f){if(H&&h.size)H={...H,accounts:H.accounts.filter((e)=>!h.has(e.id)||N1(void 0,H,e.id,B.modelId))}}let I=await QJ.getUsableFallbackAccounts(H,{modelId:B.modelId}),V0=new Map(I.map((e)=>[e.id,e])),g=[];for(let e of H?.accounts??[]){if(H&&R0(e)){if(G$(H)){let q0=V0.get(e.id);if(q0)g.push(q0);continue}if(u4(H)!=="local")continue;let A=V0.get(e.id);if(A)g.push(A);else if(e.access&&(!e.expires||e.expires>Date.now())&&!O1(e.lastRefreshError)&&!l1(e.lastRefreshError,e.id,Date.now(),D1(e.refresh))&&H?.quota?.failClosedOnUnknownQuota!==!0&&!yZ(S0(e)))g.push(e);continue}if(B.includeApiRoutes===!0&&z4(e)&&x0(e)&&gZ(e.baseURL))g.push(e)}if(!L1(H))return g;return g.filter((e)=>R0(e)?N1(S0(e),H,e.id,B.modelId):!0)}async function bJ(H){let B=H.mainQuotaIdentity?.quotaKey,f=y.getMain(B),h=f?.quota;if(!d1(f?.quota,H.storage,Date.now(),H.requestedModelId))try{h=await y.refreshMain(B,H.mainAccessToken,H.mainQuotaIdentity?.generation,"admission")}catch{}let I=await QJ.getUsableFallbackAccounts(H.storage,{modelId:H.requestedModelId}),V0=await r(j)??H.storage,g=[],e=G$(V0);if(e){let k=V0?.claustrum?.primaryAccount;if(k!==void 0&&x0(k)&&!V0?.claustrum?.disabledAccountIdentities?.includes(k.accountId))g.push({id:V$,access:"",quota:h,identity:k?{kind:"known",accountId:k.accountId}:{kind:"unknown"},order:0,scoped:!0})}else if((H.mainAccessToken||H.mainPolicyDenied)&&!O1(V0?.refresh?.mainLastRefreshError))g.push({id:V$,access:H.mainAccessToken,quota:h,identity:B?{kind:"known",accountId:B}:{kind:"unknown"},order:0});if(e)for(let[k,E]of(V0?.accounts??[]).entries()){if(!x0(E)||!R0(E))continue;if(E.claustrumScopedCredentialId){let m=S0(E);if(!d1(m,V0,Date.now(),H.requestedModelId))try{m=await y.refreshFallback(E.id,"",E)}catch{}g.push({id:E.id,access:"",quota:m,identity:{kind:"known",accountId:E.id},order:k+1,account:E,scoped:!0})}}else{let k=new Map(I.map((E)=>[E.id,E]));for(let[E,m]of(V0?.accounts??[]).entries()){if(!x0(m)||!R0(m))continue;let O0=k.get(m.id)??m;if(O1(O0.lastRefreshError))continue;let Z0=S0(O0);if(!d1(Z0,V0,Date.now(),H.requestedModelId))try{Z0=await y.refreshFallback(O0.id,O0.access??"",O0)}catch{}g.push({id:O0.id,access:O0.access??"",quota:Z0,identity:{kind:"known",accountId:O0.id},order:E+1,account:O0})}}let A=new Set(I.map((k)=>k.id)),q0=new Set(g.flatMap((k)=>{let E=k.id===V$?V0?.refresh?.mainLastRefreshError:k.account?.lastRefreshError,m=!k.scoped,O0=k.identity.kind==="known"?k.identity.accountId:void 0;if(m&&O1(E))return[];if(m&&l1(E,O0,Date.now(),k.id===V$?H.mainRefreshToken?D1(H.mainRefreshToken):void 0:k.account?.refresh?D1(k.account.refresh):void 0)&&(k.id===V$||!A.has(k.id)))return[];if(d1(k.quota,V0,Date.now(),H.requestedModelId)&&PZ({quota:k.quota,modelId:H.requestedModelId,sessionId:H.sessionId,holdUntil:u1.holdUntil(H.sessionId,k.id,Date.now(),d9(V0))}).action==="migrate")return[];if(L1(V0)&&!N1(k.quota,V0,k.id===V$?void 0:k.id,H.requestedModelId))return[];return[k.id]})),d=g.flatMap((k)=>{let E=k.id===V$?V0?.refresh?.mainLastRefreshError:k.account?.lastRefreshError,m=!k.scoped,O0=k.identity.kind==="known"?k.identity.accountId:void 0;if(m&&O1(E)||m&&l1(E,O0,Date.now(),k.id===V$?H.mainRefreshToken?D1(H.mainRefreshToken):void 0:k.account?.refresh?D1(k.account.refresh):void 0)&&(k.id===V$||!A.has(k.id)))return[];let Z0=k.id===V$?void 0:k.id,T=yZ(k.quota)?k.quota:void 0,S=T?{kind:"known",quota:T}:{kind:"unknown"};return(!L1(V0)||N1(S.kind==="known"?S.quota:void 0,V0,Z0,H.requestedModelId))&&j4(S.kind==="known"?S.quota:void 0,V0)&&(S.kind==="unknown"||a9(S.quota,H.requestedModelId)&&(k.id===V$||A.has(k.id)||Boolean(k.scoped)))?[{accountId:k.id,quota:S,order:k.order}]:[]});return{storage:V0,allRoutes:g,candidates:d,retainAccountIds:q0}}let o$=new WeakMap;async function S1(H,B,f,h,I,V0,g){if(!f.length)return I??null;let e=g?.returnLastOnExhausted??!0,A=I??null,q0=!1,d=async()=>{if(q0)return;q0=!0,await I?.body?.cancel().catch(()=>{})};for(let[k,E]of f.entries()){let m;if(z4(E))await d(),m=await q$(H,B,E,V0,`api_fallback_${k}`,h,g?.fableRequest,g?.mainAccessToken,g?.mainQuotaIdentity);else if(G$(h)&&E.claustrumScopedCredentialId){let Z0;try{Z0=await m0(E.id,B?.signal??void 0,void 0,L0(await d4(H,B)))}catch(S){if(S instanceof U1)continue;throw S}let T=Z0.scopedAttempt;if(!T)throw Error("Native vault fallback credential is unavailable");await d(),m=await M$(H,B,T.accessToken,V0,`fallback_${k}`,h,E.id,E.authLineageId,g?.fableRequest,g?.laneStartRequest,void 0,T)}else if(u4(h)==="local"&&E.access)await d(),m=await M$(H,B,E.access,V0,`fallback_${k}`,h,E.id,E.authLineageId,g?.fableRequest,g?.laneStartRequest);else continue;A=m;let O0=cZ(m,h);if(!O0){let Z0=await U0(m,V0);m=Z0.response,A=m,O0=Z0.rateLimited}if(!O0){if(o$.set(m,z4(E)?"api":"oauth"),await g?.onSuccess?.(E),R0(E)&&c0(h)&&y.shouldRefreshOnRequestCount(V9)){if(G$(h)||E.access)y.refreshFallback(E.id,G$(h)?"":E.access??"",E).then(()=>g?.onSuccess?.(E)).catch(()=>{})}return m}if(k<f.length-1||!e)await m.body?.cancel().catch(()=>{})}return e?A:null}async function lY(H,B,f,h,I,V0,g,e,A,q0,d=!1,k){if(!t(H,B?.body))return f;let E=X0(),m=V0??await r(j);if(I?.mark("fallback_load_storage",{ms:I0(X0()-E),cached:!!V0}),!(m?.accounts??[]).some((u)=>x0(u)&&(R0(u)||z4(u)&&gZ(u.baseURL))))return f;let Z0=f,T=cZ(Z0,m),S=l0(Z0,!1);if(!T){let u=await U0(Z0,I);Z0=u.response,T=u.rateLimited,S=l0(Z0,u.rateLimited)}if(!T)return Z0;let G0=!1;if(h)G0=h.some(z4);else if(S)G0=await v0(g,k);let M0=h;if(!M0){let u=X0();M0=await U$(m,{includeApiRoutes:G0,modelId:A}),I?.mark("fallback_get_accounts",{ms:I0(X0()-u),accounts:M0.length})}if(L1(m)){let u=M0.length;if(M0=M0.filter((R$)=>R0(R$)?N1(S0(R$),m,R$.id,A):!0),M0.length<u)J1("[killswitch] filtered fallbacks",{before:u,after:M0.length})}return await S1(H,B,M0,m,Z0,I,{onSuccess:e,mainAccessToken:g,mainQuotaIdentity:k,fableRequest:q0,laneStartRequest:d})??Z0}return rG({apiKey:"",async fetch(H,B){if(H instanceof Request&&B?.signal===void 0)B={...B,signal:H.signal};let f=m4(H,B),h=f.get(T9)==="1";f.delete(T9),B={...B,headers:f};let I=f.get("x-session-affinity")||f.get("x-opencode-session"),V0=R1.promptIdForHeader(f.get(e1)),g=L0(B?.body),e=Boolean(I&&g&&!p0(f)&&k0.resetForModelChange(I,g));if(e&&I){for(let R of g$.keys())if(R.startsWith(`${I}\x00`))g$.delete(R);A$.delete(I),KJ(I)}let A=k0.plan(I,B?.body),q0=jJ==="server"&&B9(A?.effectiveModel??g)?A?.effectiveModel??g:void 0,d=A?{plan:A}:void 0;if(A?.downgraded)B={...B,body:A.bodyText};let k=B?.body,E=jW({bodyBytes:typeof k==="string"?k.length:void 0}),m=(R)=>{let o=n$.get(R);return G8(R,{toolNameMap:o?.toolNameMap,onResponseFailure:o?.failThread,perf:(a,W0)=>E.mark(a,W0),laneStart:h,laneStartOAuthServed:o$.get(R)!=="api",...o?o.streaming?{onMessageStart:(a)=>z3(R,a,!1),onMessageDelta:(a)=>FY(R,a),onStreamEnd:()=>o.dumpWrite}:{onMessageResponse:(a)=>z3(R,a),onStreamEnd:()=>o.dumpWrite,responseMode:"json"}:{},contentFilterModel:A?.requestedModel,...!A?.downgraded&&A?{onContentFilter:(a)=>{if(!d?.oauthAccountId)return b.debug("fable-fallback","content filter recovery unavailable for non-OAuth route",{session:A.sessionId}),!1;let W0=Q1.get(A.recoveryKey);Q1.delete(A.recoveryKey);let $0=a0.trackedRequest(A.sessionId),n;if($0)try{let O$=JSON.parse($0.bodyText);if(typeof O$.model==="string")n=O$.model}catch{}let s0=n?X$(n):null,z1=X$(A.requestedModel),Z$=$0?.oauthAccountId,V1=W0&&$0&&Z$!==void 0&&s0!==null&&s0===z1&&Z$===d.oauthAccountId?{bodyText:$0.bodyText,oauthAccountId:Z$,...W0.accountIdentity!==void 0&&{accountIdentity:W0.accountIdentity},sentAt:W0.sentAt,model:A.requestedModel,firstAnchorFingerprint:FZ($0.bodyText)[0],url:$0.url,headers:$0.headers,...d.subagent&&{subagent:!0}}:void 0,L$=k0.activate(A,d.oauthAccountId,V1);EY(A).catch(()=>{b.warn("fable-fallback","source warm sync failed",{session:A.sessionId})}),g$.delete(A.recoveryKey),g$.set(A.recoveryKey,DW(A.requestedModel,L$));while(g$.size>128){let O$=g$.keys().next().value;if(O$)g$.delete(O$);else break}i$.delete(A.recoveryKey),b.info("fable-fallback","content filter detected; switching session to Opus 4.8",{session:A.sessionId,requestedModel:A.requestedModel,completedToolUse:a?.completedToolUse===!0,remaining:L$}),T4({sessionId:A.sessionId,mode:"opus",remaining:L$,requestedModelId:A.requestedModel},S,T)}}:{},...A&&d?{onComplete:(a)=>{if(!A.downgraded){if(k0.completeSource(A,!d.serverFallback)){let s0=X$(A.requestedModel);if(s0)a0.untrack(J4(A.sessionId,s0))}return}let W0=k0.complete(A,d.opusCacheAnchor);if(!W0.counted)return;let $0=g$.get(A.recoveryKey);if($0)g$.delete(A.recoveryKey),K$.delete(A.sessionId),B3(A.sessionId,$0);if(b.info("fable-fallback","Opus 4.8 turn completed",{session:A.sessionId,requestedModel:A.requestedModel,finishReason:a,remaining:W0.remaining}),T4({sessionId:A.sessionId,mode:"opus",remaining:W0.remaining,requestedModelId:A.requestedModel},S,T),W0.remaining===0)T4({sessionId:A.sessionId,mode:"fable",remaining:0,requestedModelId:A.requestedModel},S,T,HW(A.requestedModel))}}:{},...q0?{serverSideFallbackModel:q0,...A?{onServerSideFallbackOutcome:(a)=>{if(d)d.serverFallback=a.fallback;vY(A,a,S,T)}}:{}}:{}})},O0=X0(),Z0=A?.effectiveModel??L0(await d4(H,B)),T=await D(Z0,B?.signal??void 0,!0);if(E.mark("get_auth",{ms:I0(X0()-O0),authType:T.type,hasAccess:Boolean(T.access)}),T.type!=="oauth"){let R=p4(H),o=m4(H,B);W8(o);let a=await d4(H,B);if(typeof a==="string")try{let $0=JSON.parse(a);if(vG($0))a=JSON.stringify($0)}catch{}B?.signal?.throwIfAborted();let W0=await fetch(R.input,{...B,body:a,headers:o});return E.done("non_oauth_passthrough",{status:W0.status}),W0}let S=await r(),G0=k$(T.nativeAccountIdentity),M0=T.nativeScopedAttempt,u;if(T.access){let R=await U4(T.access,L0(B?.body),G0,M0?.recordVersion);if(R.stale)throw Error("Main OAuth identity changed while resolving request credentials");if(u={...R,routingLineage:T.nativeRoutingLineage},G0)F4=T.access,a1=R.providerAccountUuid}else if((T.modelDenied||T.credentialUnavailable||T.deferred)&&G0)await sZ("",G0,G0),u={quotaKey:G0,providerAccountUuid:G0,generation:y.getMainQuotaIdentityGeneration(),routingLineage:T.nativeRoutingLineage,stale:!1,state:G$(S)?"on-cold":"na"};let R$=X0();E.mark("load_storage",{ms:I0(X0()-R$)}),y.updateStorage(S),y.seedMainFromStorage(S,P$),y.seedFallbacksFromAccounts((S?.accounts??[]).filter(R0));let k1=I?y$.get(I):void 0;if(e||!A||jJ==="server"&&k1?.requestedModelId&&X$(k1.requestedModelId)!==X$(A.requestedModel))hY(I,S,T);let z$=t(H,B?.body),o0=L0(B?.body)??Z0,w$=T$(u,S),Q$=w0("main",u?.routingLineage,G0,S),J0=T.deferred?oZ(w$&&S?{...S,accounts:S?.accounts??[],quota:{...S?.quota,mainQuota:w$.quota}}:S,G0,Q$?.lineage===u?.routingLineage&&Q$?.generalExhausted===!0):void 0;if(J0){let R=z$?await U$(S,{includeApiRoutes:r$(void 0,u),modelId:o0}):[],o=await S1(H,B,R,S,void 0,E,{onSuccess:(a)=>_$(a.id,"fallback"),mainQuotaIdentity:u,fableRequest:d,laneStartRequest:h});if(o)return m(o);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:J0.message}}),{status:429,headers:{"content-type":"application/json","retry-after":String(J0.retryAfter)}})}let x$=async(R,o)=>{let a=await w.read();return I6(R,IG({readings:a.accounts.filter((W0)=>W0.type==="oauth"&&x0(W0)).map((W0)=>({quota:W0.quota,accountIdentity:W0.accountIdentity,accountId:W0.id})),storage:a.policyStorage,modelId:o??Z0,sessionTtlMs:u1.ttlMs(I)}))},J$=async()=>{if(G$(S))return K8({snapshot:await w.read(),modelId:Z0,sticky:$1(S)==="sticky-balanced",sessionId:I});return x$("No enabled OAuth route can serve the requested model under current quota policy.",Z0)};if(z$)V9++;if(z$&&T.access&&(!T.expires||T.expires>Date.now()))xY(S,T.access,u);async function _$(R,o){let a=S,W0=!1;if((S?.accounts??[]).some(($0)=>R0($0)&&$0.quota))try{let $0=await r(j);if($0)a=$0;else W0=!0}catch{W0=!0}m$(a,{activeId:R,route:o,mainAccessToken:T.access,skipFallbackQuotaSeed:W0})}let I$;if(z$&&I&&$1(S)==="sticky-balanced"){let R=A?.effectiveModel??o0,o=nG(R),a=a0.trackedOAuthRoute(I),W0=A?.cacheAccountId??(a?a.oauthAccountId??V$:void 0),$0=!1;try{let n=await bJ({sessionId:I,storage:S,mainAccessToken:T.access,mainRefreshToken:T.refresh,mainPolicyDenied:T.modelDenied||T.credentialUnavailable,requestedModelId:R,mainQuotaIdentity:u}),s0=await w.read(),z1=await D4.accountFor(I,R??"",s0.accounts.filter((E0)=>x0(E0)&&M8(E0,s0,R).status==="allowed"&&n.candidates.some((_0)=>_0.accountId===E0.id))),Z$;if(z1){let E0=await w.read(),_0=E0.accounts.find((N$)=>F7(z1,N$));if(_0&&x0(_0)&&M8(_0,E0,R).status==="allowed"&&n.candidates.some((N$)=>N$.accountId===_0.id)&&T7(_0.id,n.candidates,n.storage,R??""))Z$=_0.id;else D4.override(I,"unknown account, credential, account policy or Fable reserve")}let V1=async(E0)=>{let _0=await rZ(),N$=!E0&&Z$;return _0.router.resolve({sessionId:I,family:o,modelId:R,affinityModelId:g,candidates:N$?n.candidates.filter((t1)=>t1.accountId===N$):n.candidates,retainAccountIds:N$?new Set([N$]):n.retainAccountIds,storage:n.storage,inputBytes:typeof B?.body==="string"?Buffer.byteLength(B.body):1,preferredAccountId:W0,excludeAccountIds:E0,...N$&&{preserveOnNoCandidate:!0},..._0.accountIdentities&&{accountIdentities:_0.accountIdentities}})},L$=O1(n.storage?.refresh?.mainLastRefreshError),O$=n.allRoutes.length===0&&!L$||n.allRoutes.some((E0)=>!E0.quota||!d1(E0.quota,n.storage,Date.now(),R)),Y$=await V1();if(Y$?.migrated)r1.clear(I);if(Z$&&!Y$)D4.override(I,"advised account is not selectable"),Z$=void 0,Y$=await V1();if(Z$&&Y$?.accountId===Z$&&z1?.hold)return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Shared routing requested a wait; retaining session affinity."}}),{status:429,headers:{"content-type":"application/json","retry-after":String(Math.ceil(z1.hold.retry_after_ms/1000))}});if(!Y$&&O$){if(T.modelDenied)return J$();throw Error("Sticky-balanced routing is waiting for current OAuth quota snapshots")}if(!Y$){if(T.modelDenied)return J$();if(G$(S))return K8({snapshot:await w.read(),modelId:R,sticky:!0,sessionId:I});let E0=k6({mainRefreshError:n.storage?.refresh?.mainLastRefreshError,fallbackReauthLabels:o6(n.storage),routeQuotas:n.allRoutes.flatMap((_0)=>_0.quota?[_0.quota]:[]),routeIdentities:n.allRoutes.filter((_0)=>_0.quota).map((_0)=>s0.accounts.find((N$)=>N$.id===_0.id)?.accountIdentity),routeAccountIds:n.allRoutes.filter((_0)=>_0.quota).map((_0)=>_0.id),storage:n.storage,sessionId:I,modelId:R});return E.done("return_sticky_no_route",{status:E0.status}),E0}let T0=n.allRoutes.find((E0)=>E0.id===Y$?.accountId);if(Y$&&T0){if($0=!0,A?.downgraded&&k0.bindRecoveryAccount(A,T0.id)){let N0=X$(A.requestedModel);if(N0)a0.untrack(J4(A.sessionId,N0));b.info("fable-fallback","rebound recovery to migrated sticky account",{accountId:T0.id})}let E0=async(N0)=>{if(N0.scoped){let d0=(await m0(N0.id,B?.signal??void 0,void 0,R)).scopedAttempt;if(!d0)throw Error("Native vault sticky credential is unavailable");return M$(H,B,d0.accessToken,E,`sticky:${N0.id}`,n.storage,N0.id,N0.account?.authLineageId,d,h,N0.id===V$?u:void 0,d0)}return M$(H,B,N0.access??"",E,`sticky:${N0.id}`,n.storage,N0.id,N0.account?.authLineageId,d,h,N0.id===V$?u:void 0)},_0=async(N0,r0,d0=!0)=>{return await _$(N0.id,"sticky-balanced"),E.done("return_sticky_balanced",{status:r0.status,accountId:N0.id,created:Y$?.created,migrated:Y$?.migrated}),m(r0)},N$=async(N0)=>{let r0=N0,d0=cZ(N0,n.storage),t0=!1;if(!d0){let x=await U0(N0,E);r0=x.response,t0=x.rateLimited,d0=x.rateLimited}return{response:r0,routeFailure:d0,streamingRateLimit:t0}},t1=d1(T0.quota,n.storage,Date.now(),R)?PZ({quota:T0.quota,modelId:R,sessionId:I,holdUntil:u1.holdUntil(I,T0.id,Date.now(),d9(n.storage))}):void 0;if(t1?.action==="hold")return _0(T0,await L9(new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account quota resets shortly; retaining session affinity."}}),{status:429,headers:{"content-type":"application/json"}}),I,t1.retryAfterSeconds,!1,n$),!1);let Q0=await N$(await E0(T0)),K9=!1;if(!Q0.routeFailure)return _0(T0,Q0.response);if(Q0.response.status===401){let N0=dZ.get(Q0.response);if(N0){let r0=await r(j),d0=T0.id,t0=T0.id===V$?r0?.refresh?.mainLastRefreshError:r0?.accounts.find((x)=>x.id===d0&&R0(x))?.lastRefreshError;if(!O1(t0))throw N0}K9=!0}let p$=Q0.response.status===403||K9;if(Q0.response.status===429||Q0.streamingRateLimit){let N0=xG(Q0.response.headers,R);if(Object.keys(N0).length===0)try{N0=T0.id===V$?await y.refreshMain(u?.quotaKey,T0.access??"",u?.generation):await y.refreshFallback(T0.id,T0.access??"",T0.account)}catch{N0=void 0}let r0=PZ({quota:N0,modelId:R,responseHeaders:Q0.response.headers,sessionId:I,unconfirmedRetry:{counter:r1,sessionId:I,turnId:V0??I,accountId:T0.id},holdUntil:u1.holdUntil(I,T0.id,Date.now(),d9(n.storage))});if(E.mark("sticky_quota_failure",{accountId:T0.id,action:r0.action,reason:r0.reason}),r0.action==="hold")return _0(T0,await L9(Q0.response,I,r0.retryAfterSeconds,Q0.streamingRateLimit,n$));if(r0.action==="retain")return _0(T0,await L9(Q0.response,I,60,Q0.streamingRateLimit,n$,!0));p$=r0.action==="migrate"}if(p$){await m8(Q0.response,B?.signal);let N0=T0.id;if(n=await bJ({sessionId:I,storage:n.storage,mainAccessToken:T.access,mainRefreshToken:T.refresh,mainPolicyDenied:T.modelDenied||T.credentialUnavailable,requestedModelId:R,mainQuotaIdentity:u}),n.candidates.filter((d0)=>d0.accountId!==N0).length>0){await Q0.response.body?.cancel().catch(()=>{}),Y$=await V1(new Set([N0]));let d0=n.allRoutes.find((t0)=>t0.id===Y$?.accountId);if(Y$&&d0){if(r1.clear(I),T0=d0,A?.downgraded&&k0.bindRecoveryAccount(A,T0.id)){let t0=X$(A.requestedModel);if(t0)a0.untrack(J4(A.sessionId,t0))}return _0(T0,await E0(T0))}}else if((Q0.response.status===429||Q0.streamingRateLimit)&&r$(T.access,u)){let d0=(await U$(n.storage,{includeApiRoutes:!0,modelId:R})).filter(z4);if(d0.length>0){let t0=await S1(H,B,d0,n.storage,Q0.response,E,{onSuccess:(x)=>_$(x.id,"sticky-balanced"),mainAccessToken:T.access,mainQuotaIdentity:u,fableRequest:d,laneStartRequest:h});if(t0)return r1.clear(I),E.done("return_sticky_api_fallback",{status:t0.status}),m(t0)}}}return _0(T0,Q0.response)}}catch(n){if(E.mark("sticky_balanced_error",{error:n instanceof Error?n.message:String(n)}),$0||y1(n))throw n;let s0=n instanceof Error?n:Error(String(n));throw Object.assign(s0,{code:"ECONNRESET",syscall:"sticky-routing"}),s0}}if(z$&&$1(S)==="fallback-first")try{let R=X0();I$=await U$(S,{includeApiRoutes:r$(T.access,u),modelId:o0}),E.mark("fallback_first_get_accounts",{ms:I0(X0()-R),accounts:I$.length});let o=await S1(H,B,I$,S,void 0,E,{returnLastOnExhausted:!1,mainAccessToken:T.access,mainQuotaIdentity:u,onSuccess:(a)=>_$(a.id,"fallback-first"),fableRequest:d,laneStartRequest:h});if(o)return E.done("return_fallback_first",{status:o.status}),m(o);I$=void 0}catch(R){if(E.mark("fallback_first_error",{error:R instanceof Error?R.message:String(R)}),y1(R))throw R}if(T.deferred){if(Object.assign(T,await D(Z0,B?.signal??void 0)),T.access){let R=await U4(T.access,Z0,T.nativeAccountIdentity,T.nativeScopedAttempt?.recordVersion);if(R.stale)throw Error("Main OAuth identity changed while resolving request credentials");u={...R,routingLineage:T.nativeRoutingLineage},F4=T.access,a1=R.providerAccountUuid}}if(!T.modelDenied&&(!T.access||!T.expires||T.expires<Date.now())){if(G$(S))try{let $0=(await m0("main",B?.signal??void 0,void 0,Z0)).scopedAttempt;if(!$0)throw Error("Native vault main credential is unavailable");F4=$0.accessToken;let n=await M$(H,B,$0.accessToken,E,"main",S,"main",void 0,d,h,u,$0);return m(n)}catch(W0){let $0=z$?await U$(S,{modelId:o0}):[],n=await S1(H,B,$0,S,void 0,E,{onSuccess:(s0)=>_$(s0.id,"fallback"),mainAccessToken:T.access,mainQuotaIdentity:u,fableRequest:d,laneStartRequest:h});if(n)return m(n);if(W0 instanceof b$)throw new q8;throw W0}if(T.credentialFailure?.tokenRefreshFailed)throw T.credentialFailure;let R=await r(),o=R?.refresh?.mainLastRefreshError;if(o&&l1(o,T.nativeAccountIdentity??B4??R?.mainAccountId,Date.now(),T.refresh?D1(T.refresh):void 0))throw J1("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:o.nextRetryAt,retryCount:o.retryCount,expiresInMs:T.expires?T.expires-Date.now():void 0}),Error(u6(o,Date.now()));J1("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(T.access),expiresInMs:T.expires?T.expires-Date.now():void 0,expiredAgoMs:T.expires&&T.expires<Date.now()?Date.now()-T.expires:void 0});let a=X0();T.access=await P(void 0,Z0,B?.signal??void 0),E.mark("refresh_main_access",{ms:I0(X0()-a)})}if(!T.access&&!T.modelDenied)throw E.done("missing_access_error"),Error("OAuth access token is missing after refresh");function E4(){if(S?.quota?.showToasts!==!0)return;let R=y.getMain(u?.quotaKey);if(!R)return;let o=(S?.accounts??[]).filter(($0)=>$0.enabled!==!1&&R0($0)).map(($0)=>({...$0,quota:y.getFallback($0.id,$0)?.quota??$0.quota})),a=j4(R.quota,S),W0;if(a)W0="main";else W0=o.find(($0)=>j4($0.quota,S))?.id??"main";cY(R.quota,o,W0)}if(z$&&c0(S))try{let R=X0(),o=T$(u,S),a=o?.quota;if(!a)a=await y.refreshMain(u?.quotaKey,T.access,u?.generation,"admission"),o=T$(u,S),E4();else if(y.needsRefresh(V9,o0))if(H4(a)||s9(a,o0))a=await y.refreshMain(u?.quotaKey,T.access,u?.generation),o=T$(u,S);else y.refreshMain(u?.quotaKey,T.access,u?.generation).then(()=>{s1().catch(()=>{}),E4()}).catch(()=>{});m$(S,{activeId:"main",route:"main",mainAccessToken:T.access});let W0=j4(a,S)&&a9(a,o0);if(E.mark("main_quota_for_routing",{ms:I0(X0()-R),passes:W0,model:o0,modelScopedExhausted:s9(a,o0)}),!W0){let $0=X0();I$=await U$(S,{includeApiRoutes:Boolean(o&&o.refreshAfter>Date.now()&&H4(o.quota)),modelId:o0}),E.mark("preselect_fallback_accounts",{ms:I0(X0()-$0),accounts:I$.length});let n=await S1(H,B,I$,S,void 0,E,{onSuccess:(s0)=>_$(s0.id,"fallback"),mainAccessToken:T.access,mainQuotaIdentity:u,fableRequest:d,laneStartRequest:h});if(n)return E.done("return_preselected_fallback",{status:n.status}),m(n)}}catch(R){if(E.mark("main_quota_for_routing_error",{error:R instanceof Error?R.message:String(R)}),y1(R))throw R}let s$=T$(u,S)?.quota;if(S?.quota?.failClosedOnUnknownQuota&&(s$===void 0||T.access.startsWith("sk-ant-oat")&&u?.providerAccountUuid===void 0)&&y.isBackedOff()){let R=y.getLastApiError(),o=R?B8(R,Date.now()):"Quota API unavailable";return J1("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:R?.nextRetryAt,retryCount:R?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:o}}),{status:429,headers:{"content-type":"application/json","retry-after":String(R?.nextRetryAt?Math.max(1,Math.ceil((R.nextRetryAt-Date.now())/1000)):60)}})}if(L1(S)){if(y.needsRefresh(V9,o0))try{await Promise.all([y.refreshMain(u?.quotaKey,T.access,u?.generation),x1(!1,!0,void 0,"admission")])}catch(o){J1("[quota] killswitch refresh failed",{error:o instanceof Error?o.message:String(o),backedOff:y.isBackedOff()})}s$=T$(u,S)?.quota}if(L1(S)&&!N1(s$,S,void 0,o0)){let o=t(H,B?.body)?await U$(S,{includeApiRoutes:r$(T.access),modelId:o0}):[];if(o.length>0){J1("[route] skipping main (killswitch), trying fallbacks");let $0=await S1(H,B,o,S,void 0,E,{onSuccess:(n)=>_$(n.id,"fallback"),mainAccessToken:T.access,mainQuotaIdentity:u,laneStartRequest:h});if($0)return E.done("return_killswitch_fallback",{status:$0.status}),m($0)}let a=Q7({mainQuota:s$,requestModelId:o0,storage:S}),W0=U7({...a.isScopedDriven&&{modelName:a.modelName}});return x$(W0,a.isScopedDriven?a.modelId:void 0)}if(T.modelDenied){let R=z$?await U$(S,{modelId:Z0}):[],o=await S1(H,B,R,S,void 0,E,{onSuccess:(W0)=>_$(W0.id,"fallback"),fableRequest:d,laneStartRequest:h,mainAccessToken:T.access,mainQuotaIdentity:u});if(o)return m(o);if(!($1(S)!=="sticky-balanced"&&s9(s$,Z0)&&j4(s$,S)&&N1(s$,S,void 0,Z0)))return m(await J$());return m(await M$(H,B,"",E,"main",S,"main",void 0,d,h,u))}let C4=await M$(H,B,T.access,E,"main",S,"main",void 0,d,h,u,M0),E1=!1,F0=await lY(H,B,C4,I$,E,S,T.access,(R)=>{return E1=!0,_$(R.id,"fallback")},o0,d,h,u);if(!E1)await _$("main","main");return E.done("return_response",{status:F0.status}),m(F0)}})}return{}},get methods(){return[...Y6(u9("opencode").tokenPath)?[SY]:[],{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{if(await c1("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.");if(await w.read(),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");let Z=await X("max");return{url:Z.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{let W=await MZ(G,Z.verifier,Z.redirectUri,Z.state);if(W.type==="failed")return W;H$(),await w.loginOAuth({routeId:"main",replace:!0,credential:{access:W.access,refresh:W.refresh,expires:W.expires}});let K=AZ("anthropic");return{type:"success",access:K.access,refresh:K.refresh,expires:K.expires}}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let Z=await z8("console");return{url:Z.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{let W=await MZ(G,Z.verifier,Z.redirectUri,Z.state);if(W.type==="failed")return W;return{type:"success",key:(await v4("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${W.access}`}}).then((_)=>_.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}},dispose:MY};return _7?.set(q3,{drainDispatchWork:q1,primeManager:I1,quotaManager:y,cacheKeepManager:a0,fableFallbackManager:k0,resolveMainQuotaIdentity:U4,resolveSidebarQuotaAccess:O3,refreshSidebarQuota:s1,fallbackRefreshReady:UY,get scopedRuntime(){return O4(j,$.directory)},notificationMessageIdBeforeAssistant:XY,trackDesktopNoticeMessageId:U3,isDesktopNoticeMessage:Q3}),q3},WV=qW;
44
+ `);await n8($,Z.sessionID,_)}KW()},auth:{provider:"anthropic",async loader(Z,G){W1=async()=>{let Q=await Z();return{type:Q.type,active:kZ(Q,"anthropic")}},J9=Z;let W=await Z();if(W.type!=="oauth")return{};let K=await c1("opencode").catch(()=>{return});if(!tZ&&kZ(W,"anthropic")&&process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION!=="1"){tZ=!0;let Q=$9(F1.signal).then((U)=>{if(!F1.signal.aborted)return m$(U.policyStorage,{...W$,routingAuthoritative:!1})}).catch(()=>{if(!F1.signal.aborted)b.debug("quota","startup account profile hydration failed")});B1.add(Q),Q.then(()=>B1.delete(Q))}function _(Q,U=!1){if(!kZ(Q,"anthropic")&&!(U&&Z9(Q)))throw Error("Native OAuth requires inert OpenCode activation; run offline setup")}async function L(Q){_(await Z(),Q&&await c1("opencode")==="local")}let D=async(Q,U,P=!1)=>{let p=await Z();if(p.type!=="oauth")return{type:p.type,access:"",expires:0,refresh:void 0,nativeAccountIdentity:void 0,nativeRoutingLineage:void 0,nativeLocalSource:void 0,nativeScopedAttempt:void 0,modelDenied:!1,credentialUnavailable:!1,credentialFailure:void 0,deferred:!1};let i=await c1("opencode");if(i==="claustrum"&&!TY(p))throw Error("This host uses the credential vault, but OpenCode holds a separate Anthropic login. Remove it and choose the vault login, or disconnect from the vault.");H$();let t=await fG(w,U),L0=i==="claustrum"?"committed":R8(await f8(j0)),p0=k8(t);if(_(p,i==="local"&&(L0==="committed"||L0==="retired")&&p0),i==="claustrum"&&!t.accounts.some((v0)=>v0.type==="oauth"&&x0(v0)))throw new q8;let P0=g3(t.policyStorage);try{y3({mode:i==="claustrum"?"C":"L",main:dJ(p),fallbacks:i==="claustrum"?"T":P0.fallbacks,evidence:"V",authority:L0,localOAuthServable:p0}),W9=void 0}catch(v0){if(v0 instanceof R4)W9=v0.verdict;throw v0}D0=t.policyStorage;let c0=t.accounts.find((v0)=>v0.id==="main"),U0=c0?.binding,F$=c0?i0(c0,t.policyStorage):void 0,w1=F$&&F$!==c0?.quota?{...t.policyStorage,quota:{...t.policyStorage.quota,mainQuota:F$}}:t.policyStorage,q$=w0("main",H0(U0),c0?.accountIdentity,t.policyStorage),M$=Boolean(U0&&q$?.lineage===H0(U0)&&q$?.generalExhausted===!0);if(c0&&U0&&(!v$||U0.rowId!==v$.rowId||U0.credentialEpoch>v$.credentialEpoch))y.clearMain(),y.setMainQuotaAccountIdentity(c0.accountIdentity),v$={rowId:U0.rowId,credentialEpoch:U0.credentialEpoch};if(P&&($1(t.policyStorage)==="fallback-first"||oZ(w1,c0?.accountIdentity,M$))){let v0=t.accounts.find((U$)=>U$.id==="main");return U?.throwIfAborted(),{type:"oauth",access:"",expires:0,refresh:void 0,nativeAccountIdentity:v0?.accountIdentity,nativeRoutingLineage:v0?.binding?H0(v0.binding):void 0,nativeLocalSource:void 0,nativeScopedAttempt:void 0,modelDenied:!1,credentialUnavailable:!1,credentialFailure:void 0,deferred:!0}}let S0,l0,T$,r$;try{S0=await m0("main",U,void 0,Q,"serve",t)}catch(v0){if(v0 instanceof b0)throw v0;if(y1(v0))throw v0;if(v0 instanceof U1){l0=v0.account;let U$=t6(l0.quota,Q);if(U$!==void 0&&(!Number.isFinite(U$.checkedAt)||(U$.checkedAt??0)+v0.checkIntervalMs<=Date.now())||!yZ(l0.quota)&&!s9(l0.quota,Q))try{await w.fetchQuota("main",void 0,U),S0=await m0("main",U,void 0,Q),l0=void 0}catch(o$){if(y1(o$))throw o$;if(o$ instanceof U1)l0=o$.account;else if(o$ instanceof b$)T$=o$.account,r$=o$}}else if(v0 instanceof b$)T$=v0.account,r$=v0}return U?.throwIfAborted(),{type:"oauth",access:S0?.accessToken??"",expires:S0?.expires??0,refresh:void 0,nativeRoutingLineage:s(S0?.localSubject,S0?.scopedAttempt)??(c0?.binding?H0(c0.binding):void 0),nativeAccountIdentity:S0?.accountIdentity??l0?.accountIdentity??T$?.accountIdentity,modelDenied:Boolean(l0),credentialUnavailable:Boolean(T$),credentialFailure:r$,deferred:!1,nativeLocalSource:S0?.localSource,nativeScopedAttempt:S0?.scopedAttempt}};T1=D;let O={type:"oauth",access:"",expires:0};if(O.type==="oauth"){let p=function(){if(f1)Y.clearInterval(f1);let H=async()=>{try{let B=await r(j);if(!IY(B))return;let f=await D();if(f.type!=="oauth")return;if(f.nativeLocalSource==="rotated"||f.nativeLocalSource==="adopted")return;if(f.expires&&f.expires-Date.now()>D3(B))return;await P()}catch{b.warn("refresh","native main OAuth background refresh unavailable")}};f1=Y.setInterval(()=>{H()},tG+i8(l8)),f1.unref?.()},t=function(H,B){if(H instanceof Request&&H.body)return!1;return B==null||typeof B==="string"},L0=function(H){if(typeof H!=="string")return;try{let B=JSON.parse(H);return typeof B.model==="string"?B.model:void 0}catch{return}},p0=function(H){return H.has("x-parent-session-id")},P0=function(H){let B;try{B=JSON.parse(H)}catch{return!1}if(typeof B!=="object"||B===null)return!1;let f=Reflect.get(B,"error");return Reflect.get(B,"type")==="error"&&typeof f==="object"&&f!==null&&Reflect.get(f,"type")==="rate_limit_error"},c0=function(H){return H?.quota?.enabled===!0},F$=function(H,B){if(H.delete("authorization"),H.delete("x-api-key"),B.authHeader==="x-api-key")H.set("x-api-key",B.apiKey??"");else H.set("Authorization",`Bearer ${B.apiKey??""}`);H.set("Content-Type","application/json"),W8(H)},S0=function(H){return y.getFallback(H.id,H)?.quota??H.quota},l0=function(H,B){return H.status===429||B},T$=function(H,B=D0){return D$("main",H?.routingLineage,H?.providerAccountUuid,y.getMain(H?.quotaKey??P$),B)},r$=function(H,B){if(!H&&!B?.providerAccountUuid)return!1;let f=T$(B);return Boolean(f&&(H||f.quota.accountIdentity===B?.providerAccountUuid)&&f.refreshAfter>Date.now()&&H4(f.quota)&&(f.quota.source!=="headers"||w0("main",B?.routingLineage,B?.providerAccountUuid)?.generalExhausted===!0||["five_hour","seven_day"].some((h)=>f.quota.fieldSources?.[h]==="poll"&&(f.quota[h]?.remainingPercent??1)<=0)))},U=(await w.read().catch(()=>{return}))?.accounts.find((H)=>H.id==="main");if(B4=U?.binding?.rowId??U?.accountIdentity,P$??=U?.accountIdentity??B4,O.access)await U4(O.access);async function P(H,B,f){let h=Z9(await Z());await L(h),f?.throwIfAborted();let I=await m0("main",f,H,B,"refresh");return await L(h),f?.throwIfAborted(),I.accessToken}if(K==="local")p();y.seedFallbacksFromAccounts((j$?.accounts??[]).filter(R0));let i=await XW(()=>r(j)).catch(()=>({freshStorage:null,activeId:void 0,route:"main"}));await m$(i.freshStorage,{activeId:i.activeId,route:i.route,mainAccessToken:O.access,routingAuthoritative:!1});async function U0(H,B){if(!H.body||H.status!==200)return B?.mark("inspect_stream_skip",{status:H.status}),{response:H,rateLimited:!1};if(H.headers.get("x-cortexkit-relay-optimistic")==="true")return B?.mark("inspect_stream_skip",{status:H.status,reason:"optimistic_relay"}),{response:H,rateLimited:!1};let f=X0(),h=H.body.getReader(),I=[],V0=0,g=f6({maxFrameBytes:65536}),e=!1,A=!1,q0=!0;while(!A&&V0<65536){let{done:E,value:m}=await h.read().catch(async(Z0)=>{let T=NZ(Z0,n$.get(H)?.toolNameMap);if(T!==Z0)await DZ(h,T);throw T});if(E)break;I.push(m),V0+=m.byteLength;let O0;try{O0=g.push(m)}catch{break}for(let Z0 of O0){let T=PG(h6(Z0,{streamStart:q0}));if(q0=!1,T.data===void 0)continue;e=P0(T.data),A=!0;break}}if(e){NJ.get(H)?.(),NJ.delete(H),await h.cancel().catch(()=>{});try{h.releaseLock()}catch{}let E=new ReadableStream({start(O0){for(let Z0 of I)O0.enqueue(Z0);O0.close()}});B?.mark("inspect_stream_first_event",{ms:I0(X0()-f),bytes:V0,rateLimited:!0});let m=new Response(E,{status:H.status,statusText:H.statusText,headers:H.headers});return _9(n$,H,m),{response:m,rateLimited:!0}}let d=new ReadableStream({start(E){for(let m of I)E.enqueue(m)},async pull(E){let{done:m,value:O0}=await h.read();if(m){E.close();return}E.enqueue(O0)},cancel(E){return h.cancel(E)}});B?.mark("inspect_stream_first_event",{ms:I0(X0()-f),bytes:V0,rateLimited:!1});let k=new Response(d,{status:H.status,statusText:H.statusText,headers:H.headers});return _9(n$,H,k),{response:k,rateLimited:!1}}async function w1(H,B,f,h){if(H$(),!B){let g=T$(f);if(!f?.providerAccountUuid||!g||g.refreshAfter<=Date.now()||!H4(g.quota))throw Error("API fallback requires fresh general primary OAuth exhaustion");let e=await m0("main",h);if(e.accountIdentity!==f.providerAccountUuid||f.routingLineage&&s(e.localSubject,e.scopedAttempt)!==f.routingLineage)throw Error("Primary identity changed before API fallback");B=e.accessToken}let I=await w.authorizeApi(H,h),V0=(await w.read()).accounts.find((g)=>g.id==="main");if(V0?.binding&&H0(V0.binding)!==f?.routingLineage)throw Error("Primary identity changed before API fallback");if(!r$(B,f))throw Error("API fallback requires fresh general primary OAuth exhaustion");return I}async function q$(H,B,f,h,I="api_fallback",V0,g,e,A){if(g)g.oauthAccountId=void 0,g.opusCacheAnchor=void 0;let q0=X0(),d=m4(H,B),k=d.get("x-session-affinity")||d.get("x-opencode-session"),E=p0(d),m=d.get($4)??void 0,O0=M1.resolveHeader(m),Z0=O0?M1.versionsFor(O0.sessionId,O0.messageId):void 0;d.delete("x-parent-session-id"),d.delete("x-session-affinity"),d.delete("x-opencode-session"),d.delete("x-opencode-session-id"),d.delete("x-opencode-parent-session-id"),d.delete($4),d.delete(e1),d.delete(jZ);let T=await d4(H,B),S=!1,G0=null,M0,u=typeof T==="string"?T.length:void 0;if(T&&typeof T==="string"){let J0=X0(),x$=(()=>{if(!hZ())return!1;try{return C8(JSON.parse(T).model)}catch{return!1}})();try{T=await k9(T,{onToolNameMap:(J$)=>{M0=J$},cache1hEnabled:!E&&V4(),cache1hMode:W4(),fastModeEnabled:x$,sessionId:k||void 0,midConversationEffortEnabled:!1,midConversationEffortPlan:m,midConversationEffortResolvedPlan:O0,midConversationEffortPlanVersions:Z0,modelRemapEnabled:!0,perf:(J$,_$)=>h?.mark(`rewrite_body_${J$}`,{route:I,..._$})})}catch(J$){if(J$ instanceof C0)return p8(J$);if(J$ instanceof v8)return c8(J$);throw J$}if(F$(d,f),d.set("anthropic-beta",A8(d.get("anthropic-beta"),[])),x$)f9(d);try{S=JSON.parse(T).stream===!0}catch{}h?.mark("rewrite_body",{route:I,ms:I0(X0()-J0),originalBytes:u,rewrittenBytes:T.length,cacheEnabled:!E&&V4(),cacheMode:W4(),fastModeEnabled:x$,subagent:E})}else F$(d,f);let R$=await EJ(d),k1=await w1(f.id,e,A,B?.signal??void 0);f={...f,...k1},F$(d,f);let z$=p4(H,{baseURL:f.baseURL}),o0=X0(),w$=c9([f.apiKey??""],S?"event-stream":"http"),Q$;try{Q$=w$.redactResponse(await fetch(z$.input,{...B,body:T,headers:d,...HZ()&&{tls:{rejectUnauthorized:!1}}}))}catch(J0){let x$=w$.redactError(J0);if(w$.dispose(),typeof T==="string")await l9({affinity:k,route:I,error:h8,bodyText:T,url:z$.url?.toString()??K4(z$.input),method:i1(H,B),headers:d});throw x$}if(typeof T==="string")G0=await l9({affinity:k,route:I,status:Q$.status,bodyText:T,url:z$.url?.toString()??K4(z$.input),method:i1(H,B),headers:d});if(V3(Q$,{source:"turn",toolNameMap:M0,accountId:f.id,synthetic:!1,...R$,requestedModel:L0(T),dump:G0,status:Q$.status,streaming:S}),h?.mark("send_headers_received",{route:I,ms:I0(X0()-o0),status:Q$.status,relayConfigured:!1,totalSendWithAccessMs:I0(X0()-q0),baseURL:f.baseURL}),Q$.ok)A1.publish(()=>w.publishApi(k1.subject,{lastUsed:Date.now()}));return Q$}async function M$(H,B,f,h,I="unknown",V0,g="main",e,A,q0=!1,d,k){K6(f,"anthropic");let E=p4(H);if(!VZ(E.url?.toString()??K4(E.input)))return b.warn("oauth-destination","refused a Claude OAuth request to a non-Anthropic origin; nothing was sent",{route:I}),ZJ(V6);let m=Z9(await Z()),O0=X0(),Z0=V0,T=async()=>{return Z0??=await r(j),Z0},S=m4(H,B),G0=S.get("x-session-affinity")||S.get("x-opencode-session"),M0=p0(S),u=S.get($4)??void 0,R$=M1.resolveHeader(u),k1=R$?M1.versionsFor(R$.sessionId,R$.messageId):void 0,z$=S.get(e1)??void 0,o0=R1.resolveHeader(z$),w$=!M0&&!q0?o0:void 0;S.delete("x-parent-session-id"),S.delete("x-session-affinity"),S.delete("x-opencode-session"),S.delete("x-opencode-session-id"),S.delete("x-opencode-parent-session-id"),S.delete($4),S.delete(e1);let Q$=H7(S),J0=await d4(H,B),x$=G0?SJ.previousFor(G0):null,J$=x$?.messageId??null,_$,I$=!1,E4=null,s$=null,C4,E1;if(J0&&typeof J0==="string"){let x=X0();try{let Y0=JSON.parse(J0);if(typeof Y0.model==="string")E1=Y0.model}catch{}h?.mark("model_parse_for_identity",{route:I,ms:I0(X0()-x),bodyBytes:J0.length})}let F0=await m0(g,B?.signal??void 0,void 0,E1,g==="main"?"last-main":"serve");if(f=F0.accessToken,g==="main"&&d?.providerAccountUuid&&F0.accountIdentity!==d.providerAccountUuid)throw Error("Main account identity changed after request routing");k=F0.scopedAttempt;let R=X0(),o=Y1(F0.accountIdentity);h?.mark("resolve_claude_code_identity",{route:I,ms:I0(X0()-R),hasAccountUuid:Boolean(o.accountUuid)});let a=x8,W0=typeof J0==="string"?J0.length:void 0;if(J0&&typeof J0==="string"){let x=X0(),Y0=(()=>{if(!hZ())return!1;try{return C8(JSON.parse(J0).model)}catch{return!1}})(),u0=!M0&&V4();a=u0?HG:x8;let g0=W4(),S$=A?.plan.downgraded&&A.plan.standbyCacheAnchor?.oauthAccountId===g?A.plan.standbyCacheAnchor:void 0;try{J0=await k9(J0,{deferSigning:!0,onToolNameMap:(h0)=>{C4=h0},cache1hEnabled:u0,cache1hMode:g0,fastModeEnabled:Y0,identity:o,sessionId:G0||void 0,thinkingPrefixMismatchBehavior:e6(await T()),midConversationEffortEnabled:!0,turnEndNoteEnabled:!0,turnEndNote:(await T())?.turnEndNote,midConversationEffortPlan:u,midConversationEffortResolvedPlan:R$,midConversationEffortPlanVersions:k1,hybridStandbyAnchor:S$,serverSideFallbackEnabled:jJ==="server",laneStart:q0,billingLineage:w$,cacheDiagnosticsPreviousMessageId:J$,perf:(h0,c$)=>{if(h?.mark(`rewrite_body_${h0}`,{route:I,...c$}),h0==="cache_strategy"&&c$?.standbyBridgeApplied===!0&&A&&!A.standbyBridgeLogged)A.standbyBridgeLogged=!0,b.info("fable-fallback","restored standby Opus cache bridge",{session:A.plan.sessionId,distanceBlocks:c$?.standbyDistanceBlocks})}})}catch(h0){if(h0 instanceof C0)return p8(h0);if(h0 instanceof v8)return c8(h0);throw h0}if(A?.plan.downgraded&&u0&&g0==="hybrid"){let h0=$8(J0);A.opusCacheAnchor=h0?{...h0,oauthAccountId:g}:void 0}let A4=X0();try{let h0=JSON.parse(J0);G4(S,f,{body:h0,identity:o,requestClass:Q$});let c$=h0.diagnostics,M3=c$&&typeof c$==="object"&&!Array.isArray(c$)&&c$.previous_message_id===J$?J$:void 0;if(M3!==void 0&&S.get("anthropic-beta")?.split(",").map((uY)=>uY.trim()).includes(q4))_$={sessionId:G0??"session-unknown",previousMessageId:M3,...x$?{previousMessageReceivedAt:x$.receivedAt}:{},isSubagent:M0,ttlSent:N9(h0)};I$=h0.stream===!0,h?.mark("set_oauth_headers_body_parse",{route:I,ms:I0(X0()-A4),bodyBytes:J0.length,parsed:!0})}catch{G4(S,f,{identity:o,requestClass:Q$}),h?.mark("set_oauth_headers_body_parse",{route:I,ms:I0(X0()-A4),bodyBytes:J0.length,parsed:!1})}if(Y0)f9(S);h?.mark("rewrite_body",{route:I,ms:I0(X0()-x),originalBytes:W0,rewrittenBytes:J0.length,cacheEnabled:!M0&&V4(),cacheMode:W4(),fastModeEnabled:Y0,subagent:M0})}let $0=await EJ(S);if(A)A.oauthAccountId=g;if(A)A.subagent=M0;let n,s0=()=>{if(B?.signal?.aborted)return;if(G0)u1.record(G0,g,a);n?.()};if(typeof J0==="string"){let x=await T();if(V4()&&W4()==="hybrid"&&(!M0||JG(x))){let Y0=J0;n=()=>{let u0=X0(),g0=a0.track({sessionId:G0,url:E.url?.toString()??E.input.toString(),headers:S,bodyText:Y0,storage:x,cacheMode:"hybrid",ttlMs:a,oauthAccountId:g,oauthAccountIdentity:F0?.accountIdentity,isSubagent:M0});if(h?.mark("cachekeep_track",{session:G0,ms:I0(X0()-u0),tracked:g0.tracked,reason:g0.tracked?void 0:g0.reason,bodyBytes:Y0.length}),G0&&A&&!A.plan.downgraded&&g0.tracked){Q1.set(A.plan.recoveryKey,{...F0.accountIdentity!==void 0&&{accountIdentity:F0.accountIdentity},sentAt:Date.now()});while(Q1.size>128){let S$=Q1.keys().next().value;if(S$===void 0)break;Q1.delete(S$)}}}}if(G0&&!M0&&k0.hasSourceWarmForSession(G0)){if(w$&&w$.sessionId===G0)k0.noteSourceWarmUserTurn(G0,w$.promptId);if(!E8(x)||!V4()||W4()!=="hybrid")KJ(G0);else{let Y0=FZ(J0),u0=new Set(a0.trackedSessions().map((g0)=>g0.id));for(let{recoveryKey:g0,warm:S$}of k0.sourceWarmsForSession(G0)){let A4=X$(S$.model),h0=A4?J4(G0,A4):void 0;if(h0!==void 0&&!u0.has(h0)&&Date.now()-S$.sentAt>30000){k0.dropSourceWarm(g0);continue}if(S$.oauthAccountId!=="main"&&!x?.accounts.some((c$)=>c$.id===S$.oauthAccountId&&x0(c$))){if(k0.dropSourceWarm(g0),h0!==void 0)a0.untrack(h0,"policy-refused");b.info("fable-fallback","source warm stopped: bound account unavailable",{session:G0,reason:"account-unavailable"});continue}if(S$.firstAnchorFingerprint!==void 0&&!Y0.includes(S$.firstAnchorFingerprint)){if(k0.dropSourceWarm(g0),h0!==void 0)a0.untrack(h0,"policy-refused");b.warn("fable-fallback","source warm stopped: history no longer starts with the kept prefix",{session:G0,reason:"source-prefix-changed"})}}}}}let z1=F0,Z$,V1=async(x)=>{await L(m),B?.signal?.throwIfAborted();let Y0=await m0(g,B?.signal??void 0,x,E1,g==="main"?"last-main":"serve");if(await L(m),B?.signal?.throwIfAborted(),Y0.accountIdentity!==z1.accountIdentity||Boolean(Y0.scopedAttempt)!==Boolean(z1.scopedAttempt))throw Error("Native credential authority changed during the request");if(Z$&&(!Y0.scopedAttempt||Y0.scopedAttempt.credentialId!==Z$.credentialId||Y0.scopedAttempt.accountIdentity!==Z$.accountIdentity||Y0.scopedAttempt.recordVersion<=Z$.recordVersion))throw Error("Native vault retry has no strict newer same-account receipt");return Y0},L$=!1,O$=k,Y$=async()=>{L$=!0,F0=await V1(),O$=F0.scopedAttempt,S.set("authorization",`Bearer ${F0.accessToken}`),Q0={...Q0,accessToken:F0.accessToken,anthropicAccountUuid:k$(F0.accountIdentity),localSubject:F0.localSubject,scopedAttempt:F0.scopedAttempt};let x=c9([F0.accessToken],I$?"event-stream":"http");try{let Y0=(g0,S$)=>v4(E.input,{...B,body:g0,headers:S$,...HZ()&&{tls:{rejectUnauthorized:!1}}}),u0=x.redactResponse(typeof J0==="string"?await cG({url:E.url?.toString()??K4(E.input),body:J0,headers:S,latch:F,send:Y0}):await Y0(J0,S));if(u0.ok&&!B?.signal?.aborted)s0?.();if(typeof J0==="string")E4=await l9({affinity:G0,route:I,status:u0.status,bodyText:J0,url:E.url?.toString()??K4(E.input),method:i1(H,B),headers:S,tag:q0?"start":void 0});return u0}catch(Y0){let u0=x.redactError(Y0);if(x.dispose(),typeof J0==="string")await l9({affinity:G0,route:I,error:h8,bodyText:J0,url:E.url?.toString()??K4(E.input),method:i1(H,B),headers:S,tag:q0?"start":void 0});throw u0}},T0=await T(),E0;try{E0=await w.getRelayConfig()}catch(x){if(x instanceof jG&&x.code==="relay-inconsistent")return ZJ(x.message);throw x}let _0;if(typeof J0==="string"&&Q$==="main"&&!M0&&!q0&&(!E0||g6(E0.transport,E0.url)!=="websocket"))_0=await qG(N,{session:G0??void 0,account:F0.accountIdentity??g,credential:F0.scopedAttempt?.credentialId??F0.accessToken,bodyText:J0,replyToolNames:C4,headers:S,signal:B?.signal??void 0}),J0=_0.bodyText;else if(typeof J0==="string")J0=await dG(J0);let N$=g==="main"?void 0:T0?.accounts.find((x)=>x.id===g&&R0(x)),t1=l6(N$,e),Q0={accountId:g,accessToken:f,authLineageId:e,anthropicAccountUuid:k$(k?.accountIdentity)??(g==="main"?d?.providerAccountUuid:k$(o.accountUuid)??k$(t1)),localSubject:F0.localSubject,scopedAttempt:F0.scopedAttempt,...g==="main"&&d?{mainQuotaIdentity:d}:{}},K9=X0(),p$,N0=!1,r0,d0=VJ,t0=()=>pG({config:E0,input:E.input,requireUpstreamUrl:w9,init:B,headers:S,body:J0,fallback:Y$,affinity:G0,optimisticResponse:E0?.transport==="websocket",authorizeAttempt:async()=>{let x=await V1(),Y0=x.scopedAttempt;F0=x,Q0={...Q0,accessToken:x.accessToken,anthropicAccountUuid:k$(x.accountIdentity),localSubject:x.localSubject,scopedAttempt:Y0};let u0=new Headers(S);return u0.set("authorization",`Bearer ${x.accessToken}`),{headers:u0,errorSecrets:[x.accessToken],onUpstreamStatus:(g0)=>{if(g0>=200&&g0<300&&!B?.signal?.aborted)s0?.();if(g0!==401||!Y0)return;if(p$=Y0,N0)d0(Y0,"relay_status_field")}}},onResponseHeaders:(x)=>{r0=x,Y3(x,Q0),R1.commit(w$,gJ(x))},onDumpCreated:(x)=>{s$=x},dumpTag:q0?"start":void 0});return f0(async()=>{let x=await t0();if(!L$&&p$&&x.status===401&&typeof J0==="string"&&(i1(H,B)??"").toUpperCase()==="POST"&&!B?.signal?.aborted){let Y0;try{Y0=await o4(p$,"model-relay",B?.signal??void 0)}catch{}if(Y0)await x.body?.cancel().catch(()=>{}),b.info("claustrum","retrying after scoped credential rotation",{accountId:g,previousVersion:p$.recordVersion,newVersion:Y0.recordVersion,transport:"relay"}),Z$=p$,p$=void 0,x=await t0()}if(L$&&O$&&x.status===401&&typeof J0==="string"&&(i1(H,B)??"").toUpperCase()==="POST"&&!B?.signal?.aborted){let Y0;try{Y0=await o4(O$,"model",B?.signal??void 0)}catch{}if(Y0)await x.body?.cancel().catch(()=>{}),b.info("claustrum","retrying after scoped credential rotation",{accountId:g,previousVersion:O$.recordVersion,newVersion:Y0.recordVersion,transport:"direct"}),Z$=O$,x=await Y$()}if(x.status===401&&!F0.scopedAttempt&&typeof J0==="string"&&(i1(H,B)??"").toUpperCase()==="POST"&&!B?.signal?.aborted){let Y0=F0.accessToken,u0;try{u0=await V1(Y0)}catch(g0){dZ.set(x,g0)}if(u0&&u0.accessToken!==Y0)await x.body?.cancel().catch(()=>{}),x=L$?await Y$():await t0()}if(_0)x=await _0.recover(x,async(Y0)=>{return J0=Y0,t0()}),x=_0.observe(x);if(h?.mark("send_headers_received",{route:I,ms:I0(X0()-K9),status:x.status,relayConfigured:E0!=null,totalSendWithAccessMs:I0(X0()-O0)}),L$)Y3(x.headers,Q0),R1.commit(w$,gJ(x.headers));if(G0&&!q0){let Y0=L$?x.headers:r0??x.headers,u0=x.status<400&&(!h||!nZ.has(h));if(u0&&h)nZ.add(h);let g0={accountIdentity:F0.accountIdentity,credentialId:F0.scopedAttempt?.credentialId};if(D4.report(G0,g0,Y0,x.status,E1,u0),x.status===200)NJ.set(x,()=>D4.report(G0,g0,Y0,429,E1,!1))}if(V3(x,{source:q0?"start":"turn",toolNameMap:C4,failThread:_0?.fail,accountId:g,synthetic:q0,...$0,requestedModel:L0(J0),request:_$,trackSessionId:G0??void 0,dump:L$?E4:s$,status:x.status,streaming:I$}),L$&&O$&&x.status===401)await d0(O$,"direct");if(N0=!0,!L$&&p$)await d0(p$,"relay_status_field");if(x.status===401)await m8(x,B?.signal);if(x.ok)A1.publish(async()=>{if(Q0.scopedAttempt)await w.vault.publish(Q0.scopedAttempt,{lastUsed:Date.now()});else if(Q0.localSubject)await w.publishLocal(Q0.localSubject,{lastUsed:Date.now()})});return x})}async function v0(H,B){if(!H)return!1;try{return await y.refreshMain(B?.quotaKey??P$,H,B?.generation),r$(H,B)}catch{return!1}}async function U$(H,B={}){let f=L1(H),h=await x1(!1,f,B.modelId,"admission");if(H=await r(j),f){if(H&&h.size)H={...H,accounts:H.accounts.filter((e)=>!h.has(e.id)||N1(void 0,H,e.id,B.modelId))}}let I=await QJ.getUsableFallbackAccounts(H,{modelId:B.modelId}),V0=new Map(I.map((e)=>[e.id,e])),g=[];for(let e of H?.accounts??[]){if(H&&R0(e)){if(G$(H)){let q0=V0.get(e.id);if(q0)g.push(q0);continue}if(u4(H)!=="local")continue;let A=V0.get(e.id);if(A)g.push(A);else if(e.access&&(!e.expires||e.expires>Date.now())&&!O1(e.lastRefreshError)&&!l1(e.lastRefreshError,e.id,Date.now(),D1(e.refresh))&&H?.quota?.failClosedOnUnknownQuota!==!0&&!yZ(S0(e)))g.push(e);continue}if(B.includeApiRoutes===!0&&z4(e)&&x0(e)&&gZ(e.baseURL))g.push(e)}if(!L1(H))return g;return g.filter((e)=>R0(e)?N1(S0(e),H,e.id,B.modelId):!0)}async function bJ(H){let B=H.mainQuotaIdentity?.quotaKey,f=y.getMain(B),h=f?.quota;if(!d1(f?.quota,H.storage,Date.now(),H.requestedModelId))try{h=await y.refreshMain(B,H.mainAccessToken,H.mainQuotaIdentity?.generation,"admission")}catch{}let I=await QJ.getUsableFallbackAccounts(H.storage,{modelId:H.requestedModelId}),V0=await r(j)??H.storage,g=[],e=G$(V0);if(e){let k=V0?.claustrum?.primaryAccount;if(k!==void 0&&x0(k)&&!V0?.claustrum?.disabledAccountIdentities?.includes(k.accountId))g.push({id:V$,access:"",quota:h,identity:k?{kind:"known",accountId:k.accountId}:{kind:"unknown"},order:0,scoped:!0})}else if((H.mainAccessToken||H.mainPolicyDenied)&&!O1(V0?.refresh?.mainLastRefreshError))g.push({id:V$,access:H.mainAccessToken,quota:h,identity:B?{kind:"known",accountId:B}:{kind:"unknown"},order:0});if(e)for(let[k,E]of(V0?.accounts??[]).entries()){if(!x0(E)||!R0(E))continue;if(E.claustrumScopedCredentialId){let m=S0(E);if(!d1(m,V0,Date.now(),H.requestedModelId))try{m=await y.refreshFallback(E.id,"",E)}catch{}g.push({id:E.id,access:"",quota:m,identity:{kind:"known",accountId:E.id},order:k+1,account:E,scoped:!0})}}else{let k=new Map(I.map((E)=>[E.id,E]));for(let[E,m]of(V0?.accounts??[]).entries()){if(!x0(m)||!R0(m))continue;let O0=k.get(m.id)??m;if(O1(O0.lastRefreshError))continue;let Z0=S0(O0);if(!d1(Z0,V0,Date.now(),H.requestedModelId))try{Z0=await y.refreshFallback(O0.id,O0.access??"",O0)}catch{}g.push({id:O0.id,access:O0.access??"",quota:Z0,identity:{kind:"known",accountId:O0.id},order:E+1,account:O0})}}let A=new Set(I.map((k)=>k.id)),q0=new Set(g.flatMap((k)=>{let E=k.id===V$?V0?.refresh?.mainLastRefreshError:k.account?.lastRefreshError,m=!k.scoped,O0=k.identity.kind==="known"?k.identity.accountId:void 0;if(m&&O1(E))return[];if(m&&l1(E,O0,Date.now(),k.id===V$?H.mainRefreshToken?D1(H.mainRefreshToken):void 0:k.account?.refresh?D1(k.account.refresh):void 0)&&(k.id===V$||!A.has(k.id)))return[];if(d1(k.quota,V0,Date.now(),H.requestedModelId)&&PZ({quota:k.quota,modelId:H.requestedModelId,sessionId:H.sessionId,holdUntil:u1.holdUntil(H.sessionId,k.id,Date.now(),d9(V0))}).action==="migrate")return[];if(L1(V0)&&!N1(k.quota,V0,k.id===V$?void 0:k.id,H.requestedModelId))return[];return[k.id]})),d=g.flatMap((k)=>{let E=k.id===V$?V0?.refresh?.mainLastRefreshError:k.account?.lastRefreshError,m=!k.scoped,O0=k.identity.kind==="known"?k.identity.accountId:void 0;if(m&&O1(E)||m&&l1(E,O0,Date.now(),k.id===V$?H.mainRefreshToken?D1(H.mainRefreshToken):void 0:k.account?.refresh?D1(k.account.refresh):void 0)&&(k.id===V$||!A.has(k.id)))return[];let Z0=k.id===V$?void 0:k.id,T=yZ(k.quota)?k.quota:void 0,S=T?{kind:"known",quota:T}:{kind:"unknown"};return(!L1(V0)||N1(S.kind==="known"?S.quota:void 0,V0,Z0,H.requestedModelId))&&j4(S.kind==="known"?S.quota:void 0,V0)&&(S.kind==="unknown"||a9(S.quota,H.requestedModelId)&&(k.id===V$||A.has(k.id)||Boolean(k.scoped)))?[{accountId:k.id,quota:S,order:k.order}]:[]});return{storage:V0,allRoutes:g,candidates:d,retainAccountIds:q0}}let o$=new WeakMap;async function S1(H,B,f,h,I,V0,g){if(!f.length)return I??null;let e=g?.returnLastOnExhausted??!0,A=I??null,q0=!1,d=async()=>{if(q0)return;q0=!0,await I?.body?.cancel().catch(()=>{})};for(let[k,E]of f.entries()){let m;if(z4(E))await d(),m=await q$(H,B,E,V0,`api_fallback_${k}`,h,g?.fableRequest,g?.mainAccessToken,g?.mainQuotaIdentity);else if(G$(h)&&E.claustrumScopedCredentialId){let Z0;try{Z0=await m0(E.id,B?.signal??void 0,void 0,L0(await d4(H,B)))}catch(S){if(S instanceof U1)continue;throw S}let T=Z0.scopedAttempt;if(!T)throw Error("Native vault fallback credential is unavailable");await d(),m=await M$(H,B,T.accessToken,V0,`fallback_${k}`,h,E.id,E.authLineageId,g?.fableRequest,g?.laneStartRequest,void 0,T)}else if(u4(h)==="local"&&E.access)await d(),m=await M$(H,B,E.access,V0,`fallback_${k}`,h,E.id,E.authLineageId,g?.fableRequest,g?.laneStartRequest);else continue;A=m;let O0=cZ(m,h);if(!O0){let Z0=await U0(m,V0);m=Z0.response,A=m,O0=Z0.rateLimited}if(!O0){if(o$.set(m,z4(E)?"api":"oauth"),await g?.onSuccess?.(E),R0(E)&&c0(h)&&y.shouldRefreshOnRequestCount(V9)){if(G$(h)||E.access)y.refreshFallback(E.id,G$(h)?"":E.access??"",E).then(()=>g?.onSuccess?.(E)).catch(()=>{})}return m}if(k<f.length-1||!e)await m.body?.cancel().catch(()=>{})}return e?A:null}async function lY(H,B,f,h,I,V0,g,e,A,q0,d=!1,k){if(!t(H,B?.body))return f;let E=X0(),m=V0??await r(j);if(I?.mark("fallback_load_storage",{ms:I0(X0()-E),cached:!!V0}),!(m?.accounts??[]).some((u)=>x0(u)&&(R0(u)||z4(u)&&gZ(u.baseURL))))return f;let Z0=f,T=cZ(Z0,m),S=l0(Z0,!1);if(!T){let u=await U0(Z0,I);Z0=u.response,T=u.rateLimited,S=l0(Z0,u.rateLimited)}if(!T)return Z0;let G0=!1;if(h)G0=h.some(z4);else if(S)G0=await v0(g,k);let M0=h;if(!M0){let u=X0();M0=await U$(m,{includeApiRoutes:G0,modelId:A}),I?.mark("fallback_get_accounts",{ms:I0(X0()-u),accounts:M0.length})}if(L1(m)){let u=M0.length;if(M0=M0.filter((R$)=>R0(R$)?N1(S0(R$),m,R$.id,A):!0),M0.length<u)J1("[killswitch] filtered fallbacks",{before:u,after:M0.length})}return await S1(H,B,M0,m,Z0,I,{onSuccess:e,mainAccessToken:g,mainQuotaIdentity:k,fableRequest:q0,laneStartRequest:d})??Z0}return rG({apiKey:"",async fetch(H,B){if(H instanceof Request&&B?.signal===void 0)B={...B,signal:H.signal};let f=m4(H,B),h=f.get(T9)==="1";f.delete(T9),B={...B,headers:f};let I=f.get("x-session-affinity")||f.get("x-opencode-session"),V0=R1.promptIdForHeader(f.get(e1)),g=L0(B?.body),e=Boolean(I&&g&&!p0(f)&&k0.resetForModelChange(I,g));if(e&&I){for(let R of g$.keys())if(R.startsWith(`${I}\x00`))g$.delete(R);A$.delete(I),KJ(I)}let A=k0.plan(I,B?.body),q0=jJ==="server"&&B9(A?.effectiveModel??g)?A?.effectiveModel??g:void 0,d=A?{plan:A}:void 0;if(A?.downgraded)B={...B,body:A.bodyText};let k=B?.body,E=jW({bodyBytes:typeof k==="string"?k.length:void 0}),m=(R)=>{let o=n$.get(R);return G8(R,{toolNameMap:o?.toolNameMap,onResponseFailure:o?.failThread,perf:(a,W0)=>E.mark(a,W0),laneStart:h,laneStartOAuthServed:o$.get(R)!=="api",...o?o.streaming?{onMessageStart:(a)=>z3(R,a,!1),onMessageDelta:(a)=>FY(R,a),onStreamEnd:()=>o.dumpWrite}:{onMessageResponse:(a)=>z3(R,a),onStreamEnd:()=>o.dumpWrite,responseMode:"json"}:{},contentFilterModel:A?.requestedModel,...!A?.downgraded&&A?{onContentFilter:(a)=>{if(!d?.oauthAccountId)return b.debug("fable-fallback","content filter recovery unavailable for non-OAuth route",{session:A.sessionId}),!1;let W0=Q1.get(A.recoveryKey);Q1.delete(A.recoveryKey);let $0=a0.trackedRequest(A.sessionId),n;if($0)try{let O$=JSON.parse($0.bodyText);if(typeof O$.model==="string")n=O$.model}catch{}let s0=n?X$(n):null,z1=X$(A.requestedModel),Z$=$0?.oauthAccountId,V1=W0&&$0&&Z$!==void 0&&s0!==null&&s0===z1&&Z$===d.oauthAccountId?{bodyText:$0.bodyText,oauthAccountId:Z$,...W0.accountIdentity!==void 0&&{accountIdentity:W0.accountIdentity},sentAt:W0.sentAt,model:A.requestedModel,firstAnchorFingerprint:FZ($0.bodyText)[0],url:$0.url,headers:$0.headers,...d.subagent&&{subagent:!0}}:void 0,L$=k0.activate(A,d.oauthAccountId,V1);EY(A).catch(()=>{b.warn("fable-fallback","source warm sync failed",{session:A.sessionId})}),g$.delete(A.recoveryKey),g$.set(A.recoveryKey,DW(A.requestedModel,L$));while(g$.size>128){let O$=g$.keys().next().value;if(O$)g$.delete(O$);else break}i$.delete(A.recoveryKey),b.info("fable-fallback","content filter detected; switching session to Opus 4.8",{session:A.sessionId,requestedModel:A.requestedModel,completedToolUse:a?.completedToolUse===!0,remaining:L$}),T4({sessionId:A.sessionId,mode:"opus",remaining:L$,requestedModelId:A.requestedModel},S,T)}}:{},...A&&d?{onComplete:(a)=>{if(!A.downgraded){if(k0.completeSource(A,!d.serverFallback)){let s0=X$(A.requestedModel);if(s0)a0.untrack(J4(A.sessionId,s0))}return}let W0=k0.complete(A,d.opusCacheAnchor);if(!W0.counted)return;let $0=g$.get(A.recoveryKey);if($0)g$.delete(A.recoveryKey),K$.delete(A.sessionId),B3(A.sessionId,$0);if(b.info("fable-fallback","Opus 4.8 turn completed",{session:A.sessionId,requestedModel:A.requestedModel,finishReason:a,remaining:W0.remaining}),T4({sessionId:A.sessionId,mode:"opus",remaining:W0.remaining,requestedModelId:A.requestedModel},S,T),W0.remaining===0)T4({sessionId:A.sessionId,mode:"fable",remaining:0,requestedModelId:A.requestedModel},S,T,HW(A.requestedModel))}}:{},...q0?{serverSideFallbackModel:q0,...A?{onServerSideFallbackOutcome:(a)=>{if(d)d.serverFallback=a.fallback;vY(A,a,S,T)}}:{}}:{}})},O0=X0(),Z0=A?.effectiveModel??L0(await d4(H,B)),T=await D(Z0,B?.signal??void 0,!0);if(E.mark("get_auth",{ms:I0(X0()-O0),authType:T.type,hasAccess:Boolean(T.access)}),T.type!=="oauth"){let R=p4(H),o=m4(H,B);W8(o);let a=await d4(H,B);if(typeof a==="string")try{let $0=JSON.parse(a);if(vG($0))a=JSON.stringify($0)}catch{}B?.signal?.throwIfAborted();let W0=await fetch(R.input,{...B,body:a,headers:o});return E.done("non_oauth_passthrough",{status:W0.status}),W0}let S=await r(),G0=k$(T.nativeAccountIdentity),M0=T.nativeScopedAttempt,u;if(T.access){let R=await U4(T.access,L0(B?.body),G0,M0?.recordVersion);if(R.stale)throw Error("Main OAuth identity changed while resolving request credentials");if(u={...R,routingLineage:T.nativeRoutingLineage},G0)F4=T.access,a1=R.providerAccountUuid}else if((T.modelDenied||T.credentialUnavailable||T.deferred)&&G0)await sZ("",G0,G0),u={quotaKey:G0,providerAccountUuid:G0,generation:y.getMainQuotaIdentityGeneration(),routingLineage:T.nativeRoutingLineage,stale:!1,state:G$(S)?"on-cold":"na"};let R$=X0();E.mark("load_storage",{ms:I0(X0()-R$)}),y.updateStorage(S),y.seedMainFromStorage(S,P$),y.seedFallbacksFromAccounts((S?.accounts??[]).filter(R0));let k1=I?y$.get(I):void 0;if(e||!A||jJ==="server"&&k1?.requestedModelId&&X$(k1.requestedModelId)!==X$(A.requestedModel))hY(I,S,T);let z$=t(H,B?.body),o0=L0(B?.body)??Z0,w$=T$(u,S),Q$=w0("main",u?.routingLineage,G0,S),J0=T.deferred?oZ(w$&&S?{...S,accounts:S?.accounts??[],quota:{...S?.quota,mainQuota:w$.quota}}:S,G0,Q$?.lineage===u?.routingLineage&&Q$?.generalExhausted===!0):void 0;if(J0){let R=z$?await U$(S,{includeApiRoutes:r$(void 0,u),modelId:o0}):[],o=await S1(H,B,R,S,void 0,E,{onSuccess:(a)=>_$(a.id,"fallback"),mainQuotaIdentity:u,fableRequest:d,laneStartRequest:h});if(o)return m(o);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:J0.message}}),{status:429,headers:{"content-type":"application/json","retry-after":String(J0.retryAfter)}})}let x$=async(R,o)=>{let a=await w.read();return I6(R,IG({readings:a.accounts.filter((W0)=>W0.type==="oauth"&&x0(W0)).map((W0)=>({quota:W0.quota,accountIdentity:W0.accountIdentity,accountId:W0.id})),storage:a.policyStorage,modelId:o??Z0,sessionTtlMs:u1.ttlMs(I)}))},J$=async()=>{if(G$(S))return K8({snapshot:await w.read(),modelId:Z0,sticky:$1(S)==="sticky-balanced",sessionId:I});return x$("No enabled OAuth route can serve the requested model under current quota policy.",Z0)};if(z$)V9++;if(z$&&T.access&&(!T.expires||T.expires>Date.now()))xY(S,T.access,u);async function _$(R,o){let a=S,W0=!1;if((S?.accounts??[]).some(($0)=>R0($0)&&$0.quota))try{let $0=await r(j);if($0)a=$0;else W0=!0}catch{W0=!0}m$(a,{activeId:R,route:o,mainAccessToken:T.access,skipFallbackQuotaSeed:W0})}let I$;if(z$&&I&&$1(S)==="sticky-balanced"){let R=A?.effectiveModel??o0,o=nG(R),a=a0.trackedOAuthRoute(I),W0=A?.cacheAccountId??(a?a.oauthAccountId??V$:void 0),$0=!1;try{let n=await bJ({sessionId:I,storage:S,mainAccessToken:T.access,mainRefreshToken:T.refresh,mainPolicyDenied:T.modelDenied||T.credentialUnavailable,requestedModelId:R,mainQuotaIdentity:u}),s0=await w.read(),z1=await D4.accountFor(I,R??"",s0.accounts.filter((E0)=>x0(E0)&&M8(E0,s0,R).status==="allowed"&&n.candidates.some((_0)=>_0.accountId===E0.id))),Z$;if(z1){let E0=await w.read(),_0=E0.accounts.find((N$)=>F7(z1,N$));if(_0&&x0(_0)&&M8(_0,E0,R).status==="allowed"&&n.candidates.some((N$)=>N$.accountId===_0.id)&&T7(_0.id,n.candidates,n.storage,R??""))Z$=_0.id;else D4.override(I,"unknown account, credential, account policy or Fable reserve")}let V1=async(E0)=>{let _0=await rZ(),N$=!E0&&Z$;return _0.router.resolve({sessionId:I,family:o,modelId:R,affinityModelId:g,candidates:N$?n.candidates.filter((t1)=>t1.accountId===N$):n.candidates,retainAccountIds:N$?new Set([N$]):n.retainAccountIds,storage:n.storage,inputBytes:typeof B?.body==="string"?Buffer.byteLength(B.body):1,preferredAccountId:W0,excludeAccountIds:E0,...N$&&{preserveOnNoCandidate:!0},..._0.accountIdentities&&{accountIdentities:_0.accountIdentities}})},L$=O1(n.storage?.refresh?.mainLastRefreshError),O$=n.allRoutes.length===0&&!L$||n.allRoutes.some((E0)=>!E0.quota||!d1(E0.quota,n.storage,Date.now(),R)),Y$=await V1();if(Y$?.migrated)r1.clear(I);if(Z$&&!Y$)D4.override(I,"advised account is not selectable"),Z$=void 0,Y$=await V1();if(Z$&&Y$?.accountId===Z$&&z1?.hold)return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Shared routing requested a wait; retaining session affinity."}}),{status:429,headers:{"content-type":"application/json","retry-after":String(Math.ceil(z1.hold.retry_after_ms/1000))}});if(!Y$&&O$){if(T.modelDenied)return J$();throw Error("Sticky-balanced routing is waiting for current OAuth quota snapshots")}if(!Y$){if(T.modelDenied)return J$();if(G$(S))return K8({snapshot:await w.read(),modelId:R,sticky:!0,sessionId:I});let E0=k6({mainRefreshError:n.storage?.refresh?.mainLastRefreshError,fallbackReauthLabels:o6(n.storage),routeQuotas:n.allRoutes.flatMap((_0)=>_0.quota?[_0.quota]:[]),routeIdentities:n.allRoutes.filter((_0)=>_0.quota).map((_0)=>s0.accounts.find((N$)=>N$.id===_0.id)?.accountIdentity),routeAccountIds:n.allRoutes.filter((_0)=>_0.quota).map((_0)=>_0.id),storage:n.storage,sessionId:I,modelId:R});return E.done("return_sticky_no_route",{status:E0.status}),E0}let T0=n.allRoutes.find((E0)=>E0.id===Y$?.accountId);if(Y$&&T0){if($0=!0,A?.downgraded&&k0.bindRecoveryAccount(A,T0.id)){let N0=X$(A.requestedModel);if(N0)a0.untrack(J4(A.sessionId,N0),"policy-refused");b.info("fable-fallback","rebound recovery to migrated sticky account",{accountId:T0.id})}let E0=async(N0)=>{if(N0.scoped){let d0=(await m0(N0.id,B?.signal??void 0,void 0,R)).scopedAttempt;if(!d0)throw Error("Native vault sticky credential is unavailable");return M$(H,B,d0.accessToken,E,`sticky:${N0.id}`,n.storage,N0.id,N0.account?.authLineageId,d,h,N0.id===V$?u:void 0,d0)}return M$(H,B,N0.access??"",E,`sticky:${N0.id}`,n.storage,N0.id,N0.account?.authLineageId,d,h,N0.id===V$?u:void 0)},_0=async(N0,r0,d0=!0)=>{return await _$(N0.id,"sticky-balanced"),E.done("return_sticky_balanced",{status:r0.status,accountId:N0.id,created:Y$?.created,migrated:Y$?.migrated}),m(r0)},N$=async(N0)=>{let r0=N0,d0=cZ(N0,n.storage),t0=!1;if(!d0){let x=await U0(N0,E);r0=x.response,t0=x.rateLimited,d0=x.rateLimited}return{response:r0,routeFailure:d0,streamingRateLimit:t0}},t1=d1(T0.quota,n.storage,Date.now(),R)?PZ({quota:T0.quota,modelId:R,sessionId:I,holdUntil:u1.holdUntil(I,T0.id,Date.now(),d9(n.storage))}):void 0;if(t1?.action==="hold")return _0(T0,await L9(new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account quota resets shortly; retaining session affinity."}}),{status:429,headers:{"content-type":"application/json"}}),I,t1.retryAfterSeconds,!1,n$),!1);let Q0=await N$(await E0(T0)),K9=!1;if(!Q0.routeFailure)return _0(T0,Q0.response);if(Q0.response.status===401){let N0=dZ.get(Q0.response);if(N0){let r0=await r(j),d0=T0.id,t0=T0.id===V$?r0?.refresh?.mainLastRefreshError:r0?.accounts.find((x)=>x.id===d0&&R0(x))?.lastRefreshError;if(!O1(t0))throw N0}K9=!0}let p$=Q0.response.status===403||K9;if(Q0.response.status===429||Q0.streamingRateLimit){let N0=xG(Q0.response.headers,R);if(Object.keys(N0).length===0)try{N0=T0.id===V$?await y.refreshMain(u?.quotaKey,T0.access??"",u?.generation):await y.refreshFallback(T0.id,T0.access??"",T0.account)}catch{N0=void 0}let r0=PZ({quota:N0,modelId:R,responseHeaders:Q0.response.headers,sessionId:I,unconfirmedRetry:{counter:r1,sessionId:I,turnId:V0??I,accountId:T0.id},holdUntil:u1.holdUntil(I,T0.id,Date.now(),d9(n.storage))});if(E.mark("sticky_quota_failure",{accountId:T0.id,action:r0.action,reason:r0.reason}),r0.action==="hold")return _0(T0,await L9(Q0.response,I,r0.retryAfterSeconds,Q0.streamingRateLimit,n$));if(r0.action==="retain")return _0(T0,await L9(Q0.response,I,60,Q0.streamingRateLimit,n$,!0));p$=r0.action==="migrate"}if(p$){await m8(Q0.response,B?.signal);let N0=T0.id;if(n=await bJ({sessionId:I,storage:n.storage,mainAccessToken:T.access,mainRefreshToken:T.refresh,mainPolicyDenied:T.modelDenied||T.credentialUnavailable,requestedModelId:R,mainQuotaIdentity:u}),n.candidates.filter((d0)=>d0.accountId!==N0).length>0){await Q0.response.body?.cancel().catch(()=>{}),Y$=await V1(new Set([N0]));let d0=n.allRoutes.find((t0)=>t0.id===Y$?.accountId);if(Y$&&d0){if(r1.clear(I),T0=d0,A?.downgraded&&k0.bindRecoveryAccount(A,T0.id)){let t0=X$(A.requestedModel);if(t0)a0.untrack(J4(A.sessionId,t0),"policy-refused")}return _0(T0,await E0(T0))}}else if((Q0.response.status===429||Q0.streamingRateLimit)&&r$(T.access,u)){let d0=(await U$(n.storage,{includeApiRoutes:!0,modelId:R})).filter(z4);if(d0.length>0){let t0=await S1(H,B,d0,n.storage,Q0.response,E,{onSuccess:(x)=>_$(x.id,"sticky-balanced"),mainAccessToken:T.access,mainQuotaIdentity:u,fableRequest:d,laneStartRequest:h});if(t0)return r1.clear(I),E.done("return_sticky_api_fallback",{status:t0.status}),m(t0)}}}return _0(T0,Q0.response)}}catch(n){if(E.mark("sticky_balanced_error",{error:n instanceof Error?n.message:String(n)}),$0||y1(n))throw n;let s0=n instanceof Error?n:Error(String(n));throw Object.assign(s0,{code:"ECONNRESET",syscall:"sticky-routing"}),s0}}if(z$&&$1(S)==="fallback-first")try{let R=X0();I$=await U$(S,{includeApiRoutes:r$(T.access,u),modelId:o0}),E.mark("fallback_first_get_accounts",{ms:I0(X0()-R),accounts:I$.length});let o=await S1(H,B,I$,S,void 0,E,{returnLastOnExhausted:!1,mainAccessToken:T.access,mainQuotaIdentity:u,onSuccess:(a)=>_$(a.id,"fallback-first"),fableRequest:d,laneStartRequest:h});if(o)return E.done("return_fallback_first",{status:o.status}),m(o);I$=void 0}catch(R){if(E.mark("fallback_first_error",{error:R instanceof Error?R.message:String(R)}),y1(R))throw R}if(T.deferred){if(Object.assign(T,await D(Z0,B?.signal??void 0)),T.access){let R=await U4(T.access,Z0,T.nativeAccountIdentity,T.nativeScopedAttempt?.recordVersion);if(R.stale)throw Error("Main OAuth identity changed while resolving request credentials");u={...R,routingLineage:T.nativeRoutingLineage},F4=T.access,a1=R.providerAccountUuid}}if(!T.modelDenied&&(!T.access||!T.expires||T.expires<Date.now())){if(G$(S))try{let $0=(await m0("main",B?.signal??void 0,void 0,Z0)).scopedAttempt;if(!$0)throw Error("Native vault main credential is unavailable");F4=$0.accessToken;let n=await M$(H,B,$0.accessToken,E,"main",S,"main",void 0,d,h,u,$0);return m(n)}catch(W0){let $0=z$?await U$(S,{modelId:o0}):[],n=await S1(H,B,$0,S,void 0,E,{onSuccess:(s0)=>_$(s0.id,"fallback"),mainAccessToken:T.access,mainQuotaIdentity:u,fableRequest:d,laneStartRequest:h});if(n)return m(n);if(W0 instanceof b$)throw new q8;throw W0}if(T.credentialFailure?.tokenRefreshFailed)throw T.credentialFailure;let R=await r(),o=R?.refresh?.mainLastRefreshError;if(o&&l1(o,T.nativeAccountIdentity??B4??R?.mainAccountId,Date.now(),T.refresh?D1(T.refresh):void 0))throw J1("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:o.nextRetryAt,retryCount:o.retryCount,expiresInMs:T.expires?T.expires-Date.now():void 0}),Error(u6(o,Date.now()));J1("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(T.access),expiresInMs:T.expires?T.expires-Date.now():void 0,expiredAgoMs:T.expires&&T.expires<Date.now()?Date.now()-T.expires:void 0});let a=X0();T.access=await P(void 0,Z0,B?.signal??void 0),E.mark("refresh_main_access",{ms:I0(X0()-a)})}if(!T.access&&!T.modelDenied)throw E.done("missing_access_error"),Error("OAuth access token is missing after refresh");function E4(){if(S?.quota?.showToasts!==!0)return;let R=y.getMain(u?.quotaKey);if(!R)return;let o=(S?.accounts??[]).filter(($0)=>$0.enabled!==!1&&R0($0)).map(($0)=>({...$0,quota:y.getFallback($0.id,$0)?.quota??$0.quota})),a=j4(R.quota,S),W0;if(a)W0="main";else W0=o.find(($0)=>j4($0.quota,S))?.id??"main";cY(R.quota,o,W0)}if(z$&&c0(S))try{let R=X0(),o=T$(u,S),a=o?.quota;if(!a)a=await y.refreshMain(u?.quotaKey,T.access,u?.generation,"admission"),o=T$(u,S),E4();else if(y.needsRefresh(V9,o0))if(H4(a)||s9(a,o0))a=await y.refreshMain(u?.quotaKey,T.access,u?.generation),o=T$(u,S);else y.refreshMain(u?.quotaKey,T.access,u?.generation).then(()=>{s1().catch(()=>{}),E4()}).catch(()=>{});m$(S,{activeId:"main",route:"main",mainAccessToken:T.access});let W0=j4(a,S)&&a9(a,o0);if(E.mark("main_quota_for_routing",{ms:I0(X0()-R),passes:W0,model:o0,modelScopedExhausted:s9(a,o0)}),!W0){let $0=X0();I$=await U$(S,{includeApiRoutes:Boolean(o&&o.refreshAfter>Date.now()&&H4(o.quota)),modelId:o0}),E.mark("preselect_fallback_accounts",{ms:I0(X0()-$0),accounts:I$.length});let n=await S1(H,B,I$,S,void 0,E,{onSuccess:(s0)=>_$(s0.id,"fallback"),mainAccessToken:T.access,mainQuotaIdentity:u,fableRequest:d,laneStartRequest:h});if(n)return E.done("return_preselected_fallback",{status:n.status}),m(n)}}catch(R){if(E.mark("main_quota_for_routing_error",{error:R instanceof Error?R.message:String(R)}),y1(R))throw R}let s$=T$(u,S)?.quota;if(S?.quota?.failClosedOnUnknownQuota&&(s$===void 0||T.access.startsWith("sk-ant-oat")&&u?.providerAccountUuid===void 0)&&y.isBackedOff()){let R=y.getLastApiError(),o=R?B8(R,Date.now()):"Quota API unavailable";return J1("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:R?.nextRetryAt,retryCount:R?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:o}}),{status:429,headers:{"content-type":"application/json","retry-after":String(R?.nextRetryAt?Math.max(1,Math.ceil((R.nextRetryAt-Date.now())/1000)):60)}})}if(L1(S)){if(y.needsRefresh(V9,o0))try{await Promise.all([y.refreshMain(u?.quotaKey,T.access,u?.generation),x1(!1,!0,void 0,"admission")])}catch(o){J1("[quota] killswitch refresh failed",{error:o instanceof Error?o.message:String(o),backedOff:y.isBackedOff()})}s$=T$(u,S)?.quota}if(L1(S)&&!N1(s$,S,void 0,o0)){let o=t(H,B?.body)?await U$(S,{includeApiRoutes:r$(T.access),modelId:o0}):[];if(o.length>0){J1("[route] skipping main (killswitch), trying fallbacks");let $0=await S1(H,B,o,S,void 0,E,{onSuccess:(n)=>_$(n.id,"fallback"),mainAccessToken:T.access,mainQuotaIdentity:u,laneStartRequest:h});if($0)return E.done("return_killswitch_fallback",{status:$0.status}),m($0)}let a=Q7({mainQuota:s$,requestModelId:o0,storage:S}),W0=U7({...a.isScopedDriven&&{modelName:a.modelName}});return x$(W0,a.isScopedDriven?a.modelId:void 0)}if(T.modelDenied){let R=z$?await U$(S,{modelId:Z0}):[],o=await S1(H,B,R,S,void 0,E,{onSuccess:(W0)=>_$(W0.id,"fallback"),fableRequest:d,laneStartRequest:h,mainAccessToken:T.access,mainQuotaIdentity:u});if(o)return m(o);if(!($1(S)!=="sticky-balanced"&&s9(s$,Z0)&&j4(s$,S)&&N1(s$,S,void 0,Z0)))return m(await J$());return m(await M$(H,B,"",E,"main",S,"main",void 0,d,h,u))}let C4=await M$(H,B,T.access,E,"main",S,"main",void 0,d,h,u,M0),E1=!1,F0=await lY(H,B,C4,I$,E,S,T.access,(R)=>{return E1=!0,_$(R.id,"fallback")},o0,d,h,u);if(!E1)await _$("main","main");return E.done("return_response",{status:F0.status}),m(F0)}})}return{}},get methods(){return[...Y6(u9("opencode").tokenPath)?[SY]:[],{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{if(await c1("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.");if(await w.read(),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");let Z=await X("max");return{url:Z.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{let W=await MZ(G,Z.verifier,Z.redirectUri,Z.state);if(W.type==="failed")return W;H$(),await w.loginOAuth({routeId:"main",replace:!0,credential:{access:W.access,refresh:W.refresh,expires:W.expires}});let K=AZ("anthropic");return{type:"success",access:K.access,refresh:K.refresh,expires:K.expires}}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let Z=await z8("console");return{url:Z.url,instructions:"Paste the authorization code here:",method:"code",callback:async(G)=>{let W=await MZ(G,Z.verifier,Z.redirectUri,Z.state);if(W.type==="failed")return W;return{type:"success",key:(await v4("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${W.access}`}}).then((_)=>_.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}},dispose:MY};return _7?.set(q3,{drainDispatchWork:q1,primeManager:I1,quotaManager:y,cacheKeepManager:a0,fableFallbackManager:k0,resolveMainQuotaIdentity:U4,resolveSidebarQuotaAccess:O3,refreshSidebarQuota:s1,fallbackRefreshReady:UY,get scopedRuntime(){return O4(j,$.directory)},notificationMessageIdBeforeAssistant:XY,trackDesktopNoticeMessageId:U3,isDesktopNoticeMessage:Q3}),q3},WV=qW;
45
45
  export{e1 as a,gJ as b,yJ as c,$4 as d,C0 as e,X7 as f,T9 as g,w9 as h,D7 as i,F7 as j,T7 as k,w7 as l,f7 as m,v7 as n,h7 as o,G4 as p,p4 as q,k9 as r,G8 as s,WV as t};