@cortexkit/opencode-anthropic-auth 2.1.2 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +36 -36
- package/dist/{index-f2ne65w4.js → index-62x1p34p.js} +1 -1
- package/dist/index-88zg9ztr.js +2 -0
- package/dist/{index-x325vp4e.js → index-8ysjtqek.js} +13 -13
- package/dist/{index-ah5s0bew.js → index-ppdrzs41.js} +1 -1
- package/dist/index-xbwa4x53.js +2 -0
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.d.ts +54 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/transform.d.ts +4 -0
- package/dist/tui/claude-sidebar.d.ts +99 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/menu-contract.d.ts +3 -0
- package/dist/v2/rpc.d.ts +9 -0
- package/dist/v2/server.js +4 -4
- package/dist/v2/sidebar.d.ts +13 -0
- package/dist/v2/source.d.ts +2 -0
- package/dist/v2/tui.d.ts +9 -1
- package/dist/v2/tui.js +2 -2
- package/dist/v2/wire.d.ts +4 -0
- package/package.json +5 -5
- package/src/sidebar-state.ts +133 -3
- package/src/tui/claude-sidebar.tsx +1146 -0
- package/src/tui/entry.mjs +15 -1
- package/src/tui-compiled/sidebar-state.ts +133 -3
- package/src/tui-compiled/tui/claude-sidebar.tsx +1310 -0
- package/src/tui-compiled/tui.tsx +46 -1137
- package/src/tui.tsx +15 -886
- package/dist/index-53nnxq39.js +0 -2
- package/dist/index-jexctf5w.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{q as J8}from"./index-6chd6jnr.js";import{s as Z8}from"./index-hazrk5c3.js";import{C as W8}from"./index-b1dvkp15.js";import{G as X8,L as M9,N as Y8,O as G8}from"./index-53nnxq39.js";import{aa as y3}from"./index-ah5s0bew.js";import{randomUUID as iJ}from"node:crypto";import{existsSync as oY}from"node:fs";import{acquireNativeAccountRuntime as rY,applyCustomHeaders as U7,assertNotCustodyTombstone as sY,authorize as Q7,buildAccountList as g$,buildClaudeQuotaSummary as aY,buildFallbackQuotaSummaries as tY,buildPrimeRequestBody as eY,CACHE_KEEP_EXTENDED_TTL_BETA as $5,CacheKeepManager as J5,CacheKeepSessionRegistry as Z5,CLAUDE_FABLE_MYTHOS_5_1_PRICING as W5,CLAUDE_FABLE_MYTHOS_5_CONTEXT_WINDOW as X5,CLAUDE_FABLE_MYTHOS_5_MAX_OUTPUT_TOKENS as Y5,CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS as G5,CLAUDE_FABLE_MYTHOS_5_PRICING as V5,CLAUDE_HAIKU_4_5_MODEL_ID as B7,CLAUDE_HAIKU_5_5_CONTEXT_WINDOW as K5,CLAUDE_HAIKU_5_5_LONG_CONTEXT_PRICING as L9,CLAUDE_HAIKU_5_5_LONG_CONTEXT_THRESHOLD as z5,CLAUDE_HAIKU_5_5_MAX_OUTPUT_TOKENS as O5,CLAUDE_HAIKU_5_5_MODEL_ID as N9,CLAUDE_HAIKU_5_5_PRICING as H9,CLAUDE_HAIKU_5_5_RELEASE_DATE as j5,CLAUDE_OPUS_5_5_CONTEXT_WINDOW as _5,CLAUDE_OPUS_5_5_MAX_OUTPUT_TOKENS as L5,CLAUDE_OPUS_5_5_MODEL_ID as D9,CLAUDE_OPUS_5_5_PRICING as U9,CLAUDE_OPUS_5_5_RELEASE_DATE as N5,CLAUDE_SONNET_5_5_CONTEXT_WINDOW as H5,CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS as D5,CLAUDE_SONNET_5_5_MODEL_ID as Q9,CLAUDE_SONNET_5_5_PRICING as B9,CLAUDE_SONNET_5_5_RELEASE_DATE as U5,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as nJ,computeXxhash64Hex as Q5,configuredAnthropicOAuthAccountCount as B5,createEmptyStorage as o$,createNativeUsagePublisher as F5,createProviderErrorResponseScope as F9,createSseFramer as w5,createStickyNoRouteResponse as T5,custodyTombstoneOAuth as oJ,decideStickyQuotaFailure as rJ,decodeSseFrame as S5,detectClaustrumConnection as F7,dumpDirectRequest as w9,dumpResponseArtifact as sJ,effectiveRelayStatus as E5,exchange as aJ,executeAccountCommand as C5,executeCache1hCommand as tJ,executeCacheKeepCommand as P5,executeDumpCommand as w7,executeFastModeCommand as T7,executeKillswitchCommand as S7,executeLaneStartCommand as E7,executeLoggingCommand as C7,executePrimeCommand as A5,executeRoutingCommand as P7,FALLBACK_BACKGROUND_TICK_MS as R5,fallbackAccountUuidForLineage as q5,formatEnrollmentStatus as A7,formatNativeAccountState as eJ,formatOAuthAccountTier as B4,formatQuotaBackoffMessage as R7,formatRefreshBackoffMessage as M5,getAccountStoragePath as I5,getCache1hMode as F4,getCache1hPersistentMode as w4,getCacheKeepWindow as q7,getClaudeCodeIdentityForVerifiedAccount as x5,getClaudeFableMythos5ReleaseDate as f5,getClaustrumMode as T4,getDefaultCacheKeepRegistryDirectory as k5,getFallbackReauthLabels as v5,getHostClaustrumEnrollmentPaths as T9,getKillswitchConfig as $Z,getPersistedLogLevel as JZ,getQuotaCheckIntervalMs as M7,getQuotaNextRefreshAt as F1,getRequestGzipLatch as h5,getRequestGzipLatchPath as b5,getRoutingMode as e$,getScopedQuotaWindowForModel as g5,getThinkingPrefixMismatchBehavior as y5,inspectNativeHostAuthEntry as m5,isApiKeyAccount as c1,isCache1hEnabled as S4,isCache1hPersistentlyEnabled as S9,isCacheKeepAlways as I7,isCacheKeepHybridActive as x7,isCacheKeepPersistentlyEnabled as c5,isCacheKeepSubagentsEnabled as p5,isClaudeFable51Model as l5,isClaudeFableOrMythos51Model as V8,isClaudeHaiku55Model as u5,isClaudeOpus5FamilyModel as d5,isClaudeOpus5Model as i5,isClaudeOpus55Model as n5,isClaudeSonnet55Model as o5,isCostZeroingEnabled as r5,isCustodyTombstoneOAuth as ZZ,isDumpPersistentlyEnabled as WZ,isFastModeEnabled as XZ,isFastModePersistentlyEnabled as YZ,isFastModeSupportedModel as f7,isKillswitchEnabled as r$,isNativeTransientAccountError as w1,isOAuthAccount as B0,isPermanentRefreshError as s$,isPrimePersistentlyEnabled as E9,isQuotaBearingHeaderFrame as s5,isValidApiBaseURL as GZ,killswitchPassesPolicy as a$,killswitchRetryAfterSeconds as k7,log as y$,logger as h,mergeAnthropicBetas as v7,mergeHeaderQuotaForPersistence as h7,NativeCustodyError as a5,NativeRuntimeError as t5,NativeVaultNoAccountError as VZ,nativeAccountCanServe as y0,nativeLocalQuotaLineage as e5,nativeMigrationAuthorityPhase as b7,normalizeQuotaHeaders as $G,oauthProfileIsFresh as C9,oauthProfileMatchesIdentity as JG,PARALLEL_TOOL_CALLS_SYSTEM_PROMPT as ZG,PrimeManager as WG,parseAccountCommandAction as XG,parseCache1hCommandAction as YG,parseCacheKeepCommandAction as GG,parseDumpCommandAction as VG,parseFastModeCommandAction as KG,parseLaneStartCommandAction as zG,parseLoggingCommandAction as OG,parsePrimeCommandAction as jG,parseRoutingCommandAction as _G,parseSseFrame as LG,QUOTA_HEADER_FEED_SCHEMA_VERSION as P9,QuotaHeaderFeedRegistry as NG,QuotaManager as HG,quotaSnapshotCheckedAt as T1,quotaSnapshotHasStandardWindows as KZ,quotaSnapshotModelScopeIsExhausted as A9,quotaSnapshotPassesModelScope as R9,quotaSnapshotPassesPolicy as p1,readClaustrumEnrollmentStatus as g7,readNativeAccountsForRequest as DG,readNativeEnrollmentMode as S1,readNativeHostAuthKind as UG,readNativeMigrationJournal as y7,refreshBackoffActive as E1,remapRequestBodyModel as QG,resetClaustrumEnrollmentState as BG,resolveNativePoolPaths as FG,STICKY_ROUTING_MAIN_ACCOUNT_ID as W$,StickySessionRouter as wG,sendViaRelay as TG,sendWithRequestGzip as SG,setCache1hState as q9,setDumpEnabled as zZ,setFastModeEnabled as OZ,setLogLevel as EG,shouldFallbackStatus as CG,snapshotHasServableLocalOAuth as m7,stickyQuotaSnapshotIsFresh as C1,stickyRouteFamilyForModel as PG,TrailingAssistantHistoryError as c7,tokenFingerprint as t$}from"@cortexkit/anthropic-auth-core";import{randomUUID as rZ}from"node:crypto";import{isValidAnthropicRequestId as sZ,isValidBillingPromptId as a8}from"@cortexkit/anthropic-auth-core";var Y4="x-cortexkit-billing-lineage",t8=4096,e8=4096,$W=1024,aZ=new Set(["title","summary","compaction"]),JW="[lane start] — automated cache warm; no response needed.";function ZW($){let J=$.info?.sessionID??$.info?.sessionId;return typeof J==="string"&&J.length>0?J:void 0}function WW($){if($.info?.synthetic===!0||$.info?.ignored===!0||typeof $.info?.agent==="string"&&aZ.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===JW)return!0}return!1}function Q1($,J){while($.size>J){let W=$.keys().next().value;if(W===void 0)return;$.delete(W)}}function _J($){let J=$.get("request-id")??$.get("x-request-id");return J&&sZ(J)?J:void 0}class LJ{#$;#j;#z;#_;#X;#J=new Map;#W=new Map;#Z=new Map;#Y=new Map;#G=new Map;#V=new Map;#K=new Map;constructor($={}){this.#$=$.createPromptId??rZ,this.#j=$.createRequestToken??rZ,this.#z=$.maxPrompts??t8,this.#_=$.maxRequests??e8,this.#X=$.maxSessions??$W}observeMessages($){let J;for(let H=$.length-1;H>=0;H-=1)if($[H]?.info?.role==="user"){J=$[H];break}if(!J)return;let W=ZW(J),X=J.info?.id;if(!W||typeof X!=="string"||X.length===0)return;let V=this.#O(W,X);if(WW(J)){this.#W.delete(V),this.#W.set(V,!0),Q1(this.#W,this.#z),this.#J.delete(V);return}this.#W.delete(V);let O=this.#J.get(V);if(O){this.#J.delete(V),this.#J.set(V,O);return}let z=this.#$();if(!a8(z))return;this.#J.set(V,z),Q1(this.#J,this.#z)}markHeaders($){let J=this.#O($.sessionId,$.messageId);if(aZ.has($.agent??"")||this.#W.has(J))return!1;let W=this.#J.get(J);if(!W)return!1;let X=this.#j();if(!X||/[\r\n]/.test(X))return!1;let V={sessionId:$.sessionId,messageId:$.messageId,promptId:W,requestToken:X,generation:this.#G.get($.sessionId)??0,sequence:0};return this.#Z.set(X,V),Q1(this.#Z,this.#_),$.headers[Y4]=X,!0}resolveHeader($){if(!$)return;let J=this.#Z.get($);if(!J)return;this.#Z.delete($),this.#Z.set($,J);let W=(this.#V.get(J.sessionId)??0)+1;this.#V.delete(J.sessionId),this.#V.set(J.sessionId,W),Q1(this.#V,this.#X);let X={...J,previousRequestId:this.#Y.get(J.sessionId),sequence:W};if(X.previousRequestId===void 0)delete X.previousRequestId;return X}commit($,J){if(!$||!J||!sZ(J))return!1;if((this.#G.get($.sessionId)??0)!==$.generation)return!1;let W=this.#Z.get($.requestToken);if(!W||W.sessionId!==$.sessionId||W.messageId!==$.messageId||W.promptId!==$.promptId||W.generation!==$.generation)return!1;if(this.#J.get(this.#O($.sessionId,$.messageId))!==$.promptId)return!1;if($.sequence<(this.#K.get($.sessionId)??0))return!1;return this.#K.delete($.sessionId),this.#K.set($.sessionId,$.sequence),Q1(this.#K,this.#X),this.#Y.delete($.sessionId),this.#Y.set($.sessionId,J),Q1(this.#Y,this.#X),!0}clearSession($){this.#G.set($,(this.#G.get($)??0)+1),this.#Y.delete($),this.#V.delete($),this.#K.delete($);let J=`${$}\x00`;for(let W of this.#J.keys())if(W.startsWith(J))this.#J.delete(W);for(let W of this.#W.keys())if(W.startsWith(J))this.#W.delete(W);for(let[W,X]of this.#Z)if(X.sessionId===$)this.#Z.delete(W);Q1(this.#G,this.#X)}#O($,J){return`${$}\x00${J}`}}import{setBounded as eZ,stickyRetryAfterWithJitter as XW}from"@cortexkit/anthropic-auth-core";var V4="cache-diagnosis-2026-04-07",YW="MC-CACHE-DIAG ",GW=1000,VW=300000,KW={turn:!1,start:!0,prewarm_cachekeep:!0},zW=1000;class NJ{entries=new Map;previousFor($){return this.entries.get($)??null}capture($,J,W){eZ(this.entries,$,{messageId:J,receivedAt:W},GW)}}class HJ{hashes=new Map;capture($,J){if(this.hashes.has($))return null;return eZ(this.hashes,$,!0,zW),`MC-CACHE-DIAG-BETAS ${JSON.stringify({hash:$,betas:[...J].sort()})}`}}function n4($,J,W){let X=$.get(J);if(X)$.set(W,X)}async function DJ($,J,W,X,V){let O=new Headers($.headers);if(O.set("retry-after",String(XW(J,W))),X)return await $.body?.cancel().catch(()=>{}),O.set("content-type","application/json"),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account five-hour quota resets shortly; retaining session affinity."}}),{status:429,headers:O});let z=new Response($.body,{status:$.status,statusText:$.statusText,headers:O});return n4(V,$,z),z}function o4($,J){$.diagnostics={previous_message_id:J}}function d$($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function OW($){return d$($)&&$.type==="ephemeral"}function $3($,J){if(!OW($))return;J.push($.ttl==="1h"?"1h":"5m")}function tZ($,J){if(!Array.isArray($))return;for(let W of $)if(d$(W))$3(W.cache_control,J)}function r4($){if(!d$($))return null;let J=[];if($3($.cache_control,J),tZ($.system,J),Array.isArray($.messages)){for(let W of $.messages)if(d$(W))tZ(W.content,J)}return J.at(-1)??null}function jW($){if(!Object.hasOwn($,"diagnostics"))return{state:"absent"};let J=$.diagnostics;if(J===null)return{state:"server_null"};if(!d$(J))return null;if(!Object.hasOwn(J,"cache_miss_reason"))return null;let W=J.cache_miss_reason;if(W===null)return{state:"pending"};if(!d$(W)||typeof W.type!=="string"||!W.type)return null;let X=W.cache_missed_input_tokens;if(X!==void 0&&typeof X!=="number")return null;return{state:"populated",missReason:W.type,cacheMissedInputTokens:X}}function G4($,J){let W=$[J];return typeof W==="number"&&Number.isFinite(W)&&W>=0?W:null}function J3($){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=KW[$.source];if(J!==void 0&&J!==$.synthetic)$.onWarning?.(`cache diagnostics source/synthetic mismatch: source=${$.source} expected=${J} actual=${$.synthetic}`);let W=Math.trunc($.receivedAt);if(!Number.isFinite($.receivedAt)||W!==$.receivedAt)return{};if(!d$($.message))return{};let X=$.message.id,V=$.message.model,O=$.message.usage;if(typeof X!=="string"||X.length===0)return{};if(typeof V!=="string"||V.length===0||!d$(O))return{};let z=G4(O,"input_tokens"),H=G4(O,"cache_read_input_tokens"),w=G4(O,"cache_creation_input_tokens"),R=O.cache_creation;if(z===null||H===null||w===null||!d$(R))return{};let A=G4(R,"ephemeral_5m_input_tokens"),c=G4(R,"ephemeral_1h_input_tokens");if(A===null||c===null)return{};let a=jW($.message);if(!a)return{};let u={v:2,source:$.source,account_id:$.accountId,synthetic:$.synthetic,betas_hash:$.betasHash,session_id:$.request.sessionId,ts_ms_received:W,model:V,is_subagent:$.request.isSubagent,ttl_sent:$.request.ttlSent,cache_read:H,cache_creation:w,input_tokens:z,ephemeral_5m_tokens:A,ephemeral_1h_tokens:c,message_id:X,previous_message_id:$.request.previousMessageId,diag_state:a.state};if(a.missReason!==void 0)u.miss_reason=a.missReason;if(a.cacheMissedInputTokens!==void 0)u.cache_missed_input_tokens=a.cacheMissedInputTokens;if($.requestedModel!==void 0&&$.requestedModel!==V)u.requested_model=$.requestedModel;let s=a.missReason==="previous_message_not_found"&&$.request.previousMessageId!==null&&$.request.previousMessageReceivedAt!==void 0&&$.receivedAt-$.request.previousMessageReceivedAt<VW&&$.receivedAt>=$.request.previousMessageReceivedAt?{messageId:X,previousMessageId:$.request.previousMessageId}:void 0;return{record:u,messageId:X,...s?{canary:s}:{}}}function Z3($){return`${YW}${JSON.stringify($)}`}import{getClaustrumMode as s4,hasNoLocalCredential as UJ,isCustodyTombstoneOAuth as _W,isOAuthAccount as QJ,nativeAccountCanServe as BJ}from"@cortexkit/anthropic-auth-core";function K4($,J){if(s4(J)!=="claustrum"||!J?.claustrum?.scopedRoster)return!1;let W=J.accounts.find((X)=>X.id===$);return Boolean(W&&QJ(W)&&BJ(W)&&W.claustrumScopedCredentialId&&W.anthropicAccountUuid&&UJ(W))}function W3($){if(s4($)!=="claustrum")return{fallbacks:"R",evidence:"V"};if(!$?.claustrum?.scopedRoster)return{fallbacks:"M",evidence:"N"};return{fallbacks:$.accounts.filter((W)=>BJ(W)&&QJ(W)).every((W)=>Boolean(W.claustrumScopedCredentialId&&W.anthropicAccountUuid&&UJ(W)))?"T":"R",evidence:"V"}}function FJ($){if(_W($,"anthropic"))return"T";if($.type==="oauth"&&$.access&&$.refresh)return"R";return"X"}function wJ($,J){if($.role==="main"){if(s4(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 BJ(X)?"on-vault-served":"on-cold"}if(s4(J)!=="claustrum")return"off";let W=J?.accounts.find((X)=>X.id===$.id);if(!W||!QJ(W)||!W.claustrumScopedCredentialId||!W.anthropicAccountUuid||!UJ(W))return"off";if(W.claustrumScopedState==="needs_reauth")return"on-vault-reauth";return K4($.id,J)?"on-vault-served":"on-cold"}class z4 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 X3($){if($.authority!=="committed"&&$.authority!=="retired")throw new z4("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 z4("FAIL_CLOSED",$)}import{createHash as LW}from"node:crypto";import{defaultAdaptiveEffort as NW,isClaudeFable51Model as SJ,isClaudeOpus55Model as HW,isClaudeSonnet55Model as DW,normalizeAdaptiveEffort as UW,supportsPerMessageEffort as QW}from"@cortexkit/anthropic-auth-core";var z3=512,BW=1024,FW=4096,O4=32,j4=32,t4="[A-Za-z0-9_-]{1,128}",wW="<cortexkit-internal-effort ",TW="<cortexkit-internal-effort-plan ",O3=/^\s*(?:§[0-9]+§\s*)+$/,_4={low:"l",medium:"m",high:"h",xhigh:"x",max:"z"},CJ=Object.fromEntries(Object.entries(_4).map(([$,J])=>[J,$])),PJ="<cortexkit-internal-effort-v2 ",AJ="<cortexkit-internal-effort-anchor-v1 ",v1="x-cortexkit-effort-plan";class S0 extends Error{check;details;constructor($,J="unspecified",W={}){super($);this.check=J;this.details=W;this.name="EffortMarkerCorrelationError"}}function o0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function SW($){if(SJ($))return"fable-5-1";if(HW($))return"opus-5-5";if(DW($))return"sonnet-5-5";return}function TJ($){if($?.info?.role!=="user")return;if($.info.model?.providerID!=="anthropic")return;return SW($.info.model.modelID)}function Y3($){return UW($.info?.model?.variant)??NW($.info?.model?.modelID)}function G3($){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 O1($){return LW("sha256").update($).digest("hex")}function EW($){return O1(`scope:${$}`).slice(0,j4)}function e4($){return O1(`cortexkit-effort-v2:${$}`).slice(0,O4)}function CW($,J,W){let X=_4[W],V=`transition:${$}:${J}:${X}`;return`${PJ}scope="${$}" boundary="${J}" effort="${X}" check="${e4(V)}"/>`}function j3($){let J=$.match(new RegExp(`^${PJ}scope="([0-9a-f]{${j4}})" boundary="(${t4})" effort="([lmhxz])" check="([0-9a-f]{${O4}})"/>$`));if(!J)return null;let[,W,X,V,O]=J,z=CJ[V??""];if(!W||!X||!V||!O||!z)return null;let H=`transition:${W}:${X}:${V}`;if(e4(H)!==O)return null;return{scope:W,boundary:X,effort:z,token:$}}function PW($,J,W,X){let V=_4[W],O=`anchor:${$}:${J}:${V}:${X}`;return`${AJ}scope="${$}" boundary="${J}" effort="${V}" digest="${X}" check="${e4(O)}"/>`}function _3($){let J=$.match(new RegExp(`^${AJ}scope="([0-9a-f]{${j4}})" boundary="(${t4})" effort="([lmhxz])" digest="([0-9a-f]{64})" check="([0-9a-f]{${O4}})"/>$`));if(!J)return null;let[,W,X,V,O,z]=J,H=CJ[V??""];if(!W||!X||!V||!O||!z||!H)return null;let w=`anchor:${W}:${X}:${V}:${O}`;if(e4(w)!==z)return null;return{scope:W,boundary:X,effort:H,digest:O,token:$}}function EJ($){return $.trim()===""||O3.test($)}function V3(){return new RegExp(`(?:${TW}nonce="[^"]+" baseline="[^"]+" count="[^"]+" sig="[0-9a-f]+"/>|${wW}nonce="[^"]+" effort="[^"]+" sig="[0-9a-f]+"/>)`,"g")}function AW(){return new RegExp(`${PJ}scope="[0-9a-f]{${j4}}" boundary="${t4}" effort="[lmhxz]" check="[0-9a-f]{${O4}}"/>`,"g")}function RW(){return new RegExp(`${AJ}scope="[0-9a-f]{${j4}}" boundary="${t4}" effort="[lmhxz]" digest="[0-9a-f]{64}" check="[0-9a-f]{${O4}}"/>`,"g")}function L3($,J,W){let X=0,V=$,O=$.replace(V3(),"");if(O!==$&&O3.test(O))X+=[...$.matchAll(V3())].length,V=O;return V=V.replace(AW(),(z)=>{let H=j3(z);if(!H)return z;return J?.(H),X++,""}),V=V.replace(RW(),(z)=>{let H=_3(z);if(!H)return z;return W?.(H),X++,""}),{text:V,removed:X}}function qW($){for(let J of $){if(!Array.isArray(J.parts))continue;J.parts=J.parts.flatMap((W)=>{if(W.type!=="text"||typeof W.text!=="string"||!W.text.includes("<cortexkit-internal-effort"))return[W];let X=L3(W.text);if(X.removed===0)return[W];if(EJ(X.text))return[];return W.text=X.text,[W]})}}function a4($,J,W,X,V){let O=V?`:${V}`:"",z=`plan:${$}:${_4[J]}:${W.toString(36)}${O}`;return O1([z,...X].join(`
|
|
1
|
+
import{q as J8}from"./index-6chd6jnr.js";import{s as Z8}from"./index-hazrk5c3.js";import{C as W8}from"./index-b1dvkp15.js";import{G as X8,L as M9,N as Y8,O as G8}from"./index-xbwa4x53.js";import{fa as y3}from"./index-ppdrzs41.js";import{randomUUID as iJ}from"node:crypto";import{existsSync as rY}from"node:fs";import{acquireNativeAccountRuntime as sY,applyCustomHeaders as U7,assertNotCustodyTombstone as aY,authorize as Q7,buildAccountList as g$,buildClaudeQuotaSummary as tY,buildFallbackQuotaSummaries as eY,buildPrimeRequestBody as $5,CACHE_KEEP_EXTENDED_TTL_BETA as J5,CacheKeepManager as Z5,CacheKeepSessionRegistry as W5,CLAUDE_FABLE_MYTHOS_5_1_PRICING as X5,CLAUDE_FABLE_MYTHOS_5_CONTEXT_WINDOW as Y5,CLAUDE_FABLE_MYTHOS_5_MAX_OUTPUT_TOKENS as G5,CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS as V5,CLAUDE_FABLE_MYTHOS_5_PRICING as K5,CLAUDE_HAIKU_4_5_MODEL_ID as B7,CLAUDE_HAIKU_5_5_CONTEXT_WINDOW as z5,CLAUDE_HAIKU_5_5_LONG_CONTEXT_PRICING as L9,CLAUDE_HAIKU_5_5_LONG_CONTEXT_THRESHOLD as O5,CLAUDE_HAIKU_5_5_MAX_OUTPUT_TOKENS as j5,CLAUDE_HAIKU_5_5_MODEL_ID as N9,CLAUDE_HAIKU_5_5_PRICING as H9,CLAUDE_HAIKU_5_5_RELEASE_DATE as _5,CLAUDE_OPUS_5_5_CONTEXT_WINDOW as L5,CLAUDE_OPUS_5_5_MAX_OUTPUT_TOKENS as N5,CLAUDE_OPUS_5_5_MODEL_ID as D9,CLAUDE_OPUS_5_5_PRICING as U9,CLAUDE_OPUS_5_5_RELEASE_DATE as H5,CLAUDE_SONNET_5_5_CONTEXT_WINDOW as D5,CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS as U5,CLAUDE_SONNET_5_5_MODEL_ID as Q9,CLAUDE_SONNET_5_5_PRICING as B9,CLAUDE_SONNET_5_5_RELEASE_DATE as Q5,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as nJ,computeXxhash64Hex as B5,configuredAnthropicOAuthAccountCount as F5,createEmptyStorage as o$,createNativeUsagePublisher as w5,createProviderErrorResponseScope as F9,createSseFramer as T5,createStickyNoRouteResponse as S5,custodyTombstoneOAuth as oJ,decideStickyQuotaFailure as rJ,decodeSseFrame as E5,detectClaustrumConnection as F7,dumpDirectRequest as w9,dumpResponseArtifact as sJ,effectiveRelayStatus as C5,exchange as aJ,executeAccountCommand as P5,executeCache1hCommand as tJ,executeCacheKeepCommand as A5,executeDumpCommand as w7,executeFastModeCommand as T7,executeKillswitchCommand as S7,executeLaneStartCommand as E7,executeLoggingCommand as C7,executePrimeCommand as R5,executeRoutingCommand as P7,FALLBACK_BACKGROUND_TICK_MS as q5,fallbackAccountUuidForLineage as M5,formatEnrollmentStatus as A7,formatNativeAccountState as eJ,formatOAuthAccountTier as B4,formatQuotaBackoffMessage as R7,formatRefreshBackoffMessage as I5,getAccountStoragePath as x5,getCache1hMode as F4,getCache1hPersistentMode as w4,getCacheKeepWindow as q7,getClaudeCodeIdentityForVerifiedAccount as f5,getClaudeFableMythos5ReleaseDate as k5,getClaustrumMode as T4,getDefaultCacheKeepRegistryDirectory as v5,getFallbackReauthLabels as h5,getHostClaustrumEnrollmentPaths as T9,getKillswitchConfig as $Z,getPersistedLogLevel as JZ,getQuotaCheckIntervalMs as M7,getQuotaNextRefreshAt as F1,getRequestGzipLatch as b5,getRequestGzipLatchPath as g5,getRoutingMode as e$,getScopedQuotaWindowForModel as y5,getThinkingPrefixMismatchBehavior as m5,inspectNativeHostAuthEntry as c5,isApiKeyAccount as c1,isCache1hEnabled as S4,isCache1hPersistentlyEnabled as S9,isCacheKeepAlways as I7,isCacheKeepHybridActive as x7,isCacheKeepPersistentlyEnabled as p5,isCacheKeepSubagentsEnabled as l5,isClaudeFable51Model as u5,isClaudeFableOrMythos51Model as V8,isClaudeHaiku55Model as d5,isClaudeOpus5FamilyModel as i5,isClaudeOpus5Model as n5,isClaudeOpus55Model as o5,isClaudeSonnet55Model as r5,isCostZeroingEnabled as s5,isCustodyTombstoneOAuth as ZZ,isDumpPersistentlyEnabled as WZ,isFastModeEnabled as XZ,isFastModePersistentlyEnabled as YZ,isFastModeSupportedModel as f7,isKillswitchEnabled as r$,isNativeTransientAccountError as w1,isOAuthAccount as B0,isPermanentRefreshError as s$,isPrimePersistentlyEnabled as E9,isQuotaBearingHeaderFrame as a5,isValidApiBaseURL as GZ,killswitchPassesPolicy as a$,killswitchRetryAfterSeconds as k7,log as y$,logger as h,mergeAnthropicBetas as v7,mergeHeaderQuotaForPersistence as h7,NativeCustodyError as t5,NativeRuntimeError as e5,NativeVaultNoAccountError as VZ,nativeAccountCanServe as y0,nativeLocalQuotaLineage as $G,nativeMigrationAuthorityPhase as b7,normalizeQuotaHeaders as JG,oauthProfileIsFresh as C9,oauthProfileMatchesIdentity as ZG,PARALLEL_TOOL_CALLS_SYSTEM_PROMPT as WG,PrimeManager as XG,parseAccountCommandAction as YG,parseCache1hCommandAction as GG,parseCacheKeepCommandAction as VG,parseDumpCommandAction as KG,parseFastModeCommandAction as zG,parseLaneStartCommandAction as OG,parseLoggingCommandAction as jG,parsePrimeCommandAction as _G,parseRoutingCommandAction as LG,parseSseFrame as NG,QUOTA_HEADER_FEED_SCHEMA_VERSION as P9,QuotaHeaderFeedRegistry as HG,QuotaManager as DG,quotaSnapshotCheckedAt as T1,quotaSnapshotHasStandardWindows as KZ,quotaSnapshotModelScopeIsExhausted as A9,quotaSnapshotPassesModelScope as R9,quotaSnapshotPassesPolicy as p1,readClaustrumEnrollmentStatus as g7,readNativeAccountsForRequest as UG,readNativeEnrollmentMode as S1,readNativeHostAuthKind as QG,readNativeMigrationJournal as y7,refreshBackoffActive as E1,remapRequestBodyModel as BG,resetClaustrumEnrollmentState as FG,resolveNativePoolPaths as wG,STICKY_ROUTING_MAIN_ACCOUNT_ID as W$,StickySessionRouter as TG,sendViaRelay as SG,sendWithRequestGzip as EG,setCache1hState as q9,setDumpEnabled as zZ,setFastModeEnabled as OZ,setLogLevel as CG,shouldFallbackStatus as PG,snapshotHasServableLocalOAuth as m7,stickyQuotaSnapshotIsFresh as C1,stickyRouteFamilyForModel as AG,TrailingAssistantHistoryError as c7,tokenFingerprint as t$}from"@cortexkit/anthropic-auth-core";import{randomUUID as rZ}from"node:crypto";import{isValidAnthropicRequestId as sZ,isValidBillingPromptId as a8}from"@cortexkit/anthropic-auth-core";var Y4="x-cortexkit-billing-lineage",t8=4096,e8=4096,$W=1024,aZ=new Set(["title","summary","compaction"]),JW="[lane start] — automated cache warm; no response needed.";function ZW($){let J=$.info?.sessionID??$.info?.sessionId;return typeof J==="string"&&J.length>0?J:void 0}function WW($){if($.info?.synthetic===!0||$.info?.ignored===!0||typeof $.info?.agent==="string"&&aZ.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===JW)return!0}return!1}function Q1($,J){while($.size>J){let W=$.keys().next().value;if(W===void 0)return;$.delete(W)}}function _J($){let J=$.get("request-id")??$.get("x-request-id");return J&&sZ(J)?J:void 0}class LJ{#$;#j;#z;#_;#X;#J=new Map;#W=new Map;#Z=new Map;#Y=new Map;#G=new Map;#V=new Map;#K=new Map;constructor($={}){this.#$=$.createPromptId??rZ,this.#j=$.createRequestToken??rZ,this.#z=$.maxPrompts??t8,this.#_=$.maxRequests??e8,this.#X=$.maxSessions??$W}observeMessages($){let J;for(let H=$.length-1;H>=0;H-=1)if($[H]?.info?.role==="user"){J=$[H];break}if(!J)return;let W=ZW(J),X=J.info?.id;if(!W||typeof X!=="string"||X.length===0)return;let V=this.#O(W,X);if(WW(J)){this.#W.delete(V),this.#W.set(V,!0),Q1(this.#W,this.#z),this.#J.delete(V);return}this.#W.delete(V);let O=this.#J.get(V);if(O){this.#J.delete(V),this.#J.set(V,O);return}let z=this.#$();if(!a8(z))return;this.#J.set(V,z),Q1(this.#J,this.#z)}markHeaders($){let J=this.#O($.sessionId,$.messageId);if(aZ.has($.agent??"")||this.#W.has(J))return!1;let W=this.#J.get(J);if(!W)return!1;let X=this.#j();if(!X||/[\r\n]/.test(X))return!1;let V={sessionId:$.sessionId,messageId:$.messageId,promptId:W,requestToken:X,generation:this.#G.get($.sessionId)??0,sequence:0};return this.#Z.set(X,V),Q1(this.#Z,this.#_),$.headers[Y4]=X,!0}resolveHeader($){if(!$)return;let J=this.#Z.get($);if(!J)return;this.#Z.delete($),this.#Z.set($,J);let W=(this.#V.get(J.sessionId)??0)+1;this.#V.delete(J.sessionId),this.#V.set(J.sessionId,W),Q1(this.#V,this.#X);let X={...J,previousRequestId:this.#Y.get(J.sessionId),sequence:W};if(X.previousRequestId===void 0)delete X.previousRequestId;return X}commit($,J){if(!$||!J||!sZ(J))return!1;if((this.#G.get($.sessionId)??0)!==$.generation)return!1;let W=this.#Z.get($.requestToken);if(!W||W.sessionId!==$.sessionId||W.messageId!==$.messageId||W.promptId!==$.promptId||W.generation!==$.generation)return!1;if(this.#J.get(this.#O($.sessionId,$.messageId))!==$.promptId)return!1;if($.sequence<(this.#K.get($.sessionId)??0))return!1;return this.#K.delete($.sessionId),this.#K.set($.sessionId,$.sequence),Q1(this.#K,this.#X),this.#Y.delete($.sessionId),this.#Y.set($.sessionId,J),Q1(this.#Y,this.#X),!0}clearSession($){this.#G.set($,(this.#G.get($)??0)+1),this.#Y.delete($),this.#V.delete($),this.#K.delete($);let J=`${$}\x00`;for(let W of this.#J.keys())if(W.startsWith(J))this.#J.delete(W);for(let W of this.#W.keys())if(W.startsWith(J))this.#W.delete(W);for(let[W,X]of this.#Z)if(X.sessionId===$)this.#Z.delete(W);Q1(this.#G,this.#X)}#O($,J){return`${$}\x00${J}`}}import{setBounded as eZ,stickyRetryAfterWithJitter as XW}from"@cortexkit/anthropic-auth-core";var V4="cache-diagnosis-2026-04-07",YW="MC-CACHE-DIAG ",GW=1000,VW=300000,KW={turn:!1,start:!0,prewarm_cachekeep:!0},zW=1000;class NJ{entries=new Map;previousFor($){return this.entries.get($)??null}capture($,J,W){eZ(this.entries,$,{messageId:J,receivedAt:W},GW)}}class HJ{hashes=new Map;capture($,J){if(this.hashes.has($))return null;return eZ(this.hashes,$,!0,zW),`MC-CACHE-DIAG-BETAS ${JSON.stringify({hash:$,betas:[...J].sort()})}`}}function n4($,J,W){let X=$.get(J);if(X)$.set(W,X)}async function DJ($,J,W,X,V){let O=new Headers($.headers);if(O.set("retry-after",String(XW(J,W))),X)return await $.body?.cancel().catch(()=>{}),O.set("content-type","application/json"),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account five-hour quota resets shortly; retaining session affinity."}}),{status:429,headers:O});let z=new Response($.body,{status:$.status,statusText:$.statusText,headers:O});return n4(V,$,z),z}function o4($,J){$.diagnostics={previous_message_id:J}}function d$($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function OW($){return d$($)&&$.type==="ephemeral"}function $3($,J){if(!OW($))return;J.push($.ttl==="1h"?"1h":"5m")}function tZ($,J){if(!Array.isArray($))return;for(let W of $)if(d$(W))$3(W.cache_control,J)}function r4($){if(!d$($))return null;let J=[];if($3($.cache_control,J),tZ($.system,J),Array.isArray($.messages)){for(let W of $.messages)if(d$(W))tZ(W.content,J)}return J.at(-1)??null}function jW($){if(!Object.hasOwn($,"diagnostics"))return{state:"absent"};let J=$.diagnostics;if(J===null)return{state:"server_null"};if(!d$(J))return null;if(!Object.hasOwn(J,"cache_miss_reason"))return null;let W=J.cache_miss_reason;if(W===null)return{state:"pending"};if(!d$(W)||typeof W.type!=="string"||!W.type)return null;let X=W.cache_missed_input_tokens;if(X!==void 0&&typeof X!=="number")return null;return{state:"populated",missReason:W.type,cacheMissedInputTokens:X}}function G4($,J){let W=$[J];return typeof W==="number"&&Number.isFinite(W)&&W>=0?W:null}function J3($){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=KW[$.source];if(J!==void 0&&J!==$.synthetic)$.onWarning?.(`cache diagnostics source/synthetic mismatch: source=${$.source} expected=${J} actual=${$.synthetic}`);let W=Math.trunc($.receivedAt);if(!Number.isFinite($.receivedAt)||W!==$.receivedAt)return{};if(!d$($.message))return{};let X=$.message.id,V=$.message.model,O=$.message.usage;if(typeof X!=="string"||X.length===0)return{};if(typeof V!=="string"||V.length===0||!d$(O))return{};let z=G4(O,"input_tokens"),H=G4(O,"cache_read_input_tokens"),w=G4(O,"cache_creation_input_tokens"),R=O.cache_creation;if(z===null||H===null||w===null||!d$(R))return{};let A=G4(R,"ephemeral_5m_input_tokens"),c=G4(R,"ephemeral_1h_input_tokens");if(A===null||c===null)return{};let a=jW($.message);if(!a)return{};let u={v:2,source:$.source,account_id:$.accountId,synthetic:$.synthetic,betas_hash:$.betasHash,session_id:$.request.sessionId,ts_ms_received:W,model:V,is_subagent:$.request.isSubagent,ttl_sent:$.request.ttlSent,cache_read:H,cache_creation:w,input_tokens:z,ephemeral_5m_tokens:A,ephemeral_1h_tokens:c,message_id:X,previous_message_id:$.request.previousMessageId,diag_state:a.state};if(a.missReason!==void 0)u.miss_reason=a.missReason;if(a.cacheMissedInputTokens!==void 0)u.cache_missed_input_tokens=a.cacheMissedInputTokens;if($.requestedModel!==void 0&&$.requestedModel!==V)u.requested_model=$.requestedModel;let s=a.missReason==="previous_message_not_found"&&$.request.previousMessageId!==null&&$.request.previousMessageReceivedAt!==void 0&&$.receivedAt-$.request.previousMessageReceivedAt<VW&&$.receivedAt>=$.request.previousMessageReceivedAt?{messageId:X,previousMessageId:$.request.previousMessageId}:void 0;return{record:u,messageId:X,...s?{canary:s}:{}}}function Z3($){return`${YW}${JSON.stringify($)}`}import{getClaustrumMode as s4,hasNoLocalCredential as UJ,isCustodyTombstoneOAuth as _W,isOAuthAccount as QJ,nativeAccountCanServe as BJ}from"@cortexkit/anthropic-auth-core";function K4($,J){if(s4(J)!=="claustrum"||!J?.claustrum?.scopedRoster)return!1;let W=J.accounts.find((X)=>X.id===$);return Boolean(W&&QJ(W)&&BJ(W)&&W.claustrumScopedCredentialId&&W.anthropicAccountUuid&&UJ(W))}function W3($){if(s4($)!=="claustrum")return{fallbacks:"R",evidence:"V"};if(!$?.claustrum?.scopedRoster)return{fallbacks:"M",evidence:"N"};return{fallbacks:$.accounts.filter((W)=>BJ(W)&&QJ(W)).every((W)=>Boolean(W.claustrumScopedCredentialId&&W.anthropicAccountUuid&&UJ(W)))?"T":"R",evidence:"V"}}function FJ($){if(_W($,"anthropic"))return"T";if($.type==="oauth"&&$.access&&$.refresh)return"R";return"X"}function wJ($,J){if($.role==="main"){if(s4(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 BJ(X)?"on-vault-served":"on-cold"}if(s4(J)!=="claustrum")return"off";let W=J?.accounts.find((X)=>X.id===$.id);if(!W||!QJ(W)||!W.claustrumScopedCredentialId||!W.anthropicAccountUuid||!UJ(W))return"off";if(W.claustrumScopedState==="needs_reauth")return"on-vault-reauth";return K4($.id,J)?"on-vault-served":"on-cold"}class z4 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 X3($){if($.authority!=="committed"&&$.authority!=="retired")throw new z4("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 z4("FAIL_CLOSED",$)}import{createHash as LW}from"node:crypto";import{defaultAdaptiveEffort as NW,isClaudeFable51Model as SJ,isClaudeOpus55Model as HW,isClaudeSonnet55Model as DW,normalizeAdaptiveEffort as UW,supportsPerMessageEffort as QW}from"@cortexkit/anthropic-auth-core";var z3=512,BW=1024,FW=4096,O4=32,j4=32,t4="[A-Za-z0-9_-]{1,128}",wW="<cortexkit-internal-effort ",TW="<cortexkit-internal-effort-plan ",O3=/^\s*(?:§[0-9]+§\s*)+$/,_4={low:"l",medium:"m",high:"h",xhigh:"x",max:"z"},CJ=Object.fromEntries(Object.entries(_4).map(([$,J])=>[J,$])),PJ="<cortexkit-internal-effort-v2 ",AJ="<cortexkit-internal-effort-anchor-v1 ",v1="x-cortexkit-effort-plan";class S0 extends Error{check;details;constructor($,J="unspecified",W={}){super($);this.check=J;this.details=W;this.name="EffortMarkerCorrelationError"}}function o0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function SW($){if(SJ($))return"fable-5-1";if(HW($))return"opus-5-5";if(DW($))return"sonnet-5-5";return}function TJ($){if($?.info?.role!=="user")return;if($.info.model?.providerID!=="anthropic")return;return SW($.info.model.modelID)}function Y3($){return UW($.info?.model?.variant)??NW($.info?.model?.modelID)}function G3($){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 O1($){return LW("sha256").update($).digest("hex")}function EW($){return O1(`scope:${$}`).slice(0,j4)}function e4($){return O1(`cortexkit-effort-v2:${$}`).slice(0,O4)}function CW($,J,W){let X=_4[W],V=`transition:${$}:${J}:${X}`;return`${PJ}scope="${$}" boundary="${J}" effort="${X}" check="${e4(V)}"/>`}function j3($){let J=$.match(new RegExp(`^${PJ}scope="([0-9a-f]{${j4}})" boundary="(${t4})" effort="([lmhxz])" check="([0-9a-f]{${O4}})"/>$`));if(!J)return null;let[,W,X,V,O]=J,z=CJ[V??""];if(!W||!X||!V||!O||!z)return null;let H=`transition:${W}:${X}:${V}`;if(e4(H)!==O)return null;return{scope:W,boundary:X,effort:z,token:$}}function PW($,J,W,X){let V=_4[W],O=`anchor:${$}:${J}:${V}:${X}`;return`${AJ}scope="${$}" boundary="${J}" effort="${V}" digest="${X}" check="${e4(O)}"/>`}function _3($){let J=$.match(new RegExp(`^${AJ}scope="([0-9a-f]{${j4}})" boundary="(${t4})" effort="([lmhxz])" digest="([0-9a-f]{64})" check="([0-9a-f]{${O4}})"/>$`));if(!J)return null;let[,W,X,V,O,z]=J,H=CJ[V??""];if(!W||!X||!V||!O||!z||!H)return null;let w=`anchor:${W}:${X}:${V}:${O}`;if(e4(w)!==z)return null;return{scope:W,boundary:X,effort:H,digest:O,token:$}}function EJ($){return $.trim()===""||O3.test($)}function V3(){return new RegExp(`(?:${TW}nonce="[^"]+" baseline="[^"]+" count="[^"]+" sig="[0-9a-f]+"/>|${wW}nonce="[^"]+" effort="[^"]+" sig="[0-9a-f]+"/>)`,"g")}function AW(){return new RegExp(`${PJ}scope="[0-9a-f]{${j4}}" boundary="${t4}" effort="[lmhxz]" check="[0-9a-f]{${O4}}"/>`,"g")}function RW(){return new RegExp(`${AJ}scope="[0-9a-f]{${j4}}" boundary="${t4}" effort="[lmhxz]" digest="[0-9a-f]{64}" check="[0-9a-f]{${O4}}"/>`,"g")}function L3($,J,W){let X=0,V=$,O=$.replace(V3(),"");if(O!==$&&O3.test(O))X+=[...$.matchAll(V3())].length,V=O;return V=V.replace(AW(),(z)=>{let H=j3(z);if(!H)return z;return J?.(H),X++,""}),V=V.replace(RW(),(z)=>{let H=_3(z);if(!H)return z;return W?.(H),X++,""}),{text:V,removed:X}}function qW($){for(let J of $){if(!Array.isArray(J.parts))continue;J.parts=J.parts.flatMap((W)=>{if(W.type!=="text"||typeof W.text!=="string"||!W.text.includes("<cortexkit-internal-effort"))return[W];let X=L3(W.text);if(X.removed===0)return[W];if(EJ(X.text))return[];return W.text=X.text,[W]})}}function a4($,J,W,X,V){let O=V?`:${V}`:"",z=`plan:${$}:${_4[J]}:${W.toString(36)}${O}`;return O1([z,...X].join(`
|
|
2
2
|
`))}function MW($){return["v2",$.scope,_4[$.baseline],$.markerCount.toString(36),$.digest].join(".")}function IW($){if(!$)return null;let J=$.match(/^v2\.([0-9a-f]{32})\.([lmhxz])\.([0-9a-z]+)\.([0-9a-f]{64})$/);if(!J)return null;let[,W,X,V,O]=J,z=CJ[X??""],H=Number.parseInt(V??"",36);if(!W||!z||!O||!Number.isSafeInteger(H)||H<0||H>z3)return null;return{scope:W,baseline:z,markerCount:H,digest:O}}function N3($){let J=$.findLast((u)=>u.info?.role==="user"),W=TJ(J);if(!J||!W)return null;if(qW($),!Array.isArray(J.parts)||!G3(J))return null;let X=J.info?.sessionID,V=J.info?.id;if(typeof X!=="string"||typeof V!=="string")throw new S0("Cannot correlate Fable 5.1 effort markers without session and message IDs");let O=EW(X),z=$.findLast((u)=>u.info?.role==="user"&&u.parts?.some((s)=>s.type==="compaction")),H=typeof z?.info?.id==="string"?z.info.id:void 0,w,R;if(z&&TJ(z)===W)w=Y3(z),R=w;let A=[];for(let u of $){let s=u.info;if(s?.role!=="user")continue;if(H&&typeof s.id==="string"&&s.id<=H)continue;if(TJ(u)!==W||!G3(u))continue;let T=Y3(u);if(!w){w=T,R=T;continue}if(T===R)continue;if(A.length>=z3)throw new S0("Too many Fable 5.1 effort changes in the active context");if(!Array.isArray(u.parts)||typeof s.id!=="string")throw new S0("Cannot mark a Fable 5.1 effort change without message identity");let o=CW(O,s.id,T);u.parts.push({type:"text",text:o}),A.push(o),R=T}if(!w)return null;let c=a4(O,w,A.length,A,A.length>0?V:void 0),a=A.length>0?PW(O,V,R??w,c):void 0;if(a)J.parts.push({type:"text",text:a});return{scope:O,baseline:w,markerCount:A.length,digest:c,transitionTokens:A,anchorToken:a,sessionId:X,messageId:V}}function xW($){let J=Array.isArray($.messages)?$.messages:[],W=[];for(let X of J){let V=[],O=[];if(!o0(X)||X.role!=="user"){W.push({value:X,transitions:V,anchors:O});continue}let z=(H)=>L3(H,(w)=>V.push(w),(w)=>O.push(w));if(typeof X.content==="string"){let H=z(X.content);X.content=H.removed>0&&EJ(H.text)?"":H.text}else if(Array.isArray(X.content))X.content=X.content.flatMap((H)=>{if(!o0(H)||H.type!=="text"||typeof H.text!=="string")return[H];let w=z(H.text);if(w.removed>0&&EJ(w.text))return[];return[{...H,text:w.text}]});W.push({value:X,transitions:V,anchors:O})}return $.messages=W.map((X)=>X.value),{messages:W}}function fW($,J){let W=$[J]?.value,X=$[J-1]?.value;if(!o0(W)||W.role!=="user"||!Array.isArray(W.content)||W.content.length===0||!o0(X)||X.role!=="assistant"||!Array.isArray(X.content))return!1;let V=new Set(X.content.flatMap((O)=>o0(O)&&O.type==="tool_use"&&typeof O.id==="string"?[O.id]:[]));return W.content.every((O)=>o0(O)&&O.type==="tool_result"&&typeof O.tool_use_id==="string"&&V.has(O.tool_use_id))}function kW($,J){if(J<0)return!1;let W=$.flatMap((X,V)=>V>J&&o0(X.value)&&X.value.role==="user"?[V]:[]);return W.length>0&&W.every((X)=>fW($,X))}function K3($){if(!o0($))return null;if(typeof $.id==="string")return $.id;return typeof $.message_id==="string"?$.message_id:null}function vW($,J){if(!J)return null;if(J.scope!==$.scope||J.baseline!==$.baseline||J.markerCount!==$.markerCount||J.digest!==$.digest||J.transitionTokens.length!==$.markerCount)throw new S0("Fable 5.1 effort marker request plan mismatch");let W=J.transitionTokens.map((O)=>j3(O)),X=J.anchorToken?_3(J.anchorToken):null,V=W.at(-1)?.effort??$.baseline;if(W.some((O)=>O===null)||W.some((O)=>O?.scope!==$.scope)||$.markerCount>0&&(!X||X.scope!==$.scope||X.boundary!==J.messageId||X.effort!==V||X.digest!==$.digest)||$.markerCount===0&&X!==null||$.digest!==a4($.scope,$.baseline,$.markerCount,J.transitionTokens,J.markerCount>0?J.messageId:void 0))throw new S0("Fable 5.1 effort marker request plan mismatch");return{transitions:W,anchor:X}}function H3($,J,W,X){if(!Array.isArray($.messages))return{found:0,inserted:0};let V=IW(W);if(W&&!V)throw new S0("Missing or invalid internal Fable 5.1 effort request plan");let O=V?vW(V,X):null,z=O?.transitions??null;if(!$.messages.some((b)=>{if(!o0(b)||b.role!=="user")return!1;if(typeof b.content==="string"&&b.content.includes("<cortexkit-internal-effort"))return!0;return Array.isArray(b.content)&&b.content.some((O0)=>o0(O0)&&O0.type==="text"&&typeof O0.text==="string"&&O0.text.includes("<cortexkit-internal-effort"))})){if(!V)return{found:0,inserted:0};if(V.markerCount!==0){let b=$.messages.findLastIndex((q)=>o0(q)&&q.role==="user"),O0=$.messages[b],m0=o0(O0)&&Array.isArray(O0.content)?O0.content:[];throw new S0(`Fable 5.1 effort marker correlation failed: expected ${V.markerCount}, found 0`,"missing_all_markers",{markerCount:V.markerCount,resolvedPlan:O!==null,plannedBoundaryId:O?.anchor?.boundary??null,expectedAnchorHash:O?.anchor?O1(O.anchor.token):null,retainedMessageCount:$.messages.length,retainedUserMessageCount:$.messages.filter((q)=>o0(q)&&q.role==="user").length,lastUserMessageIndex:b,lastUserTextBlockCount:m0.filter((q)=>o0(q)&&q.type==="text").length,lastUserToolResultBlockCount:m0.filter((q)=>o0(q)&&q.type==="tool_result").length})}if(!z&&V.digest!==a4(V.scope,V.baseline,0,[]))throw new S0("Fable 5.1 effort marker request plan mismatch");if(J&&SJ($.model)){let b=o0($.output_config)?{...$.output_config}:{};b.effort=z?.at(-1)?.effort??V.baseline,$.output_config=b}return{found:0,inserted:0}}let w=xW($),R=w.messages.flatMap((b)=>b.transitions),A=w.messages.flatMap((b)=>b.anchors),c=R.length;if(!V){if(c===0)return{found:0,inserted:0};throw new S0("Missing or invalid internal Fable 5.1 effort request plan")}for(let b of w.messages){for(let O0 of b.transitions)if(O0.scope!==V.scope)throw new S0("Fable 5.1 effort marker scope mismatch");if(b.anchors.length>1)throw new S0("Multiple internal Fable 5.1 effort anchors on one user boundary")}let a=w.messages.findIndex((b)=>b.anchors.length===1),u=w.messages.findLastIndex((b)=>o0(b.value)&&b.value.role==="user"),s=A[0],T=w.messages[u]?.value,o=kW(w.messages,a);if(V.markerCount>0&&(A.length!==1||a!==u&&!o||!s||s.scope!==V.scope))throw new S0("Missing or invalid internal Fable 5.1 effort anchor placement","anchor_placement",{anchorBoundaryId:s?.boundary??null,plannedBoundaryId:O?.anchor?.boundary??null,lastUserMessageId:K3(T),anchorMessageIndex:a,lastUserMessageIndex:u,validToolContinuationSuffix:o,anchorsFound:A.length,markerCount:V.markerCount,scope:V.scope,foundScope:s?.scope??null,expectedAnchorHash:O?.anchor?O1(O.anchor.token):null,foundAnchorHash:s?O1(s.token):null,anchorMatchesExpected:O?.anchor!=null&&s?.token===O.anchor.token});if(V.markerCount===0&&A.length!==0)throw new S0("Unexpected internal Fable 5.1 effort anchor");if(O?.anchor&&s?.token!==O.anchor.token)throw new S0("Mismatched internal Fable 5.1 effort anchor token","anchor_token",{anchorBoundaryId:s?.boundary??null,plannedBoundaryId:O.anchor.boundary,lastUserMessageId:K3(T),anchorMessageIndex:a,lastUserMessageIndex:u,anchorsFound:A.length,markerCount:V.markerCount,scope:V.scope,foundScope:s?.scope??null,expectedAnchorHash:O1(O.anchor.token),foundAnchorHash:s?O1(s.token):null,anchorMatchesExpected:!1});let q0=V.baseline;if(z){let b=z.length-c;if(b<0)throw new S0(`Fable 5.1 effort marker correlation failed: expected ${V.markerCount}, found ${c}`);let O0=z.slice(b);if(R.some((q,s0)=>q.token!==O0[s0]?.token))throw new S0("Fable 5.1 effort marker non-prefix loss");let m0=z.slice(0,b);if(s&&m0.some((q)=>q.boundary===s.boundary))throw new S0("Fable 5.1 effort marker non-prefix loss");q0=m0.at(-1)?.effort??V.baseline}else{if(c!==V.markerCount)throw new S0(`Fable 5.1 effort marker correlation failed: expected ${V.markerCount}, found ${c}`);let b=a4(V.scope,V.baseline,V.markerCount,R.map((m0)=>m0.token),s?.boundary);if(V.digest!==b)throw new S0("Fable 5.1 effort marker request plan mismatch");let O0=R.at(-1)?.effort??V.baseline;if(s&&(s.effort!==O0||s.digest!==V.digest))throw new S0("Missing or invalid internal Fable 5.1 effort anchor")}let G0=J&&QW($),I0=0,L0=[];for(let b of w.messages){let O0=b.transitions.at(-1);if(O0&&G0)L0.push({role:"system",content:[],output_config:{effort:O0.effort}}),I0++;L0.push(b.value)}if($.messages=L0,G0&&(I0>0||SJ($.model))){let b=o0($.output_config)?{...$.output_config}:{};b.effort=q0,$.output_config=b}return{found:c,inserted:I0}}class RJ{plans=new Map;history=new Map;historyByMessage=new Map;record($){let J=this.key($.sessionId,$.messageId),W={...$,transitionTokens:[...$.transitionTokens]};this.remember(J,W),this.plans.delete(J),this.plans.set(J,W);while(this.plans.size>BW){let X=this.plans.keys().next().value;if(typeof X!=="string")break;this.plans.delete(X)}}clear($,J){let W=this.key($,J);this.plans.delete(W);for(let X of this.historyByMessage.get(W)??[])this.history.delete(X);this.historyByMessage.delete(W)}markHeaders($){let J=this.key($.sessionId,$.messageId),W=this.plans.get(J);if(!W)return!1;return $.headers[v1]=this.remember(J,W),this.plans.delete(J),this.plans.set(J,W),!0}resolveHeader($){return $?this.history.get($):void 0}remember($,J){let W=MW(J),X=this.history.get(W);if(X&&this.key(X.sessionId,X.messageId)!==$){if(X.markerCount!==0||J.markerCount!==0||X.sessionId!==J.sessionId)throw new S0("Fable 5.1 effort plan header collision");let O=this.key(X.sessionId,X.messageId),z=this.historyByMessage.get(O);if(z?.delete(W),z?.size===0)this.historyByMessage.delete(O)}this.history.delete(W),this.history.set(W,J);let V=this.historyByMessage.get($)??new Set;V.add(W),this.historyByMessage.set($,V);while(this.history.size>FW){let O=this.history.entries().next().value;if(!O)break;let[z,H]=O;this.history.delete(z);let w=this.key(H.sessionId,H.messageId),R=this.historyByMessage.get(w);if(R?.delete(z),R?.size===0)this.historyByMessage.delete(w)}return W}key($,J){return`${$}\x00${J}`}}import{CLAUDE_FABLE_5_1_MODEL_ID as D3,CLAUDE_FABLE_5_MODEL_ID as U3,isClaudeOpus5Model as hW,isClaudeOpus55Model as bW,normalizeAnthropicModelId as gW}from"@cortexkit/anthropic-auth-core";var Q3="claude-opus-4-8",qJ=10,B3=128,yW=86400000;function h$($){if(typeof $!=="string")return null;let J=gW($);if(bW(J))return"opus-5-5";if(hW(J))return"opus-5";if(J===D3||J.startsWith(`${D3}-`))return"fable-5-1";if(J===U3||J.startsWith(`${U3}-`))return"fable-5";return null}function h1($){return h$($)!==null}function mW($,J){let W=h$(J);return W?`${$}\x00${W}`:null}function cW($){try{let J=JSON.parse($);return typeof J.model==="string"?{body:J,model:J.model}:null}catch{return null}}class MJ{now;recoveries=new Map;selectedModels=new Map;nextCycle=1;constructor($=Date.now){this.now=$}prune(){let $=this.now();for(let[J,W]of this.recoveries)if($-W.updatedAt>=yW)this.recoveries.delete(J);while(this.recoveries.size>B3){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 W=this.selectedModels.get($),X=W!==void 0&&W!==J;if(X)this.clearSession($);this.selectedModels.delete($),this.selectedModels.set($,J);while(this.selectedModels.size>B3){let V=this.selectedModels.keys().next().value;if(V===void 0)break;this.selectedModels.delete(V)}return X}plan($,J){if(!$||typeof J!=="string")return null;this.prune();for(let[O,z]of[...this.recoveries]){if(!O.startsWith(`${$}\x00`))continue;z.updatedAt=this.now(),this.recoveries.delete(O),this.recoveries.set(O,z)}let W=cW(J);if(!W||!h1(W.model))return null;let X=mW($,W.model);if(!X)return null;let V=this.recoveries.get(X);if(V)V.nextRequestSequence++;if(!V||V.remaining<=0)return{sessionId:$,recoveryKey:X,requestedModel:W.model,effectiveModel:W.model,bodyText:J,downgraded:!1,cycle:V?.cycle,standbyCacheAnchor:V?.standbyCacheAnchor};return V.updatedAt=this.now(),this.recoveries.delete(X),this.recoveries.set(X,V),W.body.model=Q3,{sessionId:$,recoveryKey:X,requestedModel:V.model,effectiveModel:Q3,bodyText:JSON.stringify(W.body),downgraded:!0,cycle:V.cycle,cacheAccountId:V.cacheAccountId,standbyCacheAnchor:V.standbyCacheAnchor,requestSequence:V.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 W=this.recoveries.get($.recoveryKey);if(!W||W.cycle!==$.cycle)return!1;if(W.cacheAccountId===J)return!1;return W.cacheAccountId=J,W.standbyCacheAnchor=void 0,W.standbyAnchorSequence=0,W.updatedAt=this.now(),$.cacheAccountId=J,$.standbyCacheAnchor=void 0,!0}activate($,J){if($.downgraded||!h1($.requestedModel))return this.remaining($);let W=this.recoveries.get($.recoveryKey),X=W&&W.sourceSuccesses<qJ?W.reRefusals+1:0,V={model:$.requestedModel,remaining:qJ*2**Math.min(X,2),reRefusals:X,sourceSuccesses:0,cycle:this.nextCycle++,cacheAccountId:J,standbyCacheAnchor:$.standbyCacheAnchor,nextRequestSequence:0,standbyAnchorSequence:0,updatedAt:this.now()};return this.recoveries.delete($.recoveryKey),this.recoveries.set($.recoveryKey,V),this.prune(),V.remaining}completeSource($,J=!0){if($.downgraded||$.cycle==null||$.completed)return!1;$.completed=!0;let W=this.recoveries.get($.recoveryKey);if(!W||W.cycle!==$.cycle||W.remaining>0)return!1;if(!J)return W.sourceSuccesses=0,!1;return W.sourceSuccesses=Math.min(W.sourceSuccesses+1,qJ),W.updatedAt=this.now(),!0}complete($,J){if(!$.downgraded||$.cycle==null||$.completed)return{counted:!1,remaining:this.remaining($)};$.completed=!0;let W=this.recoveries.get($.recoveryKey);if(!W||W.cycle!==$.cycle||W.remaining<=0)return{counted:!1,remaining:W?.remaining??0};if(W.remaining--,J&&(!W.cacheAccountId||J.oauthAccountId===W.cacheAccountId)&&$.requestSequence!=null&&$.requestSequence>=W.standbyAnchorSequence)W.standbyCacheAnchor=J,W.standbyAnchorSequence=$.requestSequence;return W.updatedAt=this.now(),this.recoveries.delete($.recoveryKey),this.recoveries.set($.recoveryKey,W),{counted:!0,remaining:W.remaining}}remaining($){return this.prune(),this.recoveries.get($.recoveryKey)?.remaining??0}}function i$($){return typeof $==="object"&&$!==null}function pW($){if(Array.isArray($))return $;if(i$($)&&Array.isArray($.data))return $.data;return[]}function T3($){if(!i$($)||!i$($.info))return;return $.info}function F3($){let J=T3($);return typeof J?.role==="string"?J.role:void 0}function lW($){let J=T3($);return typeof J?.id==="string"?J.id:void 0}function IJ($){if(!i$($)||!i$($.info))return null;let J=$.info,W=i$(J.model)?J.model:void 0,X=typeof J.agent==="string"?J.agent:void 0,V=typeof W?.providerID==="string"?W.providerID:typeof J.providerID==="string"?J.providerID:void 0,O=typeof W?.modelID==="string"?W.modelID:typeof W?.id==="string"?W.id:typeof J.modelID==="string"?J.modelID:void 0,z=typeof W?.variant==="string"?W.variant:typeof J.variant==="string"?J.variant:void 0;if(!X&&(!V||!O)&&!z)return null;let H={};if(X)H.agent=X;if(V&&O)H.model={providerID:V,modelID:O};if(z)H.variant=z;return H}function xJ($,J){return{agent:$.agent??J.agent,model:$.model??J.model,variant:$.variant??J.variant,latestAssistantMessageId:$.latestAssistantMessageId??J.latestAssistantMessageId,latestUserMessageId:$.latestUserMessageId??J.latestUserMessageId}}function w3($){return Boolean($.agent&&$.model&&$.variant)}async function $9($,J){if(!$||!J)return null;let W=$,X=[];if(typeof W.session?.messages==="function")try{X=pW(await Promise.resolve(W.session.messages({path:{id:J},query:{limit:100}})))}catch{X=[]}let V,O;for(let H of X){let w=lW(H);if(!w)continue;let R=F3(H);if(R==="assistant"&&(!V||w>V))V=w;if(R==="user"&&(!O||w>O))O=w}let z={latestAssistantMessageId:V,latestUserMessageId:O};for(let H=X.length-1;H>=0;H--){if(F3(X[H])!=="assistant")continue;let w=IJ(X[H]);if(!w)continue;if(z=xJ(z,w),w3(z))return z}for(let H=X.length-1;H>=0;H--){let w=IJ(X[H]);if(!w)continue;if(z=xJ(z,w),w3(z))return z}if(typeof W.session?.get==="function")try{let H=await Promise.resolve(W.session.get({path:{id:J}})),w=i$(H)&&i$(H.data)?H.data:i$(H)?H:void 0,R=w?IJ({info:w}):null;if(R)z=xJ(z,R)}catch{}if(!z.agent&&!z.model&&!z.variant&&!z.latestAssistantMessageId&&!z.latestUserMessageId)return null;return z}var S3="[lane start] — automated cache warm; no response needed.",J9="x-cortexkit-lane-start",uW=1000;function dW($){if(!$||typeof $!=="object")return!1;let J=$;return J.type==="text"&&J.text===S3&&J.synthetic===!0}async function E3($,J){let W=$?.session;if(typeof W?.promptAsync!=="function")throw Error("OpenCode plugin client does not support session.promptAsync");let X=await $9($,J),V={noReply:!1,parts:[{type:"text",text:S3,synthetic:!0}]};if(X?.agent)V.agent=X.agent;if(X?.model)V.model=X.model;if(X?.variant)V.variant=X.variant;await Promise.resolve(W.promptAsync({path:{id:J},body:V}))}class fJ{#$=new Map;observeSyntheticMessage($){if(!$.parts.some(dW))return!1;let J=`${$.sessionId}\x00${$.messageId}`;if(!this.#$.has(J)&&this.#$.size>=uW){let W=this.#$.keys().next().value;if(W!==void 0)this.#$.delete(W)}return this.#$.set(J,$.sessionId),!0}markHeaders($){let J=`${$.sessionId}\x00${$.messageId}`;if(!this.#$.has(J))return!1;return this.#$.delete(J),$.headers[J9]="1",!0}clearSession($){for(let[J,W]of this.#$)if(W===$)this.#$.delete(J)}}import{createNativeUi as iW,disconnectNativeVaultForHost as nW,readNativeEnrollmentMode as oW}from"@cortexkit/anthropic-auth-core";function C3($){if(!$?.trim())throw TypeError("sessionId is required");return $}function P3($){if($.host!=="opencode")throw TypeError("OpenCode host is required");let J=iW({...$,readMode:$.readMode??(()=>oW("opencode",process.env)),disconnectVault:$.disconnectVault??(()=>nW({host:"opencode",env:process.env}))});return{menu:J,open(W){return J.open({sessionId:C3(W),notify(){}})},apply(W){return J.apply(W,{sessionId:C3(W.sessionId),notify(){}})}}}import{primeStorageFingerprint as rW}from"@cortexkit/anthropic-auth-core";var Z9=new Map,W9=new Map;function A3($,J){let W=W9.get($);if(W?.fingerprint!==J.fingerprint||W.marker!==J.marker)return;let X=Z9.get(J.fingerprint);if(X?.slots.delete($),X?.slots.size===0)X.manager.stop(),Z9.delete(J.fingerprint);W9.delete($)}function R3($,J,W){let X=rW($),V=Z9.get(X),O=V?.manager??J();if(V)W.rebind(O);let z=W9.get(W.slot);if(z&&z.fingerprint!==X)A3(W.slot,z);let H=V??{manager:O,slots:new Set};if(!V)Z9.set(X,H);let w={fingerprint:X,marker:Symbol(W.slot)};return H.slots.add(W.slot),W9.set(W.slot,w),{manager:O,release:()=>A3(W.slot,w)}}import{classifySafeErrorForLog as sW,logger as aW}from"@cortexkit/anthropic-auth-core";function q3($,J,W){aW.warn("quota","fallback quota preflight could not obtain a reading",{accountId:$,requiredByPolicy:J,...sW(W)})}var kJ="x-cortexkit-request-class",tW=new Set(["title","summary","prime"]);function M3($){return typeof $==="string"&&tW.has($)}function I3($){let J=$.get("x-cortexkit-request-class");return $.delete("x-cortexkit-request-class"),J==="auxiliary"?"auxiliary":"main"}import{getKillswitchThresholdsForAccount as eW,getScopedQuotaWindowForModel as $X,killswitchPassesPolicy as JX}from"@cortexkit/anthropic-auth-core";function x3($){let J=Math.floor($.retryAfterSeconds/60),W=$.retryAfterSeconds%60,X=`Retry in ${J}m ${W}s.`;return $.modelName?`${$.modelName} weekly limit reached, no routable accounts. ${X}`:`Killswitch: no routable accounts. ${X}`}function f3($){if(!$.requestModelId)return{isScopedDriven:!1};if(!JX($.mainQuota,$.storage))return{isScopedDriven:!1};let J=$X($.mainQuota,$.requestModelId);if(!J)return{isScopedDriven:!1};if(!Number.isFinite(J.remainingPercent))return{isScopedDriven:!1};let W=eW($.storage);if(J.remainingPercent<=W.scoped)return{isScopedDriven:!0,modelName:J.modelName,modelId:$.requestModelId};return{isScopedDriven:!1}}var n$=[],k3=1,v3=new Map;function h3($){if(typeof $!=="string"||$.length===0)throw TypeError("sessionId is required")}function b3($,J){if(h3(J),"menu"in $){if($.command!=="claude"||$.menu.command!=="claude")throw TypeError("Only the claude menu is supported");n$.push({id:k3++,type:"open-menu",payload:$,sessionId:J})}else n$.push({id:k3++,type:"open-dialog",payload:$,sessionId:J});if(n$.length>100)n$=n$.slice(n$.length-100)}function g3($,J){if(h3(J),v3.set(J,Date.now()),$>0)n$=n$.filter((W)=>W.id>$||W.sessionId!==J);return n$.filter((W)=>W.id>$&&W.sessionId===J)}function X9($){let J=Date.now(),W=v3.get($)??0;return W>0&&J-W<3000}import{randomBytes as ZX,timingSafeEqual as WX}from"node:crypto";import{readFile as XX,unlink as YX}from"node:fs/promises";import{createServer as GX}from"node:http";import{join as VX}from"node:path";import{parseApplyRequest as KX}from"@cortexkit/anthropic-auth-core";function zX($){return new Promise((J,W)=>{let X=[],V=0;$.on("data",(O)=>{if(V+=O.length,V>1e6){$.destroy(),W(Error("body too large"));return}X.push(O)}),$.on("end",()=>J(Buffer.concat(X).toString("utf8"))),$.on("error",W)})}function OX($,J){if(!$?.startsWith("Bearer "))return!1;let W=Buffer.from($.slice(7)),X=Buffer.from(J);return W.length===X.length&&WX(W,X)}async function m3($){let J=ZX(32).toString("hex"),W=GX((O,z)=>{X(O,z)});async function X(O,z){let H=(w,R)=>{z.writeHead(w,{"content-type":"application/json"}),z.end(JSON.stringify(R))};try{let w=O.url??"";if(O.method==="GET"&&w==="/health")return H(200,{ok:!0});if(O.method!=="POST"||!w.startsWith("/rpc/"))return H(404,{error:"not found"});if(!OX(O.headers.authorization,J))return H(401,{error:"unauthorized"});let R=w.slice(5),A=JSON.parse(await zX(O)||"{}");if(R==="pending-notifications"){if(typeof A.sessionId!=="string"||A.sessionId.length===0)return H(400,{error:"sessionId is required"});let c=$.drain(Number(A.lastReceivedId??0),A.sessionId);return H(200,{messages:c})}if(R==="apply"){if(!$.apply)return H(501,{error:"text apply unavailable"});let c=await $.apply(A);return H(200,c)}if(R==="apply-menu"){let c=KX(A);if(c?.command!=="claude"||!c.sessionId?.trim())return H(400,{error:"invalid menu request"});if(!$.applyMenu)return H(501,{error:"menu unavailable"});return H(200,await $.applyMenu(c))}return H(404,{error:"unknown method"})}catch{if(!z.headersSent&&!z.writableEnded&&!z.destroyed)H(500,{error:"RPC request failed"})}}let V=await new Promise((O,z)=>{W.on("error",z),W.listen(0,"127.0.0.1",()=>{let H=W.address();if(H&&typeof H==="object")O(H.port);else z(Error("no port"))})});W.unref();try{await y3($.dir,{port:V,token:J,pid:process.pid})}catch(O){throw await new Promise((z)=>W.close(()=>z())),O}return{port:V,token:J,async stop(){await new Promise((O)=>W.close(()=>O()));try{let O=VX($.dir,`port-${process.pid}.json`),z=JSON.parse(await XX(O,"utf8"));if(z.port===V&&z.pid===process.pid)await YX(O)}catch{}}}}async function c3($,J){let W=globalThis,X=W.__anthropicAuthRpcServers??new Map,V=W.__anthropicAuthRpcServersPending??new Map;W.__anthropicAuthRpcServers=X,W.__anthropicAuthRpcServersPending=V;let O=V.get($)??Promise.resolve(),z,H=O.catch(()=>{}).then(async()=>{let R=X.get($);if(R){if(await R.stop(),X.get($)===R)X.delete($)}z=await J(),X.set($,z)});V.set($,H);try{await H}finally{if(V.get($)===H)V.delete($)}let w=z;if(!w)throw Error("RPC server failed to start");return{server:w,release:async()=>{if(X.get($)!==w)return;if(await w.stop(),X.get($)===w)X.delete($)}}}import{isClaudeFable51Model as jX}from"@cortexkit/anthropic-auth-core";var u3="server-side-fallback-2026-07-01",d3="",Y9="cortexkit-server-fallback-v1:";function M$($){return $!==null&&typeof $==="object"&&!Array.isArray($)?$:void 0}function b1($,J){let W=$?.[J];return typeof W==="string"?W:void 0}function g1($){return typeof $==="string"&&$.length>0&&$.length<=128&&/^claude-[a-z0-9-]+$/i.test($)}function _X($){return`${Y9}${$.fromModel}|${$.toModel}`}function LX($){if(typeof $!=="string"||!$.startsWith(Y9))return null;let J=$.slice(Y9.length),W=J.indexOf("|");if(W<=0||W!==J.lastIndexOf("|"))return null;let X=J.slice(0,W),V=J.slice(W+1);if(!g1(X)||!g1(V))return null;return{fromModel:X,toModel:V}}function NX($){if($.type!=="fallback")return null;let J=b1(M$($.from),"model"),W=b1(M$($.to),"model");if(!g1(J)||!g1(W))return null;return{fromModel:J,toModel:W}}function HX($){return{type:"fallback",from:{model:$.fromModel},to:{model:$.toModel}}}function DX($,J){let W=0,X=0;if(!Array.isArray($.messages))return{restoredMarkers:W,droppedMarkers:X};for(let V of $.messages){let O=M$(V);if(O?.role!=="assistant"||!Array.isArray(O.content))continue;let z=[];for(let H of O.content){let w=M$(H);if(!(w?.type==="thinking"&&(w.thinking===d3||w.thinking==="")&&typeof w.signature==="string"&&w.signature.startsWith(Y9))){z.push(H);continue}let A=LX(w.signature);if(J&&A)z.push(HX(A)),W++;else X++}O.content=z}return{restoredMarkers:W,droppedMarkers:X}}function i3($){return $?.trim().toLowerCase()==="legacy"?"legacy":"server"}function n3($,J){let W=J&&(h1($.model)||jX($.model)),X=DX($,W);if(W)$.fallbacks="default";else if($.fallbacks==="default")delete $.fallbacks;return{enabled:W,...X}}function UX($){let J,W=[];for(let V of $.split(/\r?\n/))if(V.startsWith("event:"))J=V.slice(6).trim();else if(V.startsWith("data:")){let O=V.slice(5);W.push(O.startsWith(" ")?O.slice(1):O)}let X=W.join(`
|
|
3
3
|
`);if(!X||X==="[DONE]")return{event:J};try{return{event:J,data:M$(JSON.parse(X))}}catch{return{event:J}}}function p3($){let J=$.indexOf(`
|
|
4
4
|
|
|
@@ -9,22 +9,22 @@ data: ${JSON.stringify(J)}
|
|
|
9
9
|
|
|
10
10
|
`}function QX($,J){return l3("content_block_start",{type:"content_block_start",index:$,content_block:{type:"thinking",thinking:d3}})+l3("content_block_delta",{type:"content_block_delta",index:$,delta:{type:"signature_delta",signature:_X(J)}})}function BX($,J){let W=h$($),X=h$(J);if(W&&X)return W===X;return $===J}function o3($){let J="",W=0,X=!1,V="",O,z,H,w=!1,R=!1,A=new Set,c=(T)=>{if(!Array.isArray(T?.iterations))return;for(let o of T.iterations){let q0=M$(o);if(q0?.type!=="fallback_message")continue;let G0=b1(q0,"model");if(g1(G0))H=G0}},a=(T)=>{if(w)return;w=!0;let o=z?.toModel??H??(O&&!BX($.requestedModel,O)?O:void 0);$.onOutcome?.({requestedModel:$.requestedModel,servedModel:O,targetModel:o,fallback:Boolean(o),handoff:Boolean(z),stopReason:T})},u=(T,o)=>{let q0=UX(T),G0=q0.data,I0=b1(G0,"type")??q0.event;if(I0==="message_start"){let L0=M$(G0?.message),b=b1(L0,"model");if(g1(b))O=b;c(M$(L0?.usage))}else if(I0==="content_block_start"){let L0=M$(G0?.content_block),b=G0?.index;if(L0?.type==="tool_use"&&typeof b==="number"&&Number.isInteger(b)&&b>=0)A.add(b);let O0=L0?NX(L0):null;if(O0){if(z=O0,typeof b==="number"&&Number.isInteger(b)&&b>=0)return QX(b,O0)}}else if(I0==="content_block_stop"){let L0=G0?.index;if(typeof L0==="number"&&A.delete(L0))R=!0}else if(I0==="message_delta"){c(M$(G0?.usage));let L0=M$(G0?.delta),b=b1(L0,"stop_reason");if(b)a(b);if(b==="refusal"&&R&&A.size===0&&L0&&$.onRefusalAfterToolUse&&$.onRefusalAfterToolUse()!==!1)return L0.stop_reason="tool_use",`${q0.event?`event: ${q0.event}
|
|
11
11
|
`:""}${G0?`data: ${JSON.stringify(G0)}
|
|
12
|
-
`:""}${o}`}return T+o},s=()=>{let T="";while(!0){let o=p3(J);if(!o)break;let q0=J.slice(0,o.index),G0=J.slice(o.index,o.index+o.length);J=J.slice(o.index+o.length),W=new TextEncoder().encode(J).byteLength,T+=u(q0,G0)}return T};return{pendingLength(){return W},push(T){let o="";if(X){let G0=V+T,I0=p3(G0);if(!I0)return V=G0.slice(-3),T;let L0=I0.index+I0.length;o=T.slice(0,Math.max(0,L0-V.length)),T=G0.slice(L0),X=!1,V=""}if(!T)return o;let q0=new TextEncoder().encode(T).byteLength;if(J+=T,W+=q0,o+=s(),$.maxPendingBytes!==void 0&&W>$.maxPendingBytes){let G0=J;return J="",W=0,X=!0,V=G0.slice(-3),o+G0}return o},flush(){if(X)return V="","";let T=s();if(!J)return T;let o=u(J,"");return J="",W=0,T+o}}}import{createHash as FX}from"node:crypto";import{applyClaudeCodeHeaders as wX,applyClaudeCodeMetadata as TX,applyThinkingBindingControls as SX,
|
|
12
|
+
`:""}${o}`}return T+o},s=()=>{let T="";while(!0){let o=p3(J);if(!o)break;let q0=J.slice(0,o.index),G0=J.slice(o.index,o.index+o.length);J=J.slice(o.index+o.length),W=new TextEncoder().encode(J).byteLength,T+=u(q0,G0)}return T};return{pendingLength(){return W},push(T){let o="";if(X){let G0=V+T,I0=p3(G0);if(!I0)return V=G0.slice(-3),T;let L0=I0.index+I0.length;o=T.slice(0,Math.max(0,L0-V.length)),T=G0.slice(L0),X=!1,V=""}if(!T)return o;let q0=new TextEncoder().encode(T).byteLength;if(J+=T,W+=q0,o+=s(),$.maxPendingBytes!==void 0&&W>$.maxPendingBytes){let G0=J;return J="",W=0,X=!0,V=G0.slice(-3),o+G0}return o},flush(){if(X)return V="","";let T=s();if(!J)return T;let o=u(J,"");return J="",W=0,T+o}}}import{createHash as FX}from"node:crypto";import{applyClaudeCodeHeaders as wX,applyClaudeCodeMetadata as TX,applyThinkingBindingControls as SX,applyTurnEndNotes as EX,assertNotCustodyTombstone as CX,buildBillingHeaderValue as PX,CLAUDE_CODE_ENTRYPOINT as AX,CLAUDE_CODE_IDENTITY as N4,CLAUDE_FABLE_MYTHOS_5_SUMMARIZED_THINKING as RX,CLAUDE_HAIKU_5_5_ADAPTIVE_THINKING as qX,CLAUDE_OPUS_5_5_ADAPTIVE_THINKING as MX,CLAUDE_OPUS_5_ADAPTIVE_THINKING as IX,CLAUDE_SONNET_5_5_ADAPTIVE_THINKING as xX,CLAUDE_SONNET_5_ADAPTIVE_THINKING as fX,ClaudeCodeFirstUserTextTracker as kX,countUserPrompts as vX,createSseFramer as hX,FAST_MODE_BETA as bX,isClaudeFableOrMythos5Model as gX,isClaudeFableOrMythos51Model as yX,isClaudeHaiku55Model as mX,isClaudeOpus5Model as W7,isClaudeOpus55Model as cX,isClaudeSonnet5Model as pX,isClaudeSonnet55Model as lX,isFastModeSupportedModel as uX,isOpenAIReasoningSignature as dX,mergeAnthropicBetas as iX,OPENCODE_IDENTITY_PREFIX as nX,orderClaudeCodeBody as oX,PARAGRAPH_REMOVAL_ANCHORS as rX,parseSseFrame as sX,REQUIRED_BETAS as n2,remapRequestBodyModel as aX,SseFrameTooLargeError as X7,selectClaudeCodeBetas as tX,signRequestBody as eX,stripEmptyTrailingAssistantMessages as $Y,TEXT_REPLACEMENTS as JY,TOOL_PREFIX as Y7,TrailingAssistantHistoryError as ZY}from"@cortexkit/anthropic-auth-core";import{applyEdits as G7,parseTree as WY}from"jsonc-parser";function r3($,J){let W=new Map,X=0,V=0,O=0,z=0,H=0,w=(c)=>{let a=performance.now(),u=$(c);return H+=performance.now()-a,O++,u};return{call:(c)=>{if(!J.enabled())return w(c);let a=W.get(c);if(a!==void 0)return V++,W.delete(c),W.set(c,a),a;let u=w(c),s=c.length+u.length;if(s>J.maxBytes)return u;W.set(c,u),X+=s;while(X>J.maxBytes&&W.size>1){let T=W.keys().next().value,o=W.get(T)??"";W.delete(T),X-=T.length+o.length,z++}return u},stats:()=>({hits:V,misses:O,evictions:z,entries:W.size,cacheBytes:X,computeMsTotal:H})}}var I$=8388608;function z9($){return`${Y7}${$.charAt(0).toUpperCase()}${$.slice(1)}`}function XY($){if($==="StructuredOutput")return $;return`${$.charAt(0).toLowerCase()}${$.slice(1)}`}class D4 extends Error{retryable=!1;isRetryable=!1;constructor(){super("Response tool-name mapping could not be validated safely");this.name="UnsafeToolNameResponseError"}}function H4($){if($?.hazardousWireNames.size)throw new D4}function gJ($,J){return $ instanceof X7&&J?.hazardousWireNames.size?new D4:$}async function yJ($,J){try{$.cancel(J).catch(()=>{})}catch{}try{await Promise.allSettled([$.closed])}finally{try{$.releaseLock()}catch{}}}function YY($){let J=new Set;if(Array.isArray($)){for(let O of $)if(Z0(O)&&typeof O.name==="string"&&O.name)J.add(O.name)}let W=new Map,X=(O,z,H)=>{O.set(z,O.has(z)&&O.get(z)!==H?null:H)},V=new Map;for(let O of J){let z=O.split("_");for(let H=0;H<z.length;H++){let w=z.slice(H).join("_");if(!w)continue;for(let R of new Set([w,XY(w),w.charAt(0).toUpperCase()+w.slice(1)]))X(W,R,O),X(W,`${Y7}${R}`,O)}X(V,z9(O),O)}for(let O of J)W.set(O,O);for(let[O,z]of V)W.set(O,z);return Object.assign(W,{declaredHostNames:J,hazardousWireNames:new Set([...V.keys()].filter((O)=>J.has(O)))})}function U4($,J){let W=new Headers;if($ instanceof Request)$.headers.forEach((V,O)=>{W.set(O,V)});let X=J?.headers;if(X){if(X instanceof Headers)X.forEach((V,O)=>{W.set(O,V)});else if(Array.isArray(X))for(let V of X){let[O,z]=V;if(typeof z<"u")W.set(O,String(z))}else for(let[V,O]of Object.entries(X))if(typeof O<"u")W.set(V,String(O))}return W}function j9($){return $.set("anthropic-beta",iX($.get("anthropic-beta"),[bX])),$}function m1($,J,W={}){return CX(J,"anthropic"),wX($,J,{...W,extraBetas:[...W.body?.fallbacks==="default"?[u3]:[]]})}function GY($){if($.tools&&Array.isArray($.tools))$.tools=$.tools.map((W)=>({...W,name:W.name?z9(W.name):W.name}));let J=$.tool_choice;if(Z0(J)&&J.type==="tool"&&typeof J.name==="string")$.tool_choice={...J,name:z9(J.name)};if($.messages&&Array.isArray($.messages))$.messages=$.messages.map((W)=>{if(W.content&&Array.isArray(W.content))W.content=W.content.map((X)=>{if(X.type==="tool_use"&&X.name)return{...X,name:z9(X.name)};return X});return W});return JSON.stringify(oX($))}function VY($,J){return G7($,V7($,J,!1))}function L4($,J){if($?.type!=="object")return;return $.children?.filter((X)=>X.children?.[0]?.value===J)?.at(-1)?.children?.[1]}function V7($,J,W,X=!0){if(!J?.size)return[];let V=$.charCodeAt(0)===65279?1:0,O=[],z;try{z=WY($.slice(V),O,{disallowComments:!0,allowTrailingComma:!1})}catch{return H4(J),[]}if(O.length||z?.type!=="object")return H4(J),[];let H=L4(z,"type")?.value,w;if(W){X&&=H==="content_block_start";let A=L4(z,"content_block");w=A?[A]:[]}else{X&&=H===void 0||H==="message";let A=L4(z,"content");w=A?.type==="array"?A.children??[]:[]}let R=[];for(let A of w){if(L4(A,"type")?.value!=="tool_use")continue;let c=L4(A,"name");if(c?.type!=="string")continue;let a=J.get(c.value);if(J.hazardousWireNames.has(c.value)&&(!X||a===null))throw new D4;if(!X)continue;if(a&&a!==c.value)R.push({offset:V+c.offset,length:c.length,content:JSON.stringify(a)})}return R}function KY($,J){let W=$.charCodeAt(0)===65279?1:0,X=sX($.slice(W));if(X.data===void 0)return $;let V=V7(X.data,J,!0,X.event===void 0||X.event==="content_block_start");if(!V.length)return $;let O=[],z=0;for(let w of $.slice(W).matchAll(/([^\r\n]*)(?:\r\n|\r|\n|$)/g)){let R=/^data(?:: ?(.*))?$/.exec(w[1]??"");if(!R)continue;let A=R[1]?.length??0;O.push({dataOffset:z,frameOffset:W+(w.index??0)+R[0].length-A,length:A}),z+=A+1}let H=[];for(let w of V){let R=O.find((A)=>w.offset>=A.dataOffset&&w.offset+w.length<=A.dataOffset+A.length);if(!R)return H4(J),$;H.push({...w,offset:R.frameOffset+w.offset-R.dataOffset})}return G7($,H)}function zY($,J){let W=new TextEncoder,X=new TextDecoder("utf-8",{ignoreBOM:!0}),V=hX({maxFrameBytes:I$}),O="",z=0,H=!$?.size;return{pendingLength:()=>O.length,push(w,R=!1){if(H||!$)return w;let A=O+w;if(J){if(z+=W.encode(w).byteLength,z>I$)return H=!0,O="",H4($),A;return O=R?"":A,R?VY(A,$):""}let c;try{c=V.push(W.encode(w))}catch(u){if(!(u instanceof X7))throw u;return H=!0,O="",H4($),A}let a=c.map((u)=>X.decode(u));if(O=A.slice(a.reduce((u,s)=>u+s.length,0)),R){let u=V.finish();if(u)a.push(X.decode(u));O=""}return a.map((u)=>KY(u,$)).join("")}}}function mJ(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let $=process.env.ANTHROPIC_INSECURE?.trim();return $==="1"||$==="true"}function K7($){let J=$?.trim();if(!J)return null;try{let W=new URL(J);if(W.protocol!=="http:"&&W.protocol!=="https:"||W.username||W.password)return null;return W}catch{return null}}function OY(){return K7(process.env.ANTHROPIC_BASE_URL)}function Q4($,J={}){let W=null;try{if(typeof $==="string"||$ instanceof URL)W=new URL($.toString());else if($ instanceof Request)W=new URL($.url)}catch{W=null}if(!W)return{input:$,url:null};let X=W.href,V=J.baseURL?K7(J.baseURL):OY();if(V){let z=V.pathname.replace(/\/$/,""),H=W.pathname;if(W.protocol=V.protocol,W.host=V.host,!(H===z||z!==""&&H.startsWith(`${z}/`))){let R=/\/v\d[^/]*$/.test(z);if(H==="/messages")W.pathname=R?`${z}/messages`:`${z}/v1/messages`;else if(H==="/v1/messages"&&R)W.pathname=`${z}/messages`;else W.pathname=`${z}${H}`}else if(H===`${z}/messages`){if(!/\/v\d[^/]*$/.test(z))W.pathname=`${z}/v1/messages`}}if(W.pathname.endsWith("/v1/messages")&&!W.searchParams.has("beta"))W.searchParams.set("beta","true");if(W.href===X)return{input:$,url:W};return{input:$ instanceof Request?new Request(W.toString(),$):W,url:W}}function jY($){let X=$.split(/\n\n+/).filter((V)=>{if(V.includes(nX))return!1;for(let O of rX)if(V.includes(O))return!1;return!0}).join(`
|
|
13
13
|
|
|
14
|
-
`);for(let V of
|
|
15
|
-
`);J.splice(X,J.length-X,{...V,type:"text",text:O})}function t3($){if(Array.isArray($.system)){let J=$.system.findIndex((V)=>Z0(V)&&V.text===N4),W=$.system.slice(J>=0?J+1:0).filter(Z0),X=W[W.length-1];O9(X,!0)}else O9($.system,!0)}function
|
|
16
|
-
`),V={event:J,rawBytes:B1($),dataBytes:B1(X)};if(!X||X==="[DONE]")return V.type=X==="[DONE]"?"done":void 0,V.event??=V.type,V;let O;try{O=JSON.parse(X)}catch{return V}let z=b$(O),H=b$(z?.delta),w=b$(z?.content_block),R=b$(z?.message),A=b$(z?.usage)??b$(R?.usage);if(V.type=r0(z,"type"),V.event??=V.type,V.index=
|
|
14
|
+
`);for(let V of JY)X=X.replace(V.match,V.replacement);return X.trim()}var _Y=8388608;function LY(){return process.env.OPENCODE_ANTHROPIC_AUTH_MEMO!=="0"}var NY=r3(jY,{maxBytes:_Y,enabled:LY});function G9($){return NY.call($)}function Z0($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function HY($){let J={type:"text",text:N4};if($==null)return[J];if(typeof $==="string"){let X=G9($);if(X===N4)return[J];return[J,{type:"text",text:X}]}if(Z0($)){let X=typeof $.type==="string"?$.type:"text",V=typeof $.text==="string"?$.text:"";return[J,{...$,type:X,text:G9(V)}]}if(!Array.isArray($))return[J];let W=$.map((X)=>{if(typeof X==="string")return{type:"text",text:G9(X)};if(Z0(X)&&X.type==="text"&&typeof X.text==="string")return{...X,type:"text",text:G9(X.text)};return{type:"text",text:String(X)}});if(W[0]?.text===N4)return W;return[J,...W]}var z7={type:"ephemeral",ttl:"1h"},s3=20;function cJ($){if(Z0($.cache_control))return $.cache_control;if(Z0($.cacheControl))return $.cacheControl;return null}function O9($,J){if(!Z0($))return!1;return delete $.cacheControl,$.cache_control=J?{...z7}:{type:"ephemeral"},!0}function hJ($){if(!Z0($))return;delete $.cache_control,delete $.cacheControl}function pJ($){if(Array.isArray($))return $;if(typeof $==="string")return[{type:"text",text:$}];return null}function bJ($){if(Array.isArray($))return $.map(bJ);if(!Z0($))return $;let J={};for(let W of Object.keys($).sort()){if(W==="cache_control"||W==="cacheControl")continue;J[W]=bJ($[W])}return J}function O7($){if(!Z0($))return;let J=pJ($.content);if(!J?.length)return;let W=bJ({...$,content:J});return FX("sha256").update(JSON.stringify(W)).digest("hex")}function DY($){if(!Z0($))return!1;let J=pJ($.content);return Boolean(J?.some((W)=>Z0(W)&&cJ(W)?.type==="ephemeral"))}function j7($){try{let J=JSON.parse($);if(!Array.isArray(J.messages))return;for(let W=J.messages.length-1;W>1;W--){let X=J.messages[W];if(!Z0(X)||X.role!=="user"||!DY(X))continue;let V=O7(X);if(!V)return;return{fingerprint:V,messageIndex:W,messageCount:J.messages.length}}return}catch{return}}function _7($,J){if(!Z0($))return;let W=cJ($);if(W?.type!=="ephemeral")return;if(J)W.ttl="1h";else delete W.ttl}function a3($,J){lJ($,(W)=>_7(W,J))}function lJ($,J){if(Array.isArray($.tools))for(let W of $.tools)J(W);if(Array.isArray($.system))for(let W of $.system)J(W);else J($.system);if(!Array.isArray($.messages))return;for(let W of $.messages)if(J(W),Z0(W)&&Array.isArray(W.content))for(let X of W.content)J(X)}function L7($){hJ($),lJ($,hJ)}function UY($){L7($),$.cache_control={...z7}}function QY($){return Z0($)&&$.type!=="thinking"&&$.type!=="redacted_thinking"}function N7($){let J=pJ($.content);if(!J?.length)return;let W=J.filter(QY);if(!W.length)return;return{content:J,cacheableBlocks:W}}function BY($){if(!Z0($))return!1;let J=N7($);if(!J||J.cacheableBlocks.length<2)return!1;let[W,X,V]=J.content,z=$.role==="user"&&Z0(W)&&W.type==="text"&&typeof W.text==="string"&&Z0(X)&&X.type==="image"&&Z0(V)&&V.type==="text"&&typeof V.text==="string"&&/<memory-mural>[\s\S]*?<\/memory-mural>/.test(W.text)?[X,V]:J.cacheableBlocks.slice(0,2);$.content=J.content;for(let H of z)O9(H,!0);return!0}function V9($){if(!Z0($))return!1;let J=N7($);if(!J)return!1;let W=J.cacheableBlocks[J.cacheableBlocks.length-1];return $.content=J.content,O9(W,!0)}function FY($){if(!Z0($))return 0;let J=$.content;if(Array.isArray(J))return J.length;if(J==null)return 0;return 1}function wY($){let J=[],W=0;return $.forEach((X,V)=>{let O=FY(X);if(Z0(X)&&X.role==="user"&&O>0)J.push({index:V,blockPosition:W+O-1});W+=O}),J}function TY($,J,W,X){if(!X)return;let V=[],O=J.find((z)=>z.index===X.messageIndex&&z.index>1&&z.index<W.index);if(O)V.push(O);for(let z of[...J].reverse()){if(z.index<=1||z.index>=W.index||z.index===O?.index)continue;V.push(z)}for(let z of V)if(O7($[z.index])===X.fingerprint)return z;return}function SY($,J){let W=wY($),X=[...W].reverse().find((A)=>A.index>1);if(!X)return{latest:void 0,bridge:void 0,standbyAnchorMatched:!1,standbyBridgeApplied:!1};let V=TY($,W,X,J),O=V?X.blockPosition-V.blockPosition+1:void 0,z=V&&O!=null&&O>s3?V:void 0,H=[...W].reverse().find((A)=>A.index<X.index),w=H?X.blockPosition-H.blockPosition+1:0,R=H&&H.index>1&&w>s3?H:void 0;return{latest:X,bridge:z??R,standbyAnchorMatched:Boolean(V),standbyDistanceBlocks:O,standbyBridgeApplied:Boolean(z)}}function vJ($){return Z0($)&&typeof $.text==="string"?$.text:""}function EY($){if(!Array.isArray($.system))return;let J=$.system,W=0;if(vJ(J[W]).startsWith("x-anthropic-billing-header:"))W++;if(vJ(J[W])===N4)W++;let X=W+1;if(X>=J.length-1)return;let V=J[X];if(!Z0(V))return;let O=J.slice(X).map(vJ).join(`
|
|
15
|
+
`);J.splice(X,J.length-X,{...V,type:"text",text:O})}function t3($){if(Array.isArray($.system)){let J=$.system.findIndex((V)=>Z0(V)&&V.text===N4),W=$.system.slice(J>=0?J+1:0).filter(Z0),X=W[W.length-1];O9(X,!0)}else O9($.system,!0)}function CY($,J){if(L7($),EY($),!Array.isArray($.messages))return t3($),{standbyAnchorMatched:!1,standbyBridgeApplied:!1};let{latest:W,bridge:X,standbyAnchorMatched:V,standbyDistanceBlocks:O,standbyBridgeApplied:z}=SY($.messages,J);if(!X)t3($);if(!BY($.messages[0]))V9($.messages[0]),V9($.messages[1]);if(X)V9($.messages[X.index]);if(W)V9($.messages[W.index]);return{standbyAnchorMatched:V,standbyDistanceBlocks:O,standbyBridgeApplied:z,...z&&X?{standbyBridgeMessageIndex:X.index}:{}}}function PY($){if(!Array.isArray($.messages))return 0;let J=0;return $.messages=$.messages.filter((W)=>{if(!Z0(W)||!Array.isArray(W.content))return!0;if(W.role!=="assistant")return!0;let X=W.content.filter((V)=>{if(!Z0(V)||V.type!=="thinking")return!0;if(!dX(V.signature))return!0;return J+=1,!1});if(X.length===W.content.length)return!0;return W.content=X,X.length>0}),J}function uJ($){let J=$.tool_choice;if(Z0(J)&&(J.type==="any"||J.type==="tool"))delete $.tool_choice}function AY($){if(!gX($.model))return null;let J=Object.hasOwn($,"thinking");if($.thinking={...RX},yX($.model))uJ($);return{replacedExisting:J}}function RY($){if(lX($.model)){uJ($);let X=Object.hasOwn($,"thinking"),V=$.thinking;if(Z0(V)&&(V.type==="disabled"||V.type==="between_tools")){$.thinking={type:"between_tools"};let O=$.output_config;if(Z0(O)&&(O.effort==="xhigh"||O.effort==="max"))O.effort="high";return{replacedExisting:X,display:"between_tools"}}return $.thinking={...xX},{replacedExisting:X,display:"summarized"}}if(!pX($.model))return null;let J=Object.hasOwn($,"thinking"),W=$.thinking;if(Z0(W)&&W.type==="disabled")return $.thinking={type:"disabled"},{replacedExisting:J,display:"disabled"};return $.thinking={...fX},{replacedExisting:J,display:"summarized"}}function qY($){if(cX($.model)){uJ($);let X=Object.hasOwn($,"thinking");return $.thinking={...MX},{replacedExisting:X,display:"summarized"}}if(!W7($.model))return null;let J=Object.hasOwn($,"thinking"),W=$.thinking;if(Z0(W)&&W.type==="disabled"){$.thinking={type:"disabled"};let X=$.output_config;if(Z0(X)&&X.effort==="xhigh")X.effort="high";else if(Z0(X)&&X.effort==="max")X.effort="high";return{replacedExisting:J,display:"disabled"}}return $.thinking={...IX},{replacedExisting:J,display:"summarized"}}function MY($){if(!mX($.model))return null;delete $.temperature,delete $.top_p,delete $.top_k;let J=Object.hasOwn($,"thinking");if(Z0($.thinking)&&$.thinking.type==="disabled"){$.thinking={type:"disabled"};let W=$.output_config;if(Z0(W)&&(W.effort==="xhigh"||W.effort==="max"))W.effort="high";return{replacedExisting:J,display:"disabled"}}return $.thinking={...qX},{replacedExisting:J,display:"summarized"}}function IY($,J){if(!J.enabled)return a3($,!1),delete $.cache_control,delete $.cacheControl,{};if(J.mode==="automatic")return UY($),{};if(J.mode==="hybrid")return CY($,J.hybridStandbyAnchor);a3($,!0),delete $.cacheControl;let W=[];if(lJ($,(X)=>{if(Z0(X)&&cJ(X))W.push(X)}),Z0($.cache_control))_7($,!0),W.push($);for(let X of W.slice(0,-4))hJ(X);return{}}function xY($){if(!Array.isArray($.messages))return 0;for(let J=$.messages.length-1;J>=0;J--){let W=$.messages[J];if(!Z0(W)||W.role!=="assistant")continue;if(!Array.isArray(W.content))return 0;if(!W.content.some((V)=>Z0(V)&&V.type==="tool_use"))return 0;let X=0;while(W.content.length){let V=W.content[W.content.length-1];if(!Z0(V)||V.type!=="text"||typeof V.text!=="string"||V.text.trim())break;W.content.pop(),X++}return X}return 0}var fY=1000,kY=new kX(fY);function vY($,J,W){return kY.resolve($,J,!W)}function F0(){return performance.now()}function B$($){return Math.round($*10)/10}function e3($){let J=0,W=0,X=0,V=Array.isArray($.messages)?$.messages:[];J=V.length;for(let O of V){if(!O||typeof O!=="object")continue;let z=O.content;if(!Array.isArray(z))continue;W+=z.length;for(let H of z)if(H&&typeof H==="object"&&H.type==="tool_use")X++}return{messageCount:J,contentBlockCount:W,toolDefinitionCount:Array.isArray($.tools)?$.tools.length:0,toolUseCount:X,systemBlockCount:Array.isArray($.system)?$.system.length:0}}async function _9($,J={}){try{let W=F0(),X=JSON.parse($);J.perf?.("parse",{ms:B$(F0()-W),inputBytes:$.length,...e3(X)});let V=F0(),O=Array.isArray(X.messages)?X.messages.length:void 0;$Y(X.messages);let z=xY(X),H=Array.isArray(X.messages)?X.messages.length:void 0;J.perf?.("strip_trailing_assistant",{ms:B$(F0()-V),removedMessages:typeof O==="number"&&typeof H==="number"?O-H:void 0,removedWhitespaceBlocks:z});let w=F0(),R=PY(X),A=n3(X,J.serverSideFallbackEnabled===!0),c=AY(X),a=RY(X),u=qY(X),s=MY(X);if(J.perf?.("model_normalize",{ms:B$(F0()-w),model:typeof X.model==="string"?X.model:void 0,fableMythosThinkingDisplay:c?"summarized":void 0,replacedFableMythosThinking:c?.replacedExisting??!1,sonnet5ThinkingDisplay:a?.display,replacedSonnet5Thinking:a?.replacedExisting??!1,opus5ThinkingDisplay:u?.display,replacedOpus5Thinking:u?.replacedExisting??!1,haiku55ThinkingDisplay:s?.display,replacedHaiku55Thinking:s?.replacedExisting??!1,removedNonAnthropicThinking:R,serverSideFallbackEnabled:A.enabled,serverFallbackMarkersRestored:A.restoredMarkers,serverFallbackMarkersDropped:A.droppedMarkers,hasOutputConfig:Object.hasOwn(X,"output_config")}),J.laneStart===!0)X.max_tokens=1,delete X.thinking;if(H3(X,J.midConversationEffortEnabled===!0,J.midConversationEffortPlan,J.midConversationEffortResolvedPlan),SX(X,J.thinkingPrefixMismatchBehavior??"account-default"),J.turnEndNoteEnabled)EX(X,{tools:J.turnEndNote?.tools});let T=F0(),o=Array.isArray(X.messages)&&X.messages.some((A1)=>A1.role==="user")?PX(X.messages,void 0,AX,J.sessionId?vY(J.sessionId,X.messages,J.laneStart===!0):void 0,J.billingLineage?.promptId?{...J.billingLineage,promptIndex:J.billingLineage.promptIndex??vX(X.messages)}:J.billingLineage):null;J.perf?.("billing_header",{ms:B$(F0()-T),hasBillingHeader:Boolean(o)});let q0=F0();if(X.system=HY(X.system),J.perf?.("system_identity",{ms:B$(F0()-q0),systemBlockCount:Array.isArray(X.system)?X.system.length:0}),o&&Array.isArray(X.system))X.system.unshift({type:"text",text:o});let G0=F0(),I0=IY(X,{enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit",hybridStandbyAnchor:J.hybridStandbyAnchor});if(J.perf?.("cache_strategy",{ms:B$(F0()-G0),enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit",...I0}),J.fastModeEnabled&&uX(X.model))X.speed="fast";else if(X.speed==="fast")delete X.speed;if(J.cacheDiagnosticsPreviousMessageId!==void 0&&tX(X).split(",").includes(V4))o4(X,J.cacheDiagnosticsPreviousMessageId);let L0=F0();if(J.identity)TX(X,J.identity);J.perf?.("metadata",{ms:B$(F0()-L0),hasAccountUuid:Boolean(J.identity?.accountUuid)});let b=F0();if(J.modelRemapEnabled===!0)aX(X);let O0=YY(X.tools),m0=GY(X);J.perf?.("prefix_tools_stringify",{ms:B$(F0()-b),outputBytesBeforeSign:m0.length,...e3(X)});let q=F0(),s0=await eX(m0);return J.perf?.("cch_sign",{ms:B$(F0()-q),outputBytes:s0.length}),J.onToolNameMap?.(O0),s0}catch(W){if(W instanceof S0||W instanceof ZY)throw W;return $}}var H7=new TextEncoder;function hY(){return{pending:"",pendingOverflowCount:0,disabled:!1,events:0,parseErrors:0,eventCounts:{},typeCounts:{},deltaTypeCounts:{},contentBlockTypeCounts:{},textDeltaBytes:0,thinkingDeltaBytes:0,inputJsonDeltaBytes:0,signatureDeltaBytes:0,redactedThinkingBytes:0}}function K9($,J){if(!J)return;$[J]=($[J]??0)+1}function B1($){return H7.encode($).byteLength}function b$($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function r0($,J){let W=$?.[J];return typeof W==="string"?W:void 0}function bY($,J){let W=$?.[J];return typeof W==="number"?W:void 0}function dJ($){if(!$.trim())return null;let J,W=[];for(let c of $.split(/\r?\n/)){if(c.startsWith("event:")){J=c.slice(6).trim();continue}if(c.startsWith("data:")){let a=c.slice(5);W.push(a.startsWith(" ")?a.slice(1):a)}}let X=W.join(`
|
|
16
|
+
`),V={event:J,rawBytes:B1($),dataBytes:B1(X)};if(!X||X==="[DONE]")return V.type=X==="[DONE]"?"done":void 0,V.event??=V.type,V;let O;try{O=JSON.parse(X)}catch{return V}let z=b$(O),H=b$(z?.delta),w=b$(z?.content_block),R=b$(z?.message),A=b$(z?.usage)??b$(R?.usage);if(V.type=r0(z,"type"),V.event??=V.type,V.index=bY(z,"index"),V.contentBlockType=r0(w,"type"),V.deltaType=r0(H,"type"),V.stopReason=r0(H,"stop_reason")??r0(z,"stop_reason"),V.deltaType==="text_delta")V.textDeltaBytes=B1(r0(H,"text")??"");if(V.deltaType==="thinking_delta")V.thinkingDeltaBytes=B1(r0(H,"thinking")??"");if(V.deltaType==="input_json_delta")V.inputJsonDeltaBytes=B1(r0(H,"partial_json")??"");if(V.deltaType==="signature_delta")V.signatureDeltaBytes=B1(r0(H,"signature")??"");if(V.contentBlockType==="redacted_thinking")V.redactedThinkingBytes=B1(r0(w,"data")??"");if(A)V.usage=A,V.stopReason??=r0(R,"stop_reason");if(V.type==="message_start"&&R)V.message=R;return V}function y1($){let J=$.indexOf(`
|
|
17
17
|
|
|
18
18
|
`),W=$.indexOf(`\r
|
|
19
19
|
\r
|
|
20
|
-
`);if(J===-1)return W===-1?null:{index:W,length:4};if(W===-1||J<W)return{index:J,length:2};return{index:W,length:4}}function $7($,J,W,X){if(!J||$.disabled)return;$.pending+=J;while(!0){let V=y1($.pending);if(!V)break;let O=$.pending.slice(0,V.index);$.pending=$.pending.slice(V.index+V.length);let z=dJ(O);if(!z)continue;if($.events++,K9($.eventCounts,z.event??"unknown"),K9($.typeCounts,z.type),K9($.deltaTypeCounts,z.deltaType),K9($.contentBlockTypeCounts,z.contentBlockType),$.textDeltaBytes+=z.textDeltaBytes??0,$.thinkingDeltaBytes+=z.thinkingDeltaBytes??0,$.inputJsonDeltaBytes+=z.inputJsonDeltaBytes??0,$.signatureDeltaBytes+=z.signatureDeltaBytes??0,$.redactedThinkingBytes+=z.redactedThinkingBytes??0,$.last=z,X?.(z),z.dataBytes>0&&!z.type&&!z.event)$.parseErrors++}if(H7.encode($.pending).byteLength>W)$.pending="",$.disabled=!0,$.pendingOverflowCount++}function
|
|
21
|
-
`);if(!X||X==="[DONE]")return null;let V;try{V=JSON.parse(X)}catch{return null}let O=b$(V);if(J!=="error"&&r0(O,"type")!=="error")return null;let z=b$(O?.error),H=r0(z,"type")??r0(z,"code")??void 0,w=r0(z,"message")??r0(O,"message")??H??"Anthropic stream error";if(!
|
|
22
|
-
`))),X=b$(W?.error);if(r0(X,"type")!=="relay_upstream_error")return;let V=X?.status;if(typeof V==="number"&&Number.isInteger(V))return{status:V,source:"relay_status_field"};let z=r0(X,"message")?.match(/HTTP\s+(\d{3})\b/i);return z?{status:Number(z[1]),source:"relay_message_parse"}:void 0}catch{return}}function Z7($,J,W,X){if(!J)return null;if($.disabled){let O=$.resyncCarry+J,z=y1(O);if(!z)return $.resyncCarry=O.slice(-3),null;if($.disabled=!1,$.resyncCarry="",J=O.slice(z.index+z.length),!J)return null}$.pending+=J;let V=null;while(!0){let O=y1($.pending);if(!O)break;let z=$.pending.slice(0,O.index);$.pending=$.pending.slice(O.index+O.length);let H=iY(z);if(H!==void 0)X?.(H);let w=dY(z);V??=w}if(new TextEncoder().encode($.pending).byteLength>W){let O=$.pending;$.pending="",$.disabled=!0,$.resyncCarry=O.slice(-3)}return V}function nY($){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 D7($,J={}){if(!$.body)return $;let W=$.body.getReader(),X=new TextDecoder("utf-8",{ignoreBOM:!0}),V=new TextEncoder,O=J.responseMode==="json",z=KY(J.toolNameMap,O),H=!0,w="",R=0,A=0,c=0,a=0,u=0,s=!1,T=!1,o=F0(),q0=F0(),G0=J.perf||J.onMessageStart||J.onMessageDelta?vY():void 0,I0="",L0=0,b=!1,O0=(x0)=>{if(!x0)return;try{x0()}catch{}},m0=cY(),q=J.onContentFilter||J.onComplete?bY():void 0,s0=J.laneStart&&J.laneStartOAuthServed!==!1?yY():void 0,A1=!1,A4=!1,R4=(x0=!1)=>{if(!J.onContentFilter)return!1;if(!A1)A1=!0,A4=J.onContentFilter({completedToolUse:x0})!==!1;return A4},$1=J.serverSideFallbackModel?o3({requestedModel:J.serverSideFallbackModel,maxPendingBytes:I$,onOutcome:J.onServerSideFallbackOutcome,onRefusalAfterToolUse:J.onContentFilter?()=>R4(!0):void 0}):void 0,R1=(x0)=>{if(!q)return null;let w$=gY(q,x0,I$);if(w$?.type==="content-filter"&&J.onContentFilter)return R4()?uY(J.contentFilterModel):null;if(w$?.type==="complete")J.onComplete?.(w$.finishReason);return null},q4=(x0,w$=!1)=>s0?mY(s0,x0,I$,w$):x0,j1=()=>{if(T)return;T=!0,W.releaseLock()},f9=async(x0)=>{try{await W.cancel(x0)}catch{}finally{j1()}},k9=(x0={})=>({chunks:R,pulls:A,inputBytes:c,outputBytes:a,pendingChars:z.pendingLength(),sseErrorPending:m0.pending.length,sseFinishPending:q?.pending.length??0,sseFinishDisabled:q?.disabled??!1,serverFallbackPending:$1?.pendingLength()??0,rewriteMs:B$(u),totalMs:B$(F0()-q0),...G0?nY(G0):{},...x0}),x$=(x0,w$={})=>{J.perf?.(x0,k9(w$))};J.perf?.("stream_tool_prefix_wrapper_created",{status:$.status,hasBody:!0});let v9=new ReadableStream({async pull(x0){if(A++,!s)s=!0,x$("stream_tool_prefix_first_pull");while(!0){let w$=F0();try{let{done:l1,value:T$}=await W.read(),a0=B$(F0()-w$);if(l1){let E0=X.decode();if(G0&&!O)$7(G0,E0,I$,(M0)=>{let L1=M0.message;if(M0.type==="message_start"&&L1)O0(()=>J.onMessageStart?.(L1));if(M0.type==="message_delta"&&(M0.usage||M0.stopReason))O0(()=>J.onMessageDelta?.({...M0.usage?{usage:M0.usage}:{},...M0.stopReason?{stopReason:M0.stopReason}:{}}))});if(O){let M0=V.encode(E0).byteLength;if(L0+M0<=I$)I0+=E0,L0+=M0;else b=!0}if(O&&!b)try{let M0=JSON.parse(I0);if(M0&&typeof M0==="object"&&!Array.isArray(M0))O0(()=>J.onMessageResponse?.(M0))}catch{}let O$=F0(),A0=$1?$1.push(E0)+$1.flush():E0,q1=q4(A0,!0),_1=O?R1(q1):Z7(m0,E0,I$,J.onRelayUpstreamError)??R1(q1);if(_1)throw x$("stream_tool_prefix_retryable_error",{providerErrorType:_1.providerErrorType}),await f9(_1),_1;let i1=z.push(q1,!0);if(u+=F0()-O$,i1||w){let M0=V.encode(w+i1);w="",a+=M0.byteLength,x0.enqueue(M0)}if(x$("stream_tool_prefix_rewrite",{readMs:a0}),j1(),J.onStreamEnd)try{await J.onStreamEnd()}catch{}x0.close();return}R++,c+=T$.byteLength;let b0=X.decode(T$,{stream:!0});if(H&&b0){if(H=!1,b0.charCodeAt(0)===65279)w=b0[0]??"",b0=b0.slice(1)}if(O){let E0=T$.byteLength;if(L0+E0<=I$)I0+=b0,L0+=E0;else b=!0}if(G0&&!O)$7(G0,b0,I$,(E0)=>{let O$=E0.message;if(E0.type==="message_start"&&O$)O0(()=>J.onMessageStart?.(O$));if(E0.type==="message_delta"&&(E0.usage||E0.stopReason))O0(()=>J.onMessageDelta?.({...E0.usage?{usage:E0.usage}:{},...E0.stopReason?{stopReason:E0.stopReason}:{}}))});let h9=F0(),u1=$1?$1.push(b0):b0,d1=q4(u1),G$=O?R1(d1):Z7(m0,b0,I$,J.onRelayUpstreamError)??R1(d1);if(G$)throw x$("stream_tool_prefix_retryable_error",{providerErrorType:G$.providerErrorType,readMs:a0,lastChunkBytes:T$.byteLength}),j1(),G$;let J1=z.push(d1);if(u+=F0()-h9,J1){let E0=V.encode(w+J1);w="",a+=E0.byteLength,x0.enqueue(E0)}let Z1=F0();if(R===1||R%25===0||Z1-o>5000)o=Z1,x$("stream_tool_prefix_progress",{readMs:a0,lastChunkBytes:T$.byteLength});if(J1)return}catch(l1){let T$=gJ(l1,J.toolNameMap);if(x$("stream_tool_prefix_error"),T$ instanceof D4)await yJ(W,T$),T=!0,O0(J.onToolNameRefusal);else j1();throw T$}}},async cancel(x0){x$("stream_tool_prefix_cancel");try{await W.cancel(x0)}finally{j1()}}});return new Response(v9,{status:$.status,statusText:$.statusText,headers:$.headers})}import{mergeNativeSettingsSection as W2,nativeCacheKeepAlways as X2,nativeSettingsRecord as Y2}from"@cortexkit/anthropic-auth-core";var p7="physical send failed before a response",AG="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",l7="~effect/http/HttpServerResponse",u7="~effect/http/Cookies",d7="~effect/http/HttpBody",RG="~effect/ErrorReporter/ignore",qG="https://api.anthropic.com/v1/messages",K8=new WeakSet;function _Z($){let J=new Response(JSON.stringify({type:"error",error:{type:"invalid_request_error",message:$}}),{status:400,headers:{"content-type":"application/json"}});return K8.add(J),J}async function i7($,J){if(!J?.aborted)return;await $.body?.cancel().catch(()=>{}),J.throwIfAborted()}function jZ($,J){return($.status!==400||!K8.has($))&&CG($.status,J)}function n7($){return h.warn("effort-history","refused uncorrelated Fable 5.1 request",{check:$.check,...$.details}),_Z($.message)}function o7($){return h.warn("transform","refused request ending on assistant history",{check:$.check,...$.details}),_Z($.message)}var MG=60000,r7=60000,z8=240,IG=z8,xG=600000;function fG($,J){return($?.accounts??[]).some((W)=>W.id===J&&y0(W)&&B0(W))}function kG($){let J=($?.accounts??[]).find((W)=>y0(W)&&B0(W));if(e$($)==="fallback-first"&&J)return{activeId:J.id,route:"fallback-first"};return{activeId:"main",route:"main"}}function s7($,J){if($?.activeId==="main"||$?.activeId&&fG(J,$.activeId))return $;return kG(J)}function O8($,J,W){let X=Date.now()-$.lastUpdated;if(!$.activeId||X<0||X>xG)return s7(W,J);return s7($,J)}async function vG($,J,W){let X;try{X=await J()}catch(V){return h.warn("sidebar","account storage reload failed; routing preserved",{message:V instanceof Error?V.message:String(V)}),{...$.activeId?{activeId:$.activeId,route:$.route}:W??{activeId:"main",route:"main"},freshStorage:null}}return{...O8($,X,W),freshStorage:X}}async function hG($){await M9()?.beforeStorageLoad?.();let J;try{J=await $()}catch{return{activeId:"main",route:"main",freshStorage:null}}finally{await M9()?.afterStorageLoad?.()}await M9()?.beforeSidebarRead?.();let W=await Y8();return{...O8(W,J),freshStorage:J}}var bG=4,gG=25,yG=1,a7=!1;function I9(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function $0(){return performance.now()}function P0($){return Math.round($*10)/10}function t7($){return Math.floor(Math.random()*Math.max(0,$))}function E4($){if(typeof $==="string")return $;if($ instanceof URL)return $.toString();return $.url}function P1($,J){return J?.method??($ instanceof Request?$.method:void 0)}async function C4($,J){if(J?.body!==void 0)return J.body;if(!($ instanceof Request)||$.body===null)return;try{return await $.clone().text()}catch{return}}function mG(){if(a7||!1||!I9())return;a7=!0;let $=100,J=250,W=$0()+$;setInterval(()=>{let X=$0(),V=X-W;if(W=X+$,V<J)return;y$("[perf] opencode event_loop_lag",{lagMs:P0(V),thresholdMs:J})},$).unref?.()}function cG($){let J=$0(),W={requestId:String(yG++),start:J,last:J,mark(X,V){let O=$0();if(I9())y$("[perf] opencode request stage",{requestId:W.requestId,stage:X,deltaMs:P0(O-W.last),totalMs:P0(O-W.start),...V});W.last=O},done(X,V){let O=$0();if(I9())y$("[perf] opencode request done",{requestId:W.requestId,stage:X,deltaMs:P0(O-W.last),totalMs:P0(O-W.start),...V});W.last=O}};if(I9())y$("[perf] opencode request start",{requestId:W.requestId,...$});return W}function j8($,J){let W=/^msg_([0-9a-fA-F]{12})/.exec($);if(!W)return;let X=BigInt(`0x${W[1]}`);if(X<=0n)return;let O=`msg_${(X-1n).toString(16).padStart(12,"0")}${"z".repeat(14)}`,z=J&&O<=J?`${J}z`:O;if(z.length>128||z>=$)return;return z}async function e7($,J,W,X={}){let V=$.client.session,O=await $9($.client,J),z={path:{id:J},body:{noReply:X.noReply??!0,parts:[{type:"text",text:W,ignored:!0}]}};if(X.beforeActiveAssistant){let H=X.latestPreparedMessageId?.(),w=O?.latestUserMessageId,R=H&&(!w||H>w)?H:w,A=O?.latestAssistantMessageId?j8(O.latestAssistantMessageId,R):void 0;if(!A)return!1;z.body.messageID=A}if(O?.agent)z.body.agent=O.agent;if(O?.model)z.body.model=O.model;if(O?.variant)z.body.variant=O.variant;if(X.canSend&&!X.canSend())return!1;if(z.body.messageID)X.onPreparedMessageId?.(z.body.messageID);if(typeof V?.promptAsync==="function")return await V.promptAsync(z),!0;if(typeof V?.prompt==="function")return await Promise.resolve(V.prompt(z)),!0;throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function pG(){throw Object.assign(Error(AG),{[l7]:l7,[RG]:!0,status:204,statusText:void 0,headers:{},cookies:{[u7]:u7,cookies:{}},body:{[d7]:d7,_tag:"Empty"}})}function lG($){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 uG($){if($.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return $.push(ZG),!0}var dG={input:0,output:0,cache:{read:0,write:0}},iG=1000;function F$($){return $}function nG($,J){let W=P4($);return`${W} content filter detected. Switched to Opus 4.8 for a ${J}-response recovery window before trying ${W} again.`}function oG($){let J=P4($);return`${J} recovery window complete. Returning to ${J}.`}function P4($){if(n5($))return"Opus 5.5";if(i5($))return"Opus 5";if(V8($)){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 rG($,J){return`Anthropic safety fallback active: ${P4($)} → ${P4(J)}. Follow-up requests may remain on the fallback model for about one hour.`}function sG($){return`Anthropic safety fallback ended. Returning to ${P4($)}.`}function aG(){return{input:H9.input,output:H9.output,cache:{read:H9.cacheRead,write:H9.cacheWrite5m},tiers:[{tier:{type:"context",size:z5},input:L9.input,output:L9.output,cache:{read:L9.cacheRead,write:L9.cacheWrite5m}}]}}function tG($){let J=$["claude-opus-4-8"]??$["claude-opus-4-5"]??Object.values($)[0];if(!J)return $;return{...$,...Object.fromEntries(Object.values(G5).map((W)=>{let X=V8(W.id)?W5:V5;return[W.id,{...J,id:W.id,name:W.name,api:J.api?{...J.api,id:W.id}:void 0,cost:{input:X.input,output:X.output,cache:{read:X.cacheRead,write:X.cacheWrite5m}},limit:{...J.limit??{},context:X5,output:Y5},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:f5(W.id)}]})),...$[N9]?{}:{[N9]:{...J,id:N9,name:"Claude Haiku 5.5",api:J.api?{...J.api,id:N9}:void 0,cost:aG(),limit:{...J.limit??{},context:K5,output:O5},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:j5,variants:x9()}},...$[Q9]?{}:{[Q9]:{...J,id:Q9,name:"Claude Sonnet 5.5",api:J.api?{...J.api,id:Q9}:void 0,cost:{input:B9.input,output:B9.output,cache:{read:B9.cacheRead,write:B9.cacheWrite5m}},limit:{...J.limit??{},context:H5,output:D5},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:U5,variants:x9()}},...$[D9]?{}:{[D9]:{...J,id:D9,name:"Claude Opus 5.5",api:J.api?{...J.api,id:D9}:void 0,cost:{input:U9.input,output:U9.output,cache:{read:U9.cacheRead,write:U9.cacheWrite5m}},limit:{...J.limit??{},context:_5,output:L5},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:N5,variants:x9()}}}}var eG=["low","medium","high","xhigh","max"];function x9(){return Object.fromEntries(eG.map(($)=>[$,{thinking:{type:"adaptive",display:"summarized"},effort:$}]))}function $2($){return Object.fromEntries(Object.entries($).map(([J,W])=>{let X=W.api?.id??W.id??J;return[J,d5(X)||l5(X)||o5(X)||u5(X)?{...W,variants:x9()}:W]}))}function J2($){return Object.fromEntries(Object.entries($).map(([J,W])=>[J,{...W,cost:dG}]))}function $8(){return process.env.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||void 0}var Z2=async($,J={})=>{let W={setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,setInterval:globalThis.setInterval,clearInterval:globalThis.clearInterval,...J},X=J.authorize??Q7;mG();let{client:V}=$,O=globalThis.fetch,z=I5(),H=h5(b5(z)),w=600000,R=50,A=new Map;function c(){let Z=Date.now();for(let[Y,G]of A)if(Z-G.createdAt>w)A.delete(Y)}function a(Z,Y){if(c(),A.size>=R){let G="",K=1/0;for(let[j,L]of A)if(L.createdAt<K)K=L.createdAt,G=j;if(G)A.delete(G)}A.set(Z,Y)}function u(Z){c();let Y=A.get(Z);if(!Y)return;if(Date.now()-Y.createdAt>w){A.delete(Z);return}return Y}let s=await FG(z),T=rY({paths:s,host:"opencode",local:J.nativeLocal,vault:J.claustrumScopedConnect?{connect:J.claustrumScopedConnect}:void 0}),o=T.quotaObservations,q0=null;function G0(Z){return e5(Z)}function I0(Z,Y){return Z?G0(Z.binding):Y?JSON.stringify([Y.credentialId,Y.accountIdentity,Y.recordVersion]):void 0}function L0(Z,Y,G,K=q0){let j=o.get(Z);if(!j||!Y||j.lineage!==Y||j.accountUuid!==G||F1(j.entry.quota,K,j.entry.checkedAt)<=Date.now())return;return j}function b(Z,Y,G,K,j=q0){let L=L0(Z,Y,G,j);if(!L)return K;if(!K)return{...L.entry,refreshAfter:F1(L.entry.quota,j,L.entry.checkedAt)};let N=L.entry.quota.source!=="headers"&&T1(K.quota)>T1(L.entry.quota)?K.quota:h7(K.quota,L.entry.quota);return{...L.entry,quota:N,refreshAfter:F1(N,j,T1(N))}}function O0(Z,Y,G){if(!o.has(Z.id))return Z.quota;let K=Z.binding?G0(Z.binding):I0(void 0,G),j=T1(Z.quota);return b(Z.id,K,Z.accountIdentity,Z.quota?{quota:Z.quota,checkedAt:j,refreshAfter:F1(Z.quota,Y,j)}:null,Y)?.quota}let m0;async function q(Z=z){if(Z!==z)throw Error("Native account storage mismatch");let Y=await T.read();if(q0=Y.policyStorage,!m0){let j=Y.accounts.find((L)=>L.id==="main")?.binding;if(j)m0={rowId:j.rowId,credentialEpoch:j.credentialEpoch}}if(Y.mode!=="claustrum")return Y.policyStorage;let G=Y.accounts.find((j)=>j.id==="main"&&j.source==="vault"),K=F$(G?.accountIdentity);return{...Y.policyStorage,claustrum:{...Y.policyStorage.claustrum,mode:"claustrum",scopedRoster:!0,primaryAccount:G?.credentialId&&K?{credentialId:G.credentialId,accountId:K,state:G.state??"cold",enabled:G.enabled}:void 0}}}async function s0(Z,Y){return await T.updateSettings((G)=>W2(G,Z,Y)),q()}let A1=async(Z)=>{return await T.updateSettings((Y)=>({...Y,claudeCache:{...Y2(Y.claudeCache),enabled:Z,mode:w4({...Y,version:1,accounts:[]})}})),q()},A4=(Z)=>s0("claudeCache",{mode:Z}),R4=(Z)=>s0("cacheKeep",{enabled:Z}),$1=async()=>{return await T.updateSettings(X2),q()},R1=(Z,Y)=>s0("cacheKeep",{enabled:!0,always:!1,startHour:Z,endHour:Y}),q4=(Z)=>s0("cacheKeep",{subagents:Z}),j1=(Z)=>s0("dump",{enabled:Z}),f9=(Z)=>s0("claudeFast",{enabled:Z}),k9=async(Z)=>{return await T.setLoggingLevel(Z),q()},x$=(Z,Y=z)=>s0("prime",{enabled:Z}),v9=(Z,Y=z)=>s0("routing",{mode:Z}),x0=(Z)=>s0("killswitch",Z),w$=(Z,Y,G=z)=>T.setEnabled(Z,Y),l1=(Z,Y=z)=>T.remove(Z),T$=(Z,Y=z,G)=>T.reorder(Z,G),a0=null;try{a0=await q()}catch{}function b0(Z){return Boolean(Z&&T4(Z)==="claustrum"&&Z.claustrum?.scopedRoster===!0)}function h9(Z=z,Y=$.directory){if(Z!==z)throw Error("Native vault storage mismatch");return T.vault}let u1=F5("native-auth");async function d1(Z=z){n9?.close(),await u1.drain(),await T.drainQuotaPublications(),await Promise.all([...m9.values()].map((Y)=>Y.drain())),await T.drainRoutingPublications(),T.close()}function G$(){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native OAuth cannot serve while OPENCODE_AUTH_CONTENT is set")}function J1(Z){let Y=F$(Z);if(!Y)throw Error("Native wire identity requires an admitted provider account");return x5(Y,Y)}class Z1 extends Error{account;checkIntervalMs;constructor(Z,Y){super("OAuth account cannot serve the requested model under current quota policy");this.account=Z;this.checkIntervalMs=Y}}class E0 extends Error{constructor(){super("Native OAuth requires a Claude Pro/Max credential. An API key belongs in OpenCode stock Anthropic authentication.")}}class O$ extends Error{account;tokenRefreshFailed;failure;constructor(Z,Y,G=!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: ${Y}`);this.account=Z;this.tokenRefreshFailed=G;this.failure=K}}async function A0(Z,Y,G,K,j="serve",L){G$(),Y?.throwIfAborted();let N=L??await T.read(),_=N.accounts.find((m)=>m.id===Z);if(_?.state==="unsupported-access")throw new E0;if(_?.source==="vault"&&!y0(_))throw new O$(_,"not-active");if(_?.type!=="oauth"||!y0(_))throw Error("Native OAuth account is unavailable");let Q=(m,J0,j0)=>{let f0=O0(m,J0,j0),w0=j==="last-main"&&Z==="main"&&e$(J0)!=="sticky-balanced";if(K&&(r$(J0)&&!a$(f0,J0,Z==="main"?void 0:Z,K)||!w0&&!R9(f0,K)))throw new Z1(m,M7(J0))};Q(_,N.policyStorage);let U;if(_.source==="vault"){let m=await T.authorizeVault(Z,Y).catch((J0)=>{if(Y?.throwIfAborted(),J0 instanceof a5&&["not-active","route-declined","route-unavailable"].includes(J0.code))throw new O$(_,J0.code);throw J0});U={accessToken:m.accessToken,expires:m.expiresAtMs??void 0,accountIdentity:m.accountIdentity,scopedAttempt:m}}else{let m=await T.authorizeLocal(Z,{signal:Y,rejectedAccessToken:G,intent:G?"refresh":j==="last-main"?"serve":j});if(m.status!=="usable")throw new O$(_,m.status,m.status==="failed"&&m.failure.kind==="provider",m.status==="failed"?m.failure:void 0);U={accessToken:m.access,expires:m.expires,accountIdentity:m.binding.identity,localSubject:m.subject,localSource:m.source}}let C=await T.read(),f=C.accounts.find((m)=>m.id===Z);if(Y?.aborted)throw Y.reason??Error("Request aborted");if(!f||!y0(f)||f.source!==_.source||f.accountIdentity!==U.accountIdentity)throw Error("Native OAuth account changed before dispatch");if(U.localSubject&&(!f.binding||f.binding.storageId!==U.localSubject.binding.storageId||f.binding.rowId!==U.localSubject.binding.rowId||f.binding.credentialEpoch!==U.localSubject.binding.credentialEpoch||f.binding.identity!==U.localSubject.binding.identity))throw Error("Native local account binding changed before dispatch");if(U.scopedAttempt&&f.credentialId!==U.scopedAttempt.credentialId)throw Error("Native vault credential binding changed before dispatch");return Q(f,C.policyStorage,U.scopedAttempt),U}async function q1(Z,Y){let K=(await T.read()).accounts.find((L)=>L.id===Z);if(K?.type!=="oauth")throw Error("Native OAuth account is unavailable");let j=K.source==="vault"?await T.authorizeVault(Z,Y):await T.captureLocalSubject(Z);if(!await T.resetBackoff(Z,j))throw Error("Native reset fence changed")}let _1=new WeakMap,i1=new WeakSet;async function M0(Z,Y){if(i1.has(Z))return;i1.add(Z),await T.vault.reportFailure(Z,401,Y).catch(()=>{h.warn("claustrum","native auth-failure report unavailable")})}async function L1(Z,Y,G){let K=await T.vault.prepareRetry(Z,G,Y);return K.retry?K.receipt:void 0}let b9=i3(process.env.OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE),W1=new MJ,g9=new fJ,n1=new RJ,M1=new LJ,f$=new Map,N$=new Map,S$=new Map,M4=new Map,X$=new Set,y9=new Map,I4=new Map,m$=new Map,o1=new Map,m9=new Map;async function LZ(){let Z=await T.read(),Y=Z.routingPath;if(!Y)throw Error(Z.mode==="claustrum"?"Vault routing storage is unavailable":"Native routing storage is unavailable");let G;if(Z.mode==="claustrum"){G=new Map;for(let j of Z.accounts)if(j.source==="vault"&&j.accountIdentity)G.set(j.id,j.accountIdentity)}let K=m9.get(Y);if(!K)K=new wG({path:Y,vaultSeed:Z.routingSeed,onLockEvent:T.onLockEvent,localRecoveryPath:Z.mode==="local"?Z.routingRecoveryPath:void 0}),m9.set(Y,K);return K.setVaultSeed(Z.routingSeed),{router:K,...G&&{accountIdentities:G}}}let k=new HG({storage:a0,pauseBetweenQuotaCalls:J.quotaCallPause,fetchQuotaSnapshot:(Z,Y)=>{G$();let G=Z.kind==="main"?"main":Z.accountId;if(!G)throw Error("Quota request has no account identity");return T.fetchQuota(G,void 0,void 0,Y,Z.purpose)}});function r1(Z){return["five_hour","seven_day"].some((Y)=>(Z?.[Y]?.remainingPercent??1)<=0)}function NZ(Z,Y,G=!1){if(!Z||Z.quota?.enabled===!1||!Y||e$(Z)==="sticky-balanced"||s$(Z.refresh?.mainLastRefreshError))return;let K=Date.now(),j=Z.quota?.mainLastQuotaApiError;if(j&&j.accountIdentity===Y&&j.nextRetryAt!==void 0&&j.nextRetryAt>K)return{message:R7(j,K),retryAfter:Math.max(1,Math.ceil((j.nextRetryAt-K)/1000))};let L=Z.quota?.mainQuota,N=T1(L);if(L?.accountIdentity!==Y||L.source==="headers"&&!G||!r1(L)||N<=0||N>K||F1(L,Z,N)<=K)return;let _=["five_hour","seven_day"].flatMap((Q)=>{let U=L[Q],C=U?.resetsAt?Date.parse(U.resetsAt):Number.NaN;return U&&U.remainingPercent<=0&&Number.isFinite(C)&&C>K?[C]:[]});return{message:"Claude OAuth quota is exhausted for this account.",retryAfter:Math.max(1,Math.ceil(((_.length?Math.max(..._):K+M7(Z))-K)/1000))}}async function HZ(Z,Y,G){if(JJ===Z&&H$===Y)return;let K=D1!==void 0&&G!==void 0&&D1!==G;JJ=Z,H$=Y,k.setMainQuotaAccountIdentity(Y,!0,K)}async function s1(Z,Y,G,K){let j=Z,L=c4.get(j);if(L){let _=await L.promise;return K===L.recordVersion?_:{..._,stale:!0}}let N=(async()=>{let _=++fZ,Q=e1,U=await T.read(),C=U.policyStorage,f=U.accounts.find((V1)=>V1.id==="main")?.accountIdentity,m=J1(G??f),J0=U.mode==="claustrum",j0=J0?C?.claustrum?.primaryAccount?.accountId:void 0;if(G!==void 0&&G!==f||J0&&G===void 0)return{quotaKey:void 0,providerAccountUuid:void 0,generation:k.getMainQuotaIdentityGeneration(),stale:!0,state:"on-identity-mismatch"};let f0=f??j0??Q,w0=C?.main?.profile?.providerAccountUuid??C?.main?.profile?.accountIdentity,k0=F$(G)??F$(m.accountUuid),N0=G?k0:Z.startsWith("sk-ant-oat")?k0??F$(w0):void 0,j$=T4(C)!=="claustrum"?"na":w0===void 0||k0===void 0?"unknown-identity":w0!==void 0&&k0!==void 0&&w0!==k0?"on-identity-mismatch":"on-vault-served";if(_!==fZ){let V1=JJ!==Z||H$!==f0;return{quotaKey:f0,providerAccountUuid:N0,generation:k.getMainQuotaIdentityGeneration(),stale:V1,state:j$}}if(await HZ(Z,f0,N0),Z.startsWith("sk-ant-oat")&&N0===void 0)k.clearMain();if(D1=N0,Z.startsWith("sk-ant-oat"))$4=Z;return{quotaKey:f0,providerAccountUuid:N0,generation:k.getMainQuotaIdentityGeneration(),stale:!1,state:j$}})();c4.set(j,{promise:N,recordVersion:K});try{return await N}finally{if(c4.get(j)?.promise===N)c4.delete(j)}}let c9=a0?.quotaHeaderFeed?.enabled===!0?new NG:null,c$=new Map,DZ=new Map,X1=new Set,Y1=new AbortController,UZ=!1;function x4(Z,Y){return JSON.stringify([Z,Y??null])}function p9(Z){let Y=Z.binding;if(Z.source!=="local"||!Y)return;return JSON.stringify([Y.storageId,Y.rowId,Y.credentialEpoch])}function l9(Z,Y){return Z.lineage!==void 0&&Z.lineage===p9(Y)&&(!Z.profile||Z.profile.accountIdentity===Y.accountIdentity)}async function f4(Z,Y){if(!Z?.profile||!C9(Z.profile,Y)||!await Z.isCurrent?.())return;return Z.persistence==="refused"?void 0:Z.profile}function QZ(Z){if(!Z)return[];let Y=new Set([...Z.main?["main"]:[],...(Z.accounts??[]).filter((G)=>B0(G)&&(G.enabled!==!1||Boolean(G.claustrumScopedCredentialId))).map((G)=>G.id)]);return[...new Set(c$.values())].filter((G)=>G.persistence==="failed"&&G.profile!==void 0&&Y.has(G.accountId))}async function _8(Z,Y,G,K){let j=Y.accountId,L=G.accounts.find((Q)=>Q.id===j),N=L?.source==="local"?l9(Y,L):L?.source==="vault"&&L.accountIdentity===K.accountIdentity;if(L?.type!=="oauth"||!y0(L)||L.accountIdentity!==K.accountIdentity||!N||await f4(Y,Date.now())!==K)return Z;if(j==="main")return Z.main?{...Z,main:{...Z.main,profile:K}}:Z;let _=Z.accounts?.find((Q)=>Q.id===j);if(!_||!B0(_))return Z;return{...Z,accounts:Z.accounts.map((Q)=>Q.id===j&&B0(Q)?{...Q,profile:K}:Q)}}async function BZ(Z,Y,G=QZ(Z)){if(!Z||G.length===0)return Z;let K=[];for(let N of G){let _=await f4(N,Date.now());if(_)K.push({hydration:N,profile:_})}if(!K.length)return Z;let j=Y??await T.read(),L=Z;for(let N of K)L=await _8(L,N.hydration,j,N.profile);return L}function L8(Z,Y,G){G$();let K=!1,j=Object.assign((N,_)=>{return K=!0,O(N,_)},{preconnect:O.preconnect}),L={accountId:Z.id,fetched:Promise.resolve(),lineage:p9(Z),...G&&{deadline:G}};return L.fetched=T.fetchProfileForDisplay(Z.id,j,AbortSignal.any([Y1.signal,...G?[G]:[]])).then(({profile:N,persisted:_,isCurrent:Q})=>{if(L.settled=!0,N.accountIdentity!==void 0)DZ.set(x4(Z.id,N.accountIdentity),N);if(Z.accountIdentity===void 0||N.accountIdentity===Z.accountIdentity)L.profile=N,L.isCurrent=Q,L.persistence="pending";let U=_.then(async(C)=>{if(L.persistence=C,C==="failed")h.warn("quota","failed to persist account profile",{account:Z.id});else if(C==="refused")h.debug("quota","refused account profile publication",{account:Z.id});if((C==="saved"||C==="failed")&&!Y1.signal.aborted){let f=C==="failed"&&await f4(L,Date.now());if(C==="saved"||f)try{let m=await T.read();if(!Y1.signal.aborted)await C$(m.policyStorage,{...$$,routingAuthoritative:!1},m)}catch{h.debug("quota","failed to publish account profile to sidebar",{account:Z.id})}}});X1.add(U),U.then(()=>X1.delete(U))},(N)=>{if(L.settled=!0,L.failed=K,h.debug("quota","failed to hydrate account profile",{account:Z.id,error:N instanceof Error?N.message:String(N)}),!K&&c$.get(Y)===L)c$.delete(Y)}),X1.add(L.fetched),L.fetched.then(()=>X1.delete(L.fetched)),L}function N8(Z,Y){let G=[Y,Z.deadline].filter((j)=>j!==void 0);if(!G.length)return Z.fetched;let K=AbortSignal.any(G);if(K.aborted)return Promise.resolve();return new Promise((j)=>{let L=()=>{K.removeEventListener("abort",L),j()};K.addEventListener("abort",L,{once:!0}),Z.fetched.then(L)})}function FZ(Z,Y){return C9(Z.profile,Y)&&JG(Z.profile,Z.accountIdentity)}async function k4(Z){let Y=await T.read();if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return Y;let G=Date.now(),K=[],j=new Map;for(let _ of Y.accounts){if(_.type!=="oauth"||!y0(_)||FZ(_,G))continue;let Q=x4(_.id,_.accountIdentity),U=c$.get(Q);if(U&&_.accountIdentity===void 0&&(U.lineage===void 0||U.lineage!==p9(_)))U=void 0;if(!U&&_.accountIdentity!==void 0){let C=c$.get(x4(_.id));if(C&&l9(C,_))U=C,j.set(_.id,C)}if(U?.failed)continue;if(!U&&C9(DZ.get(Q),G))continue;if(!U||!U.profile&&(U.deadline?.aborted||U.settled)||U.profile&&!C9(U.profile,G)){if(Z?.aborted||Y1.signal.aborted)continue;U=L8(_,Q,Z),c$.set(Q,U)}if(_.accountIdentity===void 0)j.set(_.id,U);K.push(N8(U,Z))}if(!K.length)return Y;await Promise.all(K);let L=await T.read(),N=Date.now();for(let _ of L.accounts){if(_.type!=="oauth"||!y0(_))continue;let Q=x4(_.id,_.accountIdentity),U=j.get(_.id);if(U&&_.accountIdentity!==void 0&&!c$.has(Q)&&l9(U,_))c$.set(Q,U);if(FZ(_,N))continue;let C=await f4(c$.get(Q),N);if(!C||C.accountIdentity!==_.accountIdentity)continue;if(_.profile=C,_.id==="main"){if(L.policyStorage.main)L.policyStorage.main.profile=C}else for(let f of L.policyStorage.accounts)if(f.id===_.id&&B0(f))f.profile=C}return L}async function H8(Z,Y,G,K){if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return Z;return(await k4(G)).policyStorage}let wZ=new Set;async function D8(Z,Y,G){let j=(await T.read()).accounts.find((U)=>U.id===Z.accountId);if(!j||!Z.anthropicAccountUuid||j.accountIdentity!==Z.anthropicAccountUuid)return null;let L={...h7(j.quota,Y.quota),accountIdentity:j.accountIdentity};if(!(Z.scopedAttempt?await T.vault.publish(Z.scopedAttempt,{quota:L}):Z.localSubject?await T.publishLocal(Z.localSubject,{quota:L}):!1)){if(Z.accountId==="main"){if(k.getMain(Z.mainQuotaIdentity?.quotaKey)===G)k.clearMain()}else if(k.getAllFallbacks().get(Z.accountId)===G)k.clearFallback(Z.accountId);return h.debug("quota","native quota publication refused",{accountId:Z.accountId}),null}let _=await T.read(),Q=_.accounts.find((U)=>U.id===Z.accountId);if(!Q?.quota||Q.accountIdentity!==Z.anthropicAccountUuid||Q.source!==j.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{...Y,quota:Q.quota,refreshAfter:F1(Q.quota,_.policyStorage,Y.checkedAt)}}function U8(Z){h.warn("quota","failed to persist harvested response quota",{error:Z instanceof Error?Z.message:String(Z)})}function Q8(Z){let Y=Z instanceof Error?Z.name:typeof Z,G=Z instanceof Error?Z.message:String(Z),K=`${Y}:${G}`;if(wZ.has(K))return;wZ.add(K),h.warn("quota","failed to normalize response quota headers",{error:G})}function B8(Z){if(!Z||typeof Z!=="object")return;let Y=Z,G=Y.credential_id;if(typeof G==="string"&&G&&G!=="main")return G;let K=Y.vault;if(K&&typeof K==="object"){let j=K.credential_id;if(typeof j==="string"&&j&&j!=="main")return j}return}async function F8(Z,Y){if(!c9)return;if(Z.accountId==="main"&&!Z.mainQuotaIdentity?.quotaKey)return;let G=await q(z)??o$(),j=(await G1?.())?.type==="oauth",L=Z.accountId==="main"?G.main:G.accounts.find((m)=>m.id===Z.accountId),N=B8(L),_=B5({storage:G,mainOAuthConfigured:j}),Q=Y.checkedAt,U={five_hour:Y.quota.five_hour,seven_day:Y.quota.seven_day,bindingWindow:Y.quota.bindingWindow,fallbackAdvised:Y.quota.fallbackAdvised,scoped:Y.quota.scoped,extraUsage:Y.quota.extraUsage,fieldSources:Y.quota.fieldSources},C=N??(Z.accountId==="main"?Z.mainQuotaIdentity?.quotaKey??"main":Z.accountId),f=N?{identity_source:"credential_id",credential_id:N,schema_version:P9,provider:"anthropic",configured_account_count:_,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C}:Z.accountId==="main"&&Z.mainQuotaIdentity?.quotaKey?{identity_source:"account_ref",account_ref:Z.mainQuotaIdentity.quotaKey,schema_version:P9,provider:"anthropic",configured_account_count:_,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C}:Z.accountId==="main"?{identity_source:"none",schema_version:P9,provider:"anthropic",configured_account_count:_,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C}:{identity_source:"account_ref",account_ref:Z.accountId,schema_version:P9,provider:"anthropic",configured_account_count:_,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C};await c9.publish(f)}function w8(Z){h.debug("quota","failed to publish quota header feed",{error:Z instanceof Error?Z.message:String(Z)})}function TZ(Z,Y){try{if(!s5(Z)){h.trace("quota","skipped non-quota response headers",{account:Y.accountId});return}let G=$G(Z),K=Y.accountId==="main"?Y.mainQuotaIdentity:void 0;if(Y.accountId==="main"){if(!K||k.getMainQuotaIdentityGeneration()!==K.generation){h.trace("quota","discarded stale main quota headers",{boundIdentity:K?.quotaKey,currentGeneration:k.getMainQuotaIdentityGeneration()});return}}let j=Y.accountId==="main"?k.getMain(K?.quotaKey):k.getAllFallbacks().get(Y.accountId),L=G.checkedAt??Date.now(),N=I0(Y.localSubject,Y.scopedAttempt),_=N&&Y.anthropicAccountUuid?{lineage:N,accountUuid:Y.anthropicAccountUuid,entry:{quota:{...G,accountIdentity:Y.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 G[Q]!==void 0&&U!==null&&Number.isFinite(Number(U))&&Number(U)>=1})}:void 0;if(_){if(o.delete(Y.accountId),o.size>=iG){let Q=o.keys().next().value;if(Q!==void 0)o.delete(Q)}o.set(Y.accountId,_)}(async()=>{let Q=!1;try{let U;try{U=await D8(Y,{quota:G,checkedAt:L,refreshAfter:L},j)}catch(f){U8(f);return}if(U===null)return;if(Y.accountId==="main"&&k.getMainQuotaIdentityGeneration()!==K?.generation)return;let C=U;if(_&&o.get(Y.accountId)===_)_.entry=C,Q=!0;if(Y.accountId==="main")k.setMain(K?.quotaKey,C);else k.setFallback(Y.accountId,C,{authLineageId:Y.authLineageId});x1().catch(()=>{}),await F8(Y,C),h.debug("quota","harvested response quota",{account:Y.accountId,fiveHourPercent:C.quota.five_hour?.usedPercent,sevenDayPercent:C.quota.seven_day?.usedPercent,source:"headers"})}finally{if(!Q&&_&&o.get(Y.accountId)===_)o.delete(Y.accountId),h.debug("quota","discarded pending response quota",{accountId:Y.accountId})}})().catch(w8),h.trace("quota","response quota awaiting publication",{account:Y.accountId})}catch(G){Q8(G)}}let SZ=Promise.resolve();function N1(Z=!1,Y=!1,G,K){let j=SZ.then(()=>T8(Z,Y,G,K));return SZ=j.then(()=>{},()=>{}),j}async function T8(Z,Y,G,K){let j=await T.read(),L=new Set;if(!Z&&!Y&&j.policyStorage.quota?.enabled===!1)return L;for(let N of j.accounts){if(N.id==="main"||N.type!=="oauth")continue;if(!y0(N)){if(Y)L.add(N.id);continue}if(!Z&&F1(N.quota,j.policyStorage,T1(N.quota))>Date.now()&&(!G||C1(N.quota,j.policyStorage,Date.now(),G)))continue;try{if(!await k.refreshFallback(N.id,"",j.policyStorage.accounts.find((Q)=>Q.id===N.id&&B0(Q)),Z?void 0:K))L.add(N.id),h.debug("quota","fallback quota preflight returned no reading",{accountId:N.id,requiredByPolicy:Y})}catch(_){if(Y&&w1(_))throw _;L.add(N.id),q3(N.id,Y,_)}}return x1().catch(()=>{}),L}let u9={refreshQuotaForDueAccounts:async()=>{await N1()},refreshQuotaForAllAccounts:async(Z)=>{await N1(!0)},refreshAccount:async(Z,Y,G)=>{let K=await A0(Z.id,void 0,G?.force?Z.access:void 0);return{...Z,access:K.accessToken,expires:K.expires}},refreshAccountQuota:async(Z,Y)=>{G$();let G=await T.fetchQuota(Z.id);return{account:{...Z,quota:G},fetched:!0}},getUsableFallbackAccounts:async(Z,Y)=>{Z=Z??null;let G=[],K=Z?.accounts.some((j)=>B0(j)&&o.has(j.id))?(await T.read()).accounts:[];for(let j of Z?.accounts??[]){if(!B0(j)||!y0(j))continue;let L=K.find((Q)=>Q.id===j.id),N=k.getFallback(j.id,L?.binding?{authLineageId:JSON.stringify(L.binding)}:j)?.quota??L?.quota??j.quota,_=L&&Z?O0({...L,quota:N},Z):N;if(!p1(_,Z)||!R9(_,Y?.modelId)||r$(Z)&&!a$(_,Z,j.id,Y?.modelId))continue;if(b0(Z)){if(K4(j.id,Z))G.push(j);continue}try{let Q=await A0(j.id,void 0,void 0,Y?.modelId);G.push({...j,access:Q.accessToken,expires:Q.expires})}catch(Q){if(w1(Q))throw Q}}return G}};async function d9(){G$();let Z=await T.read();if(Z.mode==="local"&&Z.policyStorage.refresh?.enabled!==!1)for(let Y of Z.accounts){if(Y.id==="main"||Y.type!=="oauth"||!y0(Y))continue;try{let G=await A0(Y.id);if(E1(Y.lastRefreshError,Y.accountIdentity,Date.now(),void 0))continue;if(G.localSource!=="rotated"&&G.localSource!=="adopted"&&(!G.expires||G.expires-Date.now()<=kZ(Z.policyStorage)))await A0(Y.id,void 0,void 0,void 0,"refresh")}catch{}}await N1(!1,!1,void 0,"background")}let i9=a0!==null&&process.env.OPENCODE_AUTH_CONTENT===void 0,EZ=new Set;async function S8(){let Z=await T.read(),Y=new Set(Z.accounts.filter((K)=>K.id!=="main"&&K.source==="vault"&&K.type==="oauth"&&y0(K)).map((K)=>K.id)),G=[...Y].some((K)=>!EZ.has(K));if(EZ=Y,G)await N1(!1,!1,void 0,"background");await x1()}let n9=i9&&b0(a0)?T.vault.watch({intervalMs:J.scopedRosterPollIntervalMs??2000,shouldRefresh:()=>process.env.OPENCODE_AUTH_CONTENT===void 0,onRefresh:S8,setInterval:W.setInterval,clearInterval:W.clearInterval}):void 0,E8=i9?(n9?n9.ready.then(()=>d9()):d9()).catch(()=>{}):Promise.resolve(),o9=i9?W.setInterval(()=>{d9().catch(()=>{})},R5+t7(r7)):null;o9?.unref?.();let C8=(Z,Y)=>{let G=wJ({id:Z,role:"fallback"},Y);return G==="na"?"off":G},r9=new NJ,P8=new HJ,p$=new WeakMap,a1=new Map;async function s9(Z){let Y=(Z.get("anthropic-beta")??"").split(",").map((G)=>G.trim()).filter(Boolean).sort();return{betas:Y,betasHash:await Q5(Y.join(","))}}function CZ(Z){try{if(!Z.request)return;let Y=J3({request:Z.request,source:Z.source,accountId:Z.accountId,synthetic:Z.synthetic,betasHash:Z.betasHash,requestedModel:Z.requestedModel,onWarning:(K)=>h.warn("cache-diagnostics",K),message:Z.message,receivedAt:Z.receivedAt});if(!Y.record||!Y.messageId){h.debug("cache-diagnostics","skipped invalid response envelope",{status:Z.status});return}h.debug("cache-diagnostics",Z3(Y.record));let G=P8.capture(Z.betasHash,Z.betas);if(G)h.debug("cache-diagnostics",G);if(Y.canary)h.warn("cache-diagnostics","short-gap previous_message_not_found",{message_id:Y.canary.messageId,previous_message_id:Y.canary.previousMessageId});if(Z.trackSessionId)r9.capture(Z.trackSessionId,Y.messageId,Z.receivedAt)}catch(Y){h.debug("cache-diagnostics","response observation failed",{status:Z.status,error:Y instanceof Error?Y.message:String(Y)})}}function PZ(Z,Y,G=!0){let K=p$.get(Z);if(!K)return;if(Y&&typeof Y==="object"&&!Array.isArray(Y)&&!G)K.messageStart=Y;K.dumpWrite=K.dumpWrite.then(()=>sJ(K.dump,{status:K.status,message:Y,complete:G})).catch(()=>{}),CZ({...K,message:Y,receivedAt:Date.now()})}function A8(Z,Y){let G=p$.get(Z);if(!G)return;let K=G.messageStart??{},j=K.usage&&typeof K.usage==="object"&&!Array.isArray(K.usage)?K.usage:{},L={...K,...Y.usage?{usage:{...j,...Y.usage}}:{},...Y.stopReason?{stop_reason:Y.stopReason}:{}};G.dumpWrite=G.dumpWrite.then(()=>sJ(G.dump,{status:G.status,message:L,complete:!0})).catch(()=>{})}function AZ(Z,Y){let G=Promise.resolve(sJ(Y.dump,{status:Y.status,message:null,complete:!1})).catch(()=>{});p$.set(Z,{...Y,dumpWrite:G})}let l$=null,v4=null;function h4(Z){return Z!==null&&typeof Z==="object"&&FJ(Z)==="R"}function R8(Z){let Y=oJ("anthropic");if(!Z||typeof Z!=="object")return!1;let G=Z;return G.type===Y.type&&G.access===Y.access&&G.refresh===Y.refresh&&G.expires===Y.expires}async function q8(){if(v4){let Z=await v4();return m5("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 UG("opencode",W8())}async function RZ(){if(await S1("opencode")!=="claustrum")throw Error("This host is not connected to the credential vault; run setup to connect it first");if(await q8()!=="absent")throw Error("OpenCode already holds an Anthropic login; remove it before choosing the vault login")}let M8={label:"Claude via credential vault",type:"oauth",authorize:async()=>{return await RZ(),{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 RZ();let Z=oJ("anthropic");return{type:"success",access:Z.access,refresh:Z.refresh,expires:Z.expires}}}}},a9=new Z5({directory:process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||k5("opencode")}),b4=[],I1=new Map,t1=new J5({loadStorage:()=>q(z),setIntervalImpl:W.setInterval,clearIntervalImpl:W.clearInterval,onTrackedSessionsChanged:async(Z)=>{await a9.publish(Z),b4=await a9.list(Z)},prepareBody:(Z,Y)=>{if(!new Headers(Y.headers).get("anthropic-beta")?.split(",").map((G)=>G.trim()).includes(V4))return Z;try{let G=JSON.parse(Z),K=r9.previousFor(Y.id),j=K?.messageId??null;return o4(G,j),a1.set(Y.id,{sessionId:Y.id,previousMessageId:j,...K?{previousMessageReceivedAt:K.receivedAt}:{},isSubagent:Y.isSubagent,ttlSent:r4(G),accountId:Y.oauthAccountId??"main",synthetic:!0,requestedModel:typeof G.model==="string"?G.model:void 0}),JSON.stringify(G)}catch{return Z}},onResponse:async({target:Z,bodyText:Y,status:G,data:K,receivedAt:j,attempt:L})=>{let N=I1.get(L.id);if(G===401&&N?.scopedAttempt)await M0(N.scopedAttempt,"direct");let _=a1.get(Z.id);if(!_?.betasHash||!_.betas){a1.delete(Z.id);return}try{let Q=JSON.parse(Y),U=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q.diagnostics:void 0,C=U&&typeof U==="object"&&!Array.isArray(U)&&U.previous_message_id===_.previousMessageId?_.previousMessageId:void 0;if(C===void 0)return;CZ({source:"prewarm_cachekeep",accountId:_.accountId,synthetic:_.synthetic,betasHash:_.betasHash,betas:_.betas,requestedModel:_.requestedModel,request:{..._,previousMessageId:C,ttlSent:r4(Q)},trackSessionId:Z.id,status:G,message:K,receivedAt:j})}catch{}finally{a1.delete(Z.id)}},onComplete:({attempt:Z})=>{I1.delete(Z.id)},retryOnUnauthorized:async({target:Z,headers:Y,attempt:G})=>{let K=I1.get(G.id);if(!K)return;let j;try{let _=JSON.parse(Z.bodyText);if(typeof _.model==="string")j=_.model}catch{}if(K.scopedAttempt&&!await L1(K.scopedAttempt,"cachekeep",G.signal))return;let L=await A0(Z.oauthAccountId??"main",G.signal,K.scopedAttempt?void 0:K.accessToken,j);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 N=new Headers(Y);return N.set("authorization",`Bearer ${L.accessToken}`),I1.set(G.id,L),N},prepareHeaders:async(Z,Y,G)=>{let K=Y.oauthAccountId??"main",j;try{let Q=JSON.parse(Y.bodyText);if(typeof Q.model==="string")j=Q.model}catch{}let L=await A0(K,G.signal,void 0,j),N=L.accessToken;I1.set(G.id,L);try{let Q=JSON.parse(Y.bodyText),U=J1(L.accountIdentity);if(Z.delete("anthropic-beta"),m1(Z,N,{body:Q,identity:U}),Z.set("anthropic-beta",v7(Z.get("anthropic-beta"),[$5])),Q.speed==="fast")j9(Z);let C=a1.get(Y.id);if(C){let{betas:f,betasHash:m}=await s9(Z);C.betas=f,C.betasHash=m}}catch{m1(Z,N)}let _=await A0(K,G.signal,void 0,j);if(_.accountIdentity!==L.accountIdentity||Boolean(_.scopedAttempt)!==Boolean(L.scopedAttempt))throw Error("CacheKeep credential authority changed before dispatch");return Z.set("authorization",`Bearer ${_.accessToken}`),I1.set(G.id,_),Z}});async function I8(Z){if(!l$||!(await l$()).active)throw Error("Native main OAuth activation is not available");let Y=await A0("main",Z);return{...Y,credentialAccountId:F$(Y.accountIdentity)}}async function x8(){let Z=await I8();if((await s1(Z.accessToken,void 0,Z.credentialAccountId)).stale&&Z.credentialAccountId!==void 0)throw Error("Main account identity changed before the prime refresh");let G=await k.refreshMainWithMetadata(H$,Z.accessToken);return{quota:G.quota,fresh:G.fetched}}async function f8(Z){G$();let Y=await q(z),G=Y?.accounts.find((j)=>j.id===Z&&y0(j)&&B0(j));if(!G||!Y)throw Error(`prime: OAuth account ${Z} is unavailable`);let K=await u9.refreshAccountQuota(G,Y);return{quota:K.account.quota??{},fresh:K.fetched}}let t9=new Map;async function k8(Z){let Y=performance.now(),G,K,j,L="",N;try{if(Z==="main"&&(!l$||!(await l$()).active))throw Error("Native main OAuth activation is not available");let _=await A0(Z,void 0,void 0,B7);if(G=_.accessToken,j=_.scopedAttempt,K=B7,!G)return{ok:!1,error:"prime: no access token available"};let Q=eY(),U=J1(_.accountIdentity),C=await _9(JSON.stringify(Q),{identity:U}),f=new Headers({"content-type":"application/json"});m1(f,G,{body:JSON.parse(C),identity:U,requestClass:"auxiliary"}),f.delete("content-length"),f.delete("transfer-encoding");let m=Q4(qG,{baseURL:""}),J0=m.url?.toString()??m.input.toString(),j0=AbortSignal.timeout(30000),f0={method:"POST",headers:f,body:C,signal:j0},w0=await A0(Z,j0,void 0,K);if(w0.accountIdentity!==_.accountIdentity||Boolean(w0.scopedAttempt)!==Boolean(_.scopedAttempt))throw Error("Prime credential authority changed before dispatch");j=w0.scopedAttempt,L=w0.accessToken,f.set("authorization",`Bearer ${L}`);let k0=async()=>{let Q0=F9([L],"http");return N=Q0,Q0.redactResponse(await fetch(J0,f0))},N0=await k0();if(N0.status===401&&j&&!j0.aborted){let Q0;try{Q0=await L1(j,"prime",j0)}catch{}if(Q0){N?.dispose(),await N0.body?.cancel().catch(()=>{}),h.info("claustrum","retrying Prime after scoped credential rotation",{accountId:Z,previousVersion:j.recordVersion,newVersion:Q0.recordVersion}),w0=await A0(Z,j0,void 0,K);let v0=w0.scopedAttempt;if(!v0||v0.credentialId!==j.credentialId||v0.accountIdentity!==j.accountIdentity||v0.recordVersion<=j.recordVersion)throw Error("Prime vault retry lost its strict newer receipt");j=v0,L=v0.accessToken,f.set("authorization",`Bearer ${L}`),N0=await k0()}}if(N0.status===401&&!w0.scopedAttempt&&!j0.aborted){let Q0=w0.accessToken,v0=await A0(Z,j0,Q0,K).catch(()=>{return});if(v0&&v0.accessToken!==Q0&&v0.accountIdentity===_.accountIdentity&&!v0.scopedAttempt){if(N?.dispose(),await N0.body?.cancel().catch(()=>{}),w0=await A0(Z,j0,void 0,K),w0.scopedAttempt||w0.accountIdentity!==_.accountIdentity)throw Error("Prime local authority changed before retry");L=w0.accessToken,f.set("authorization",`Bearer ${L}`),N0=await k0()}}let j$=Math.round(performance.now()-Y);if(!N0.ok){let Q0;try{Q0=await N0.text().catch(()=>"")||`HTTP ${N0.status}`}finally{N?.dispose()}if(N0.status===401&&j)await M0(j,"direct");return{ok:!1,status:N0.status,ms:j$,error:Q0}}let D$=(await N0.json().catch(()=>null))?.usage,U$=D$&&(Number.isFinite(D$.input_tokens)||Number.isFinite(D$.output_tokens))?{inputTokens:Number.isFinite(D$.input_tokens)?D$.input_tokens:void 0,outputTokens:Number.isFinite(D$.output_tokens)?D$.output_tokens:void 0}:void 0;return t9.set(Z,w0),{ok:!0,status:N0.status,ms:j$,...U$&&{usage:U$}}}catch(_){N?.dispose();let Q=F9([L],"http"),U=Q.redactError(_);return Q.dispose(),{ok:!1,..._ instanceof O$&&_.tokenRefreshFailed&&{reason:"token-refresh"},ms:Math.round(performance.now()-Y),error:U instanceof Error?U.message:String(U)}}}let qZ={storagePath:z,loadStorage:()=>q(z),getAccountFingerprint:async(Z)=>{if(Z==="main"&&(!l$||!(await l$()).active))return;let Y=await A0(Z),G=Y.scopedAttempt??Y.localSubject;if(!G)return;let K=await T.getOrCreateAuthLineage(Z,G);return K?t$(K):void 0},refreshQuota:async(Z)=>{if(Z==="main")return x8();return f8(Z)},sendPrime:k8,recordSuccess:async(Z,Y)=>{let G=t9.get(Z);t9.delete(Z);let K=G?.scopedAttempt??G?.localSubject;if(!K||!await T.incrementPrimeUsage(Z,K,Y))throw Error("Prime usage publication lost its native credential fence");let j=(await T.read()).accounts.find((L)=>L.id===Z)?.prime;if(!j)throw Error("Prime usage counters are unavailable after publication");return j},setIntervalImpl:W.setInterval,clearIntervalImpl:W.clearInterval,setTimeoutImpl:W.setTimeout,clearTimeoutImpl:W.clearTimeout},MZ=R3(z,()=>new WG(qZ),{slot:$.directory??"default",rebind:(Z)=>Z.updateOptions(qZ)}),H1=MZ.manager;if(E9(a0))H1.start();async function g4(){return b4=await a9.list(t1.trackedSessions()),b4}let IZ=J.cacheKeepAggregateRefreshIntervalMs??1e4,e9=IZ>0?W.setInterval(()=>{g4().catch(()=>{})},IZ):void 0;if(e9?.unref?.(),q9({enabled:S9(a0),mode:w4(a0)}),zZ(WZ(a0)),OZ(YZ(a0)),!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)EG(JZ(a0)??"info");let $J=null,v8=async()=>{Y1.abort();while(X1.size)await Promise.all([...X1]);try{await d1(z)}catch(Z){h.warn("claustrum","failed to close scoped runtime",{error:Z instanceof Error?Z.message:String(Z)})}try{k.close()}catch{}try{await c9?.dispose()}catch(Z){h.warn("quota-header-feed","failed to dispose",{error:Z instanceof Error?Z.message:String(Z)})}try{if(U1)W.clearInterval(U1),U1=null}catch(Z){h.warn("main-background","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{if(o9)W.clearInterval(o9)}catch(Z){h.warn("fallback-background","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{if(e9!==void 0)W.clearInterval(e9)}catch(Z){h.warn("cachekeep","failed to stop aggregate refresh",{error:Z instanceof Error?Z.message:String(Z)})}try{t1.stop()}catch(Z){h.warn("cachekeep","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{MZ.release()}catch(Z){h.warn("prime","failed to release slot",{error:Z instanceof Error?Z.message:String(Z)})}if(!$J)return;try{await $J.release()}catch(Z){h.warn("rpc","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}},$$={activeId:"main",route:"main"},h8=X8(),E$=new Map;function y4(Z,Y){if(k.updateStorage(Z),k.seedMainFromStorage(Z,H$),!Y.skipFallbackQuotaSeed)k.seedFallbacksFromAccounts((Z?.accounts??[]).filter(B0));let G=k.getMain(H$),K=k.getLastApiError(),j=Z?.refresh?.mainLastRefreshError,L=Z?.claustrum?.primaryAccount,N=b0(Z)&&!y0(L)?eJ({source:"vault",enabled:L?.enabled,state:L?.state}):void 0;return{main:{quota:G?.quota??null,enabled:L?.enabled,tierLabel:B4(Z?.main?.profile),quotaBackedOff:k.isBackedOff(),quotaBackoffUntil:K?.nextRetryAt,refreshBackedOff:j?E1(j,e1??Z?.mainAccountId,Date.now(),Y.mainRefreshToken?t$(Y.mainRefreshToken):void 0):!1,refreshBackoffUntil:j?.nextRetryAt,stateLine:N,quotaDated:Boolean(N)},fallbacks:(Z?.accounts??[]).filter((_)=>B0(_)&&(_.enabled!==!1||Boolean(_.claustrumScopedCredentialId))).map((_)=>{let Q=K4(_.id,Z),U=C8(_.id,Z),C=_.claustrumScopedCredentialId&&!Q?eJ({source:"vault",enabled:_.enabled!==!1,state:_.claustrumScopedState}):void 0;return{id:_.id,label:_.label,tierLabel:B4(_.profile),quota:Y.skipFallbackQuotaSeed?null:k.getFallback(_.id,_)?.quota??_.quota??null,needsReauth:_.lastRefreshError!=null&&E1(_.lastRefreshError,_.id,Date.now(),t$(_.refresh))&&s$(_.lastRefreshError),vaultReauth:U==="on-vault-reauth",vaultServed:Q,custodyState:U,enabled:_.enabled!==!1,stateLine:C,quotaDated:Boolean(C)}}),activeId:Y.activeId,route:Y.route,relay:E5(Z?.relay),fastMode:XZ(),cacheKeep:{enabled:x7(Z),window:I7(Z)?"always":Z?.cacheKeep?.startHour!=null&&Z?.cacheKeep?.endHour!=null?`${Z.cacheKeep.startHour}-${Z.cacheKeep.endHour}`:void 0,trackedSessions:b4.length},prime:E9(Z)?{enabled:!0,accounts:H1.stats(Z)}:void 0,fableRecoveries:E$.size>0?[...E$.values()]:void 0,lastUpdated:Date.now()}}function C$(Z,Y,G){let K=Y.routingAuthoritative!==!1;if(K)$$={activeId:Y.activeId,route:Y.route};function j(L){return G8(L,h8,{routingAuthoritative:K,resolvePreservedRouting:K?void 0:async(N)=>{let _=await vG(N,()=>q(z),{activeId:L.activeId,route:L.route}),Q=await BZ(_.freshStorage,G);return{activeId:_.activeId,route:_.route,state:y4(Q,{...Y,activeId:_.activeId,route:_.route})}},onRoutingResolved:K?void 0:(N)=>{$$=N}}).catch((N)=>h.warn("sidebar","state write failed",{error:N instanceof Error?N.message:String(N)}))}if(K){let L=QZ(Z);if(L.length>0)return BZ(Z,G,L).then((N)=>j(y4(N,Y))).catch(()=>{return h.debug("quota","failed to recheck account profile for sidebar"),j(y4(Z,Y))})}return j(y4(Z,Y))}async function xZ(){return{storage:await q(z),access:void 0}}async function x1(){await g4().catch(()=>{});let{storage:Z,access:Y}=await xZ();C$(Z,{activeId:$$.activeId,route:$$.route,mainAccessToken:Y,mainRefreshToken:void 0,routingAuthoritative:!1})}function b8(Z,Y,G){if(!Y)return;if(Z?.quota?.enabled!==!0)return;let K=G?.quotaKey??H$;if(k.getMain(K))return;if(ZJ)return;ZJ=!0,k.refreshMain(K,Y,G?.generation).then(()=>x1()).catch(()=>{}).finally(()=>{ZJ=!1})}let G1=null,m4,e1,H$,$4,D1,JJ,fZ=0,c4=new Map,ZJ=!1,U1=null,p4=0;function kZ(Z){let Y=Z?.refresh?.refreshBeforeExpiryMinutes??IG;return Math.max(z8,Y)*60000}function g8(Z){return Z?.refresh?.enabled!==!1}async function vZ(Z=!1){let Y=new Map;if(Z){if(l$&&(await l$()).active)try{await T.fetchQuota("main")}catch{Y.set("main","Native primary usage refresh unavailable")}await N1(!0)}let G=await k4(AbortSignal.timeout(3000));k.updateStorage(G.policyStorage),k.seedMainFromStorage(G.policyStorage,H$),k.seedFallbacksFromAccounts(G.policyStorage.accounts.filter(B0));let K=[],j=G.accounts.find((N)=>N.id==="main"&&N.type==="oauth");if(j)K.push({name:j.label??"OpenCode anthropic",role:"main",quota:j.quota,tierLabel:B4(j.profile),error:Y.get("main")??j.lastQuotaRefreshError?.message});K.push(...tY(G.policyStorage,Y));let L=Math.max(0,...G.accounts.map((N)=>T1(N.quota)));return aY({accounts:K,refreshedAt:L||void 0})}async function WJ(Z){await g4().catch(()=>{}),await C$(Z,{activeId:$$.activeId,route:$$.route,routingAuthoritative:!1})}function J4(Z,Y,G,K){if(E$.delete(Z.sessionId),E$.set(Z.sessionId,{...Z,changedAt:Date.now()}),E$.size>128){let j=E$.keys().next().value;if(j)E$.delete(j)}if(C$(Y,{activeId:$$.activeId,route:$$.route,mainAccessToken:G.access,mainRefreshToken:G.refresh,routingAuthoritative:!1}),K)gZ(Z.sessionId,K)}function hZ(Z,Y){let G=m$.get(Z)??new Set;G.delete(Y),G.add(Y);while(G.size>4){let K=G.values().next().value;if(typeof K!=="string")break;G.delete(K)}m$.delete(Z),m$.set(Z,G);while(m$.size>128){let K=m$.keys().next().value;if(typeof K!=="string")break;m$.delete(K)}}function bZ(Z,Y){return typeof Y==="string"&&m$.get(Z)?.has(Y)===!0}function gZ(Z,Y){if(X9(Z))return;N$.delete(Z),N$.set(Z,[Y]);while(N$.size>128){let G=N$.keys().next().value;if(G)N$.delete(G);else break}if(X$.has(Z))XJ(Z)}function XJ(Z,Y=0){if(!N$.has(Z)||o1.has(Z))return;o1.set(Z,Y);let G=()=>{if(o1.get(Z)!==Y)return;o1.delete(Z),y8(Z,Y)};if(Y===0)setImmediate(G);else setTimeout(G,gG*Y)}function YJ(Z,Y){if(Y+1<bG)XJ(Z,Y+1)}async function y8(Z,Y){if(!X$.has(Z)||!N$.has(Z))return;let G=$.client.session;if(typeof G?.status==="function")try{let K=await Promise.resolve(G.status()),j=K!==null&&typeof K==="object"?K:void 0,L=j&&Object.hasOwn(j,"data")?j.data:j;if(L===null||typeof L!=="object"||Array.isArray(L)){YJ(Z,Y);return}let N=L[Z];if(N!==void 0&&(!N||typeof N!=="object"||N.type!=="idle")){YJ(Z,Y);return}}catch{YJ(Z,Y);return}if(!X$.has(Z))return;await m8(Z)}function m8(Z){let Y=M4.get(Z);if(Y)return Y;let G=(async()=>{while(!0){let K=N$.get(Z),j=K?.[0];if(!j){N$.delete(Z);return}try{let L=()=>N$.get(Z)===K&&K[0]===j;if(!await e7($,Z,j,{noReply:!0,beforeActiveAssistant:!0,canSend:()=>X$.has(Z)&&L(),onPreparedMessageId:(_)=>hZ(Z,_),latestPreparedMessageId:()=>[...m$.get(Z)??[]].at(-1)})){if(X$.has(Z)&&!L())continue;return}if(L())K.shift()}catch(L){h.warn("fable-fallback","Desktop notification failed",{session:Z,error:L instanceof Error?L.message:String(L)})}}})();return M4.set(Z,G),G.finally(()=>{if(M4.get(Z)===G)M4.delete(Z)}),G}function c8(Z,Y,G,K){if(Y.fallback&&Y.targetModel){let j=f$.get(Z.recoveryKey);f$.delete(Z.recoveryKey),f$.set(Z.recoveryKey,Y.targetModel);while(f$.size>128){let N=f$.keys().next().value;if(N)f$.delete(N);else break}let L=E$.get(Z.sessionId);if(j===Y.targetModel&&L?.mode==="server"&&h$(L.requestedModelId)===h$(Z.requestedModel)&&L.targetModelId===Y.targetModel)return;h.info("fable-fallback","Anthropic server-side safety fallback active",{session:Z.sessionId,requestedModel:Z.requestedModel,targetModel:Y.targetModel,handoff:Y.handoff}),J4({sessionId:Z.sessionId,mode:"server",remaining:0,requestedModelId:Z.requestedModel,targetModelId:Y.targetModel},G,K,rG(Z.requestedModel,Y.targetModel));return}if(Y.stopReason==="refusal"||!f$.delete(Z.recoveryKey))return;h.info("fable-fallback","Anthropic server-side safety fallback ended",{session:Z.sessionId,requestedModel:Z.requestedModel}),J4({sessionId:Z.sessionId,mode:"fable",remaining:0,requestedModelId:Z.requestedModel},G,K,sG(Z.requestedModel))}function p8(Z,Y,G){if(!Z)return;for(let K of f$.keys())if(K.startsWith(`${Z}\x00`))f$.delete(K);if(!E$.delete(Z))return;C$(Y,{activeId:$$.activeId,route:$$.route,mainAccessToken:G.access,mainRefreshToken:G.refresh,routingAuthoritative:!1})}async function GJ(Z){let Y=YG(Z);if(Y.type==="enable"||Y.type==="disable"){let L=Y.type==="enable",N=await A1(L),_=w4(N);return q9({enabled:L,mode:_}),h.info("commands","cache enabled changed",{enabled:L}),tJ({argumentsText:Z,enabled:L,mode:_,settingsPath:await T.getSettingsPath()})}if(Y.type==="mode"){let L=await A4(Y.mode),N=S9(L);return q9({enabled:N,mode:Y.mode}),h.info("commands","cache mode changed",{mode:Y.mode}),tJ({argumentsText:Z,enabled:N,mode:Y.mode,settingsPath:await T.getSettingsPath()})}let G=await q(z),K=S9(G),j=w4(G);return q9({enabled:K,mode:j}),tJ({argumentsText:Z,enabled:K,mode:j})}async function Z4(Z){let Y=GG(Z),G=await q(z);if(Y.type==="window")G=await R1(Y.startHour,Y.endHour),h.info("commands","cachekeep schedule changed",{schedule:`${Y.startHour}-${Y.endHour}`});else if(Y.type==="always")G=await $1(),h.info("commands","cachekeep schedule changed",{schedule:"always"});else if(Y.type==="disable")G=await R4(!1),h.info("commands","cachekeep enabled changed",{enabled:!1});else if(Y.type==="subagents")G=await q4(Y.enabled),h.info("commands","cachekeep subagents changed",{subagents:Y.enabled});let K=q7(G),j=await g4(),L=j.length?Math.min(...j.map((N)=>N.nextPrewarmAt)):void 0;return P5({argumentsText:Z,enabled:c5(G),always:I7(G),window:K,hybridActive:x7(G),trackedSessions:j.length,trackedSessionDetails:j,nextPrewarmAt:L})}async function yZ(Z){let Y=VG(Z);if(Y.type==="enable"||Y.type==="disable"){let j=Y.type==="enable";return await j1(j),zZ(j),h.info("commands","dump changed",{enabled:j}),w7({argumentsText:Z,enabled:j,settingsPath:await T.getSettingsPath()})}let G=await q(z),K=WZ(G);return zZ(K),w7({argumentsText:Z,enabled:K})}async function mZ(Z){let Y=KG(Z);if(Y.type==="enable"||Y.type==="disable"){let j=Y.type==="enable";return await f9(j),OZ(j),h.info("commands","fast mode changed",{enabled:j}),T7({argumentsText:Z,enabled:j,settingsPath:await T.getSettingsPath()})}let G=await q(z),K=YZ(G);return OZ(K),T7({argumentsText:Z,enabled:K})}async function cZ(Z,Y){if(zG(Z).type==="fire"){if(!Y)return`## Claude Start Failed
|
|
20
|
+
`);if(J===-1)return W===-1?null:{index:W,length:4};if(W===-1||J<W)return{index:J,length:2};return{index:W,length:4}}function $7($,J,W,X){if(!J||$.disabled)return;$.pending+=J;while(!0){let V=y1($.pending);if(!V)break;let O=$.pending.slice(0,V.index);$.pending=$.pending.slice(V.index+V.length);let z=dJ(O);if(!z)continue;if($.events++,K9($.eventCounts,z.event??"unknown"),K9($.typeCounts,z.type),K9($.deltaTypeCounts,z.deltaType),K9($.contentBlockTypeCounts,z.contentBlockType),$.textDeltaBytes+=z.textDeltaBytes??0,$.thinkingDeltaBytes+=z.thinkingDeltaBytes??0,$.inputJsonDeltaBytes+=z.inputJsonDeltaBytes??0,$.signatureDeltaBytes+=z.signatureDeltaBytes??0,$.redactedThinkingBytes+=z.redactedThinkingBytes??0,$.last=z,X?.(z),z.dataBytes>0&&!z.type&&!z.event)$.parseErrors++}if(H7.encode($.pending).byteLength>W)$.pending="",$.disabled=!0,$.pendingOverflowCount++}function gY(){return{pending:"",completed:!1,disabled:!1,resyncCarry:""}}function yY($,J,W){if(!J||$.completed)return null;if($.disabled){let V=$.resyncCarry+J,O=y1(V);if(!O)return $.resyncCarry=V.slice(-3),null;if($.disabled=!1,$.resyncCarry="",J=V.slice(O.index+O.length),!J)return null}$.pending+=J;let X=null;while(!0){let V=y1($.pending);if(!V)break;let O=$.pending.slice(0,V.index);$.pending=$.pending.slice(V.index+V.length);let z=dJ(O);if(z?.type!=="message_delta"||!z.stopReason)continue;$.completed=!0,X??=z.stopReason==="refusal"?{type:"content-filter"}:{type:"complete",finishReason:z.stopReason}}if(new TextEncoder().encode($.pending).byteLength>W){let V=$.pending;$.pending="",$.disabled=!0,$.resyncCarry=V.slice(-3)}return X}function mY(){return{pending:"",disabled:!1}}function J7($){let J=dJ($);if(J?.type!=="message_delta"||J.stopReason!=="max_tokens")return $;return $.replace(/("stop_reason"\s*:\s*)"max_tokens"/,'$1"end_turn"')}function cY($,J,W,X=!1){if(!J&&!X)return"";if($.disabled)return J;if(new TextEncoder().encode($.pending+J).byteLength>W){let O=$.pending+J;return $.pending="",$.disabled=!0,O}$.pending+=J;let V="";while(!0){let O=y1($.pending);if(!O)break;let z=$.pending.slice(0,O.index),H=$.pending.slice(O.index,O.index+O.length);$.pending=$.pending.slice(O.index+O.length),V+=J7(z),V+=H}if(X&&$.pending)V+=J7($.pending),$.pending="";return V}function pY(){return{pending:"",disabled:!1,resyncCarry:""}}function lY($,J){let W=$?.toLowerCase(),X=J.toLowerCase();return W==="api_error"||W==="overloaded_error"||W==="server_error"||W==="internal_server_error"||X.includes("internal server error")||X.includes("server overloaded")}function uY($,J){let W=$?`${$}: ${J}`:J,X=Error(`Anthropic stream error: ${W}`);if(X.code="ECONNRESET",X.syscall="anthropic-sse",$)X.providerErrorType=$;return X}function dY($){let J=W7($)?"Opus 5":"Fable",W=Error(`${J} response was blocked by the provider content filter; retrying with Opus 4.8`);return W.code="ECONNRESET",W.syscall="anthropic-sse",W.providerErrorType="refusal",W}function iY($){if(!$.includes("error"))return null;let J,W=[];for(let R of $.split(/\r?\n/)){if(R.startsWith("event:")){J=R.slice(6).trim();continue}if(R.startsWith("data:")){let A=R.slice(5);W.push(A.startsWith(" ")?A.slice(1):A)}}let X=W.join(`
|
|
21
|
+
`);if(!X||X==="[DONE]")return null;let V;try{V=JSON.parse(X)}catch{return null}let O=b$(V);if(J!=="error"&&r0(O,"type")!=="error")return null;let z=b$(O?.error),H=r0(z,"type")??r0(z,"code")??void 0,w=r0(z,"message")??r0(O,"message")??H??"Anthropic stream error";if(!lY(H,w))return null;return uY(H,w)}function nY($){if(!$.includes("relay_upstream_error"))return;let J=[];for(let W of $.split(/\r?\n/))if(W.startsWith("data:")){let X=W.slice(5);J.push(X.startsWith(" ")?X.slice(1):X)}if(!J.length)return;try{let W=b$(JSON.parse(J.join(`
|
|
22
|
+
`))),X=b$(W?.error);if(r0(X,"type")!=="relay_upstream_error")return;let V=X?.status;if(typeof V==="number"&&Number.isInteger(V))return{status:V,source:"relay_status_field"};let z=r0(X,"message")?.match(/HTTP\s+(\d{3})\b/i);return z?{status:Number(z[1]),source:"relay_message_parse"}:void 0}catch{return}}function Z7($,J,W,X){if(!J)return null;if($.disabled){let O=$.resyncCarry+J,z=y1(O);if(!z)return $.resyncCarry=O.slice(-3),null;if($.disabled=!1,$.resyncCarry="",J=O.slice(z.index+z.length),!J)return null}$.pending+=J;let V=null;while(!0){let O=y1($.pending);if(!O)break;let z=$.pending.slice(0,O.index);$.pending=$.pending.slice(O.index+O.length);let H=nY(z);if(H!==void 0)X?.(H);let w=iY(z);V??=w}if(new TextEncoder().encode($.pending).byteLength>W){let O=$.pending;$.pending="",$.disabled=!0,$.resyncCarry=O.slice(-3)}return V}function oY($){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 D7($,J={}){if(!$.body)return $;let W=$.body.getReader(),X=new TextDecoder("utf-8",{ignoreBOM:!0}),V=new TextEncoder,O=J.responseMode==="json",z=zY(J.toolNameMap,O),H=!0,w="",R=0,A=0,c=0,a=0,u=0,s=!1,T=!1,o=F0(),q0=F0(),G0=J.perf||J.onMessageStart||J.onMessageDelta?hY():void 0,I0="",L0=0,b=!1,O0=(x0)=>{if(!x0)return;try{x0()}catch{}},m0=pY(),q=J.onContentFilter||J.onComplete?gY():void 0,s0=J.laneStart&&J.laneStartOAuthServed!==!1?mY():void 0,A1=!1,A4=!1,R4=(x0=!1)=>{if(!J.onContentFilter)return!1;if(!A1)A1=!0,A4=J.onContentFilter({completedToolUse:x0})!==!1;return A4},$1=J.serverSideFallbackModel?o3({requestedModel:J.serverSideFallbackModel,maxPendingBytes:I$,onOutcome:J.onServerSideFallbackOutcome,onRefusalAfterToolUse:J.onContentFilter?()=>R4(!0):void 0}):void 0,R1=(x0)=>{if(!q)return null;let w$=yY(q,x0,I$);if(w$?.type==="content-filter"&&J.onContentFilter)return R4()?dY(J.contentFilterModel):null;if(w$?.type==="complete")J.onComplete?.(w$.finishReason);return null},q4=(x0,w$=!1)=>s0?cY(s0,x0,I$,w$):x0,j1=()=>{if(T)return;T=!0,W.releaseLock()},f9=async(x0)=>{try{await W.cancel(x0)}catch{}finally{j1()}},k9=(x0={})=>({chunks:R,pulls:A,inputBytes:c,outputBytes:a,pendingChars:z.pendingLength(),sseErrorPending:m0.pending.length,sseFinishPending:q?.pending.length??0,sseFinishDisabled:q?.disabled??!1,serverFallbackPending:$1?.pendingLength()??0,rewriteMs:B$(u),totalMs:B$(F0()-q0),...G0?oY(G0):{},...x0}),x$=(x0,w$={})=>{J.perf?.(x0,k9(w$))};J.perf?.("stream_tool_prefix_wrapper_created",{status:$.status,hasBody:!0});let v9=new ReadableStream({async pull(x0){if(A++,!s)s=!0,x$("stream_tool_prefix_first_pull");while(!0){let w$=F0();try{let{done:l1,value:T$}=await W.read(),a0=B$(F0()-w$);if(l1){let E0=X.decode();if(G0&&!O)$7(G0,E0,I$,(M0)=>{let L1=M0.message;if(M0.type==="message_start"&&L1)O0(()=>J.onMessageStart?.(L1));if(M0.type==="message_delta"&&(M0.usage||M0.stopReason))O0(()=>J.onMessageDelta?.({...M0.usage?{usage:M0.usage}:{},...M0.stopReason?{stopReason:M0.stopReason}:{}}))});if(O){let M0=V.encode(E0).byteLength;if(L0+M0<=I$)I0+=E0,L0+=M0;else b=!0}if(O&&!b)try{let M0=JSON.parse(I0);if(M0&&typeof M0==="object"&&!Array.isArray(M0))O0(()=>J.onMessageResponse?.(M0))}catch{}let O$=F0(),A0=$1?$1.push(E0)+$1.flush():E0,q1=q4(A0,!0),_1=O?R1(q1):Z7(m0,E0,I$,J.onRelayUpstreamError)??R1(q1);if(_1)throw x$("stream_tool_prefix_retryable_error",{providerErrorType:_1.providerErrorType}),await f9(_1),_1;let i1=z.push(q1,!0);if(u+=F0()-O$,i1||w){let M0=V.encode(w+i1);w="",a+=M0.byteLength,x0.enqueue(M0)}if(x$("stream_tool_prefix_rewrite",{readMs:a0}),j1(),J.onStreamEnd)try{await J.onStreamEnd()}catch{}x0.close();return}R++,c+=T$.byteLength;let b0=X.decode(T$,{stream:!0});if(H&&b0){if(H=!1,b0.charCodeAt(0)===65279)w=b0[0]??"",b0=b0.slice(1)}if(O){let E0=T$.byteLength;if(L0+E0<=I$)I0+=b0,L0+=E0;else b=!0}if(G0&&!O)$7(G0,b0,I$,(E0)=>{let O$=E0.message;if(E0.type==="message_start"&&O$)O0(()=>J.onMessageStart?.(O$));if(E0.type==="message_delta"&&(E0.usage||E0.stopReason))O0(()=>J.onMessageDelta?.({...E0.usage?{usage:E0.usage}:{},...E0.stopReason?{stopReason:E0.stopReason}:{}}))});let h9=F0(),u1=$1?$1.push(b0):b0,d1=q4(u1),G$=O?R1(d1):Z7(m0,b0,I$,J.onRelayUpstreamError)??R1(d1);if(G$)throw x$("stream_tool_prefix_retryable_error",{providerErrorType:G$.providerErrorType,readMs:a0,lastChunkBytes:T$.byteLength}),j1(),G$;let J1=z.push(d1);if(u+=F0()-h9,J1){let E0=V.encode(w+J1);w="",a+=E0.byteLength,x0.enqueue(E0)}let Z1=F0();if(R===1||R%25===0||Z1-o>5000)o=Z1,x$("stream_tool_prefix_progress",{readMs:a0,lastChunkBytes:T$.byteLength});if(J1)return}catch(l1){let T$=gJ(l1,J.toolNameMap);if(x$("stream_tool_prefix_error"),T$ instanceof D4)await yJ(W,T$),T=!0,O0(J.onToolNameRefusal);else j1();throw T$}}},async cancel(x0){x$("stream_tool_prefix_cancel");try{await W.cancel(x0)}finally{j1()}}});return new Response(v9,{status:$.status,statusText:$.statusText,headers:$.headers})}import{mergeNativeSettingsSection as X2,nativeCacheKeepAlways as Y2,nativeSettingsRecord as G2}from"@cortexkit/anthropic-auth-core";var p7="physical send failed before a response",RG="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",l7="~effect/http/HttpServerResponse",u7="~effect/http/Cookies",d7="~effect/http/HttpBody",qG="~effect/ErrorReporter/ignore",MG="https://api.anthropic.com/v1/messages",K8=new WeakSet;function _Z($){let J=new Response(JSON.stringify({type:"error",error:{type:"invalid_request_error",message:$}}),{status:400,headers:{"content-type":"application/json"}});return K8.add(J),J}async function i7($,J){if(!J?.aborted)return;await $.body?.cancel().catch(()=>{}),J.throwIfAborted()}function jZ($,J){return($.status!==400||!K8.has($))&&PG($.status,J)}function n7($){return h.warn("effort-history","refused uncorrelated Fable 5.1 request",{check:$.check,...$.details}),_Z($.message)}function o7($){return h.warn("transform","refused request ending on assistant history",{check:$.check,...$.details}),_Z($.message)}var IG=60000,r7=60000,z8=240,xG=z8,fG=600000;function kG($,J){return($?.accounts??[]).some((W)=>W.id===J&&y0(W)&&B0(W))}function vG($){let J=($?.accounts??[]).find((W)=>y0(W)&&B0(W));if(e$($)==="fallback-first"&&J)return{activeId:J.id,route:"fallback-first"};return{activeId:"main",route:"main"}}function s7($,J){if($?.activeId==="main"||$?.activeId&&kG(J,$.activeId))return $;return vG(J)}function O8($,J,W){let X=Date.now()-$.lastUpdated;if(!$.activeId||X<0||X>fG)return s7(W,J);return s7($,J)}async function hG($,J,W){let X;try{X=await J()}catch(V){return h.warn("sidebar","account storage reload failed; routing preserved",{message:V instanceof Error?V.message:String(V)}),{...$.activeId?{activeId:$.activeId,route:$.route}:W??{activeId:"main",route:"main"},freshStorage:null}}return{...O8($,X,W),freshStorage:X}}async function bG($){await M9()?.beforeStorageLoad?.();let J;try{J=await $()}catch{return{activeId:"main",route:"main",freshStorage:null}}finally{await M9()?.afterStorageLoad?.()}await M9()?.beforeSidebarRead?.();let W=await Y8();return{...O8(W,J),freshStorage:J}}var gG=4,yG=25,mG=1,a7=!1;function I9(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function $0(){return performance.now()}function P0($){return Math.round($*10)/10}function t7($){return Math.floor(Math.random()*Math.max(0,$))}function E4($){if(typeof $==="string")return $;if($ instanceof URL)return $.toString();return $.url}function P1($,J){return J?.method??($ instanceof Request?$.method:void 0)}async function C4($,J){if(J?.body!==void 0)return J.body;if(!($ instanceof Request)||$.body===null)return;try{return await $.clone().text()}catch{return}}function cG(){if(a7||!1||!I9())return;a7=!0;let $=100,J=250,W=$0()+$;setInterval(()=>{let X=$0(),V=X-W;if(W=X+$,V<J)return;y$("[perf] opencode event_loop_lag",{lagMs:P0(V),thresholdMs:J})},$).unref?.()}function pG($){let J=$0(),W={requestId:String(mG++),start:J,last:J,mark(X,V){let O=$0();if(I9())y$("[perf] opencode request stage",{requestId:W.requestId,stage:X,deltaMs:P0(O-W.last),totalMs:P0(O-W.start),...V});W.last=O},done(X,V){let O=$0();if(I9())y$("[perf] opencode request done",{requestId:W.requestId,stage:X,deltaMs:P0(O-W.last),totalMs:P0(O-W.start),...V});W.last=O}};if(I9())y$("[perf] opencode request start",{requestId:W.requestId,...$});return W}function j8($,J){let W=/^msg_([0-9a-fA-F]{12})/.exec($);if(!W)return;let X=BigInt(`0x${W[1]}`);if(X<=0n)return;let O=`msg_${(X-1n).toString(16).padStart(12,"0")}${"z".repeat(14)}`,z=J&&O<=J?`${J}z`:O;if(z.length>128||z>=$)return;return z}async function e7($,J,W,X={}){let V=$.client.session,O=await $9($.client,J),z={path:{id:J},body:{noReply:X.noReply??!0,parts:[{type:"text",text:W,ignored:!0}]}};if(X.beforeActiveAssistant){let H=X.latestPreparedMessageId?.(),w=O?.latestUserMessageId,R=H&&(!w||H>w)?H:w,A=O?.latestAssistantMessageId?j8(O.latestAssistantMessageId,R):void 0;if(!A)return!1;z.body.messageID=A}if(O?.agent)z.body.agent=O.agent;if(O?.model)z.body.model=O.model;if(O?.variant)z.body.variant=O.variant;if(X.canSend&&!X.canSend())return!1;if(z.body.messageID)X.onPreparedMessageId?.(z.body.messageID);if(typeof V?.promptAsync==="function")return await V.promptAsync(z),!0;if(typeof V?.prompt==="function")return await Promise.resolve(V.prompt(z)),!0;throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function lG(){throw Object.assign(Error(RG),{[l7]:l7,[qG]:!0,status:204,statusText:void 0,headers:{},cookies:{[u7]:u7,cookies:{}},body:{[d7]:d7,_tag:"Empty"}})}function uG($){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 dG($){if($.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return $.push(WG),!0}var iG={input:0,output:0,cache:{read:0,write:0}},nG=1000;function F$($){return $}function oG($,J){let W=P4($);return`${W} content filter detected. Switched to Opus 4.8 for a ${J}-response recovery window before trying ${W} again.`}function rG($){let J=P4($);return`${J} recovery window complete. Returning to ${J}.`}function P4($){if(o5($))return"Opus 5.5";if(n5($))return"Opus 5";if(V8($)){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 sG($,J){return`Anthropic safety fallback active: ${P4($)} → ${P4(J)}. Follow-up requests may remain on the fallback model for about one hour.`}function aG($){return`Anthropic safety fallback ended. Returning to ${P4($)}.`}function tG(){return{input:H9.input,output:H9.output,cache:{read:H9.cacheRead,write:H9.cacheWrite5m},tiers:[{tier:{type:"context",size:O5},input:L9.input,output:L9.output,cache:{read:L9.cacheRead,write:L9.cacheWrite5m}}]}}function eG($){let J=$["claude-opus-4-8"]??$["claude-opus-4-5"]??Object.values($)[0];if(!J)return $;return{...$,...Object.fromEntries(Object.values(V5).map((W)=>{let X=V8(W.id)?X5:K5;return[W.id,{...J,id:W.id,name:W.name,api:J.api?{...J.api,id:W.id}:void 0,cost:{input:X.input,output:X.output,cache:{read:X.cacheRead,write:X.cacheWrite5m}},limit:{...J.limit??{},context:Y5,output:G5},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:k5(W.id)}]})),...$[N9]?{}:{[N9]:{...J,id:N9,name:"Claude Haiku 5.5",api:J.api?{...J.api,id:N9}:void 0,cost:tG(),limit:{...J.limit??{},context:z5,output:j5},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:_5,variants:x9()}},...$[Q9]?{}:{[Q9]:{...J,id:Q9,name:"Claude Sonnet 5.5",api:J.api?{...J.api,id:Q9}:void 0,cost:{input:B9.input,output:B9.output,cache:{read:B9.cacheRead,write:B9.cacheWrite5m}},limit:{...J.limit??{},context:D5,output:U5},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:Q5,variants:x9()}},...$[D9]?{}:{[D9]:{...J,id:D9,name:"Claude Opus 5.5",api:J.api?{...J.api,id:D9}:void 0,cost:{input:U9.input,output:U9.output,cache:{read:U9.cacheRead,write:U9.cacheWrite5m}},limit:{...J.limit??{},context:L5,output:N5},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:H5,variants:x9()}}}}var $2=["low","medium","high","xhigh","max"];function x9(){return Object.fromEntries($2.map(($)=>[$,{thinking:{type:"adaptive",display:"summarized"},effort:$}]))}function J2($){return Object.fromEntries(Object.entries($).map(([J,W])=>{let X=W.api?.id??W.id??J;return[J,i5(X)||u5(X)||r5(X)||d5(X)?{...W,variants:x9()}:W]}))}function Z2($){return Object.fromEntries(Object.entries($).map(([J,W])=>[J,{...W,cost:iG}]))}function $8(){return process.env.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||void 0}var W2=async($,J={})=>{let W={setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,setInterval:globalThis.setInterval,clearInterval:globalThis.clearInterval,...J},X=J.authorize??Q7;cG();let{client:V}=$,O=globalThis.fetch,z=x5(),H=b5(g5(z)),w=600000,R=50,A=new Map;function c(){let Z=Date.now();for(let[Y,G]of A)if(Z-G.createdAt>w)A.delete(Y)}function a(Z,Y){if(c(),A.size>=R){let G="",K=1/0;for(let[j,L]of A)if(L.createdAt<K)K=L.createdAt,G=j;if(G)A.delete(G)}A.set(Z,Y)}function u(Z){c();let Y=A.get(Z);if(!Y)return;if(Date.now()-Y.createdAt>w){A.delete(Z);return}return Y}let s=await wG(z),T=sY({paths:s,host:"opencode",local:J.nativeLocal,vault:J.claustrumScopedConnect?{connect:J.claustrumScopedConnect}:void 0}),o=T.quotaObservations,q0=null;function G0(Z){return $G(Z)}function I0(Z,Y){return Z?G0(Z.binding):Y?JSON.stringify([Y.credentialId,Y.accountIdentity,Y.recordVersion]):void 0}function L0(Z,Y,G,K=q0){let j=o.get(Z);if(!j||!Y||j.lineage!==Y||j.accountUuid!==G||F1(j.entry.quota,K,j.entry.checkedAt)<=Date.now())return;return j}function b(Z,Y,G,K,j=q0){let L=L0(Z,Y,G,j);if(!L)return K;if(!K)return{...L.entry,refreshAfter:F1(L.entry.quota,j,L.entry.checkedAt)};let N=L.entry.quota.source!=="headers"&&T1(K.quota)>T1(L.entry.quota)?K.quota:h7(K.quota,L.entry.quota);return{...L.entry,quota:N,refreshAfter:F1(N,j,T1(N))}}function O0(Z,Y,G){if(!o.has(Z.id))return Z.quota;let K=Z.binding?G0(Z.binding):I0(void 0,G),j=T1(Z.quota);return b(Z.id,K,Z.accountIdentity,Z.quota?{quota:Z.quota,checkedAt:j,refreshAfter:F1(Z.quota,Y,j)}:null,Y)?.quota}let m0;async function q(Z=z){if(Z!==z)throw Error("Native account storage mismatch");let Y=await T.read();if(q0=Y.policyStorage,!m0){let j=Y.accounts.find((L)=>L.id==="main")?.binding;if(j)m0={rowId:j.rowId,credentialEpoch:j.credentialEpoch}}if(Y.mode!=="claustrum")return Y.policyStorage;let G=Y.accounts.find((j)=>j.id==="main"&&j.source==="vault"),K=F$(G?.accountIdentity);return{...Y.policyStorage,claustrum:{...Y.policyStorage.claustrum,mode:"claustrum",scopedRoster:!0,primaryAccount:G?.credentialId&&K?{credentialId:G.credentialId,accountId:K,state:G.state??"cold",enabled:G.enabled}:void 0}}}async function s0(Z,Y){return await T.updateSettings((G)=>X2(G,Z,Y)),q()}let A1=async(Z)=>{return await T.updateSettings((Y)=>({...Y,claudeCache:{...G2(Y.claudeCache),enabled:Z,mode:w4({...Y,version:1,accounts:[]})}})),q()},A4=(Z)=>s0("claudeCache",{mode:Z}),R4=(Z)=>s0("cacheKeep",{enabled:Z}),$1=async()=>{return await T.updateSettings(Y2),q()},R1=(Z,Y)=>s0("cacheKeep",{enabled:!0,always:!1,startHour:Z,endHour:Y}),q4=(Z)=>s0("cacheKeep",{subagents:Z}),j1=(Z)=>s0("dump",{enabled:Z}),f9=(Z)=>s0("claudeFast",{enabled:Z}),k9=async(Z)=>{return await T.setLoggingLevel(Z),q()},x$=(Z,Y=z)=>s0("prime",{enabled:Z}),v9=(Z,Y=z)=>s0("routing",{mode:Z}),x0=(Z)=>s0("killswitch",Z),w$=(Z,Y,G=z)=>T.setEnabled(Z,Y),l1=(Z,Y=z)=>T.remove(Z),T$=(Z,Y=z,G)=>T.reorder(Z,G),a0=null;try{a0=await q()}catch{}function b0(Z){return Boolean(Z&&T4(Z)==="claustrum"&&Z.claustrum?.scopedRoster===!0)}function h9(Z=z,Y=$.directory){if(Z!==z)throw Error("Native vault storage mismatch");return T.vault}let u1=w5("native-auth");async function d1(Z=z){n9?.close(),await u1.drain(),await T.drainQuotaPublications(),await Promise.all([...m9.values()].map((Y)=>Y.drain())),await T.drainRoutingPublications(),T.close()}function G$(){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native OAuth cannot serve while OPENCODE_AUTH_CONTENT is set")}function J1(Z){let Y=F$(Z);if(!Y)throw Error("Native wire identity requires an admitted provider account");return f5(Y,Y)}class Z1 extends Error{account;checkIntervalMs;constructor(Z,Y){super("OAuth account cannot serve the requested model under current quota policy");this.account=Z;this.checkIntervalMs=Y}}class E0 extends Error{constructor(){super("Native OAuth requires a Claude Pro/Max credential. An API key belongs in OpenCode stock Anthropic authentication.")}}class O$ extends Error{account;tokenRefreshFailed;failure;constructor(Z,Y,G=!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: ${Y}`);this.account=Z;this.tokenRefreshFailed=G;this.failure=K}}async function A0(Z,Y,G,K,j="serve",L){G$(),Y?.throwIfAborted();let N=L??await T.read(),_=N.accounts.find((m)=>m.id===Z);if(_?.state==="unsupported-access")throw new E0;if(_?.source==="vault"&&!y0(_))throw new O$(_,"not-active");if(_?.type!=="oauth"||!y0(_))throw Error("Native OAuth account is unavailable");let Q=(m,J0,j0)=>{let f0=O0(m,J0,j0),w0=j==="last-main"&&Z==="main"&&e$(J0)!=="sticky-balanced";if(K&&(r$(J0)&&!a$(f0,J0,Z==="main"?void 0:Z,K)||!w0&&!R9(f0,K)))throw new Z1(m,M7(J0))};Q(_,N.policyStorage);let U;if(_.source==="vault"){let m=await T.authorizeVault(Z,Y).catch((J0)=>{if(Y?.throwIfAborted(),J0 instanceof t5&&["not-active","route-declined","route-unavailable"].includes(J0.code))throw new O$(_,J0.code);throw J0});U={accessToken:m.accessToken,expires:m.expiresAtMs??void 0,accountIdentity:m.accountIdentity,scopedAttempt:m}}else{let m=await T.authorizeLocal(Z,{signal:Y,rejectedAccessToken:G,intent:G?"refresh":j==="last-main"?"serve":j});if(m.status!=="usable")throw new O$(_,m.status,m.status==="failed"&&m.failure.kind==="provider",m.status==="failed"?m.failure:void 0);U={accessToken:m.access,expires:m.expires,accountIdentity:m.binding.identity,localSubject:m.subject,localSource:m.source}}let C=await T.read(),f=C.accounts.find((m)=>m.id===Z);if(Y?.aborted)throw Y.reason??Error("Request aborted");if(!f||!y0(f)||f.source!==_.source||f.accountIdentity!==U.accountIdentity)throw Error("Native OAuth account changed before dispatch");if(U.localSubject&&(!f.binding||f.binding.storageId!==U.localSubject.binding.storageId||f.binding.rowId!==U.localSubject.binding.rowId||f.binding.credentialEpoch!==U.localSubject.binding.credentialEpoch||f.binding.identity!==U.localSubject.binding.identity))throw Error("Native local account binding changed before dispatch");if(U.scopedAttempt&&f.credentialId!==U.scopedAttempt.credentialId)throw Error("Native vault credential binding changed before dispatch");return Q(f,C.policyStorage,U.scopedAttempt),U}async function q1(Z,Y){let K=(await T.read()).accounts.find((L)=>L.id===Z);if(K?.type!=="oauth")throw Error("Native OAuth account is unavailable");let j=K.source==="vault"?await T.authorizeVault(Z,Y):await T.captureLocalSubject(Z);if(!await T.resetBackoff(Z,j))throw Error("Native reset fence changed")}let _1=new WeakMap,i1=new WeakSet;async function M0(Z,Y){if(i1.has(Z))return;i1.add(Z),await T.vault.reportFailure(Z,401,Y).catch(()=>{h.warn("claustrum","native auth-failure report unavailable")})}async function L1(Z,Y,G){let K=await T.vault.prepareRetry(Z,G,Y);return K.retry?K.receipt:void 0}let b9=i3(process.env.OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE),W1=new MJ,g9=new fJ,n1=new RJ,M1=new LJ,f$=new Map,N$=new Map,S$=new Map,M4=new Map,X$=new Set,y9=new Map,I4=new Map,m$=new Map,o1=new Map,m9=new Map;async function LZ(){let Z=await T.read(),Y=Z.routingPath;if(!Y)throw Error(Z.mode==="claustrum"?"Vault routing storage is unavailable":"Native routing storage is unavailable");let G;if(Z.mode==="claustrum"){G=new Map;for(let j of Z.accounts)if(j.source==="vault"&&j.accountIdentity)G.set(j.id,j.accountIdentity)}let K=m9.get(Y);if(!K)K=new TG({path:Y,vaultSeed:Z.routingSeed,onLockEvent:T.onLockEvent,localRecoveryPath:Z.mode==="local"?Z.routingRecoveryPath:void 0}),m9.set(Y,K);return K.setVaultSeed(Z.routingSeed),{router:K,...G&&{accountIdentities:G}}}let k=new DG({storage:a0,pauseBetweenQuotaCalls:J.quotaCallPause,fetchQuotaSnapshot:(Z,Y)=>{G$();let G=Z.kind==="main"?"main":Z.accountId;if(!G)throw Error("Quota request has no account identity");return T.fetchQuota(G,void 0,void 0,Y,Z.purpose)}});function r1(Z){return["five_hour","seven_day"].some((Y)=>(Z?.[Y]?.remainingPercent??1)<=0)}function NZ(Z,Y,G=!1){if(!Z||Z.quota?.enabled===!1||!Y||e$(Z)==="sticky-balanced"||s$(Z.refresh?.mainLastRefreshError))return;let K=Date.now(),j=Z.quota?.mainLastQuotaApiError;if(j&&j.accountIdentity===Y&&j.nextRetryAt!==void 0&&j.nextRetryAt>K)return{message:R7(j,K),retryAfter:Math.max(1,Math.ceil((j.nextRetryAt-K)/1000))};let L=Z.quota?.mainQuota,N=T1(L);if(L?.accountIdentity!==Y||L.source==="headers"&&!G||!r1(L)||N<=0||N>K||F1(L,Z,N)<=K)return;let _=["five_hour","seven_day"].flatMap((Q)=>{let U=L[Q],C=U?.resetsAt?Date.parse(U.resetsAt):Number.NaN;return U&&U.remainingPercent<=0&&Number.isFinite(C)&&C>K?[C]:[]});return{message:"Claude OAuth quota is exhausted for this account.",retryAfter:Math.max(1,Math.ceil(((_.length?Math.max(..._):K+M7(Z))-K)/1000))}}async function HZ(Z,Y,G){if(JJ===Z&&H$===Y)return;let K=D1!==void 0&&G!==void 0&&D1!==G;JJ=Z,H$=Y,k.setMainQuotaAccountIdentity(Y,!0,K)}async function s1(Z,Y,G,K){let j=Z,L=c4.get(j);if(L){let _=await L.promise;return K===L.recordVersion?_:{..._,stale:!0}}let N=(async()=>{let _=++fZ,Q=e1,U=await T.read(),C=U.policyStorage,f=U.accounts.find((V1)=>V1.id==="main")?.accountIdentity,m=J1(G??f),J0=U.mode==="claustrum",j0=J0?C?.claustrum?.primaryAccount?.accountId:void 0;if(G!==void 0&&G!==f||J0&&G===void 0)return{quotaKey:void 0,providerAccountUuid:void 0,generation:k.getMainQuotaIdentityGeneration(),stale:!0,state:"on-identity-mismatch"};let f0=f??j0??Q,w0=C?.main?.profile?.providerAccountUuid??C?.main?.profile?.accountIdentity,k0=F$(G)??F$(m.accountUuid),N0=G?k0:Z.startsWith("sk-ant-oat")?k0??F$(w0):void 0,j$=T4(C)!=="claustrum"?"na":w0===void 0||k0===void 0?"unknown-identity":w0!==void 0&&k0!==void 0&&w0!==k0?"on-identity-mismatch":"on-vault-served";if(_!==fZ){let V1=JJ!==Z||H$!==f0;return{quotaKey:f0,providerAccountUuid:N0,generation:k.getMainQuotaIdentityGeneration(),stale:V1,state:j$}}if(await HZ(Z,f0,N0),Z.startsWith("sk-ant-oat")&&N0===void 0)k.clearMain();if(D1=N0,Z.startsWith("sk-ant-oat"))$4=Z;return{quotaKey:f0,providerAccountUuid:N0,generation:k.getMainQuotaIdentityGeneration(),stale:!1,state:j$}})();c4.set(j,{promise:N,recordVersion:K});try{return await N}finally{if(c4.get(j)?.promise===N)c4.delete(j)}}let c9=a0?.quotaHeaderFeed?.enabled===!0?new HG:null,c$=new Map,DZ=new Map,X1=new Set,Y1=new AbortController,UZ=!1;function x4(Z,Y){return JSON.stringify([Z,Y??null])}function p9(Z){let Y=Z.binding;if(Z.source!=="local"||!Y)return;return JSON.stringify([Y.storageId,Y.rowId,Y.credentialEpoch])}function l9(Z,Y){return Z.lineage!==void 0&&Z.lineage===p9(Y)&&(!Z.profile||Z.profile.accountIdentity===Y.accountIdentity)}async function f4(Z,Y){if(!Z?.profile||!C9(Z.profile,Y)||!await Z.isCurrent?.())return;return Z.persistence==="refused"?void 0:Z.profile}function QZ(Z){if(!Z)return[];let Y=new Set([...Z.main?["main"]:[],...(Z.accounts??[]).filter((G)=>B0(G)&&(G.enabled!==!1||Boolean(G.claustrumScopedCredentialId))).map((G)=>G.id)]);return[...new Set(c$.values())].filter((G)=>G.persistence==="failed"&&G.profile!==void 0&&Y.has(G.accountId))}async function _8(Z,Y,G,K){let j=Y.accountId,L=G.accounts.find((Q)=>Q.id===j),N=L?.source==="local"?l9(Y,L):L?.source==="vault"&&L.accountIdentity===K.accountIdentity;if(L?.type!=="oauth"||!y0(L)||L.accountIdentity!==K.accountIdentity||!N||await f4(Y,Date.now())!==K)return Z;if(j==="main")return Z.main?{...Z,main:{...Z.main,profile:K}}:Z;let _=Z.accounts?.find((Q)=>Q.id===j);if(!_||!B0(_))return Z;return{...Z,accounts:Z.accounts.map((Q)=>Q.id===j&&B0(Q)?{...Q,profile:K}:Q)}}async function BZ(Z,Y,G=QZ(Z)){if(!Z||G.length===0)return Z;let K=[];for(let N of G){let _=await f4(N,Date.now());if(_)K.push({hydration:N,profile:_})}if(!K.length)return Z;let j=Y??await T.read(),L=Z;for(let N of K)L=await _8(L,N.hydration,j,N.profile);return L}function L8(Z,Y,G){G$();let K=!1,j=Object.assign((N,_)=>{return K=!0,O(N,_)},{preconnect:O.preconnect}),L={accountId:Z.id,fetched:Promise.resolve(),lineage:p9(Z),...G&&{deadline:G}};return L.fetched=T.fetchProfileForDisplay(Z.id,j,AbortSignal.any([Y1.signal,...G?[G]:[]])).then(({profile:N,persisted:_,isCurrent:Q})=>{if(L.settled=!0,N.accountIdentity!==void 0)DZ.set(x4(Z.id,N.accountIdentity),N);if(Z.accountIdentity===void 0||N.accountIdentity===Z.accountIdentity)L.profile=N,L.isCurrent=Q,L.persistence="pending";let U=_.then(async(C)=>{if(L.persistence=C,C==="failed")h.warn("quota","failed to persist account profile",{account:Z.id});else if(C==="refused")h.debug("quota","refused account profile publication",{account:Z.id});if((C==="saved"||C==="failed")&&!Y1.signal.aborted){let f=C==="failed"&&await f4(L,Date.now());if(C==="saved"||f)try{let m=await T.read();if(!Y1.signal.aborted)await C$(m.policyStorage,{...$$,routingAuthoritative:!1},m)}catch{h.debug("quota","failed to publish account profile to sidebar",{account:Z.id})}}});X1.add(U),U.then(()=>X1.delete(U))},(N)=>{if(L.settled=!0,L.failed=K,h.debug("quota","failed to hydrate account profile",{account:Z.id,error:N instanceof Error?N.message:String(N)}),!K&&c$.get(Y)===L)c$.delete(Y)}),X1.add(L.fetched),L.fetched.then(()=>X1.delete(L.fetched)),L}function N8(Z,Y){let G=[Y,Z.deadline].filter((j)=>j!==void 0);if(!G.length)return Z.fetched;let K=AbortSignal.any(G);if(K.aborted)return Promise.resolve();return new Promise((j)=>{let L=()=>{K.removeEventListener("abort",L),j()};K.addEventListener("abort",L,{once:!0}),Z.fetched.then(L)})}function FZ(Z,Y){return C9(Z.profile,Y)&&ZG(Z.profile,Z.accountIdentity)}async function k4(Z){let Y=await T.read();if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return Y;let G=Date.now(),K=[],j=new Map;for(let _ of Y.accounts){if(_.type!=="oauth"||!y0(_)||FZ(_,G))continue;let Q=x4(_.id,_.accountIdentity),U=c$.get(Q);if(U&&_.accountIdentity===void 0&&(U.lineage===void 0||U.lineage!==p9(_)))U=void 0;if(!U&&_.accountIdentity!==void 0){let C=c$.get(x4(_.id));if(C&&l9(C,_))U=C,j.set(_.id,C)}if(U?.failed)continue;if(!U&&C9(DZ.get(Q),G))continue;if(!U||!U.profile&&(U.deadline?.aborted||U.settled)||U.profile&&!C9(U.profile,G)){if(Z?.aborted||Y1.signal.aborted)continue;U=L8(_,Q,Z),c$.set(Q,U)}if(_.accountIdentity===void 0)j.set(_.id,U);K.push(N8(U,Z))}if(!K.length)return Y;await Promise.all(K);let L=await T.read(),N=Date.now();for(let _ of L.accounts){if(_.type!=="oauth"||!y0(_))continue;let Q=x4(_.id,_.accountIdentity),U=j.get(_.id);if(U&&_.accountIdentity!==void 0&&!c$.has(Q)&&l9(U,_))c$.set(Q,U);if(FZ(_,N))continue;let C=await f4(c$.get(Q),N);if(!C||C.accountIdentity!==_.accountIdentity)continue;if(_.profile=C,_.id==="main"){if(L.policyStorage.main)L.policyStorage.main.profile=C}else for(let f of L.policyStorage.accounts)if(f.id===_.id&&B0(f))f.profile=C}return L}async function H8(Z,Y,G,K){if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return Z;return(await k4(G)).policyStorage}let wZ=new Set;async function D8(Z,Y,G){let j=(await T.read()).accounts.find((U)=>U.id===Z.accountId);if(!j||!Z.anthropicAccountUuid||j.accountIdentity!==Z.anthropicAccountUuid)return null;let L={...h7(j.quota,Y.quota),accountIdentity:j.accountIdentity};if(!(Z.scopedAttempt?await T.vault.publish(Z.scopedAttempt,{quota:L}):Z.localSubject?await T.publishLocal(Z.localSubject,{quota:L}):!1)){if(Z.accountId==="main"){if(k.getMain(Z.mainQuotaIdentity?.quotaKey)===G)k.clearMain()}else if(k.getAllFallbacks().get(Z.accountId)===G)k.clearFallback(Z.accountId);return h.debug("quota","native quota publication refused",{accountId:Z.accountId}),null}let _=await T.read(),Q=_.accounts.find((U)=>U.id===Z.accountId);if(!Q?.quota||Q.accountIdentity!==Z.anthropicAccountUuid||Q.source!==j.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{...Y,quota:Q.quota,refreshAfter:F1(Q.quota,_.policyStorage,Y.checkedAt)}}function U8(Z){h.warn("quota","failed to persist harvested response quota",{error:Z instanceof Error?Z.message:String(Z)})}function Q8(Z){let Y=Z instanceof Error?Z.name:typeof Z,G=Z instanceof Error?Z.message:String(Z),K=`${Y}:${G}`;if(wZ.has(K))return;wZ.add(K),h.warn("quota","failed to normalize response quota headers",{error:G})}function B8(Z){if(!Z||typeof Z!=="object")return;let Y=Z,G=Y.credential_id;if(typeof G==="string"&&G&&G!=="main")return G;let K=Y.vault;if(K&&typeof K==="object"){let j=K.credential_id;if(typeof j==="string"&&j&&j!=="main")return j}return}async function F8(Z,Y){if(!c9)return;if(Z.accountId==="main"&&!Z.mainQuotaIdentity?.quotaKey)return;let G=await q(z)??o$(),j=(await G1?.())?.type==="oauth",L=Z.accountId==="main"?G.main:G.accounts.find((m)=>m.id===Z.accountId),N=B8(L),_=F5({storage:G,mainOAuthConfigured:j}),Q=Y.checkedAt,U={five_hour:Y.quota.five_hour,seven_day:Y.quota.seven_day,bindingWindow:Y.quota.bindingWindow,fallbackAdvised:Y.quota.fallbackAdvised,scoped:Y.quota.scoped,extraUsage:Y.quota.extraUsage,fieldSources:Y.quota.fieldSources},C=N??(Z.accountId==="main"?Z.mainQuotaIdentity?.quotaKey??"main":Z.accountId),f=N?{identity_source:"credential_id",credential_id:N,schema_version:P9,provider:"anthropic",configured_account_count:_,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C}:Z.accountId==="main"&&Z.mainQuotaIdentity?.quotaKey?{identity_source:"account_ref",account_ref:Z.mainQuotaIdentity.quotaKey,schema_version:P9,provider:"anthropic",configured_account_count:_,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C}:Z.accountId==="main"?{identity_source:"none",schema_version:P9,provider:"anthropic",configured_account_count:_,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C}:{identity_source:"account_ref",account_ref:Z.accountId,schema_version:P9,provider:"anthropic",configured_account_count:_,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C};await c9.publish(f)}function w8(Z){h.debug("quota","failed to publish quota header feed",{error:Z instanceof Error?Z.message:String(Z)})}function TZ(Z,Y){try{if(!a5(Z)){h.trace("quota","skipped non-quota response headers",{account:Y.accountId});return}let G=JG(Z),K=Y.accountId==="main"?Y.mainQuotaIdentity:void 0;if(Y.accountId==="main"){if(!K||k.getMainQuotaIdentityGeneration()!==K.generation){h.trace("quota","discarded stale main quota headers",{boundIdentity:K?.quotaKey,currentGeneration:k.getMainQuotaIdentityGeneration()});return}}let j=Y.accountId==="main"?k.getMain(K?.quotaKey):k.getAllFallbacks().get(Y.accountId),L=G.checkedAt??Date.now(),N=I0(Y.localSubject,Y.scopedAttempt),_=N&&Y.anthropicAccountUuid?{lineage:N,accountUuid:Y.anthropicAccountUuid,entry:{quota:{...G,accountIdentity:Y.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 G[Q]!==void 0&&U!==null&&Number.isFinite(Number(U))&&Number(U)>=1})}:void 0;if(_){if(o.delete(Y.accountId),o.size>=nG){let Q=o.keys().next().value;if(Q!==void 0)o.delete(Q)}o.set(Y.accountId,_)}(async()=>{let Q=!1;try{let U;try{U=await D8(Y,{quota:G,checkedAt:L,refreshAfter:L},j)}catch(f){U8(f);return}if(U===null)return;if(Y.accountId==="main"&&k.getMainQuotaIdentityGeneration()!==K?.generation)return;let C=U;if(_&&o.get(Y.accountId)===_)_.entry=C,Q=!0;if(Y.accountId==="main")k.setMain(K?.quotaKey,C);else k.setFallback(Y.accountId,C,{authLineageId:Y.authLineageId});x1().catch(()=>{}),await F8(Y,C),h.debug("quota","harvested response quota",{account:Y.accountId,fiveHourPercent:C.quota.five_hour?.usedPercent,sevenDayPercent:C.quota.seven_day?.usedPercent,source:"headers"})}finally{if(!Q&&_&&o.get(Y.accountId)===_)o.delete(Y.accountId),h.debug("quota","discarded pending response quota",{accountId:Y.accountId})}})().catch(w8),h.trace("quota","response quota awaiting publication",{account:Y.accountId})}catch(G){Q8(G)}}let SZ=Promise.resolve();function N1(Z=!1,Y=!1,G,K){let j=SZ.then(()=>T8(Z,Y,G,K));return SZ=j.then(()=>{},()=>{}),j}async function T8(Z,Y,G,K){let j=await T.read(),L=new Set;if(!Z&&!Y&&j.policyStorage.quota?.enabled===!1)return L;for(let N of j.accounts){if(N.id==="main"||N.type!=="oauth")continue;if(!y0(N)){if(Y)L.add(N.id);continue}if(!Z&&F1(N.quota,j.policyStorage,T1(N.quota))>Date.now()&&(!G||C1(N.quota,j.policyStorage,Date.now(),G)))continue;try{if(!await k.refreshFallback(N.id,"",j.policyStorage.accounts.find((Q)=>Q.id===N.id&&B0(Q)),Z?void 0:K))L.add(N.id),h.debug("quota","fallback quota preflight returned no reading",{accountId:N.id,requiredByPolicy:Y})}catch(_){if(Y&&w1(_))throw _;L.add(N.id),q3(N.id,Y,_)}}return x1().catch(()=>{}),L}let u9={refreshQuotaForDueAccounts:async()=>{await N1()},refreshQuotaForAllAccounts:async(Z)=>{await N1(!0)},refreshAccount:async(Z,Y,G)=>{let K=await A0(Z.id,void 0,G?.force?Z.access:void 0);return{...Z,access:K.accessToken,expires:K.expires}},refreshAccountQuota:async(Z,Y)=>{G$();let G=await T.fetchQuota(Z.id);return{account:{...Z,quota:G},fetched:!0}},getUsableFallbackAccounts:async(Z,Y)=>{Z=Z??null;let G=[],K=Z?.accounts.some((j)=>B0(j)&&o.has(j.id))?(await T.read()).accounts:[];for(let j of Z?.accounts??[]){if(!B0(j)||!y0(j))continue;let L=K.find((Q)=>Q.id===j.id),N=k.getFallback(j.id,L?.binding?{authLineageId:JSON.stringify(L.binding)}:j)?.quota??L?.quota??j.quota,_=L&&Z?O0({...L,quota:N},Z):N;if(!p1(_,Z)||!R9(_,Y?.modelId)||r$(Z)&&!a$(_,Z,j.id,Y?.modelId))continue;if(b0(Z)){if(K4(j.id,Z))G.push(j);continue}try{let Q=await A0(j.id,void 0,void 0,Y?.modelId);G.push({...j,access:Q.accessToken,expires:Q.expires})}catch(Q){if(w1(Q))throw Q}}return G}};async function d9(){G$();let Z=await T.read();if(Z.mode==="local"&&Z.policyStorage.refresh?.enabled!==!1)for(let Y of Z.accounts){if(Y.id==="main"||Y.type!=="oauth"||!y0(Y))continue;try{let G=await A0(Y.id);if(E1(Y.lastRefreshError,Y.accountIdentity,Date.now(),void 0))continue;if(G.localSource!=="rotated"&&G.localSource!=="adopted"&&(!G.expires||G.expires-Date.now()<=kZ(Z.policyStorage)))await A0(Y.id,void 0,void 0,void 0,"refresh")}catch{}}await N1(!1,!1,void 0,"background")}let i9=a0!==null&&process.env.OPENCODE_AUTH_CONTENT===void 0,EZ=new Set;async function S8(){let Z=await T.read(),Y=new Set(Z.accounts.filter((K)=>K.id!=="main"&&K.source==="vault"&&K.type==="oauth"&&y0(K)).map((K)=>K.id)),G=[...Y].some((K)=>!EZ.has(K));if(EZ=Y,G)await N1(!1,!1,void 0,"background");await x1()}let n9=i9&&b0(a0)?T.vault.watch({intervalMs:J.scopedRosterPollIntervalMs??2000,shouldRefresh:()=>process.env.OPENCODE_AUTH_CONTENT===void 0,onRefresh:S8,setInterval:W.setInterval,clearInterval:W.clearInterval}):void 0,E8=i9?(n9?n9.ready.then(()=>d9()):d9()).catch(()=>{}):Promise.resolve(),o9=i9?W.setInterval(()=>{d9().catch(()=>{})},q5+t7(r7)):null;o9?.unref?.();let C8=(Z,Y)=>{let G=wJ({id:Z,role:"fallback"},Y);return G==="na"?"off":G},r9=new NJ,P8=new HJ,p$=new WeakMap,a1=new Map;async function s9(Z){let Y=(Z.get("anthropic-beta")??"").split(",").map((G)=>G.trim()).filter(Boolean).sort();return{betas:Y,betasHash:await B5(Y.join(","))}}function CZ(Z){try{if(!Z.request)return;let Y=J3({request:Z.request,source:Z.source,accountId:Z.accountId,synthetic:Z.synthetic,betasHash:Z.betasHash,requestedModel:Z.requestedModel,onWarning:(K)=>h.warn("cache-diagnostics",K),message:Z.message,receivedAt:Z.receivedAt});if(!Y.record||!Y.messageId){h.debug("cache-diagnostics","skipped invalid response envelope",{status:Z.status});return}h.debug("cache-diagnostics",Z3(Y.record));let G=P8.capture(Z.betasHash,Z.betas);if(G)h.debug("cache-diagnostics",G);if(Y.canary)h.warn("cache-diagnostics","short-gap previous_message_not_found",{message_id:Y.canary.messageId,previous_message_id:Y.canary.previousMessageId});if(Z.trackSessionId)r9.capture(Z.trackSessionId,Y.messageId,Z.receivedAt)}catch(Y){h.debug("cache-diagnostics","response observation failed",{status:Z.status,error:Y instanceof Error?Y.message:String(Y)})}}function PZ(Z,Y,G=!0){let K=p$.get(Z);if(!K)return;if(Y&&typeof Y==="object"&&!Array.isArray(Y)&&!G)K.messageStart=Y;K.dumpWrite=K.dumpWrite.then(()=>sJ(K.dump,{status:K.status,message:Y,complete:G})).catch(()=>{}),CZ({...K,message:Y,receivedAt:Date.now()})}function A8(Z,Y){let G=p$.get(Z);if(!G)return;let K=G.messageStart??{},j=K.usage&&typeof K.usage==="object"&&!Array.isArray(K.usage)?K.usage:{},L={...K,...Y.usage?{usage:{...j,...Y.usage}}:{},...Y.stopReason?{stop_reason:Y.stopReason}:{}};G.dumpWrite=G.dumpWrite.then(()=>sJ(G.dump,{status:G.status,message:L,complete:!0})).catch(()=>{})}function AZ(Z,Y){let G=Promise.resolve(sJ(Y.dump,{status:Y.status,message:null,complete:!1})).catch(()=>{});p$.set(Z,{...Y,dumpWrite:G})}let l$=null,v4=null;function h4(Z){return Z!==null&&typeof Z==="object"&&FJ(Z)==="R"}function R8(Z){let Y=oJ("anthropic");if(!Z||typeof Z!=="object")return!1;let G=Z;return G.type===Y.type&&G.access===Y.access&&G.refresh===Y.refresh&&G.expires===Y.expires}async function q8(){if(v4){let Z=await v4();return c5("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 QG("opencode",W8())}async function RZ(){if(await S1("opencode")!=="claustrum")throw Error("This host is not connected to the credential vault; run setup to connect it first");if(await q8()!=="absent")throw Error("OpenCode already holds an Anthropic login; remove it before choosing the vault login")}let M8={label:"Claude via credential vault",type:"oauth",authorize:async()=>{return await RZ(),{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 RZ();let Z=oJ("anthropic");return{type:"success",access:Z.access,refresh:Z.refresh,expires:Z.expires}}}}},a9=new W5({directory:process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||v5("opencode")}),b4=[],I1=new Map,t1=new Z5({loadStorage:()=>q(z),setIntervalImpl:W.setInterval,clearIntervalImpl:W.clearInterval,onTrackedSessionsChanged:async(Z)=>{await a9.publish(Z),b4=await a9.list(Z)},prepareBody:(Z,Y)=>{if(!new Headers(Y.headers).get("anthropic-beta")?.split(",").map((G)=>G.trim()).includes(V4))return Z;try{let G=JSON.parse(Z),K=r9.previousFor(Y.id),j=K?.messageId??null;return o4(G,j),a1.set(Y.id,{sessionId:Y.id,previousMessageId:j,...K?{previousMessageReceivedAt:K.receivedAt}:{},isSubagent:Y.isSubagent,ttlSent:r4(G),accountId:Y.oauthAccountId??"main",synthetic:!0,requestedModel:typeof G.model==="string"?G.model:void 0}),JSON.stringify(G)}catch{return Z}},onResponse:async({target:Z,bodyText:Y,status:G,data:K,receivedAt:j,attempt:L})=>{let N=I1.get(L.id);if(G===401&&N?.scopedAttempt)await M0(N.scopedAttempt,"direct");let _=a1.get(Z.id);if(!_?.betasHash||!_.betas){a1.delete(Z.id);return}try{let Q=JSON.parse(Y),U=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q.diagnostics:void 0,C=U&&typeof U==="object"&&!Array.isArray(U)&&U.previous_message_id===_.previousMessageId?_.previousMessageId:void 0;if(C===void 0)return;CZ({source:"prewarm_cachekeep",accountId:_.accountId,synthetic:_.synthetic,betasHash:_.betasHash,betas:_.betas,requestedModel:_.requestedModel,request:{..._,previousMessageId:C,ttlSent:r4(Q)},trackSessionId:Z.id,status:G,message:K,receivedAt:j})}catch{}finally{a1.delete(Z.id)}},onComplete:({attempt:Z})=>{I1.delete(Z.id)},retryOnUnauthorized:async({target:Z,headers:Y,attempt:G})=>{let K=I1.get(G.id);if(!K)return;let j;try{let _=JSON.parse(Z.bodyText);if(typeof _.model==="string")j=_.model}catch{}if(K.scopedAttempt&&!await L1(K.scopedAttempt,"cachekeep",G.signal))return;let L=await A0(Z.oauthAccountId??"main",G.signal,K.scopedAttempt?void 0:K.accessToken,j);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 N=new Headers(Y);return N.set("authorization",`Bearer ${L.accessToken}`),I1.set(G.id,L),N},prepareHeaders:async(Z,Y,G)=>{let K=Y.oauthAccountId??"main",j;try{let Q=JSON.parse(Y.bodyText);if(typeof Q.model==="string")j=Q.model}catch{}let L=await A0(K,G.signal,void 0,j),N=L.accessToken;I1.set(G.id,L);try{let Q=JSON.parse(Y.bodyText),U=J1(L.accountIdentity);if(Z.delete("anthropic-beta"),m1(Z,N,{body:Q,identity:U}),Z.set("anthropic-beta",v7(Z.get("anthropic-beta"),[J5])),Q.speed==="fast")j9(Z);let C=a1.get(Y.id);if(C){let{betas:f,betasHash:m}=await s9(Z);C.betas=f,C.betasHash=m}}catch{m1(Z,N)}let _=await A0(K,G.signal,void 0,j);if(_.accountIdentity!==L.accountIdentity||Boolean(_.scopedAttempt)!==Boolean(L.scopedAttempt))throw Error("CacheKeep credential authority changed before dispatch");return Z.set("authorization",`Bearer ${_.accessToken}`),I1.set(G.id,_),Z}});async function I8(Z){if(!l$||!(await l$()).active)throw Error("Native main OAuth activation is not available");let Y=await A0("main",Z);return{...Y,credentialAccountId:F$(Y.accountIdentity)}}async function x8(){let Z=await I8();if((await s1(Z.accessToken,void 0,Z.credentialAccountId)).stale&&Z.credentialAccountId!==void 0)throw Error("Main account identity changed before the prime refresh");let G=await k.refreshMainWithMetadata(H$,Z.accessToken);return{quota:G.quota,fresh:G.fetched}}async function f8(Z){G$();let Y=await q(z),G=Y?.accounts.find((j)=>j.id===Z&&y0(j)&&B0(j));if(!G||!Y)throw Error(`prime: OAuth account ${Z} is unavailable`);let K=await u9.refreshAccountQuota(G,Y);return{quota:K.account.quota??{},fresh:K.fetched}}let t9=new Map;async function k8(Z){let Y=performance.now(),G,K,j,L="",N;try{if(Z==="main"&&(!l$||!(await l$()).active))throw Error("Native main OAuth activation is not available");let _=await A0(Z,void 0,void 0,B7);if(G=_.accessToken,j=_.scopedAttempt,K=B7,!G)return{ok:!1,error:"prime: no access token available"};let Q=$5(),U=J1(_.accountIdentity),C=await _9(JSON.stringify(Q),{identity:U}),f=new Headers({"content-type":"application/json"});m1(f,G,{body:JSON.parse(C),identity:U,requestClass:"auxiliary"}),f.delete("content-length"),f.delete("transfer-encoding");let m=Q4(MG,{baseURL:""}),J0=m.url?.toString()??m.input.toString(),j0=AbortSignal.timeout(30000),f0={method:"POST",headers:f,body:C,signal:j0},w0=await A0(Z,j0,void 0,K);if(w0.accountIdentity!==_.accountIdentity||Boolean(w0.scopedAttempt)!==Boolean(_.scopedAttempt))throw Error("Prime credential authority changed before dispatch");j=w0.scopedAttempt,L=w0.accessToken,f.set("authorization",`Bearer ${L}`);let k0=async()=>{let Q0=F9([L],"http");return N=Q0,Q0.redactResponse(await fetch(J0,f0))},N0=await k0();if(N0.status===401&&j&&!j0.aborted){let Q0;try{Q0=await L1(j,"prime",j0)}catch{}if(Q0){N?.dispose(),await N0.body?.cancel().catch(()=>{}),h.info("claustrum","retrying Prime after scoped credential rotation",{accountId:Z,previousVersion:j.recordVersion,newVersion:Q0.recordVersion}),w0=await A0(Z,j0,void 0,K);let v0=w0.scopedAttempt;if(!v0||v0.credentialId!==j.credentialId||v0.accountIdentity!==j.accountIdentity||v0.recordVersion<=j.recordVersion)throw Error("Prime vault retry lost its strict newer receipt");j=v0,L=v0.accessToken,f.set("authorization",`Bearer ${L}`),N0=await k0()}}if(N0.status===401&&!w0.scopedAttempt&&!j0.aborted){let Q0=w0.accessToken,v0=await A0(Z,j0,Q0,K).catch(()=>{return});if(v0&&v0.accessToken!==Q0&&v0.accountIdentity===_.accountIdentity&&!v0.scopedAttempt){if(N?.dispose(),await N0.body?.cancel().catch(()=>{}),w0=await A0(Z,j0,void 0,K),w0.scopedAttempt||w0.accountIdentity!==_.accountIdentity)throw Error("Prime local authority changed before retry");L=w0.accessToken,f.set("authorization",`Bearer ${L}`),N0=await k0()}}let j$=Math.round(performance.now()-Y);if(!N0.ok){let Q0;try{Q0=await N0.text().catch(()=>"")||`HTTP ${N0.status}`}finally{N?.dispose()}if(N0.status===401&&j)await M0(j,"direct");return{ok:!1,status:N0.status,ms:j$,error:Q0}}let D$=(await N0.json().catch(()=>null))?.usage,U$=D$&&(Number.isFinite(D$.input_tokens)||Number.isFinite(D$.output_tokens))?{inputTokens:Number.isFinite(D$.input_tokens)?D$.input_tokens:void 0,outputTokens:Number.isFinite(D$.output_tokens)?D$.output_tokens:void 0}:void 0;return t9.set(Z,w0),{ok:!0,status:N0.status,ms:j$,...U$&&{usage:U$}}}catch(_){N?.dispose();let Q=F9([L],"http"),U=Q.redactError(_);return Q.dispose(),{ok:!1,..._ instanceof O$&&_.tokenRefreshFailed&&{reason:"token-refresh"},ms:Math.round(performance.now()-Y),error:U instanceof Error?U.message:String(U)}}}let qZ={storagePath:z,loadStorage:()=>q(z),getAccountFingerprint:async(Z)=>{if(Z==="main"&&(!l$||!(await l$()).active))return;let Y=await A0(Z),G=Y.scopedAttempt??Y.localSubject;if(!G)return;let K=await T.getOrCreateAuthLineage(Z,G);return K?t$(K):void 0},refreshQuota:async(Z)=>{if(Z==="main")return x8();return f8(Z)},sendPrime:k8,recordSuccess:async(Z,Y)=>{let G=t9.get(Z);t9.delete(Z);let K=G?.scopedAttempt??G?.localSubject;if(!K||!await T.incrementPrimeUsage(Z,K,Y))throw Error("Prime usage publication lost its native credential fence");let j=(await T.read()).accounts.find((L)=>L.id===Z)?.prime;if(!j)throw Error("Prime usage counters are unavailable after publication");return j},setIntervalImpl:W.setInterval,clearIntervalImpl:W.clearInterval,setTimeoutImpl:W.setTimeout,clearTimeoutImpl:W.clearTimeout},MZ=R3(z,()=>new XG(qZ),{slot:$.directory??"default",rebind:(Z)=>Z.updateOptions(qZ)}),H1=MZ.manager;if(E9(a0))H1.start();async function g4(){return b4=await a9.list(t1.trackedSessions()),b4}let IZ=J.cacheKeepAggregateRefreshIntervalMs??1e4,e9=IZ>0?W.setInterval(()=>{g4().catch(()=>{})},IZ):void 0;if(e9?.unref?.(),q9({enabled:S9(a0),mode:w4(a0)}),zZ(WZ(a0)),OZ(YZ(a0)),!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)CG(JZ(a0)??"info");let $J=null,v8=async()=>{Y1.abort();while(X1.size)await Promise.all([...X1]);try{await d1(z)}catch(Z){h.warn("claustrum","failed to close scoped runtime",{error:Z instanceof Error?Z.message:String(Z)})}try{k.close()}catch{}try{await c9?.dispose()}catch(Z){h.warn("quota-header-feed","failed to dispose",{error:Z instanceof Error?Z.message:String(Z)})}try{if(U1)W.clearInterval(U1),U1=null}catch(Z){h.warn("main-background","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{if(o9)W.clearInterval(o9)}catch(Z){h.warn("fallback-background","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{if(e9!==void 0)W.clearInterval(e9)}catch(Z){h.warn("cachekeep","failed to stop aggregate refresh",{error:Z instanceof Error?Z.message:String(Z)})}try{t1.stop()}catch(Z){h.warn("cachekeep","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{MZ.release()}catch(Z){h.warn("prime","failed to release slot",{error:Z instanceof Error?Z.message:String(Z)})}if(!$J)return;try{await $J.release()}catch(Z){h.warn("rpc","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}},$$={activeId:"main",route:"main"},h8=X8(),E$=new Map;function y4(Z,Y){if(k.updateStorage(Z),k.seedMainFromStorage(Z,H$),!Y.skipFallbackQuotaSeed)k.seedFallbacksFromAccounts((Z?.accounts??[]).filter(B0));let G=k.getMain(H$),K=k.getLastApiError(),j=Z?.refresh?.mainLastRefreshError,L=Z?.claustrum?.primaryAccount,N=b0(Z)&&!y0(L)?eJ({source:"vault",enabled:L?.enabled,state:L?.state}):void 0;return{main:{quota:G?.quota??null,enabled:L?.enabled,tierLabel:B4(Z?.main?.profile),quotaBackedOff:k.isBackedOff(),quotaBackoffUntil:K?.nextRetryAt,refreshBackedOff:j?E1(j,e1??Z?.mainAccountId,Date.now(),Y.mainRefreshToken?t$(Y.mainRefreshToken):void 0):!1,refreshBackoffUntil:j?.nextRetryAt,stateLine:N,quotaDated:Boolean(N)},fallbacks:(Z?.accounts??[]).filter((_)=>B0(_)&&(_.enabled!==!1||Boolean(_.claustrumScopedCredentialId))).map((_)=>{let Q=K4(_.id,Z),U=C8(_.id,Z),C=_.claustrumScopedCredentialId&&!Q?eJ({source:"vault",enabled:_.enabled!==!1,state:_.claustrumScopedState}):void 0;return{id:_.id,label:_.label,tierLabel:B4(_.profile),quota:Y.skipFallbackQuotaSeed?null:k.getFallback(_.id,_)?.quota??_.quota??null,needsReauth:_.lastRefreshError!=null&&E1(_.lastRefreshError,_.id,Date.now(),t$(_.refresh))&&s$(_.lastRefreshError),vaultReauth:U==="on-vault-reauth",vaultServed:Q,custodyState:U,enabled:_.enabled!==!1,stateLine:C,quotaDated:Boolean(C)}}),activeId:Y.activeId,route:Y.route,relay:C5(Z?.relay),fastMode:XZ(),cacheKeep:{enabled:x7(Z),window:I7(Z)?"always":Z?.cacheKeep?.startHour!=null&&Z?.cacheKeep?.endHour!=null?`${Z.cacheKeep.startHour}-${Z.cacheKeep.endHour}`:void 0,trackedSessions:b4.length},prime:E9(Z)?{enabled:!0,accounts:H1.stats(Z)}:void 0,fableRecoveries:E$.size>0?[...E$.values()]:void 0,lastUpdated:Date.now()}}function C$(Z,Y,G){let K=Y.routingAuthoritative!==!1;if(K)$$={activeId:Y.activeId,route:Y.route};function j(L){return G8(L,h8,{routingAuthoritative:K,resolvePreservedRouting:K?void 0:async(N)=>{let _=await hG(N,()=>q(z),{activeId:L.activeId,route:L.route}),Q=await BZ(_.freshStorage,G);return{activeId:_.activeId,route:_.route,state:y4(Q,{...Y,activeId:_.activeId,route:_.route})}},onRoutingResolved:K?void 0:(N)=>{$$=N}}).catch((N)=>h.warn("sidebar","state write failed",{error:N instanceof Error?N.message:String(N)}))}if(K){let L=QZ(Z);if(L.length>0)return BZ(Z,G,L).then((N)=>j(y4(N,Y))).catch(()=>{return h.debug("quota","failed to recheck account profile for sidebar"),j(y4(Z,Y))})}return j(y4(Z,Y))}async function xZ(){return{storage:await q(z),access:void 0}}async function x1(){await g4().catch(()=>{});let{storage:Z,access:Y}=await xZ();C$(Z,{activeId:$$.activeId,route:$$.route,mainAccessToken:Y,mainRefreshToken:void 0,routingAuthoritative:!1})}function b8(Z,Y,G){if(!Y)return;if(Z?.quota?.enabled!==!0)return;let K=G?.quotaKey??H$;if(k.getMain(K))return;if(ZJ)return;ZJ=!0,k.refreshMain(K,Y,G?.generation).then(()=>x1()).catch(()=>{}).finally(()=>{ZJ=!1})}let G1=null,m4,e1,H$,$4,D1,JJ,fZ=0,c4=new Map,ZJ=!1,U1=null,p4=0;function kZ(Z){let Y=Z?.refresh?.refreshBeforeExpiryMinutes??xG;return Math.max(z8,Y)*60000}function g8(Z){return Z?.refresh?.enabled!==!1}async function vZ(Z=!1){let Y=new Map;if(Z){if(l$&&(await l$()).active)try{await T.fetchQuota("main")}catch{Y.set("main","Native primary usage refresh unavailable")}await N1(!0)}let G=await k4(AbortSignal.timeout(3000));k.updateStorage(G.policyStorage),k.seedMainFromStorage(G.policyStorage,H$),k.seedFallbacksFromAccounts(G.policyStorage.accounts.filter(B0));let K=[],j=G.accounts.find((N)=>N.id==="main"&&N.type==="oauth");if(j)K.push({name:j.label??"OpenCode anthropic",role:"main",quota:j.quota,tierLabel:B4(j.profile),error:Y.get("main")??j.lastQuotaRefreshError?.message});K.push(...eY(G.policyStorage,Y));let L=Math.max(0,...G.accounts.map((N)=>T1(N.quota)));return tY({accounts:K,refreshedAt:L||void 0})}async function WJ(Z){await g4().catch(()=>{}),await C$(Z,{activeId:$$.activeId,route:$$.route,routingAuthoritative:!1})}function J4(Z,Y,G,K){if(E$.delete(Z.sessionId),E$.set(Z.sessionId,{...Z,changedAt:Date.now()}),E$.size>128){let j=E$.keys().next().value;if(j)E$.delete(j)}if(C$(Y,{activeId:$$.activeId,route:$$.route,mainAccessToken:G.access,mainRefreshToken:G.refresh,routingAuthoritative:!1}),K)gZ(Z.sessionId,K)}function hZ(Z,Y){let G=m$.get(Z)??new Set;G.delete(Y),G.add(Y);while(G.size>4){let K=G.values().next().value;if(typeof K!=="string")break;G.delete(K)}m$.delete(Z),m$.set(Z,G);while(m$.size>128){let K=m$.keys().next().value;if(typeof K!=="string")break;m$.delete(K)}}function bZ(Z,Y){return typeof Y==="string"&&m$.get(Z)?.has(Y)===!0}function gZ(Z,Y){if(X9(Z))return;N$.delete(Z),N$.set(Z,[Y]);while(N$.size>128){let G=N$.keys().next().value;if(G)N$.delete(G);else break}if(X$.has(Z))XJ(Z)}function XJ(Z,Y=0){if(!N$.has(Z)||o1.has(Z))return;o1.set(Z,Y);let G=()=>{if(o1.get(Z)!==Y)return;o1.delete(Z),y8(Z,Y)};if(Y===0)setImmediate(G);else setTimeout(G,yG*Y)}function YJ(Z,Y){if(Y+1<gG)XJ(Z,Y+1)}async function y8(Z,Y){if(!X$.has(Z)||!N$.has(Z))return;let G=$.client.session;if(typeof G?.status==="function")try{let K=await Promise.resolve(G.status()),j=K!==null&&typeof K==="object"?K:void 0,L=j&&Object.hasOwn(j,"data")?j.data:j;if(L===null||typeof L!=="object"||Array.isArray(L)){YJ(Z,Y);return}let N=L[Z];if(N!==void 0&&(!N||typeof N!=="object"||N.type!=="idle")){YJ(Z,Y);return}}catch{YJ(Z,Y);return}if(!X$.has(Z))return;await m8(Z)}function m8(Z){let Y=M4.get(Z);if(Y)return Y;let G=(async()=>{while(!0){let K=N$.get(Z),j=K?.[0];if(!j){N$.delete(Z);return}try{let L=()=>N$.get(Z)===K&&K[0]===j;if(!await e7($,Z,j,{noReply:!0,beforeActiveAssistant:!0,canSend:()=>X$.has(Z)&&L(),onPreparedMessageId:(_)=>hZ(Z,_),latestPreparedMessageId:()=>[...m$.get(Z)??[]].at(-1)})){if(X$.has(Z)&&!L())continue;return}if(L())K.shift()}catch(L){h.warn("fable-fallback","Desktop notification failed",{session:Z,error:L instanceof Error?L.message:String(L)})}}})();return M4.set(Z,G),G.finally(()=>{if(M4.get(Z)===G)M4.delete(Z)}),G}function c8(Z,Y,G,K){if(Y.fallback&&Y.targetModel){let j=f$.get(Z.recoveryKey);f$.delete(Z.recoveryKey),f$.set(Z.recoveryKey,Y.targetModel);while(f$.size>128){let N=f$.keys().next().value;if(N)f$.delete(N);else break}let L=E$.get(Z.sessionId);if(j===Y.targetModel&&L?.mode==="server"&&h$(L.requestedModelId)===h$(Z.requestedModel)&&L.targetModelId===Y.targetModel)return;h.info("fable-fallback","Anthropic server-side safety fallback active",{session:Z.sessionId,requestedModel:Z.requestedModel,targetModel:Y.targetModel,handoff:Y.handoff}),J4({sessionId:Z.sessionId,mode:"server",remaining:0,requestedModelId:Z.requestedModel,targetModelId:Y.targetModel},G,K,sG(Z.requestedModel,Y.targetModel));return}if(Y.stopReason==="refusal"||!f$.delete(Z.recoveryKey))return;h.info("fable-fallback","Anthropic server-side safety fallback ended",{session:Z.sessionId,requestedModel:Z.requestedModel}),J4({sessionId:Z.sessionId,mode:"fable",remaining:0,requestedModelId:Z.requestedModel},G,K,aG(Z.requestedModel))}function p8(Z,Y,G){if(!Z)return;for(let K of f$.keys())if(K.startsWith(`${Z}\x00`))f$.delete(K);if(!E$.delete(Z))return;C$(Y,{activeId:$$.activeId,route:$$.route,mainAccessToken:G.access,mainRefreshToken:G.refresh,routingAuthoritative:!1})}async function GJ(Z){let Y=GG(Z);if(Y.type==="enable"||Y.type==="disable"){let L=Y.type==="enable",N=await A1(L),_=w4(N);return q9({enabled:L,mode:_}),h.info("commands","cache enabled changed",{enabled:L}),tJ({argumentsText:Z,enabled:L,mode:_,settingsPath:await T.getSettingsPath()})}if(Y.type==="mode"){let L=await A4(Y.mode),N=S9(L);return q9({enabled:N,mode:Y.mode}),h.info("commands","cache mode changed",{mode:Y.mode}),tJ({argumentsText:Z,enabled:N,mode:Y.mode,settingsPath:await T.getSettingsPath()})}let G=await q(z),K=S9(G),j=w4(G);return q9({enabled:K,mode:j}),tJ({argumentsText:Z,enabled:K,mode:j})}async function Z4(Z){let Y=VG(Z),G=await q(z);if(Y.type==="window")G=await R1(Y.startHour,Y.endHour),h.info("commands","cachekeep schedule changed",{schedule:`${Y.startHour}-${Y.endHour}`});else if(Y.type==="always")G=await $1(),h.info("commands","cachekeep schedule changed",{schedule:"always"});else if(Y.type==="disable")G=await R4(!1),h.info("commands","cachekeep enabled changed",{enabled:!1});else if(Y.type==="subagents")G=await q4(Y.enabled),h.info("commands","cachekeep subagents changed",{subagents:Y.enabled});let K=q7(G),j=await g4(),L=j.length?Math.min(...j.map((N)=>N.nextPrewarmAt)):void 0;return A5({argumentsText:Z,enabled:p5(G),always:I7(G),window:K,hybridActive:x7(G),trackedSessions:j.length,trackedSessionDetails:j,nextPrewarmAt:L})}async function yZ(Z){let Y=KG(Z);if(Y.type==="enable"||Y.type==="disable"){let j=Y.type==="enable";return await j1(j),zZ(j),h.info("commands","dump changed",{enabled:j}),w7({argumentsText:Z,enabled:j,settingsPath:await T.getSettingsPath()})}let G=await q(z),K=WZ(G);return zZ(K),w7({argumentsText:Z,enabled:K})}async function mZ(Z){let Y=zG(Z);if(Y.type==="enable"||Y.type==="disable"){let j=Y.type==="enable";return await f9(j),OZ(j),h.info("commands","fast mode changed",{enabled:j}),T7({argumentsText:Z,enabled:j,settingsPath:await T.getSettingsPath()})}let G=await q(z),K=YZ(G);return OZ(K),T7({argumentsText:Z,enabled:K})}async function cZ(Z,Y){if(OG(Z).type==="fire"){if(!Y)return`## Claude Start Failed
|
|
23
23
|
|
|
24
24
|
- OpenCode did not provide a session ID.`;try{return await E3($.client,Y),E7({argumentsText:Z}).text}catch(K){return`## Claude Start Failed
|
|
25
25
|
|
|
26
|
-
- ${K instanceof Error?K.message:String(K)}`}}return E7({argumentsText:Z}).text}async function VJ(Z,Y){let G=
|
|
27
|
-
${U.url}`,knobs:{oauthUrl:U.url},accounts:g$(await q(z)??o$())}}if(K.type==="add-oauth-finish"){let U=Y??"default",C=u(U);if(!C)return{text:"OAuth session expired. Please start again.",accounts:g$(await q(z)??o$())};try{let f=await aJ(K.code,C.verifier,C.redirectUri,C.state);if(f.type==="failed")return{text:"OAuth authentication failed. Please check the code and try again.",accounts:g$(await q(z)??o$())};let m=Date.now(),J0={id:iJ(),type:"oauth",authLineageId:iJ(),label:K.label||void 0,access:f.access,refresh:f.refresh,expires:f.expires,enabled:!0,addedAt:m,lastUsed:m,lastRefreshedAt:m};G$(),await T.loginOAuth({routeId:J0.id,label:J0.label,credential:{access:f.access,refresh:f.refresh,expires:f.expires}});let j0=await q(z);return await WJ(j0),{text:"OAuth account added.",accounts:g$(j0??o$())}}catch{return{text:"OAuth exchange failed due to a network error. Please try again.",accounts:g$(await q(z)??o$())}}finally{A.delete(U)}}let j=await q(z);if(K.type==="status"&&j){let U;if(G1)try{let C=await G1();if(C.type==="oauth")U=$4??C.access}catch{}j=await H8(j,U,AbortSignal.timeout(3000),D1)}let L=K.type==="status"?await uZ(j):void 0,N=await
|
|
26
|
+
- ${K instanceof Error?K.message:String(K)}`}}return E7({argumentsText:Z}).text}async function VJ(Z,Y){let G=LG(Z);if(G.type==="mode")return await v9(G.mode,z),h.info("commands","routing mode changed",{mode:G.mode}),P7({argumentsText:Z,mode:G.mode});if(G.type==="reset"&&Y)await(await LZ()).router.clear(Y),h.info("commands","sticky routing assignment reset");let K=await q(z);return P7({argumentsText:Z,mode:e$(K)})}async function pZ(Z){let Y=jG(Z);if(Y.type==="level")return await k9(Y.level),C7({argumentsText:Z,level:Y.level,settingsPath:await T.getSettingsPath()});let G=await q(z),K=JZ(G)??"info";return C7({argumentsText:Z,level:K,settingsPath:await T.getSettingsPath()})}async function lZ(Z){let Y=_G(Z),G=E9(await q(z)),K=G;if(Y.type==="enable"){if(K=!0,!G)await x$(!0,z),H1.start(),h.info("commands","prime changed",{enabled:!0})}else if(Y.type==="disable"){if(K=!1,G)await x$(!1,z),H1.stop(),h.info("commands","prime changed",{enabled:!1})}if(Y.type==="enable"||Y.type==="disable"){let L=await q(z);if(L&&G1)try{let N=await G1().catch(()=>{return});await C$(L,{activeId:$$.activeId,route:$$.route,mainAccessToken:N?.access,routingAuthoritative:!1})}catch(N){h.warn("sidebar","prime-toggle sidebar write failed",{error:N instanceof Error?N.message:String(N)})}}let j=await q(z);return R5({argumentsText:Z,enabled:K,accounts:H1.stats(j)}).text}async function W4(Z,Y,G){let K=G??YG(Z);if(K.type==="add-apikey"){if(!K.apiKey)return{text:"API key is required",accounts:g$(await q(z)??o$())};let U=K.label?.trim()||void 0,C=Date.now(),f=K.baseURL?.trim()||"https://api.kie.ai/claude";if(!GZ(f))return{text:"Invalid base URL. Must be an http(s) URL without embedded credentials.",accounts:g$(await q(z)??o$())};let m=K.authHeader??"authorization-bearer",J0={id:U||iJ(),label:U||void 0,type:"api",apiKey:K.apiKey,baseURL:f,authHeader:m,enabled:!0,addedAt:C,lastUsed:C};await T.addApi({routeId:J0.id,apiKey:K.apiKey,label:J0.label,baseURL:f,authHeader:m});let j0=await q(z);await WJ(j0);let f0=g$(j0??{version:1,accounts:[]});return{text:`API key account "${J0.label??J0.id}" added.`,accounts:f0}}if(K.type==="add-oauth-start"){if(await S1("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.");let U=await X("max"),C={state:U.state,verifier:U.verifier,redirectUri:U.redirectUri,createdAt:Date.now()};return a(Y??"default",C),{text:`Open this URL in your browser:
|
|
27
|
+
${U.url}`,knobs:{oauthUrl:U.url},accounts:g$(await q(z)??o$())}}if(K.type==="add-oauth-finish"){let U=Y??"default",C=u(U);if(!C)return{text:"OAuth session expired. Please start again.",accounts:g$(await q(z)??o$())};try{let f=await aJ(K.code,C.verifier,C.redirectUri,C.state);if(f.type==="failed")return{text:"OAuth authentication failed. Please check the code and try again.",accounts:g$(await q(z)??o$())};let m=Date.now(),J0={id:iJ(),type:"oauth",authLineageId:iJ(),label:K.label||void 0,access:f.access,refresh:f.refresh,expires:f.expires,enabled:!0,addedAt:m,lastUsed:m,lastRefreshedAt:m};G$(),await T.loginOAuth({routeId:J0.id,label:J0.label,credential:{access:f.access,refresh:f.refresh,expires:f.expires}});let j0=await q(z);return await WJ(j0),{text:"OAuth account added.",accounts:g$(j0??o$())}}catch{return{text:"OAuth exchange failed due to a network error. Please try again.",accounts:g$(await q(z)??o$())}}finally{A.delete(U)}}let j=await q(z);if(K.type==="status"&&j){let U;if(G1)try{let C=await G1();if(C.type==="oauth")U=$4??C.access}catch{}j=await H8(j,U,AbortSignal.timeout(3000),D1)}let L=K.type==="status"?await uZ(j):void 0,N=await P5({argumentsText:Z,storage:j??{version:1,accounts:[]},path:z,claustrum:K.type==="status"&&!L?await F7($8()):void 0,statusProjection:L,transition:async(U)=>({text:U==="claustrum"?"Run `npx @cortexkit/opencode-anthropic-auth setup` to enroll and activate scoped custody safely while OpenCode is stopped.":"Local exit requires replacing the OpenCode auth tombstone with a verified local OAuth login while OpenCode is stopped. Do not change custody mode alone."}),resetEnrollment:async()=>{switch(await FG(T9("opencode"),nJ)){case"reset":return{text:"Terminal Claustrum enrollment state cleared. Run setup to enroll OpenCode again."};case"idle":return{text:"No Claustrum enrollment state to reset. Run setup to enroll OpenCode."};case"refused-pending":return{text:"Claustrum enrollment is still pending. Run setup to resume it or renew an expired request."};case"refused-approved":return{text:"Claustrum enrollment is already approved. Revoke it in Claustrum before removing local enrollment state."};case"busy":return{text:"Another process is updating Claustrum enrollment; retry shortly."}}}});if(N.updated){if(N.updated.action==="enable"||N.updated.action==="disable")await w$(N.updated.id,N.updated.action==="enable",z);else if(N.updated.action==="remove")await l1(N.updated.id,z);else if(N.updated.action==="reorder")await T$(N.updated.newOrder??N.updated.previousOrder??[],z,N.updated.id);else if(N.updated.action==="reset-backoff")await q1("main"),k.clearMainBackoff(),h.info("commands","native main refresh and quota backoff cleared");let U=await q(z);if(G1)try{let C=await G1();C$(U,{activeId:$$.activeId,route:$$.route,mainAccessToken:C.access,mainRefreshToken:C.refresh,routingAuthoritative:!1})}catch{}}let _=await q(z),Q=g$(_??{version:1,accounts:[]});return{text:N.text,accounts:Q,statusProjection:L}}async function uZ(Z){let Y=Z??await q(z),G=Y??o$(),K=g$(G).map((_)=>{let Q=G.accounts.find((f)=>f.id===_.id),U=_.role==="main"?"na":Q&&B0(Q)&&K4(Q.id,G)?"on":"off",C=wJ(_,Y);return{id:_.id,label:_.label,role:_.role,enabled:_.enabled,quotaPercent:_.quotaPercent,..._.tierLabel&&{tierLabel:_.tierLabel},claustrumGate:U,custodyState:C,vaultServed:C==="on-vault-served",vaultReauth:C==="on-vault-reauth"}}),j=await F7($8()),L=T4(G),N=L==="claustrum"?await g7(T9("opencode"),nJ):void 0;return{accounts:K,claustrumDetection:j.status,custodyMode:L,...N&&{claustrumEnrollment:N}}}async function l8(Z,Y,G){if(Z==="claude-quota")return{command:Z,text:await vZ(),knobs:{}};if(Z==="claude-start"){let _=await cZ(Y,G);return{command:Z,text:_,knobs:{}}}if(Z==="claude-logging"){let _=await pZ(Y),Q=await q(z);return{command:Z,text:_,knobs:{level:JZ(Q)??"info"}}}if(Z==="claude-account"){let _=await W4(Y,G),Q=_.statusProjection??await uZ(),U={accounts:Q.accounts,claustrumDetection:Q.claustrumDetection,custodyMode:Q.custodyMode,custodyModeKnown:!0,...Q.claustrumEnrollment&&{enrollmentStatus:A7(Q.claustrumEnrollment,Q.accounts.some((C)=>C.role==="main"&&C.vaultServed)).join(`
|
|
28
28
|
`)}};if("knobs"in _&&_.knobs)Object.assign(U,_.knobs);return{command:Z,text:m4?`${_.text}
|
|
29
29
|
|
|
30
30
|
- Custody startup mismatch: ${m4}`:_.text,knobs:U}}if(Z==="claude-routing"){let _=await VJ(Y,G),Q=await q(z);return{command:Z,text:_,knobs:{mode:e$(Q)}}}if(Z==="claude-fast"){let _=await mZ(Y),Q=await q(z);return{command:Z,text:_,knobs:{enabled:YZ(Q)}}}if(Z==="claude-dump"){let _=await yZ(Y),Q=await q(z);return{command:Z,text:_,knobs:{enabled:WZ(Q)}}}if(Z==="claude-cache"){let _=await GJ(Y),Q=await q(z);return{command:Z,text:_,knobs:{enabled:S9(Q),mode:w4(Q)}}}if(Z==="claude-cachekeep"){let _=await Z4(Y),Q=await q(z);return{command:Z,text:_,knobs:{window:q7(Q)}}}if(Z==="claude-prime"){let _=await lZ(Y),Q=await q(z),U=E9(Q);return{command:Z,text:_,knobs:{enabled:U,accounts:H1.stats(Q)}}}if(Z!=="claude-killswitch")throw Error(`Unhandled command modal: ${Z}`);let K=await q(),j=$Z(K),L=(K?.accounts??[]).filter((_)=>_.enabled!==!1).map((_)=>_.id),N=S7({argumentsText:Y,config:j,accountIds:L});if(N.updatedConfig)await x0(N.updatedConfig);return{command:Z,text:N.text,knobs:{config:$Z(await q()),accountIds:L}}}async function u8(Z){return{text:"Open /claude to manage native Claude settings.",knobs:{}}}let d8=async(Z,Y)=>{if(Y.signal?.aborted)throw Y.signal.reason??Error("Menu action aborted");let G;switch(Z.action){case"enable":case"disable":await T.setEnabled(Z.values.id,Z.action==="enable"),G=`Account ${Z.values.id} ${Z.action}d.`;break;case"remove":await T.remove(Z.values.id),G=`Account ${Z.values.id} removed.`;break;case"move-up":case"move-down":{let K=(await T.read()).accounts.filter((N)=>N.id!=="main").map((N)=>N.id),j=K.indexOf(Z.values.id);if(j<0)throw Error("Native account not found");let L=j+(Z.action==="move-up"?-1:1);if(L>=0&&L<K.length){let N=K[L];if(N===void 0)throw Error("Native account order changed");K[L]=Z.values.id,K[j]=N,await T.reorder(K,Z.values.id)}G="Native account order updated.";break}case"add-apikey":G=(await W4("",Z.sessionId,{type:"add-apikey",apiKey:Z.values.apiKey,label:Z.values.label??void 0,baseURL:Z.values.baseURL??void 0,authHeader:Z.values.authHeader??void 0})).text;break;case"add-oauth-start":G=(await W4("",Z.sessionId,{type:"add-oauth-start"})).text;break;case"add-oauth-finish":G=(await W4("",Z.sessionId,{type:"add-oauth-finish",...Z.values})).text;break;case"reset-backoff":{await q1("main",Y.signal),k.clearMainBackoff(),G="Native main refresh and quota backoff cleared; credential validation and quarantine are unchanged.";break}case"enrollment-reset":G=(await W4("enrollment-reset")).text;break;case"quota-refresh":G=await vZ(!0);break;case"routing-mode":G=await VJ(Z.values.mode);break;case"routing-reset":G=await VJ("reset",Z.sessionId);break;case"cache-on":case"cache-off":G=await GJ(Z.action==="cache-on"?"on":"off");break;case"cache-mode":G=await GJ(`mode ${Z.values.mode}`);break;case"cachekeep-always":G=await Z4("always");break;case"cachekeep-off":G=await Z4("off");break;case"cachekeep-window":G=await Z4(`${Z.values.startHour}-${Z.values.endHour}`);break;case"cachekeep-subagents":G=await Z4(`subagents ${Z.values.enabled}`);break;case"dump-on":case"dump-off":G=await yZ(Z.action==="dump-on"?"on":"off");break;case"fast-on":case"fast-off":G=await mZ(Z.action==="fast-on"?"on":"off");break;case"prime-on":case"prime-off":G=await lZ(Z.action==="prime-on"?"on":"off");break;case"logging-level":G=await pZ(Z.values.level);break;case"killswitch-on":case"killswitch-off":case"killswitch-set":{let j=(await T.read()).accounts.filter((L)=>L.id!=="main").map((L)=>L.id);await T.updateSettings((L)=>{let N=$Z({...L,version:1,accounts:[]});if(Z.action!=="killswitch-set"){let U=S7({argumentsText:Z.action==="killswitch-on"?"on":"off",config:N,accountIds:j});return{...L,killswitch:U.updatedConfig??N}}let _={...N.accounts},Q={...N,enabled:!0,accounts:_};for(let U of Z.values.entries){let C={five_hour:U.fh,seven_day:U.sd,...U.scoped===void 0?{}:{scoped:U.scoped}};if(U.account==="main"||U.account==="all")Q.main=C;if(U.account==="all")for(let f of j)_[f]=C;else if(U.account!=="main")_[U.account]=C}return{...L,killswitch:Q}}),G="Native killswitch policy updated.";break}case"start-fire":G=await cZ("",Z.sessionId);break;default:throw Error(`Unsupported native menu action: ${Z}`)}return WJ(await q()).catch(()=>{}),{ok:!0,text:G.split(`
|
|
@@ -36,7 +36,7 @@ ${U.url}`,knobs:{oauthUrl:U.url},accounts:g$(await q(z)??o$())}}if(K.type==="add
|
|
|
36
36
|
`))}}if(Y?.length)for(let _ of Y){let Q=_.quota;if(!Q)continue;let{five_hour:U,seven_day:C}=Q;if(!U&&!C)continue;let f=_.label||"alt",J0=G===_.id?"active":"idle",j0=iZ(U?.resetsAt),f0=[`${f} · ${J0}${j0?` (${j0})`:""}`];if(U)f0.push(l4("5h",U.usedPercent)),j=Math.max(j,U.usedPercent);if(C)f0.push(l4("7d",C.usedPercent)),j=Math.max(j,C.usedPercent);K.push(f0.join(`
|
|
37
37
|
`))}if(!K.length)return;let L=K.join(`
|
|
38
38
|
|
|
39
|
-
`),N=j>=90?"error":j>=70?"warning":"info";V.tui?.showToast?.({body:{title:"Claude Quota",message:L,variant:N,duration:N==="error"?8000:5000}})?.catch?.(()=>{})}if($.directory){let Z=Z8($.directory);try{$J=await c3(Z,()=>m3({dir:Z,drain:g3,apply:u8,applyMenu:(Y)=>dZ(Y.sessionId??"").apply(Y)}))}catch{h.warn("rpc","native menu server unavailable")}}return{"experimental.chat.messages.transform":async(Z,Y)=>{let G=Y.messages;M1.observeMessages(G);let K=N3(G);if(K){n1.record(K);return}let j=G.findLast((_)=>_.info?.role==="user"),L=j?.info?.sessionID,N=j?.info?.id;if(typeof L==="string"&&typeof N==="string")n1.clear(L,N)},"chat.message":async({sessionID:Z},Y)=>{g9.observeSyntheticMessage({sessionId:Z,messageId:Y.message.id,parts:Y.parts})},"chat.headers":async({sessionID:Z,agent:Y,message:G},K)=>{if(M3(Y))K.headers[kJ]="auxiliary";g9.markHeaders({sessionId:Z,messageId:G.id,headers:K.headers}),n1.markHeaders({sessionId:Z,messageId:G.id,headers:K.headers}),M1.markHeaders({sessionId:Z,messageId:G.id,headers:K.headers})},event:async({event:Z})=>{let Y=Z,G=Y.properties?.info,K=Y.properties?.sessionID??G?.sessionID??G?.id;if(!K)return;if(Y.type==="message.updated"&&G?.role==="user"&&!bZ(K,G.id))if(typeof G.id==="string"){if(y9.set(K,G.id),X$.has(K)&&I4.get(K)!==G.id)X$.delete(K)}else X$.delete(K);if(Y.type==="session.status"&&Y.properties?.status?.type!=="idle")X$.delete(K);if(Y.type==="session.idle"){let j=y9.get(K);if(j)I4.set(K,j);else I4.delete(K);X$.add(K);while(X$.size>128){let L=X$.values().next().value;if(L)X$.delete(L);else break}XJ(K)}if(Y.type==="session.deleted"||Y.type==="message.removed")M1.clearSession(K);if(Y.type==="session.deleted"){W1.clearSession(K),KJ.delete(K),A.delete(K),g9.clearSession(K),E$.delete(K),N$.delete(K),X$.delete(K),y9.delete(K),I4.delete(K),m$.delete(K);for(let j of S$.keys())if(j.startsWith(`${K}\x00`))S$.delete(j);o1.delete(K)}},config:async(Z)=>{let Y={...Z.command??{}};for(let G of J8)delete Y[G];Z.command={...Y,claude:{template:"claude",description:"Manage Claude accounts, quotas, routing, and cache settings."}}},"experimental.chat.system.transform":async(Z,Y)=>{if(!
|
|
39
|
+
`),N=j>=90?"error":j>=70?"warning":"info";V.tui?.showToast?.({body:{title:"Claude Quota",message:L,variant:N,duration:N==="error"?8000:5000}})?.catch?.(()=>{})}if($.directory){let Z=Z8($.directory);try{$J=await c3(Z,()=>m3({dir:Z,drain:g3,apply:u8,applyMenu:(Y)=>dZ(Y.sessionId??"").apply(Y)}))}catch{h.warn("rpc","native menu server unavailable")}}return{"experimental.chat.messages.transform":async(Z,Y)=>{let G=Y.messages;M1.observeMessages(G);let K=N3(G);if(K){n1.record(K);return}let j=G.findLast((_)=>_.info?.role==="user"),L=j?.info?.sessionID,N=j?.info?.id;if(typeof L==="string"&&typeof N==="string")n1.clear(L,N)},"chat.message":async({sessionID:Z},Y)=>{g9.observeSyntheticMessage({sessionId:Z,messageId:Y.message.id,parts:Y.parts})},"chat.headers":async({sessionID:Z,agent:Y,message:G},K)=>{if(M3(Y))K.headers[kJ]="auxiliary";g9.markHeaders({sessionId:Z,messageId:G.id,headers:K.headers}),n1.markHeaders({sessionId:Z,messageId:G.id,headers:K.headers}),M1.markHeaders({sessionId:Z,messageId:G.id,headers:K.headers})},event:async({event:Z})=>{let Y=Z,G=Y.properties?.info,K=Y.properties?.sessionID??G?.sessionID??G?.id;if(!K)return;if(Y.type==="message.updated"&&G?.role==="user"&&!bZ(K,G.id))if(typeof G.id==="string"){if(y9.set(K,G.id),X$.has(K)&&I4.get(K)!==G.id)X$.delete(K)}else X$.delete(K);if(Y.type==="session.status"&&Y.properties?.status?.type!=="idle")X$.delete(K);if(Y.type==="session.idle"){let j=y9.get(K);if(j)I4.set(K,j);else I4.delete(K);X$.add(K);while(X$.size>128){let L=X$.values().next().value;if(L)X$.delete(L);else break}XJ(K)}if(Y.type==="session.deleted"||Y.type==="message.removed")M1.clearSession(K);if(Y.type==="session.deleted"){W1.clearSession(K),KJ.delete(K),A.delete(K),g9.clearSession(K),E$.delete(K),N$.delete(K),X$.delete(K),y9.delete(K),I4.delete(K),m$.delete(K);for(let j of S$.keys())if(j.startsWith(`${K}\x00`))S$.delete(j);o1.delete(K)}},config:async(Z)=>{let Y={...Z.command??{}};for(let G of J8)delete Y[G];Z.command={...Y,claude:{template:"claude",description:"Manage Claude accounts, quotas, routing, and cache settings."}}},"experimental.chat.system.transform":async(Z,Y)=>{if(!uG(Z))return;dG(Y.system)},provider:{id:"anthropic",async models(Z,Y){let G=J2(eG(Z.models));if(Y.auth?.type!=="oauth"||!s5(a0??{}))return G;return Z2(G)}},"command.execute.before":async(Z)=>{if(Z.command!=="claude")return;let Y=await dZ(Z.sessionID).open(Z.sessionID);if(X9(Z.sessionID))b3(Y,Z.sessionID);else{let G=[Y.menu.title,...Y.menu.sections.flatMap((K)=>[`
|
|
40
40
|
## ${K.title}`,...K.lines,...K.items.map((j)=>`${j.label}${j.detail?` — ${j.detail}`:""}`)])].join(`
|
|
41
|
-
`);await e7($,Z.sessionID,G)}pG()},auth:{provider:"anthropic",async loader(Z,Y){l$=async()=>{let Q=await Z();return{type:Q.type,active:ZZ(Q,"anthropic")}},v4=Z;let G=await Z();if(G.type!=="oauth")return{};let K=await S1("opencode").catch(()=>{return});if(!UZ&&ZZ(G,"anthropic")&&process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION!=="1"){UZ=!0;let Q=k4(Y1.signal).then((U)=>{if(!Y1.signal.aborted)return C$(U.policyStorage,{...$$,routingAuthoritative:!1})}).catch(()=>{if(!Y1.signal.aborted)h.debug("quota","startup account profile hydration failed")});X1.add(Q),Q.then(()=>X1.delete(Q))}function j(Q,U=!1){if(!ZZ(Q,"anthropic")&&!(U&&h4(Q)))throw Error("Native OAuth requires inert OpenCode activation; run offline setup")}async function L(Q){j(await Z(),Q&&await S1("opencode")==="local")}let N=async(Q,U,C=!1)=>{let f=await Z();if(f.type!=="oauth")return{type:f.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 m=await S1("opencode");if(m==="claustrum"&&!R8(f))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.");G$();let J0=await DG(T,U),j0=m==="claustrum"?"committed":b7(await y7(s)),f0=m7(J0);if(j(f,m==="local"&&(j0==="committed"||j0==="retired")&&f0),m==="claustrum"&&!J0.accounts.some((R0)=>R0.type==="oauth"&&y0(R0)))throw new VZ;let w0=W3(J0.policyStorage);try{X3({mode:m==="claustrum"?"C":"L",main:FJ(f),fallbacks:m==="claustrum"?"T":w0.fallbacks,evidence:"V",authority:j0,localOAuthServable:f0}),m4=void 0}catch(R0){if(R0 instanceof z4)m4=R0.verdict;throw R0}q0=J0.policyStorage;let k0=J0.accounts.find((R0)=>R0.id==="main"),N0=k0?.binding,j$=k0?O0(k0,J0.policyStorage):void 0,V1=j$&&j$!==k0?.quota?{...J0.policyStorage,quota:{...J0.policyStorage.quota,mainQuota:j$}}:J0.policyStorage,D$=L0("main",G0(N0),k0?.accountIdentity,J0.policyStorage),U$=Boolean(N0&&D$?.lineage===G0(N0)&&D$?.generalExhausted===!0);if(k0&&N0&&(!m0||N0.rowId!==m0.rowId||N0.credentialEpoch>m0.credentialEpoch))k.clearMain(),k.setMainQuotaAccountIdentity(k0.accountIdentity),m0={rowId:N0.rowId,credentialEpoch:N0.credentialEpoch};if(C&&(e$(J0.policyStorage)==="fallback-first"||NZ(V1,k0?.accountIdentity,U$))){let R0=J0.accounts.find((V$)=>V$.id==="main");return U?.throwIfAborted(),{type:"oauth",access:"",expires:0,refresh:void 0,nativeAccountIdentity:R0?.accountIdentity,nativeRoutingLineage:R0?.binding?G0(R0.binding):void 0,nativeLocalSource:void 0,nativeScopedAttempt:void 0,modelDenied:!1,credentialUnavailable:!1,credentialFailure:void 0,deferred:!0}}let Q0,v0,_$,k$;try{Q0=await A0("main",U,void 0,Q,"serve",J0)}catch(R0){if(R0 instanceof E0)throw R0;if(w1(R0))throw R0;if(R0 instanceof Z1){v0=R0.account;let V$=g5(v0.quota,Q);if(V$!==void 0&&(!Number.isFinite(V$.checkedAt)||(V$.checkedAt??0)+R0.checkIntervalMs<=Date.now())||!KZ(v0.quota)&&!A9(v0.quota,Q))try{await T.fetchQuota("main",void 0,U),Q0=await A0("main",U,void 0,Q),v0=void 0}catch(v$){if(w1(v$))throw v$;if(v$ instanceof Z1)v0=v$.account;else if(v$ instanceof O$)_$=v$.account,k$=v$}}else if(R0 instanceof O$)_$=R0.account,k$=R0}return U?.throwIfAborted(),{type:"oauth",access:Q0?.accessToken??"",expires:Q0?.expires??0,refresh:void 0,nativeRoutingLineage:I0(Q0?.localSubject,Q0?.scopedAttempt)??(k0?.binding?G0(k0.binding):void 0),nativeAccountIdentity:Q0?.accountIdentity??v0?.accountIdentity??_$?.accountIdentity,modelDenied:Boolean(v0),credentialUnavailable:Boolean(_$),credentialFailure:k$,deferred:!1,nativeLocalSource:Q0?.localSource,nativeScopedAttempt:Q0?.scopedAttempt}};G1=N;let _={type:"oauth",access:"",expires:0};if(_.type==="oauth"){let f=function(){if(U1)W.clearInterval(U1);let D=async()=>{try{let B=await q(z);if(!g8(B))return;let x=await N();if(x.type!=="oauth")return;if(x.nativeLocalSource==="rotated"||x.nativeLocalSource==="adopted")return;if(x.expires&&x.expires-Date.now()>kZ(B))return;await C()}catch{h.warn("refresh","native main OAuth background refresh unavailable")}};U1=W.setInterval(()=>{D()},MG+t7(r7)),U1.unref?.()},J0=function(D,B){if(D instanceof Request&&D.body)return!1;return B==null||typeof B==="string"},j0=function(D){if(typeof D!=="string")return;try{let B=JSON.parse(D);return typeof B.model==="string"?B.model:void 0}catch{return}},f0=function(D){return D.has("x-parent-session-id")},w0=function(D){let B;try{B=JSON.parse(D)}catch{return!1}if(typeof B!=="object"||B===null)return!1;let x=Reflect.get(B,"error");return Reflect.get(B,"type")==="error"&&typeof x==="object"&&x!==null&&Reflect.get(x,"type")==="rate_limit_error"},k0=function(D){return D?.quota?.enabled===!0},j$=function(D,B){if(D.delete("authorization"),D.delete("x-api-key"),B.authHeader==="x-api-key")D.set("x-api-key",B.apiKey??"");else D.set("Authorization",`Bearer ${B.apiKey??""}`);D.set("Content-Type","application/json"),U7(D)},Q0=function(D){return k.getFallback(D.id,D)?.quota??D.quota},v0=function(D,B){return D.status===429||B},_$=function(D,B=q0){return b("main",D?.routingLineage,D?.providerAccountUuid,k.getMain(D?.quotaKey??H$),B)},k$=function(D,B){if(!D&&!B?.providerAccountUuid)return!1;let x=_$(B);return Boolean(x&&(D||x.quota.accountIdentity===B?.providerAccountUuid)&&x.refreshAfter>Date.now()&&r1(x.quota)&&(x.quota.source!=="headers"||L0("main",B?.routingLineage,B?.providerAccountUuid)?.generalExhausted===!0||["five_hour","seven_day"].some((v)=>x.quota.fieldSources?.[v]==="poll"&&(x.quota[v]?.remainingPercent??1)<=0)))},U=(await T.read().catch(()=>{return}))?.accounts.find((D)=>D.id==="main");if(e1=U?.binding?.rowId??U?.accountIdentity,H$??=U?.accountIdentity??e1,_.access)await s1(_.access);async function C(D,B,x){let v=h4(await Z());await L(v),x?.throwIfAborted();let d=await A0("main",x,D,B,"refresh");return await L(v),x?.throwIfAborted(),d.accessToken}if(K==="local")f();k.seedFallbacksFromAccounts((a0?.accounts??[]).filter(B0));let m=await hG(()=>q(z)).catch(()=>({freshStorage:null,activeId:void 0,route:"main"}));await C$(m.freshStorage,{activeId:m.activeId,route:m.route,mainAccessToken:_.access,routingAuthoritative:!1});async function N0(D,B){if(!D.body||D.status!==200)return B?.mark("inspect_stream_skip",{status:D.status}),{response:D,rateLimited:!1};if(D.headers.get("x-cortexkit-relay-optimistic")==="true")return B?.mark("inspect_stream_skip",{status:D.status,reason:"optimistic_relay"}),{response:D,rateLimited:!1};let x=$0(),v=D.body.getReader(),d=[],t=0,g=w5({maxFrameBytes:65536}),P=!1,_0=!1,W0=!0;while(!_0&&t<65536){let{done:I,value:n}=await v.read().catch(async(F)=>{let S=gJ(F,p$.get(D)?.toolNameMap);if(S!==F)await yJ(v,S);throw S});if(I)break;d.push(n),t+=n.byteLength;let X0;try{X0=g.push(n)}catch{break}for(let F of X0){let S=LG(S5(F,{streamStart:W0}));if(W0=!1,S.data===void 0)continue;P=w0(S.data),_0=!0;break}}if(P){await v.cancel().catch(()=>{});try{v.releaseLock()}catch{}let I=new ReadableStream({start(X0){for(let F of d)X0.enqueue(F);X0.close()}});B?.mark("inspect_stream_first_event",{ms:P0($0()-x),bytes:t,rateLimited:!0});let n=new Response(I,{status:D.status,statusText:D.statusText,headers:D.headers});return n4(p$,D,n),{response:n,rateLimited:!0}}let V0=new ReadableStream({start(I){for(let n of d)I.enqueue(n)},async pull(I){let{done:n,value:X0}=await v.read();if(n){I.close();return}I.enqueue(X0)},cancel(I){return v.cancel(I)}});B?.mark("inspect_stream_first_event",{ms:P0($0()-x),bytes:t,rateLimited:!1});let E=new Response(V0,{status:D.status,statusText:D.statusText,headers:D.headers});return n4(p$,D,E),{response:E,rateLimited:!1}}async function V1(D,B,x,v){if(G$(),!B){let g=_$(x);if(!x?.providerAccountUuid||!g||g.refreshAfter<=Date.now()||!r1(g.quota))throw Error("API fallback requires fresh general primary OAuth exhaustion");let P=await A0("main",v);if(P.accountIdentity!==x.providerAccountUuid||x.routingLineage&&I0(P.localSubject,P.scopedAttempt)!==x.routingLineage)throw Error("Primary identity changed before API fallback");B=P.accessToken}let d=await T.authorizeApi(D,v),t=(await T.read()).accounts.find((g)=>g.id==="main");if(t?.binding&&G0(t.binding)!==x?.routingLineage)throw Error("Primary identity changed before API fallback");if(!k$(B,x))throw Error("API fallback requires fresh general primary OAuth exhaustion");return d}async function D$(D,B,x,v,d="api_fallback",t,g,P,_0){if(g)g.oauthAccountId=void 0,g.opusCacheAnchor=void 0;let W0=$0(),V0=U4(D,B),E=V0.get("x-session-affinity")||V0.get("x-opencode-session"),I=f0(V0),n=V0.get(v1)??void 0,X0=n1.resolveHeader(n);V0.delete("x-parent-session-id"),V0.delete("x-session-affinity"),V0.delete("x-opencode-session"),V0.delete("x-opencode-session-id"),V0.delete("x-opencode-parent-session-id"),V0.delete(v1),V0.delete(Y4),V0.delete(kJ);let F=await C4(D,B),S=!1,K0=null,d0,y=typeof F==="string"?F.length:void 0;if(F&&typeof F==="string"){let A$=$0(),L$=(()=>{if(!XZ())return!1;try{return f7(JSON.parse(F).model)}catch{return!1}})();try{F=await _9(F,{onToolNameMap:(h0)=>{d0=h0},cache1hEnabled:!I&&S4(),cache1hMode:F4(),fastModeEnabled:L$,sessionId:E||void 0,midConversationEffortEnabled:!1,midConversationEffortPlan:n,midConversationEffortResolvedPlan:X0,modelRemapEnabled:!0,perf:(h0,K$)=>v?.mark(`rewrite_body_${h0}`,{route:d,...K$})})}catch(h0){if(h0 instanceof S0)return n7(h0);if(h0 instanceof c7)return o7(h0);throw h0}if(j$(V0,x),V0.set("anthropic-beta",v7(V0.get("anthropic-beta"),[])),L$)j9(V0);try{S=JSON.parse(F).stream===!0}catch{}v?.mark("rewrite_body",{route:d,ms:P0($0()-A$),originalBytes:y,rewrittenBytes:F.length,cacheEnabled:!I&&S4(),cacheMode:F4(),fastModeEnabled:L$,subagent:I})}else j$(V0,x);let u0=await s9(V0),P$=await V1(x.id,P,_0,B?.signal??void 0);x={...x,...P$},j$(V0,x);let J$=Q4(D,{baseURL:x.baseURL}),c0=$0(),u$=F9([x.apiKey??""],S?"event-stream":"http"),Y0;try{Y0=u$.redactResponse(await fetch(J$.input,{...B,body:F,headers:V0,...mJ()&&{tls:{rejectUnauthorized:!1}}}))}catch(A$){let L$=u$.redactError(A$);if(u$.dispose(),typeof F==="string")await w9({affinity:E,route:d,error:p7,bodyText:F,url:J$.url?.toString()??E4(J$.input),method:P1(D,B),headers:V0});throw L$}if(typeof F==="string")K0=await w9({affinity:E,route:d,status:Y0.status,bodyText:F,url:J$.url?.toString()??E4(J$.input),method:P1(D,B),headers:V0});if(AZ(Y0,{source:"turn",toolNameMap:d0,accountId:x.id,synthetic:!1,...u0,requestedModel:j0(F),dump:K0,status:Y0.status,streaming:S}),v?.mark("send_headers_received",{route:d,ms:P0($0()-c0),status:Y0.status,relayConfigured:!1,totalSendWithAccessMs:P0($0()-W0),baseURL:x.baseURL}),Y0.ok)u1.publish(()=>T.publishApi(P$.subject,{lastUsed:Date.now()}));return Y0}async function U$(D,B,x,v,d="unknown",t,g="main",P,_0,W0=!1,V0,E){sY(x,"anthropic");let I=h4(await Z()),n=$0(),X0=t,F=async()=>{return X0??=await q(z),X0},S=U4(D,B),K0=S.get("x-session-affinity")||S.get("x-opencode-session"),d0=f0(S),y=S.get(v1)??void 0,u0=n1.resolveHeader(y),P$=S.get(Y4)??void 0,J$=M1.resolveHeader(P$),c0=!d0&&!W0?J$: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(v1),S.delete(Y4);let u$=I3(S),Y0=await C4(D,B),A$=K0?r9.previousFor(K0):null,L$=A$?.messageId??null,h0,K$=!1,X4=null,R$=null,u4,f1;if(Y0&&typeof Y0==="string"){let l=$0();try{let U0=JSON.parse(Y0);if(typeof U0.model==="string")f1=U0.model}catch{}v?.mark("model_parse_for_identity",{route:d,ms:P0($0()-l),bodyBytes:Y0.length})}let p0=await A0(g,B?.signal??void 0,void 0,f1,g==="main"?"last-main":"serve");if(x=p0.accessToken,g==="main"&&V0?.providerAccountUuid&&p0.accountIdentity!==V0.providerAccountUuid)throw Error("Main account identity changed after request routing");E=p0.scopedAttempt;let M=$0(),i=J1(p0.accountIdentity);v?.mark("resolve_claude_code_identity",{route:d,ms:P0($0()-M),hasAccountUuid:Boolean(i.accountUuid)});let r=typeof Y0==="string"?Y0.length:void 0;if(Y0&&typeof Y0==="string"){let l=$0(),U0=(()=>{if(!XZ())return!1;try{return f7(JSON.parse(Y0).model)}catch{return!1}})(),Z$=!d0&&S4(),k1=F4(),jJ=_0?.plan.downgraded&&_0.plan.standbyCacheAnchor?.oauthAccountId===g?_0.plan.standbyCacheAnchor:void 0;try{Y0=await _9(Y0,{onToolNameMap:(n0)=>{u4=n0},cache1hEnabled:Z$,cache1hMode:k1,fastModeEnabled:U0,identity:i,sessionId:K0||void 0,thinkingPrefixMismatchBehavior:y5(await F()),midConversationEffortEnabled:!0,midConversationEffortPlan:y,midConversationEffortResolvedPlan:u0,hybridStandbyAnchor:jJ,serverSideFallbackEnabled:b9==="server",laneStart:W0,billingLineage:c0,cacheDiagnosticsPreviousMessageId:L$,perf:(n0,z1)=>{if(v?.mark(`rewrite_body_${n0}`,{route:d,...z1}),n0==="cache_strategy"&&z1?.standbyBridgeApplied===!0&&_0&&!_0.standbyBridgeLogged)_0.standbyBridgeLogged=!0,h.info("fable-fallback","restored standby Opus cache bridge",{session:_0.plan.sessionId,distanceBlocks:z1?.standbyDistanceBlocks})}})}catch(n0){if(n0 instanceof S0)return n7(n0);if(n0 instanceof c7)return o7(n0);throw n0}if(_0?.plan.downgraded&&Z$&&k1==="hybrid"){let n0=j7(Y0);_0.opusCacheAnchor=n0?{...n0,oauthAccountId:g}:void 0}let nZ=$0();try{let n0=JSON.parse(Y0);m1(S,x,{body:n0,identity:i,requestClass:u$});let z1=n0.diagnostics,oZ=z1&&typeof z1==="object"&&!Array.isArray(z1)&&z1.previous_message_id===L$?L$:void 0;if(oZ!==void 0&&S.get("anthropic-beta")?.split(",").map((s8)=>s8.trim()).includes(V4))h0={sessionId:K0??"session-unknown",previousMessageId:oZ,...A$?{previousMessageReceivedAt:A$.receivedAt}:{},isSubagent:d0,ttlSent:r4(n0)};K$=n0.stream===!0,v?.mark("set_oauth_headers_body_parse",{route:d,ms:P0($0()-nZ),bodyBytes:Y0.length,parsed:!0})}catch{m1(S,x,{identity:i,requestClass:u$}),v?.mark("set_oauth_headers_body_parse",{route:d,ms:P0($0()-nZ),bodyBytes:Y0.length,parsed:!1})}if(U0)j9(S);v?.mark("rewrite_body",{route:d,ms:P0($0()-l),originalBytes:r,rewrittenBytes:Y0.length,cacheEnabled:!d0&&S4(),cacheMode:F4(),fastModeEnabled:U0,subagent:d0})}let z0=await s9(S),p=Q4(D);if(_0)_0.oauthAccountId=g;if(typeof Y0==="string"&&S4()&&F4()==="hybrid"){let l=await F();if(!d0||p5(l)){let U0=$0(),Z$=t1.track({sessionId:K0,url:p.url?.toString()??p.input.toString(),headers:S,bodyText:Y0,storage:l,cacheMode:"hybrid",oauthAccountId:g,isSubagent:d0});v?.mark("cachekeep_track",{session:K0,ms:P0($0()-U0),tracked:Z$.tracked,reason:Z$.tracked?void 0:Z$.reason,bodyBytes:Y0.length})}}let e=p0,i0,Y$=async(l)=>{await L(I),B?.signal?.throwIfAborted();let U0=await A0(g,B?.signal??void 0,l,f1,g==="main"?"last-main":"serve");if(await L(I),B?.signal?.throwIfAborted(),U0.accountIdentity!==e.accountIdentity||Boolean(U0.scopedAttempt)!==Boolean(e.scopedAttempt))throw Error("Native credential authority changed during the request");if(i0&&(!U0.scopedAttempt||U0.scopedAttempt.credentialId!==i0.credentialId||U0.scopedAttempt.accountIdentity!==i0.accountIdentity||U0.scopedAttempt.recordVersion<=i0.recordVersion))throw Error("Native vault retry has no strict newer same-account receipt");return U0},Q$=!1,t0=E,T0=async()=>{Q$=!0,p0=await Y$(),t0=p0.scopedAttempt,S.set("authorization",`Bearer ${p0.accessToken}`),C0={...C0,accessToken:p0.accessToken,anthropicAccountUuid:F$(p0.accountIdentity),localSubject:p0.localSubject,scopedAttempt:p0.scopedAttempt};let l=F9([p0.accessToken],K$?"event-stream":"http");try{let U0=(k1,jJ)=>fetch(p.input,{...B,body:k1,headers:jJ,...mJ()&&{tls:{rejectUnauthorized:!1}}}),Z$=l.redactResponse(typeof Y0==="string"?await SG({url:p.url?.toString()??E4(p.input),body:Y0,headers:S,latch:H,send:U0}):await U0(Y0,S));if(typeof Y0==="string")X4=await w9({affinity:K0,route:d,status:Z$.status,bodyText:Y0,url:p.url?.toString()??E4(p.input),method:P1(D,B),headers:S,tag:W0?"start":void 0});return Z$}catch(U0){let Z$=l.redactError(U0);if(l.dispose(),typeof Y0==="string")await w9({affinity:K0,route:d,error:p7,bodyText:Y0,url:p.url?.toString()??E4(p.input),method:P1(D,B),headers:S,tag:W0?"start":void 0});throw Z$}},z$=await F(),e0;try{e0=await T.getRelayConfig()}catch(l){if(l instanceof t5&&l.code==="relay-inconsistent")return _Z(l.message);throw l}let OJ=g==="main"?void 0:z$?.accounts.find((l)=>l.id===g&&B0(l)),d4=q5(OJ,P),C0={accountId:g,accessToken:x,authLineageId:P,anthropicAccountUuid:F$(E?.accountIdentity)??(g==="main"?V0?.providerAccountUuid:F$(i.accountUuid)??F$(d4)),localSubject:p0.localSubject,scopedAttempt:p0.scopedAttempt,...g==="main"&&V0?{mainQuotaIdentity:V0}:{}},i4=$0(),q$,H0=!1,l0=M0,g0=()=>TG({config:e0,input:p.input,init:B,headers:S,body:Y0,fallback:T0,affinity:K0,optimisticResponse:e0?.transport==="websocket",authorizeAttempt:async()=>{let l=await Y$(),U0=l.scopedAttempt;p0=l,C0={...C0,accessToken:l.accessToken,anthropicAccountUuid:F$(l.accountIdentity),localSubject:l.localSubject,scopedAttempt:U0};let Z$=new Headers(S);return Z$.set("authorization",`Bearer ${l.accessToken}`),{headers:Z$,errorSecrets:[l.accessToken],onUpstreamStatus:(k1)=>{if(k1!==401||!U0)return;if(q$=U0,H0)l0(U0,"relay_status_field")}}},onResponseHeaders:(l)=>{TZ(l,C0),M1.commit(c0,_J(l))},onDumpCreated:(l)=>{R$=l},dumpTag:W0?"start":void 0}),D0=await g0();if(!Q$&&q$&&D0.status===401&&typeof Y0==="string"&&(P1(D,B)??"").toUpperCase()==="POST"&&!B?.signal?.aborted){let l;try{l=await L1(q$,"model-relay",B?.signal??void 0)}catch{}if(l)await D0.body?.cancel().catch(()=>{}),h.info("claustrum","retrying after scoped credential rotation",{accountId:g,previousVersion:q$.recordVersion,newVersion:l.recordVersion,transport:"relay"}),i0=q$,q$=void 0,D0=await g0()}if(Q$&&t0&&D0.status===401&&typeof Y0==="string"&&(P1(D,B)??"").toUpperCase()==="POST"&&!B?.signal?.aborted){let l;try{l=await L1(t0,"model",B?.signal??void 0)}catch{}if(l)await D0.body?.cancel().catch(()=>{}),h.info("claustrum","retrying after scoped credential rotation",{accountId:g,previousVersion:t0.recordVersion,newVersion:l.recordVersion,transport:"direct"}),i0=t0,D0=await T0()}if(D0.status===401&&!p0.scopedAttempt&&typeof Y0==="string"&&(P1(D,B)??"").toUpperCase()==="POST"&&!B?.signal?.aborted){let l=p0.accessToken,U0;try{U0=await Y$(l)}catch(Z$){_1.set(D0,Z$)}if(U0&&U0.accessToken!==l)await D0.body?.cancel().catch(()=>{}),D0=Q$?await T0():await g0()}if(v?.mark("send_headers_received",{route:d,ms:P0($0()-i4),status:D0.status,relayConfigured:e0!=null,totalSendWithAccessMs:P0($0()-n)}),Q$)TZ(D0.headers,C0),M1.commit(c0,_J(D0.headers));if(AZ(D0,{source:W0?"start":"turn",toolNameMap:u4,accountId:g,synthetic:W0,...z0,requestedModel:j0(Y0),request:h0,trackSessionId:K0??void 0,dump:Q$?X4:R$,status:D0.status,streaming:K$}),Q$&&t0&&D0.status===401)await l0(t0,"direct");if(H0=!0,!Q$&&q$)await l0(q$,"relay_status_field");if(D0.status===401)await i7(D0,B?.signal);if(D0.ok)u1.publish(async()=>{if(C0.scopedAttempt)await T.vault.publish(C0.scopedAttempt,{lastUsed:Date.now()});else if(C0.localSubject)await T.publishLocal(C0.localSubject,{lastUsed:Date.now()})});return D0}async function R0(D,B){if(!D)return!1;try{return await k.refreshMain(B?.quotaKey??H$,D,B?.generation),k$(D,B)}catch{return!1}}async function V$(D,B={}){let x=r$(D),v=await N1(!1,x,B.modelId,"admission");if(D=await q(z),x){if(D&&v.size)D={...D,accounts:D.accounts.filter((P)=>!v.has(P.id)||a$(void 0,D,P.id,B.modelId))}}let d=await u9.getUsableFallbackAccounts(D,{modelId:B.modelId}),t=new Map(d.map((P)=>[P.id,P])),g=[];for(let P of D?.accounts??[]){if(D&&B0(P)){if(b0(D)){let W0=t.get(P.id);if(W0)g.push(W0);continue}if(T4(D)!=="local")continue;let _0=t.get(P.id);if(_0)g.push(_0);else if(P.access&&(!P.expires||P.expires>Date.now())&&!s$(P.lastRefreshError)&&!E1(P.lastRefreshError,P.id,Date.now(),t$(P.refresh))&&D?.quota?.failClosedOnUnknownQuota!==!0&&!KZ(Q0(P)))g.push(P);continue}if(B.includeApiRoutes===!0&&c1(P)&&y0(P)&&GZ(P.baseURL))g.push(P)}if(!r$(D))return g;return g.filter((P)=>B0(P)?a$(Q0(P),D,P.id,B.modelId):!0)}async function zJ(D){let B=D.mainQuotaIdentity?.quotaKey,x=k.getMain(B),v=x?.quota;if(!C1(x?.quota,D.storage,Date.now(),D.requestedModelId))try{v=await k.refreshMain(B,D.mainAccessToken,D.mainQuotaIdentity?.generation,"admission")}catch{}let d=await u9.getUsableFallbackAccounts(D.storage,{modelId:D.requestedModelId}),t=await q(z)??D.storage,g=[],P=b0(t);if(P){let E=t?.claustrum?.primaryAccount;if(E!==void 0&&y0(E)&&!t?.claustrum?.disabledAccountIdentities?.includes(E.accountId))g.push({id:W$,access:"",quota:v,identity:E?{kind:"known",accountId:E.accountId}:{kind:"unknown"},order:0,scoped:!0})}else if((D.mainAccessToken||D.mainPolicyDenied)&&!s$(t?.refresh?.mainLastRefreshError))g.push({id:W$,access:D.mainAccessToken,quota:v,identity:B?{kind:"known",accountId:B}:{kind:"unknown"},order:0});if(P)for(let[E,I]of(t?.accounts??[]).entries()){if(!y0(I)||!B0(I))continue;if(I.claustrumScopedCredentialId){let n=Q0(I);if(!C1(n,t,Date.now(),D.requestedModelId))try{n=await k.refreshFallback(I.id,"",I)}catch{}g.push({id:I.id,access:"",quota:n,identity:{kind:"known",accountId:I.id},order:E+1,account:I,scoped:!0})}}else{let E=new Map(d.map((I)=>[I.id,I]));for(let[I,n]of(t?.accounts??[]).entries()){if(!y0(n)||!B0(n))continue;let X0=E.get(n.id)??n;if(s$(X0.lastRefreshError))continue;let F=Q0(X0);if(!C1(F,t,Date.now(),D.requestedModelId))try{F=await k.refreshFallback(X0.id,X0.access??"",X0)}catch{}g.push({id:X0.id,access:X0.access??"",quota:F,identity:{kind:"known",accountId:X0.id},order:I+1,account:X0})}}let _0=new Set(d.map((E)=>E.id)),W0=new Set(g.flatMap((E)=>{let I=E.id===W$?t?.refresh?.mainLastRefreshError:E.account?.lastRefreshError,n=!E.scoped,X0=E.identity.kind==="known"?E.identity.accountId:void 0;if(n&&s$(I))return[];if(n&&E1(I,X0,Date.now(),E.id===W$?D.mainRefreshToken?t$(D.mainRefreshToken):void 0:E.account?.refresh?t$(E.account.refresh):void 0)&&(E.id===W$||!_0.has(E.id)))return[];if(C1(E.quota,t,Date.now(),D.requestedModelId)&&rJ({quota:E.quota,modelId:D.requestedModelId}).action==="migrate")return[];if(r$(t)&&!a$(E.quota,t,E.id===W$?void 0:E.id,D.requestedModelId))return[];return[E.id]})),V0=g.flatMap((E)=>{let I=E.id===W$?t?.refresh?.mainLastRefreshError:E.account?.lastRefreshError,n=!E.scoped,X0=E.identity.kind==="known"?E.identity.accountId:void 0;if(n&&s$(I)||n&&E1(I,X0,Date.now(),E.id===W$?D.mainRefreshToken?t$(D.mainRefreshToken):void 0:E.account?.refresh?t$(E.account.refresh):void 0)&&(E.id===W$||!_0.has(E.id)))return[];let F=E.id===W$?void 0:E.id,S=KZ(E.quota)?E.quota:void 0,K0=S?{kind:"known",quota:S}:{kind:"unknown"};return(!r$(t)||a$(K0.kind==="known"?K0.quota:void 0,t,F,D.requestedModelId))&&p1(K0.kind==="known"?K0.quota:void 0,t)&&(K0.kind==="unknown"||R9(K0.quota,D.requestedModelId)&&(E.id===W$||_0.has(E.id)||Boolean(E.scoped)))?[{accountId:E.id,quota:K0,order:E.order}]:[]});return{storage:t,allRoutes:g,candidates:V0,retainAccountIds:W0}}let v$=new WeakMap;async function K1(D,B,x,v,d,t,g){if(!x.length)return d??null;let P=g?.returnLastOnExhausted??!0,_0=d??null,W0=!1,V0=async()=>{if(W0)return;W0=!0,await d?.body?.cancel().catch(()=>{})};for(let[E,I]of x.entries()){let n;if(c1(I))await V0(),n=await D$(D,B,I,t,`api_fallback_${E}`,v,g?.fableRequest,g?.mainAccessToken,g?.mainQuotaIdentity);else if(b0(v)&&I.claustrumScopedCredentialId){let F;try{F=await A0(I.id,B?.signal??void 0,void 0,j0(await C4(D,B)))}catch(K0){if(K0 instanceof Z1)continue;throw K0}let S=F.scopedAttempt;if(!S)throw Error("Native vault fallback credential is unavailable");await V0(),n=await U$(D,B,S.accessToken,t,`fallback_${E}`,v,I.id,I.authLineageId,g?.fableRequest,g?.laneStartRequest,void 0,S)}else if(T4(v)==="local"&&I.access)await V0(),n=await U$(D,B,I.access,t,`fallback_${E}`,v,I.id,I.authLineageId,g?.fableRequest,g?.laneStartRequest);else continue;_0=n;let X0=jZ(n,v);if(!X0){let F=await N0(n,t);n=F.response,_0=n,X0=F.rateLimited}if(!X0){if(v$.set(n,c1(I)?"api":"oauth"),await g?.onSuccess?.(I),B0(I)&&k0(v)&&k.shouldRefreshOnRequestCount(p4)){if(b0(v)||I.access)k.refreshFallback(I.id,b0(v)?"":I.access??"",I).then(()=>g?.onSuccess?.(I)).catch(()=>{})}return n}if(E<x.length-1||!P)await n.body?.cancel().catch(()=>{})}return P?_0:null}async function r8(D,B,x,v,d,t,g,P,_0,W0,V0=!1,E){if(!J0(D,B?.body))return x;let I=$0(),n=t??await q(z);if(d?.mark("fallback_load_storage",{ms:P0($0()-I),cached:!!t}),!(n?.accounts??[]).some((u0)=>y0(u0)&&(B0(u0)||c1(u0)&&GZ(u0.baseURL))))return x;let F=x,S=jZ(F,n),K0=v0(F,!1);if(!S){let u0=await N0(F,d);F=u0.response,S=u0.rateLimited,K0=v0(F,u0.rateLimited)}if(!S)return F;let d0=!1;if(v)d0=v.some(c1);else if(K0)d0=await R0(g,E);let y=v;if(!y){let u0=$0();y=await V$(n,{includeApiRoutes:d0,modelId:_0}),d?.mark("fallback_get_accounts",{ms:P0($0()-u0),accounts:y.length})}if(r$(n)){let u0=y.length;if(y=y.filter((P$)=>B0(P$)?a$(Q0(P$),n,P$.id,_0):!0),y.length<u0)y$("[killswitch] filtered fallbacks",{before:u0,after:y.length})}return await K1(D,B,y,n,F,d,{onSuccess:P,mainAccessToken:g,mainQuotaIdentity:E,fableRequest:W0,laneStartRequest:V0})??F}return{apiKey:"",async fetch(D,B){if(D instanceof Request&&B?.signal===void 0)B={...B,signal:D.signal};let x=U4(D,B),v=x.get(J9)==="1";x.delete(J9),B={...B,headers:x};let d=x.get("x-session-affinity")||x.get("x-opencode-session"),t=j0(B?.body),g=Boolean(d&&t&&!f0(x)&&W1.resetForModelChange(d,t));if(g&&d){for(let M of S$.keys())if(M.startsWith(`${d}\x00`))S$.delete(M);N$.delete(d)}let P=W1.plan(d,B?.body),_0=b9==="server"&&h1(P?.effectiveModel??t)?P?.effectiveModel??t:void 0,W0=P?{plan:P}:void 0;if(P?.downgraded)B={...B,body:P.bodyText};let V0=B?.body,E=cG({bodyBytes:typeof V0==="string"?V0.length:void 0}),I=(M)=>{let i=p$.get(M);return D7(M,{toolNameMap:i?.toolNameMap,perf:(r,z0)=>E.mark(r,z0),laneStart:v,laneStartOAuthServed:v$.get(M)!=="api",...i?i.streaming?{onMessageStart:(r)=>PZ(M,r,!1),onMessageDelta:(r)=>A8(M,r),onStreamEnd:()=>i.dumpWrite}:{onMessageResponse:(r)=>PZ(M,r),onStreamEnd:()=>i.dumpWrite,responseMode:"json"}:{},contentFilterModel:P?.requestedModel,...!P?.downgraded&&P?{onContentFilter:(r)=>{if(!W0?.oauthAccountId)return h.debug("fable-fallback","content filter recovery unavailable for non-OAuth route",{session:P.sessionId}),!1;let z0=W1.activate(P,W0.oauthAccountId);S$.delete(P.recoveryKey),S$.set(P.recoveryKey,nG(P.requestedModel,z0));while(S$.size>128){let p=S$.keys().next().value;if(p)S$.delete(p);else break}f$.delete(P.recoveryKey),h.info("fable-fallback","content filter detected; switching session to Opus 4.8",{session:P.sessionId,requestedModel:P.requestedModel,completedToolUse:r?.completedToolUse===!0,remaining:z0}),J4({sessionId:P.sessionId,mode:"opus",remaining:z0,requestedModelId:P.requestedModel},S,F)}}:{},...P&&W0?{onComplete:(r)=>{if(!P.downgraded){W1.completeSource(P,!W0.serverFallback);return}let z0=W1.complete(P,W0.opusCacheAnchor);if(!z0.counted)return;let p=S$.get(P.recoveryKey);if(p)S$.delete(P.recoveryKey),X$.delete(P.sessionId),gZ(P.sessionId,p);if(h.info("fable-fallback","Opus 4.8 turn completed",{session:P.sessionId,requestedModel:P.requestedModel,finishReason:r,remaining:z0.remaining}),J4({sessionId:P.sessionId,mode:"opus",remaining:z0.remaining,requestedModelId:P.requestedModel},S,F),z0.remaining===0)J4({sessionId:P.sessionId,mode:"fable",remaining:0,requestedModelId:P.requestedModel},S,F,oG(P.requestedModel))}}:{},..._0?{serverSideFallbackModel:_0,...P?{onServerSideFallbackOutcome:(r)=>{if(W0)W0.serverFallback=r.fallback;c8(P,r,S,F)}}:{}}:{}})},n=$0(),X0=P?.effectiveModel??j0(await C4(D,B)),F=await N(X0,B?.signal??void 0,!0);if(E.mark("get_auth",{ms:P0($0()-n),authType:F.type,hasAccess:Boolean(F.access)}),F.type!=="oauth"){let M=Q4(D),i=U4(D,B);U7(i);let r=await C4(D,B);if(typeof r==="string")try{let p=JSON.parse(r);if(QG(p))r=JSON.stringify(p)}catch{}let z0=await fetch(M.input,{...B,body:r,headers:i});return E.done("non_oauth_passthrough",{status:z0.status}),z0}let S=await q(),K0=F$(F.nativeAccountIdentity),d0=F.nativeScopedAttempt,y;if(F.access){let M=await s1(F.access,j0(B?.body),K0,d0?.recordVersion);if(M.stale)throw Error("Main OAuth identity changed while resolving request credentials");if(y={...M,routingLineage:F.nativeRoutingLineage},K0)$4=F.access,D1=M.providerAccountUuid}else if((F.modelDenied||F.credentialUnavailable||F.deferred)&&K0)await HZ("",K0,K0),y={quotaKey:K0,providerAccountUuid:K0,generation:k.getMainQuotaIdentityGeneration(),routingLineage:F.nativeRoutingLineage,stale:!1,state:b0(S)?"on-cold":"na"};let u0=$0();E.mark("load_storage",{ms:P0($0()-u0)}),k.updateStorage(S),k.seedMainFromStorage(S,H$),k.seedFallbacksFromAccounts((S?.accounts??[]).filter(B0));let P$=d?E$.get(d):void 0;if(g||!P||b9==="server"&&P$?.requestedModelId&&h$(P$.requestedModelId)!==h$(P.requestedModel))p8(d,S,F);let J$=J0(D,B?.body),c0=j0(B?.body)??X0,u$=_$(y,S),Y0=L0("main",y?.routingLineage,K0,S),A$=F.deferred?NZ(u$&&S?{...S,accounts:S?.accounts??[],quota:{...S?.quota,mainQuota:u$.quota}}:S,K0,Y0?.lineage===y?.routingLineage&&Y0?.generalExhausted===!0):void 0;if(A$){let M=J$?await V$(S,{includeApiRoutes:k$(void 0,y),modelId:c0}):[],i=await K1(D,B,M,S,void 0,E,{onSuccess:(r)=>h0(r.id,"fallback"),mainQuotaIdentity:y,fableRequest:W0,laneStartRequest:v});if(i)return I(i);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:A$.message}}),{status:429,headers:{"content-type":"application/json","retry-after":String(A$.retryAfter)}})}let L$=()=>{let M=k7(k.getMain(y?.quotaKey)?.quota,(S?.accounts??[]).filter(B0),Date.now(),X0);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"No enabled OAuth route can serve the requested model under current quota policy."}}),{status:429,headers:{"content-type":"application/json","retry-after":String(M)}})};if(J$)p4++;if(J$&&F.access&&(!F.expires||F.expires>Date.now()))b8(S,F.access,y);async function h0(M,i){let r=S,z0=!1;if((S?.accounts??[]).some((p)=>B0(p)&&p.quota))try{let p=await q(z);if(p)r=p;else z0=!0}catch{z0=!0}C$(r,{activeId:M,route:i,mainAccessToken:F.access,skipFallbackQuotaSeed:z0})}let K$;if(J$&&d&&e$(S)==="sticky-balanced"){let M=P?.effectiveModel??c0,i=PG(M),r=t1.trackedOAuthRoute(d),z0=P?.cacheAccountId??(r?r.oauthAccountId??W$:void 0),p=!1;try{let e=await zJ({storage:S,mainAccessToken:F.access,mainRefreshToken:F.refresh,mainPolicyDenied:F.modelDenied||F.credentialUnavailable,requestedModelId:M,mainQuotaIdentity:y}),i0=async(z$)=>{let e0=await LZ();return e0.router.resolve({sessionId:d,family:i,modelId:M,affinityModelId:t,candidates:e.candidates,retainAccountIds:e.retainAccountIds,storage:e.storage,inputBytes:typeof B?.body==="string"?Buffer.byteLength(B.body):1,preferredAccountId:z0,excludeAccountIds:z$,...e0.accountIdentities&&{accountIdentities:e0.accountIdentities}})},Y$=s$(e.storage?.refresh?.mainLastRefreshError),Q$=e.allRoutes.length===0&&!Y$||e.allRoutes.some((z$)=>!z$.quota||!C1(z$.quota,e.storage,Date.now(),M)),t0=await i0();if(!t0&&Q$){if(F.modelDenied)return L$();throw Error("Sticky-balanced routing is waiting for current OAuth quota snapshots")}if(!t0){if(F.modelDenied)return L$();if(b0(S))throw new VZ;let z$=T5({mainRefreshError:e.storage?.refresh?.mainLastRefreshError,fallbackReauthLabels:v5(e.storage),routeQuotas:e.allRoutes.flatMap((e0)=>e0.quota?[e0.quota]:[]),modelId:M});return E.done("return_sticky_no_route",{status:z$.status}),z$}let T0=e.allRoutes.find((z$)=>z$.id===t0?.accountId);if(t0&&T0){if(p=!0,P?.downgraded&&W1.bindRecoveryAccount(P,T0.id))h.info("fable-fallback","rebound recovery to migrated sticky account",{accountId:T0.id});let z$=async(H0)=>{if(H0.scoped){let g0=(await A0(H0.id,B?.signal??void 0,void 0,M)).scopedAttempt;if(!g0)throw Error("Native vault sticky credential is unavailable");return U$(D,B,g0.accessToken,E,`sticky:${H0.id}`,e.storage,H0.id,H0.account?.authLineageId,W0,v,H0.id===W$?y:void 0,g0)}return U$(D,B,H0.access??"",E,`sticky:${H0.id}`,e.storage,H0.id,H0.account?.authLineageId,W0,v,H0.id===W$?y:void 0)},e0=async(H0,l0,g0=!0)=>{return await h0(H0.id,"sticky-balanced"),E.done("return_sticky_balanced",{status:l0.status,accountId:H0.id,created:t0?.created,migrated:t0?.migrated}),I(l0)},OJ=async(H0)=>{let l0=H0,g0=jZ(H0,e.storage),D0=!1;if(!g0){let l=await N0(H0,E);l0=l.response,D0=l.rateLimited,g0=l.rateLimited}return{response:l0,routeFailure:g0,streamingRateLimit:D0}},d4=C1(T0.quota,e.storage,Date.now(),M)?rJ({quota:T0.quota,modelId:M}):void 0;if(d4?.action==="hold")return e0(T0,await DJ(new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account five-hour quota resets shortly; retaining session affinity."}}),{status:429,headers:{"content-type":"application/json"}}),d,d4.retryAfterSeconds,!1,p$),!1);let C0=await OJ(await z$(T0)),i4=!1;if(!C0.routeFailure)return e0(T0,C0.response);if(C0.response.status===401){let H0=_1.get(C0.response);if(H0){let l0=await q(z),g0=T0.id,D0=T0.id===W$?l0?.refresh?.mainLastRefreshError:l0?.accounts.find((l)=>l.id===g0&&B0(l))?.lastRefreshError;if(!s$(D0))throw H0}i4=!0}let q$=C0.response.status===403||i4;if(C0.response.status===429||C0.streamingRateLimit){let H0;try{H0=T0.id===W$?await k.refreshMain(y?.quotaKey,T0.access??"",y?.generation):await k.refreshFallback(T0.id,T0.access??"",T0.account)}catch{H0=void 0}let l0=rJ({quota:H0,modelId:M});if(E.mark("sticky_quota_failure",{accountId:T0.id,action:l0.action,reason:l0.reason}),l0.action==="hold")return e0(T0,await DJ(C0.response,d,l0.retryAfterSeconds,C0.streamingRateLimit,p$));q$=l0.action==="migrate"}if(q$){await i7(C0.response,B?.signal);let H0=T0.id;if(e=await zJ({storage:e.storage,mainAccessToken:F.access,mainRefreshToken:F.refresh,mainPolicyDenied:F.modelDenied||F.credentialUnavailable,requestedModelId:M,mainQuotaIdentity:y}),e.candidates.filter((g0)=>g0.accountId!==H0).length>0){await C0.response.body?.cancel().catch(()=>{}),t0=await i0(new Set([H0]));let g0=e.allRoutes.find((D0)=>D0.id===t0?.accountId);if(t0&&g0){if(T0=g0,P?.downgraded)W1.bindRecoveryAccount(P,T0.id);return e0(T0,await z$(T0))}}else if((C0.response.status===429||C0.streamingRateLimit)&&k$(F.access,y)){let g0=(await V$(e.storage,{includeApiRoutes:!0,modelId:M})).filter(c1);if(g0.length>0){let D0=await K1(D,B,g0,e.storage,C0.response,E,{onSuccess:(l)=>h0(l.id,"sticky-balanced"),mainAccessToken:F.access,mainQuotaIdentity:y,fableRequest:W0,laneStartRequest:v});if(D0)return E.done("return_sticky_api_fallback",{status:D0.status}),I(D0)}}}return e0(T0,C0.response)}}catch(e){if(E.mark("sticky_balanced_error",{error:e instanceof Error?e.message:String(e)}),p||w1(e))throw e;let i0=e instanceof Error?e:Error(String(e));throw Object.assign(i0,{code:"ECONNRESET",syscall:"sticky-routing"}),i0}}if(J$&&e$(S)==="fallback-first")try{let M=$0();K$=await V$(S,{includeApiRoutes:k$(F.access,y),modelId:c0}),E.mark("fallback_first_get_accounts",{ms:P0($0()-M),accounts:K$.length});let i=await K1(D,B,K$,S,void 0,E,{returnLastOnExhausted:!1,mainAccessToken:F.access,mainQuotaIdentity:y,onSuccess:(r)=>h0(r.id,"fallback-first"),fableRequest:W0,laneStartRequest:v});if(i)return E.done("return_fallback_first",{status:i.status}),I(i);K$=void 0}catch(M){if(E.mark("fallback_first_error",{error:M instanceof Error?M.message:String(M)}),w1(M))throw M}if(F.deferred){if(Object.assign(F,await N(X0,B?.signal??void 0)),F.access){let M=await s1(F.access,X0,F.nativeAccountIdentity,F.nativeScopedAttempt?.recordVersion);if(M.stale)throw Error("Main OAuth identity changed while resolving request credentials");y={...M,routingLineage:F.nativeRoutingLineage},$4=F.access,D1=M.providerAccountUuid}}if(!F.modelDenied&&(!F.access||!F.expires||F.expires<Date.now())){if(b0(S))try{let p=(await A0("main",B?.signal??void 0,void 0,X0)).scopedAttempt;if(!p)throw Error("Native vault main credential is unavailable");$4=p.accessToken;let e=await U$(D,B,p.accessToken,E,"main",S,"main",void 0,W0,v,y,p);return I(e)}catch(z0){let p=J$?await V$(S,{modelId:c0}):[],e=await K1(D,B,p,S,void 0,E,{onSuccess:(i0)=>h0(i0.id,"fallback"),mainAccessToken:F.access,mainQuotaIdentity:y,fableRequest:W0,laneStartRequest:v});if(e)return I(e);if(z0 instanceof O$)throw new VZ;throw z0}if(F.credentialFailure?.tokenRefreshFailed)throw F.credentialFailure;let M=await q(),i=M?.refresh?.mainLastRefreshError;if(i&&E1(i,F.nativeAccountIdentity??e1??M?.mainAccountId,Date.now(),F.refresh?t$(F.refresh):void 0))throw y$("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:i.nextRetryAt,retryCount:i.retryCount,expiresInMs:F.expires?F.expires-Date.now():void 0}),Error(M5(i,Date.now()));y$("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(F.access),expiresInMs:F.expires?F.expires-Date.now():void 0,expiredAgoMs:F.expires&&F.expires<Date.now()?Date.now()-F.expires:void 0});let r=$0();F.access=await C(void 0,X0,B?.signal??void 0),E.mark("refresh_main_access",{ms:P0($0()-r)})}if(!F.access&&!F.modelDenied)throw E.done("missing_access_error"),Error("OAuth access token is missing after refresh");function X4(){if(S?.quota?.showToasts!==!0)return;let M=k.getMain(y?.quotaKey);if(!M)return;let i=(S?.accounts??[]).filter((p)=>p.enabled!==!1&&B0(p)).map((p)=>({...p,quota:k.getFallback(p.id,p)?.quota??p.quota})),r=p1(M.quota,S),z0;if(r)z0="main";else z0=i.find((p)=>p1(p.quota,S))?.id??"main";o8(M.quota,i,z0)}if(J$&&k0(S))try{let M=$0(),i=_$(y,S),r=i?.quota;if(!r)r=await k.refreshMain(y?.quotaKey,F.access,y?.generation,"admission"),i=_$(y,S),X4();else if(k.needsRefresh(p4,c0))if(r1(r)||A9(r,c0))r=await k.refreshMain(y?.quotaKey,F.access,y?.generation),i=_$(y,S);else k.refreshMain(y?.quotaKey,F.access,y?.generation).then(()=>{x1().catch(()=>{}),X4()}).catch(()=>{});C$(S,{activeId:"main",route:"main",mainAccessToken:F.access});let z0=p1(r,S)&&R9(r,c0);if(E.mark("main_quota_for_routing",{ms:P0($0()-M),passes:z0,model:c0,modelScopedExhausted:A9(r,c0)}),!z0){let p=$0();K$=await V$(S,{includeApiRoutes:Boolean(i&&i.refreshAfter>Date.now()&&r1(i.quota)),modelId:c0}),E.mark("preselect_fallback_accounts",{ms:P0($0()-p),accounts:K$.length});let e=await K1(D,B,K$,S,void 0,E,{onSuccess:(i0)=>h0(i0.id,"fallback"),mainAccessToken:F.access,mainQuotaIdentity:y,fableRequest:W0,laneStartRequest:v});if(e)return E.done("return_preselected_fallback",{status:e.status}),I(e)}}catch(M){if(E.mark("main_quota_for_routing_error",{error:M instanceof Error?M.message:String(M)}),w1(M))throw M}let R$=_$(y,S)?.quota;if(S?.quota?.failClosedOnUnknownQuota&&(R$===void 0||F.access.startsWith("sk-ant-oat")&&y?.providerAccountUuid===void 0)&&k.isBackedOff()){let M=k.getLastApiError(),i=M?R7(M,Date.now()):"Quota API unavailable";return y$("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:M?.nextRetryAt,retryCount:M?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:i}}),{status:429,headers:{"content-type":"application/json","retry-after":String(M?.nextRetryAt?Math.max(1,Math.ceil((M.nextRetryAt-Date.now())/1000)):60)}})}if(r$(S)){if(k.needsRefresh(p4,c0))try{await Promise.all([k.refreshMain(y?.quotaKey,F.access,y?.generation),N1(!1,!0,void 0,"admission")])}catch(i){y$("[quota] killswitch refresh failed",{error:i instanceof Error?i.message:String(i),backedOff:k.isBackedOff()})}R$=_$(y,S)?.quota}if(r$(S)&&!a$(R$,S,void 0,c0)){let i=J0(D,B?.body)?await V$(S,{includeApiRoutes:k$(F.access),modelId:c0}):[];if(i.length>0){y$("[route] skipping main (killswitch), trying fallbacks");let Y$=await K1(D,B,i,S,void 0,E,{onSuccess:(Q$)=>h0(Q$.id,"fallback"),mainAccessToken:F.access,mainQuotaIdentity:y,laneStartRequest:v});if(Y$)return E.done("return_killswitch_fallback",{status:Y$.status}),I(Y$)}let r=Date.now(),z0=(S?.accounts??[]).filter((Y$)=>y0(Y$)&&B0(Y$)).map((Y$)=>({...Y$,quota:Q0(Y$)})),p=f3({mainQuota:R$,requestModelId:c0,storage:S}),e=k7(R$,z0,r,p.isScopedDriven?p.modelId:void 0),i0=x3({retryAfterSeconds:e,...p.isScopedDriven&&{modelName:p.modelName}});return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:i0}}),{status:429,headers:{"content-type":"application/json","retry-after":String(e)}})}if(F.modelDenied){let M=L$(),i=J$?await V$(S,{modelId:X0}):[],r=await K1(D,B,i,S,void 0,E,{onSuccess:(p)=>h0(p.id,"fallback"),fableRequest:W0,laneStartRequest:v,mainAccessToken:F.access,mainQuotaIdentity:y});if(r)return I(r);if(!(e$(S)!=="sticky-balanced"&&A9(R$,X0)&&p1(R$,S)&&a$(R$,S,void 0,X0)))return I(M);return I(await U$(D,B,"",E,"main",S,"main",void 0,W0,v,y))}let u4=await U$(D,B,F.access,E,"main",S,"main",void 0,W0,v,y,d0),f1=!1,p0=await r8(D,B,u4,K$,E,S,F.access,(M)=>{return f1=!0,h0(M.id,"fallback")},c0,W0,v,y);if(!f1)await h0("main","main");return E.done("return_response",{status:p0.status}),I(p0)}}}return{}},get methods(){return[...oY(T9("opencode").tokenPath)?[M8]:[],{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{if(await S1("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.");if(await T.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(Y)=>{let G=await aJ(Y,Z.verifier,Z.redirectUri,Z.state);if(G.type==="failed")return G;G$(),await T.loginOAuth({routeId:"main",replace:!0,credential:{access:G.access,refresh:G.refresh,expires:G.expires}});let K=oJ("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 Q7("console");return{url:Z.url,instructions:"Paste the authorization code here:",method:"code",callback:async(Y)=>{let G=await aJ(Y,Z.verifier,Z.redirectUri,Z.state);if(G.type==="failed")return G;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${G.access}`}}).then((j)=>j.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}},dispose:v8,__primeManager:H1,__quotaManager:k,__cacheKeepManager:t1,__resolveMainQuotaIdentityForTest:s1,__resolveSidebarQuotaAccessForTest:xZ,__refreshSidebarQuotaForTest:x1,__mainProviderAccountUuidForTest:()=>D1,__fallbackRefreshReady:E8,get __scopedRuntime(){return h9(z,$.directory)},__notificationMessageIdBeforeAssistantForTest:j8,__trackDesktopNoticeMessageIdForTest:hZ,__isDesktopNoticeMessageForTest:bZ}},E6=Z2;
|
|
42
|
-
export{Y4 as a,_J as b,LJ as c,v1 as d,S0 as e,S3 as f,J9 as g,M3 as h,u3 as i,i3 as j,n3 as k,m1 as l,Q4 as m,_9 as n,D7 as o,
|
|
41
|
+
`);await e7($,Z.sessionID,G)}lG()},auth:{provider:"anthropic",async loader(Z,Y){l$=async()=>{let Q=await Z();return{type:Q.type,active:ZZ(Q,"anthropic")}},v4=Z;let G=await Z();if(G.type!=="oauth")return{};let K=await S1("opencode").catch(()=>{return});if(!UZ&&ZZ(G,"anthropic")&&process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION!=="1"){UZ=!0;let Q=k4(Y1.signal).then((U)=>{if(!Y1.signal.aborted)return C$(U.policyStorage,{...$$,routingAuthoritative:!1})}).catch(()=>{if(!Y1.signal.aborted)h.debug("quota","startup account profile hydration failed")});X1.add(Q),Q.then(()=>X1.delete(Q))}function j(Q,U=!1){if(!ZZ(Q,"anthropic")&&!(U&&h4(Q)))throw Error("Native OAuth requires inert OpenCode activation; run offline setup")}async function L(Q){j(await Z(),Q&&await S1("opencode")==="local")}let N=async(Q,U,C=!1)=>{let f=await Z();if(f.type!=="oauth")return{type:f.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 m=await S1("opencode");if(m==="claustrum"&&!R8(f))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.");G$();let J0=await UG(T,U),j0=m==="claustrum"?"committed":b7(await y7(s)),f0=m7(J0);if(j(f,m==="local"&&(j0==="committed"||j0==="retired")&&f0),m==="claustrum"&&!J0.accounts.some((R0)=>R0.type==="oauth"&&y0(R0)))throw new VZ;let w0=W3(J0.policyStorage);try{X3({mode:m==="claustrum"?"C":"L",main:FJ(f),fallbacks:m==="claustrum"?"T":w0.fallbacks,evidence:"V",authority:j0,localOAuthServable:f0}),m4=void 0}catch(R0){if(R0 instanceof z4)m4=R0.verdict;throw R0}q0=J0.policyStorage;let k0=J0.accounts.find((R0)=>R0.id==="main"),N0=k0?.binding,j$=k0?O0(k0,J0.policyStorage):void 0,V1=j$&&j$!==k0?.quota?{...J0.policyStorage,quota:{...J0.policyStorage.quota,mainQuota:j$}}:J0.policyStorage,D$=L0("main",G0(N0),k0?.accountIdentity,J0.policyStorage),U$=Boolean(N0&&D$?.lineage===G0(N0)&&D$?.generalExhausted===!0);if(k0&&N0&&(!m0||N0.rowId!==m0.rowId||N0.credentialEpoch>m0.credentialEpoch))k.clearMain(),k.setMainQuotaAccountIdentity(k0.accountIdentity),m0={rowId:N0.rowId,credentialEpoch:N0.credentialEpoch};if(C&&(e$(J0.policyStorage)==="fallback-first"||NZ(V1,k0?.accountIdentity,U$))){let R0=J0.accounts.find((V$)=>V$.id==="main");return U?.throwIfAborted(),{type:"oauth",access:"",expires:0,refresh:void 0,nativeAccountIdentity:R0?.accountIdentity,nativeRoutingLineage:R0?.binding?G0(R0.binding):void 0,nativeLocalSource:void 0,nativeScopedAttempt:void 0,modelDenied:!1,credentialUnavailable:!1,credentialFailure:void 0,deferred:!0}}let Q0,v0,_$,k$;try{Q0=await A0("main",U,void 0,Q,"serve",J0)}catch(R0){if(R0 instanceof E0)throw R0;if(w1(R0))throw R0;if(R0 instanceof Z1){v0=R0.account;let V$=y5(v0.quota,Q);if(V$!==void 0&&(!Number.isFinite(V$.checkedAt)||(V$.checkedAt??0)+R0.checkIntervalMs<=Date.now())||!KZ(v0.quota)&&!A9(v0.quota,Q))try{await T.fetchQuota("main",void 0,U),Q0=await A0("main",U,void 0,Q),v0=void 0}catch(v$){if(w1(v$))throw v$;if(v$ instanceof Z1)v0=v$.account;else if(v$ instanceof O$)_$=v$.account,k$=v$}}else if(R0 instanceof O$)_$=R0.account,k$=R0}return U?.throwIfAborted(),{type:"oauth",access:Q0?.accessToken??"",expires:Q0?.expires??0,refresh:void 0,nativeRoutingLineage:I0(Q0?.localSubject,Q0?.scopedAttempt)??(k0?.binding?G0(k0.binding):void 0),nativeAccountIdentity:Q0?.accountIdentity??v0?.accountIdentity??_$?.accountIdentity,modelDenied:Boolean(v0),credentialUnavailable:Boolean(_$),credentialFailure:k$,deferred:!1,nativeLocalSource:Q0?.localSource,nativeScopedAttempt:Q0?.scopedAttempt}};G1=N;let _={type:"oauth",access:"",expires:0};if(_.type==="oauth"){let f=function(){if(U1)W.clearInterval(U1);let D=async()=>{try{let B=await q(z);if(!g8(B))return;let x=await N();if(x.type!=="oauth")return;if(x.nativeLocalSource==="rotated"||x.nativeLocalSource==="adopted")return;if(x.expires&&x.expires-Date.now()>kZ(B))return;await C()}catch{h.warn("refresh","native main OAuth background refresh unavailable")}};U1=W.setInterval(()=>{D()},IG+t7(r7)),U1.unref?.()},J0=function(D,B){if(D instanceof Request&&D.body)return!1;return B==null||typeof B==="string"},j0=function(D){if(typeof D!=="string")return;try{let B=JSON.parse(D);return typeof B.model==="string"?B.model:void 0}catch{return}},f0=function(D){return D.has("x-parent-session-id")},w0=function(D){let B;try{B=JSON.parse(D)}catch{return!1}if(typeof B!=="object"||B===null)return!1;let x=Reflect.get(B,"error");return Reflect.get(B,"type")==="error"&&typeof x==="object"&&x!==null&&Reflect.get(x,"type")==="rate_limit_error"},k0=function(D){return D?.quota?.enabled===!0},j$=function(D,B){if(D.delete("authorization"),D.delete("x-api-key"),B.authHeader==="x-api-key")D.set("x-api-key",B.apiKey??"");else D.set("Authorization",`Bearer ${B.apiKey??""}`);D.set("Content-Type","application/json"),U7(D)},Q0=function(D){return k.getFallback(D.id,D)?.quota??D.quota},v0=function(D,B){return D.status===429||B},_$=function(D,B=q0){return b("main",D?.routingLineage,D?.providerAccountUuid,k.getMain(D?.quotaKey??H$),B)},k$=function(D,B){if(!D&&!B?.providerAccountUuid)return!1;let x=_$(B);return Boolean(x&&(D||x.quota.accountIdentity===B?.providerAccountUuid)&&x.refreshAfter>Date.now()&&r1(x.quota)&&(x.quota.source!=="headers"||L0("main",B?.routingLineage,B?.providerAccountUuid)?.generalExhausted===!0||["five_hour","seven_day"].some((v)=>x.quota.fieldSources?.[v]==="poll"&&(x.quota[v]?.remainingPercent??1)<=0)))},U=(await T.read().catch(()=>{return}))?.accounts.find((D)=>D.id==="main");if(e1=U?.binding?.rowId??U?.accountIdentity,H$??=U?.accountIdentity??e1,_.access)await s1(_.access);async function C(D,B,x){let v=h4(await Z());await L(v),x?.throwIfAborted();let d=await A0("main",x,D,B,"refresh");return await L(v),x?.throwIfAborted(),d.accessToken}if(K==="local")f();k.seedFallbacksFromAccounts((a0?.accounts??[]).filter(B0));let m=await bG(()=>q(z)).catch(()=>({freshStorage:null,activeId:void 0,route:"main"}));await C$(m.freshStorage,{activeId:m.activeId,route:m.route,mainAccessToken:_.access,routingAuthoritative:!1});async function N0(D,B){if(!D.body||D.status!==200)return B?.mark("inspect_stream_skip",{status:D.status}),{response:D,rateLimited:!1};if(D.headers.get("x-cortexkit-relay-optimistic")==="true")return B?.mark("inspect_stream_skip",{status:D.status,reason:"optimistic_relay"}),{response:D,rateLimited:!1};let x=$0(),v=D.body.getReader(),d=[],t=0,g=T5({maxFrameBytes:65536}),P=!1,_0=!1,W0=!0;while(!_0&&t<65536){let{done:I,value:n}=await v.read().catch(async(F)=>{let S=gJ(F,p$.get(D)?.toolNameMap);if(S!==F)await yJ(v,S);throw S});if(I)break;d.push(n),t+=n.byteLength;let X0;try{X0=g.push(n)}catch{break}for(let F of X0){let S=NG(E5(F,{streamStart:W0}));if(W0=!1,S.data===void 0)continue;P=w0(S.data),_0=!0;break}}if(P){await v.cancel().catch(()=>{});try{v.releaseLock()}catch{}let I=new ReadableStream({start(X0){for(let F of d)X0.enqueue(F);X0.close()}});B?.mark("inspect_stream_first_event",{ms:P0($0()-x),bytes:t,rateLimited:!0});let n=new Response(I,{status:D.status,statusText:D.statusText,headers:D.headers});return n4(p$,D,n),{response:n,rateLimited:!0}}let V0=new ReadableStream({start(I){for(let n of d)I.enqueue(n)},async pull(I){let{done:n,value:X0}=await v.read();if(n){I.close();return}I.enqueue(X0)},cancel(I){return v.cancel(I)}});B?.mark("inspect_stream_first_event",{ms:P0($0()-x),bytes:t,rateLimited:!1});let E=new Response(V0,{status:D.status,statusText:D.statusText,headers:D.headers});return n4(p$,D,E),{response:E,rateLimited:!1}}async function V1(D,B,x,v){if(G$(),!B){let g=_$(x);if(!x?.providerAccountUuid||!g||g.refreshAfter<=Date.now()||!r1(g.quota))throw Error("API fallback requires fresh general primary OAuth exhaustion");let P=await A0("main",v);if(P.accountIdentity!==x.providerAccountUuid||x.routingLineage&&I0(P.localSubject,P.scopedAttempt)!==x.routingLineage)throw Error("Primary identity changed before API fallback");B=P.accessToken}let d=await T.authorizeApi(D,v),t=(await T.read()).accounts.find((g)=>g.id==="main");if(t?.binding&&G0(t.binding)!==x?.routingLineage)throw Error("Primary identity changed before API fallback");if(!k$(B,x))throw Error("API fallback requires fresh general primary OAuth exhaustion");return d}async function D$(D,B,x,v,d="api_fallback",t,g,P,_0){if(g)g.oauthAccountId=void 0,g.opusCacheAnchor=void 0;let W0=$0(),V0=U4(D,B),E=V0.get("x-session-affinity")||V0.get("x-opencode-session"),I=f0(V0),n=V0.get(v1)??void 0,X0=n1.resolveHeader(n);V0.delete("x-parent-session-id"),V0.delete("x-session-affinity"),V0.delete("x-opencode-session"),V0.delete("x-opencode-session-id"),V0.delete("x-opencode-parent-session-id"),V0.delete(v1),V0.delete(Y4),V0.delete(kJ);let F=await C4(D,B),S=!1,K0=null,d0,y=typeof F==="string"?F.length:void 0;if(F&&typeof F==="string"){let A$=$0(),L$=(()=>{if(!XZ())return!1;try{return f7(JSON.parse(F).model)}catch{return!1}})();try{F=await _9(F,{onToolNameMap:(h0)=>{d0=h0},cache1hEnabled:!I&&S4(),cache1hMode:F4(),fastModeEnabled:L$,sessionId:E||void 0,midConversationEffortEnabled:!1,midConversationEffortPlan:n,midConversationEffortResolvedPlan:X0,modelRemapEnabled:!0,perf:(h0,K$)=>v?.mark(`rewrite_body_${h0}`,{route:d,...K$})})}catch(h0){if(h0 instanceof S0)return n7(h0);if(h0 instanceof c7)return o7(h0);throw h0}if(j$(V0,x),V0.set("anthropic-beta",v7(V0.get("anthropic-beta"),[])),L$)j9(V0);try{S=JSON.parse(F).stream===!0}catch{}v?.mark("rewrite_body",{route:d,ms:P0($0()-A$),originalBytes:y,rewrittenBytes:F.length,cacheEnabled:!I&&S4(),cacheMode:F4(),fastModeEnabled:L$,subagent:I})}else j$(V0,x);let u0=await s9(V0),P$=await V1(x.id,P,_0,B?.signal??void 0);x={...x,...P$},j$(V0,x);let J$=Q4(D,{baseURL:x.baseURL}),c0=$0(),u$=F9([x.apiKey??""],S?"event-stream":"http"),Y0;try{Y0=u$.redactResponse(await fetch(J$.input,{...B,body:F,headers:V0,...mJ()&&{tls:{rejectUnauthorized:!1}}}))}catch(A$){let L$=u$.redactError(A$);if(u$.dispose(),typeof F==="string")await w9({affinity:E,route:d,error:p7,bodyText:F,url:J$.url?.toString()??E4(J$.input),method:P1(D,B),headers:V0});throw L$}if(typeof F==="string")K0=await w9({affinity:E,route:d,status:Y0.status,bodyText:F,url:J$.url?.toString()??E4(J$.input),method:P1(D,B),headers:V0});if(AZ(Y0,{source:"turn",toolNameMap:d0,accountId:x.id,synthetic:!1,...u0,requestedModel:j0(F),dump:K0,status:Y0.status,streaming:S}),v?.mark("send_headers_received",{route:d,ms:P0($0()-c0),status:Y0.status,relayConfigured:!1,totalSendWithAccessMs:P0($0()-W0),baseURL:x.baseURL}),Y0.ok)u1.publish(()=>T.publishApi(P$.subject,{lastUsed:Date.now()}));return Y0}async function U$(D,B,x,v,d="unknown",t,g="main",P,_0,W0=!1,V0,E){aY(x,"anthropic");let I=h4(await Z()),n=$0(),X0=t,F=async()=>{return X0??=await q(z),X0},S=U4(D,B),K0=S.get("x-session-affinity")||S.get("x-opencode-session"),d0=f0(S),y=S.get(v1)??void 0,u0=n1.resolveHeader(y),P$=S.get(Y4)??void 0,J$=M1.resolveHeader(P$),c0=!d0&&!W0?J$: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(v1),S.delete(Y4);let u$=I3(S),Y0=await C4(D,B),A$=K0?r9.previousFor(K0):null,L$=A$?.messageId??null,h0,K$=!1,X4=null,R$=null,u4,f1;if(Y0&&typeof Y0==="string"){let l=$0();try{let U0=JSON.parse(Y0);if(typeof U0.model==="string")f1=U0.model}catch{}v?.mark("model_parse_for_identity",{route:d,ms:P0($0()-l),bodyBytes:Y0.length})}let p0=await A0(g,B?.signal??void 0,void 0,f1,g==="main"?"last-main":"serve");if(x=p0.accessToken,g==="main"&&V0?.providerAccountUuid&&p0.accountIdentity!==V0.providerAccountUuid)throw Error("Main account identity changed after request routing");E=p0.scopedAttempt;let M=$0(),i=J1(p0.accountIdentity);v?.mark("resolve_claude_code_identity",{route:d,ms:P0($0()-M),hasAccountUuid:Boolean(i.accountUuid)});let r=typeof Y0==="string"?Y0.length:void 0;if(Y0&&typeof Y0==="string"){let l=$0(),U0=(()=>{if(!XZ())return!1;try{return f7(JSON.parse(Y0).model)}catch{return!1}})(),Z$=!d0&&S4(),k1=F4(),jJ=_0?.plan.downgraded&&_0.plan.standbyCacheAnchor?.oauthAccountId===g?_0.plan.standbyCacheAnchor:void 0;try{Y0=await _9(Y0,{onToolNameMap:(n0)=>{u4=n0},cache1hEnabled:Z$,cache1hMode:k1,fastModeEnabled:U0,identity:i,sessionId:K0||void 0,thinkingPrefixMismatchBehavior:m5(await F()),midConversationEffortEnabled:!0,turnEndNoteEnabled:!0,turnEndNote:(await F())?.turnEndNote,midConversationEffortPlan:y,midConversationEffortResolvedPlan:u0,hybridStandbyAnchor:jJ,serverSideFallbackEnabled:b9==="server",laneStart:W0,billingLineage:c0,cacheDiagnosticsPreviousMessageId:L$,perf:(n0,z1)=>{if(v?.mark(`rewrite_body_${n0}`,{route:d,...z1}),n0==="cache_strategy"&&z1?.standbyBridgeApplied===!0&&_0&&!_0.standbyBridgeLogged)_0.standbyBridgeLogged=!0,h.info("fable-fallback","restored standby Opus cache bridge",{session:_0.plan.sessionId,distanceBlocks:z1?.standbyDistanceBlocks})}})}catch(n0){if(n0 instanceof S0)return n7(n0);if(n0 instanceof c7)return o7(n0);throw n0}if(_0?.plan.downgraded&&Z$&&k1==="hybrid"){let n0=j7(Y0);_0.opusCacheAnchor=n0?{...n0,oauthAccountId:g}:void 0}let nZ=$0();try{let n0=JSON.parse(Y0);m1(S,x,{body:n0,identity:i,requestClass:u$});let z1=n0.diagnostics,oZ=z1&&typeof z1==="object"&&!Array.isArray(z1)&&z1.previous_message_id===L$?L$:void 0;if(oZ!==void 0&&S.get("anthropic-beta")?.split(",").map((s8)=>s8.trim()).includes(V4))h0={sessionId:K0??"session-unknown",previousMessageId:oZ,...A$?{previousMessageReceivedAt:A$.receivedAt}:{},isSubagent:d0,ttlSent:r4(n0)};K$=n0.stream===!0,v?.mark("set_oauth_headers_body_parse",{route:d,ms:P0($0()-nZ),bodyBytes:Y0.length,parsed:!0})}catch{m1(S,x,{identity:i,requestClass:u$}),v?.mark("set_oauth_headers_body_parse",{route:d,ms:P0($0()-nZ),bodyBytes:Y0.length,parsed:!1})}if(U0)j9(S);v?.mark("rewrite_body",{route:d,ms:P0($0()-l),originalBytes:r,rewrittenBytes:Y0.length,cacheEnabled:!d0&&S4(),cacheMode:F4(),fastModeEnabled:U0,subagent:d0})}let z0=await s9(S),p=Q4(D);if(_0)_0.oauthAccountId=g;if(typeof Y0==="string"&&S4()&&F4()==="hybrid"){let l=await F();if(!d0||l5(l)){let U0=$0(),Z$=t1.track({sessionId:K0,url:p.url?.toString()??p.input.toString(),headers:S,bodyText:Y0,storage:l,cacheMode:"hybrid",oauthAccountId:g,isSubagent:d0});v?.mark("cachekeep_track",{session:K0,ms:P0($0()-U0),tracked:Z$.tracked,reason:Z$.tracked?void 0:Z$.reason,bodyBytes:Y0.length})}}let e=p0,i0,Y$=async(l)=>{await L(I),B?.signal?.throwIfAborted();let U0=await A0(g,B?.signal??void 0,l,f1,g==="main"?"last-main":"serve");if(await L(I),B?.signal?.throwIfAborted(),U0.accountIdentity!==e.accountIdentity||Boolean(U0.scopedAttempt)!==Boolean(e.scopedAttempt))throw Error("Native credential authority changed during the request");if(i0&&(!U0.scopedAttempt||U0.scopedAttempt.credentialId!==i0.credentialId||U0.scopedAttempt.accountIdentity!==i0.accountIdentity||U0.scopedAttempt.recordVersion<=i0.recordVersion))throw Error("Native vault retry has no strict newer same-account receipt");return U0},Q$=!1,t0=E,T0=async()=>{Q$=!0,p0=await Y$(),t0=p0.scopedAttempt,S.set("authorization",`Bearer ${p0.accessToken}`),C0={...C0,accessToken:p0.accessToken,anthropicAccountUuid:F$(p0.accountIdentity),localSubject:p0.localSubject,scopedAttempt:p0.scopedAttempt};let l=F9([p0.accessToken],K$?"event-stream":"http");try{let U0=(k1,jJ)=>fetch(p.input,{...B,body:k1,headers:jJ,...mJ()&&{tls:{rejectUnauthorized:!1}}}),Z$=l.redactResponse(typeof Y0==="string"?await EG({url:p.url?.toString()??E4(p.input),body:Y0,headers:S,latch:H,send:U0}):await U0(Y0,S));if(typeof Y0==="string")X4=await w9({affinity:K0,route:d,status:Z$.status,bodyText:Y0,url:p.url?.toString()??E4(p.input),method:P1(D,B),headers:S,tag:W0?"start":void 0});return Z$}catch(U0){let Z$=l.redactError(U0);if(l.dispose(),typeof Y0==="string")await w9({affinity:K0,route:d,error:p7,bodyText:Y0,url:p.url?.toString()??E4(p.input),method:P1(D,B),headers:S,tag:W0?"start":void 0});throw Z$}},z$=await F(),e0;try{e0=await T.getRelayConfig()}catch(l){if(l instanceof e5&&l.code==="relay-inconsistent")return _Z(l.message);throw l}let OJ=g==="main"?void 0:z$?.accounts.find((l)=>l.id===g&&B0(l)),d4=M5(OJ,P),C0={accountId:g,accessToken:x,authLineageId:P,anthropicAccountUuid:F$(E?.accountIdentity)??(g==="main"?V0?.providerAccountUuid:F$(i.accountUuid)??F$(d4)),localSubject:p0.localSubject,scopedAttempt:p0.scopedAttempt,...g==="main"&&V0?{mainQuotaIdentity:V0}:{}},i4=$0(),q$,H0=!1,l0=M0,g0=()=>SG({config:e0,input:p.input,init:B,headers:S,body:Y0,fallback:T0,affinity:K0,optimisticResponse:e0?.transport==="websocket",authorizeAttempt:async()=>{let l=await Y$(),U0=l.scopedAttempt;p0=l,C0={...C0,accessToken:l.accessToken,anthropicAccountUuid:F$(l.accountIdentity),localSubject:l.localSubject,scopedAttempt:U0};let Z$=new Headers(S);return Z$.set("authorization",`Bearer ${l.accessToken}`),{headers:Z$,errorSecrets:[l.accessToken],onUpstreamStatus:(k1)=>{if(k1!==401||!U0)return;if(q$=U0,H0)l0(U0,"relay_status_field")}}},onResponseHeaders:(l)=>{TZ(l,C0),M1.commit(c0,_J(l))},onDumpCreated:(l)=>{R$=l},dumpTag:W0?"start":void 0}),D0=await g0();if(!Q$&&q$&&D0.status===401&&typeof Y0==="string"&&(P1(D,B)??"").toUpperCase()==="POST"&&!B?.signal?.aborted){let l;try{l=await L1(q$,"model-relay",B?.signal??void 0)}catch{}if(l)await D0.body?.cancel().catch(()=>{}),h.info("claustrum","retrying after scoped credential rotation",{accountId:g,previousVersion:q$.recordVersion,newVersion:l.recordVersion,transport:"relay"}),i0=q$,q$=void 0,D0=await g0()}if(Q$&&t0&&D0.status===401&&typeof Y0==="string"&&(P1(D,B)??"").toUpperCase()==="POST"&&!B?.signal?.aborted){let l;try{l=await L1(t0,"model",B?.signal??void 0)}catch{}if(l)await D0.body?.cancel().catch(()=>{}),h.info("claustrum","retrying after scoped credential rotation",{accountId:g,previousVersion:t0.recordVersion,newVersion:l.recordVersion,transport:"direct"}),i0=t0,D0=await T0()}if(D0.status===401&&!p0.scopedAttempt&&typeof Y0==="string"&&(P1(D,B)??"").toUpperCase()==="POST"&&!B?.signal?.aborted){let l=p0.accessToken,U0;try{U0=await Y$(l)}catch(Z$){_1.set(D0,Z$)}if(U0&&U0.accessToken!==l)await D0.body?.cancel().catch(()=>{}),D0=Q$?await T0():await g0()}if(v?.mark("send_headers_received",{route:d,ms:P0($0()-i4),status:D0.status,relayConfigured:e0!=null,totalSendWithAccessMs:P0($0()-n)}),Q$)TZ(D0.headers,C0),M1.commit(c0,_J(D0.headers));if(AZ(D0,{source:W0?"start":"turn",toolNameMap:u4,accountId:g,synthetic:W0,...z0,requestedModel:j0(Y0),request:h0,trackSessionId:K0??void 0,dump:Q$?X4:R$,status:D0.status,streaming:K$}),Q$&&t0&&D0.status===401)await l0(t0,"direct");if(H0=!0,!Q$&&q$)await l0(q$,"relay_status_field");if(D0.status===401)await i7(D0,B?.signal);if(D0.ok)u1.publish(async()=>{if(C0.scopedAttempt)await T.vault.publish(C0.scopedAttempt,{lastUsed:Date.now()});else if(C0.localSubject)await T.publishLocal(C0.localSubject,{lastUsed:Date.now()})});return D0}async function R0(D,B){if(!D)return!1;try{return await k.refreshMain(B?.quotaKey??H$,D,B?.generation),k$(D,B)}catch{return!1}}async function V$(D,B={}){let x=r$(D),v=await N1(!1,x,B.modelId,"admission");if(D=await q(z),x){if(D&&v.size)D={...D,accounts:D.accounts.filter((P)=>!v.has(P.id)||a$(void 0,D,P.id,B.modelId))}}let d=await u9.getUsableFallbackAccounts(D,{modelId:B.modelId}),t=new Map(d.map((P)=>[P.id,P])),g=[];for(let P of D?.accounts??[]){if(D&&B0(P)){if(b0(D)){let W0=t.get(P.id);if(W0)g.push(W0);continue}if(T4(D)!=="local")continue;let _0=t.get(P.id);if(_0)g.push(_0);else if(P.access&&(!P.expires||P.expires>Date.now())&&!s$(P.lastRefreshError)&&!E1(P.lastRefreshError,P.id,Date.now(),t$(P.refresh))&&D?.quota?.failClosedOnUnknownQuota!==!0&&!KZ(Q0(P)))g.push(P);continue}if(B.includeApiRoutes===!0&&c1(P)&&y0(P)&&GZ(P.baseURL))g.push(P)}if(!r$(D))return g;return g.filter((P)=>B0(P)?a$(Q0(P),D,P.id,B.modelId):!0)}async function zJ(D){let B=D.mainQuotaIdentity?.quotaKey,x=k.getMain(B),v=x?.quota;if(!C1(x?.quota,D.storage,Date.now(),D.requestedModelId))try{v=await k.refreshMain(B,D.mainAccessToken,D.mainQuotaIdentity?.generation,"admission")}catch{}let d=await u9.getUsableFallbackAccounts(D.storage,{modelId:D.requestedModelId}),t=await q(z)??D.storage,g=[],P=b0(t);if(P){let E=t?.claustrum?.primaryAccount;if(E!==void 0&&y0(E)&&!t?.claustrum?.disabledAccountIdentities?.includes(E.accountId))g.push({id:W$,access:"",quota:v,identity:E?{kind:"known",accountId:E.accountId}:{kind:"unknown"},order:0,scoped:!0})}else if((D.mainAccessToken||D.mainPolicyDenied)&&!s$(t?.refresh?.mainLastRefreshError))g.push({id:W$,access:D.mainAccessToken,quota:v,identity:B?{kind:"known",accountId:B}:{kind:"unknown"},order:0});if(P)for(let[E,I]of(t?.accounts??[]).entries()){if(!y0(I)||!B0(I))continue;if(I.claustrumScopedCredentialId){let n=Q0(I);if(!C1(n,t,Date.now(),D.requestedModelId))try{n=await k.refreshFallback(I.id,"",I)}catch{}g.push({id:I.id,access:"",quota:n,identity:{kind:"known",accountId:I.id},order:E+1,account:I,scoped:!0})}}else{let E=new Map(d.map((I)=>[I.id,I]));for(let[I,n]of(t?.accounts??[]).entries()){if(!y0(n)||!B0(n))continue;let X0=E.get(n.id)??n;if(s$(X0.lastRefreshError))continue;let F=Q0(X0);if(!C1(F,t,Date.now(),D.requestedModelId))try{F=await k.refreshFallback(X0.id,X0.access??"",X0)}catch{}g.push({id:X0.id,access:X0.access??"",quota:F,identity:{kind:"known",accountId:X0.id},order:I+1,account:X0})}}let _0=new Set(d.map((E)=>E.id)),W0=new Set(g.flatMap((E)=>{let I=E.id===W$?t?.refresh?.mainLastRefreshError:E.account?.lastRefreshError,n=!E.scoped,X0=E.identity.kind==="known"?E.identity.accountId:void 0;if(n&&s$(I))return[];if(n&&E1(I,X0,Date.now(),E.id===W$?D.mainRefreshToken?t$(D.mainRefreshToken):void 0:E.account?.refresh?t$(E.account.refresh):void 0)&&(E.id===W$||!_0.has(E.id)))return[];if(C1(E.quota,t,Date.now(),D.requestedModelId)&&rJ({quota:E.quota,modelId:D.requestedModelId}).action==="migrate")return[];if(r$(t)&&!a$(E.quota,t,E.id===W$?void 0:E.id,D.requestedModelId))return[];return[E.id]})),V0=g.flatMap((E)=>{let I=E.id===W$?t?.refresh?.mainLastRefreshError:E.account?.lastRefreshError,n=!E.scoped,X0=E.identity.kind==="known"?E.identity.accountId:void 0;if(n&&s$(I)||n&&E1(I,X0,Date.now(),E.id===W$?D.mainRefreshToken?t$(D.mainRefreshToken):void 0:E.account?.refresh?t$(E.account.refresh):void 0)&&(E.id===W$||!_0.has(E.id)))return[];let F=E.id===W$?void 0:E.id,S=KZ(E.quota)?E.quota:void 0,K0=S?{kind:"known",quota:S}:{kind:"unknown"};return(!r$(t)||a$(K0.kind==="known"?K0.quota:void 0,t,F,D.requestedModelId))&&p1(K0.kind==="known"?K0.quota:void 0,t)&&(K0.kind==="unknown"||R9(K0.quota,D.requestedModelId)&&(E.id===W$||_0.has(E.id)||Boolean(E.scoped)))?[{accountId:E.id,quota:K0,order:E.order}]:[]});return{storage:t,allRoutes:g,candidates:V0,retainAccountIds:W0}}let v$=new WeakMap;async function K1(D,B,x,v,d,t,g){if(!x.length)return d??null;let P=g?.returnLastOnExhausted??!0,_0=d??null,W0=!1,V0=async()=>{if(W0)return;W0=!0,await d?.body?.cancel().catch(()=>{})};for(let[E,I]of x.entries()){let n;if(c1(I))await V0(),n=await D$(D,B,I,t,`api_fallback_${E}`,v,g?.fableRequest,g?.mainAccessToken,g?.mainQuotaIdentity);else if(b0(v)&&I.claustrumScopedCredentialId){let F;try{F=await A0(I.id,B?.signal??void 0,void 0,j0(await C4(D,B)))}catch(K0){if(K0 instanceof Z1)continue;throw K0}let S=F.scopedAttempt;if(!S)throw Error("Native vault fallback credential is unavailable");await V0(),n=await U$(D,B,S.accessToken,t,`fallback_${E}`,v,I.id,I.authLineageId,g?.fableRequest,g?.laneStartRequest,void 0,S)}else if(T4(v)==="local"&&I.access)await V0(),n=await U$(D,B,I.access,t,`fallback_${E}`,v,I.id,I.authLineageId,g?.fableRequest,g?.laneStartRequest);else continue;_0=n;let X0=jZ(n,v);if(!X0){let F=await N0(n,t);n=F.response,_0=n,X0=F.rateLimited}if(!X0){if(v$.set(n,c1(I)?"api":"oauth"),await g?.onSuccess?.(I),B0(I)&&k0(v)&&k.shouldRefreshOnRequestCount(p4)){if(b0(v)||I.access)k.refreshFallback(I.id,b0(v)?"":I.access??"",I).then(()=>g?.onSuccess?.(I)).catch(()=>{})}return n}if(E<x.length-1||!P)await n.body?.cancel().catch(()=>{})}return P?_0:null}async function r8(D,B,x,v,d,t,g,P,_0,W0,V0=!1,E){if(!J0(D,B?.body))return x;let I=$0(),n=t??await q(z);if(d?.mark("fallback_load_storage",{ms:P0($0()-I),cached:!!t}),!(n?.accounts??[]).some((u0)=>y0(u0)&&(B0(u0)||c1(u0)&&GZ(u0.baseURL))))return x;let F=x,S=jZ(F,n),K0=v0(F,!1);if(!S){let u0=await N0(F,d);F=u0.response,S=u0.rateLimited,K0=v0(F,u0.rateLimited)}if(!S)return F;let d0=!1;if(v)d0=v.some(c1);else if(K0)d0=await R0(g,E);let y=v;if(!y){let u0=$0();y=await V$(n,{includeApiRoutes:d0,modelId:_0}),d?.mark("fallback_get_accounts",{ms:P0($0()-u0),accounts:y.length})}if(r$(n)){let u0=y.length;if(y=y.filter((P$)=>B0(P$)?a$(Q0(P$),n,P$.id,_0):!0),y.length<u0)y$("[killswitch] filtered fallbacks",{before:u0,after:y.length})}return await K1(D,B,y,n,F,d,{onSuccess:P,mainAccessToken:g,mainQuotaIdentity:E,fableRequest:W0,laneStartRequest:V0})??F}return{apiKey:"",async fetch(D,B){if(D instanceof Request&&B?.signal===void 0)B={...B,signal:D.signal};let x=U4(D,B),v=x.get(J9)==="1";x.delete(J9),B={...B,headers:x};let d=x.get("x-session-affinity")||x.get("x-opencode-session"),t=j0(B?.body),g=Boolean(d&&t&&!f0(x)&&W1.resetForModelChange(d,t));if(g&&d){for(let M of S$.keys())if(M.startsWith(`${d}\x00`))S$.delete(M);N$.delete(d)}let P=W1.plan(d,B?.body),_0=b9==="server"&&h1(P?.effectiveModel??t)?P?.effectiveModel??t:void 0,W0=P?{plan:P}:void 0;if(P?.downgraded)B={...B,body:P.bodyText};let V0=B?.body,E=pG({bodyBytes:typeof V0==="string"?V0.length:void 0}),I=(M)=>{let i=p$.get(M);return D7(M,{toolNameMap:i?.toolNameMap,perf:(r,z0)=>E.mark(r,z0),laneStart:v,laneStartOAuthServed:v$.get(M)!=="api",...i?i.streaming?{onMessageStart:(r)=>PZ(M,r,!1),onMessageDelta:(r)=>A8(M,r),onStreamEnd:()=>i.dumpWrite}:{onMessageResponse:(r)=>PZ(M,r),onStreamEnd:()=>i.dumpWrite,responseMode:"json"}:{},contentFilterModel:P?.requestedModel,...!P?.downgraded&&P?{onContentFilter:(r)=>{if(!W0?.oauthAccountId)return h.debug("fable-fallback","content filter recovery unavailable for non-OAuth route",{session:P.sessionId}),!1;let z0=W1.activate(P,W0.oauthAccountId);S$.delete(P.recoveryKey),S$.set(P.recoveryKey,oG(P.requestedModel,z0));while(S$.size>128){let p=S$.keys().next().value;if(p)S$.delete(p);else break}f$.delete(P.recoveryKey),h.info("fable-fallback","content filter detected; switching session to Opus 4.8",{session:P.sessionId,requestedModel:P.requestedModel,completedToolUse:r?.completedToolUse===!0,remaining:z0}),J4({sessionId:P.sessionId,mode:"opus",remaining:z0,requestedModelId:P.requestedModel},S,F)}}:{},...P&&W0?{onComplete:(r)=>{if(!P.downgraded){W1.completeSource(P,!W0.serverFallback);return}let z0=W1.complete(P,W0.opusCacheAnchor);if(!z0.counted)return;let p=S$.get(P.recoveryKey);if(p)S$.delete(P.recoveryKey),X$.delete(P.sessionId),gZ(P.sessionId,p);if(h.info("fable-fallback","Opus 4.8 turn completed",{session:P.sessionId,requestedModel:P.requestedModel,finishReason:r,remaining:z0.remaining}),J4({sessionId:P.sessionId,mode:"opus",remaining:z0.remaining,requestedModelId:P.requestedModel},S,F),z0.remaining===0)J4({sessionId:P.sessionId,mode:"fable",remaining:0,requestedModelId:P.requestedModel},S,F,rG(P.requestedModel))}}:{},..._0?{serverSideFallbackModel:_0,...P?{onServerSideFallbackOutcome:(r)=>{if(W0)W0.serverFallback=r.fallback;c8(P,r,S,F)}}:{}}:{}})},n=$0(),X0=P?.effectiveModel??j0(await C4(D,B)),F=await N(X0,B?.signal??void 0,!0);if(E.mark("get_auth",{ms:P0($0()-n),authType:F.type,hasAccess:Boolean(F.access)}),F.type!=="oauth"){let M=Q4(D),i=U4(D,B);U7(i);let r=await C4(D,B);if(typeof r==="string")try{let p=JSON.parse(r);if(BG(p))r=JSON.stringify(p)}catch{}let z0=await fetch(M.input,{...B,body:r,headers:i});return E.done("non_oauth_passthrough",{status:z0.status}),z0}let S=await q(),K0=F$(F.nativeAccountIdentity),d0=F.nativeScopedAttempt,y;if(F.access){let M=await s1(F.access,j0(B?.body),K0,d0?.recordVersion);if(M.stale)throw Error("Main OAuth identity changed while resolving request credentials");if(y={...M,routingLineage:F.nativeRoutingLineage},K0)$4=F.access,D1=M.providerAccountUuid}else if((F.modelDenied||F.credentialUnavailable||F.deferred)&&K0)await HZ("",K0,K0),y={quotaKey:K0,providerAccountUuid:K0,generation:k.getMainQuotaIdentityGeneration(),routingLineage:F.nativeRoutingLineage,stale:!1,state:b0(S)?"on-cold":"na"};let u0=$0();E.mark("load_storage",{ms:P0($0()-u0)}),k.updateStorage(S),k.seedMainFromStorage(S,H$),k.seedFallbacksFromAccounts((S?.accounts??[]).filter(B0));let P$=d?E$.get(d):void 0;if(g||!P||b9==="server"&&P$?.requestedModelId&&h$(P$.requestedModelId)!==h$(P.requestedModel))p8(d,S,F);let J$=J0(D,B?.body),c0=j0(B?.body)??X0,u$=_$(y,S),Y0=L0("main",y?.routingLineage,K0,S),A$=F.deferred?NZ(u$&&S?{...S,accounts:S?.accounts??[],quota:{...S?.quota,mainQuota:u$.quota}}:S,K0,Y0?.lineage===y?.routingLineage&&Y0?.generalExhausted===!0):void 0;if(A$){let M=J$?await V$(S,{includeApiRoutes:k$(void 0,y),modelId:c0}):[],i=await K1(D,B,M,S,void 0,E,{onSuccess:(r)=>h0(r.id,"fallback"),mainQuotaIdentity:y,fableRequest:W0,laneStartRequest:v});if(i)return I(i);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:A$.message}}),{status:429,headers:{"content-type":"application/json","retry-after":String(A$.retryAfter)}})}let L$=()=>{let M=k7(k.getMain(y?.quotaKey)?.quota,(S?.accounts??[]).filter(B0),Date.now(),X0);return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"No enabled OAuth route can serve the requested model under current quota policy."}}),{status:429,headers:{"content-type":"application/json","retry-after":String(M)}})};if(J$)p4++;if(J$&&F.access&&(!F.expires||F.expires>Date.now()))b8(S,F.access,y);async function h0(M,i){let r=S,z0=!1;if((S?.accounts??[]).some((p)=>B0(p)&&p.quota))try{let p=await q(z);if(p)r=p;else z0=!0}catch{z0=!0}C$(r,{activeId:M,route:i,mainAccessToken:F.access,skipFallbackQuotaSeed:z0})}let K$;if(J$&&d&&e$(S)==="sticky-balanced"){let M=P?.effectiveModel??c0,i=AG(M),r=t1.trackedOAuthRoute(d),z0=P?.cacheAccountId??(r?r.oauthAccountId??W$:void 0),p=!1;try{let e=await zJ({storage:S,mainAccessToken:F.access,mainRefreshToken:F.refresh,mainPolicyDenied:F.modelDenied||F.credentialUnavailable,requestedModelId:M,mainQuotaIdentity:y}),i0=async(z$)=>{let e0=await LZ();return e0.router.resolve({sessionId:d,family:i,modelId:M,affinityModelId:t,candidates:e.candidates,retainAccountIds:e.retainAccountIds,storage:e.storage,inputBytes:typeof B?.body==="string"?Buffer.byteLength(B.body):1,preferredAccountId:z0,excludeAccountIds:z$,...e0.accountIdentities&&{accountIdentities:e0.accountIdentities}})},Y$=s$(e.storage?.refresh?.mainLastRefreshError),Q$=e.allRoutes.length===0&&!Y$||e.allRoutes.some((z$)=>!z$.quota||!C1(z$.quota,e.storage,Date.now(),M)),t0=await i0();if(!t0&&Q$){if(F.modelDenied)return L$();throw Error("Sticky-balanced routing is waiting for current OAuth quota snapshots")}if(!t0){if(F.modelDenied)return L$();if(b0(S))throw new VZ;let z$=S5({mainRefreshError:e.storage?.refresh?.mainLastRefreshError,fallbackReauthLabels:h5(e.storage),routeQuotas:e.allRoutes.flatMap((e0)=>e0.quota?[e0.quota]:[]),modelId:M});return E.done("return_sticky_no_route",{status:z$.status}),z$}let T0=e.allRoutes.find((z$)=>z$.id===t0?.accountId);if(t0&&T0){if(p=!0,P?.downgraded&&W1.bindRecoveryAccount(P,T0.id))h.info("fable-fallback","rebound recovery to migrated sticky account",{accountId:T0.id});let z$=async(H0)=>{if(H0.scoped){let g0=(await A0(H0.id,B?.signal??void 0,void 0,M)).scopedAttempt;if(!g0)throw Error("Native vault sticky credential is unavailable");return U$(D,B,g0.accessToken,E,`sticky:${H0.id}`,e.storage,H0.id,H0.account?.authLineageId,W0,v,H0.id===W$?y:void 0,g0)}return U$(D,B,H0.access??"",E,`sticky:${H0.id}`,e.storage,H0.id,H0.account?.authLineageId,W0,v,H0.id===W$?y:void 0)},e0=async(H0,l0,g0=!0)=>{return await h0(H0.id,"sticky-balanced"),E.done("return_sticky_balanced",{status:l0.status,accountId:H0.id,created:t0?.created,migrated:t0?.migrated}),I(l0)},OJ=async(H0)=>{let l0=H0,g0=jZ(H0,e.storage),D0=!1;if(!g0){let l=await N0(H0,E);l0=l.response,D0=l.rateLimited,g0=l.rateLimited}return{response:l0,routeFailure:g0,streamingRateLimit:D0}},d4=C1(T0.quota,e.storage,Date.now(),M)?rJ({quota:T0.quota,modelId:M}):void 0;if(d4?.action==="hold")return e0(T0,await DJ(new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account five-hour quota resets shortly; retaining session affinity."}}),{status:429,headers:{"content-type":"application/json"}}),d,d4.retryAfterSeconds,!1,p$),!1);let C0=await OJ(await z$(T0)),i4=!1;if(!C0.routeFailure)return e0(T0,C0.response);if(C0.response.status===401){let H0=_1.get(C0.response);if(H0){let l0=await q(z),g0=T0.id,D0=T0.id===W$?l0?.refresh?.mainLastRefreshError:l0?.accounts.find((l)=>l.id===g0&&B0(l))?.lastRefreshError;if(!s$(D0))throw H0}i4=!0}let q$=C0.response.status===403||i4;if(C0.response.status===429||C0.streamingRateLimit){let H0;try{H0=T0.id===W$?await k.refreshMain(y?.quotaKey,T0.access??"",y?.generation):await k.refreshFallback(T0.id,T0.access??"",T0.account)}catch{H0=void 0}let l0=rJ({quota:H0,modelId:M});if(E.mark("sticky_quota_failure",{accountId:T0.id,action:l0.action,reason:l0.reason}),l0.action==="hold")return e0(T0,await DJ(C0.response,d,l0.retryAfterSeconds,C0.streamingRateLimit,p$));q$=l0.action==="migrate"}if(q$){await i7(C0.response,B?.signal);let H0=T0.id;if(e=await zJ({storage:e.storage,mainAccessToken:F.access,mainRefreshToken:F.refresh,mainPolicyDenied:F.modelDenied||F.credentialUnavailable,requestedModelId:M,mainQuotaIdentity:y}),e.candidates.filter((g0)=>g0.accountId!==H0).length>0){await C0.response.body?.cancel().catch(()=>{}),t0=await i0(new Set([H0]));let g0=e.allRoutes.find((D0)=>D0.id===t0?.accountId);if(t0&&g0){if(T0=g0,P?.downgraded)W1.bindRecoveryAccount(P,T0.id);return e0(T0,await z$(T0))}}else if((C0.response.status===429||C0.streamingRateLimit)&&k$(F.access,y)){let g0=(await V$(e.storage,{includeApiRoutes:!0,modelId:M})).filter(c1);if(g0.length>0){let D0=await K1(D,B,g0,e.storage,C0.response,E,{onSuccess:(l)=>h0(l.id,"sticky-balanced"),mainAccessToken:F.access,mainQuotaIdentity:y,fableRequest:W0,laneStartRequest:v});if(D0)return E.done("return_sticky_api_fallback",{status:D0.status}),I(D0)}}}return e0(T0,C0.response)}}catch(e){if(E.mark("sticky_balanced_error",{error:e instanceof Error?e.message:String(e)}),p||w1(e))throw e;let i0=e instanceof Error?e:Error(String(e));throw Object.assign(i0,{code:"ECONNRESET",syscall:"sticky-routing"}),i0}}if(J$&&e$(S)==="fallback-first")try{let M=$0();K$=await V$(S,{includeApiRoutes:k$(F.access,y),modelId:c0}),E.mark("fallback_first_get_accounts",{ms:P0($0()-M),accounts:K$.length});let i=await K1(D,B,K$,S,void 0,E,{returnLastOnExhausted:!1,mainAccessToken:F.access,mainQuotaIdentity:y,onSuccess:(r)=>h0(r.id,"fallback-first"),fableRequest:W0,laneStartRequest:v});if(i)return E.done("return_fallback_first",{status:i.status}),I(i);K$=void 0}catch(M){if(E.mark("fallback_first_error",{error:M instanceof Error?M.message:String(M)}),w1(M))throw M}if(F.deferred){if(Object.assign(F,await N(X0,B?.signal??void 0)),F.access){let M=await s1(F.access,X0,F.nativeAccountIdentity,F.nativeScopedAttempt?.recordVersion);if(M.stale)throw Error("Main OAuth identity changed while resolving request credentials");y={...M,routingLineage:F.nativeRoutingLineage},$4=F.access,D1=M.providerAccountUuid}}if(!F.modelDenied&&(!F.access||!F.expires||F.expires<Date.now())){if(b0(S))try{let p=(await A0("main",B?.signal??void 0,void 0,X0)).scopedAttempt;if(!p)throw Error("Native vault main credential is unavailable");$4=p.accessToken;let e=await U$(D,B,p.accessToken,E,"main",S,"main",void 0,W0,v,y,p);return I(e)}catch(z0){let p=J$?await V$(S,{modelId:c0}):[],e=await K1(D,B,p,S,void 0,E,{onSuccess:(i0)=>h0(i0.id,"fallback"),mainAccessToken:F.access,mainQuotaIdentity:y,fableRequest:W0,laneStartRequest:v});if(e)return I(e);if(z0 instanceof O$)throw new VZ;throw z0}if(F.credentialFailure?.tokenRefreshFailed)throw F.credentialFailure;let M=await q(),i=M?.refresh?.mainLastRefreshError;if(i&&E1(i,F.nativeAccountIdentity??e1??M?.mainAccountId,Date.now(),F.refresh?t$(F.refresh):void 0))throw y$("[refresh] opencode main oauth request skipped backoff",{nextRetryAt:i.nextRetryAt,retryCount:i.retryCount,expiresInMs:F.expires?F.expires-Date.now():void 0}),Error(I5(i,Date.now()));y$("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(F.access),expiresInMs:F.expires?F.expires-Date.now():void 0,expiredAgoMs:F.expires&&F.expires<Date.now()?Date.now()-F.expires:void 0});let r=$0();F.access=await C(void 0,X0,B?.signal??void 0),E.mark("refresh_main_access",{ms:P0($0()-r)})}if(!F.access&&!F.modelDenied)throw E.done("missing_access_error"),Error("OAuth access token is missing after refresh");function X4(){if(S?.quota?.showToasts!==!0)return;let M=k.getMain(y?.quotaKey);if(!M)return;let i=(S?.accounts??[]).filter((p)=>p.enabled!==!1&&B0(p)).map((p)=>({...p,quota:k.getFallback(p.id,p)?.quota??p.quota})),r=p1(M.quota,S),z0;if(r)z0="main";else z0=i.find((p)=>p1(p.quota,S))?.id??"main";o8(M.quota,i,z0)}if(J$&&k0(S))try{let M=$0(),i=_$(y,S),r=i?.quota;if(!r)r=await k.refreshMain(y?.quotaKey,F.access,y?.generation,"admission"),i=_$(y,S),X4();else if(k.needsRefresh(p4,c0))if(r1(r)||A9(r,c0))r=await k.refreshMain(y?.quotaKey,F.access,y?.generation),i=_$(y,S);else k.refreshMain(y?.quotaKey,F.access,y?.generation).then(()=>{x1().catch(()=>{}),X4()}).catch(()=>{});C$(S,{activeId:"main",route:"main",mainAccessToken:F.access});let z0=p1(r,S)&&R9(r,c0);if(E.mark("main_quota_for_routing",{ms:P0($0()-M),passes:z0,model:c0,modelScopedExhausted:A9(r,c0)}),!z0){let p=$0();K$=await V$(S,{includeApiRoutes:Boolean(i&&i.refreshAfter>Date.now()&&r1(i.quota)),modelId:c0}),E.mark("preselect_fallback_accounts",{ms:P0($0()-p),accounts:K$.length});let e=await K1(D,B,K$,S,void 0,E,{onSuccess:(i0)=>h0(i0.id,"fallback"),mainAccessToken:F.access,mainQuotaIdentity:y,fableRequest:W0,laneStartRequest:v});if(e)return E.done("return_preselected_fallback",{status:e.status}),I(e)}}catch(M){if(E.mark("main_quota_for_routing_error",{error:M instanceof Error?M.message:String(M)}),w1(M))throw M}let R$=_$(y,S)?.quota;if(S?.quota?.failClosedOnUnknownQuota&&(R$===void 0||F.access.startsWith("sk-ant-oat")&&y?.providerAccountUuid===void 0)&&k.isBackedOff()){let M=k.getLastApiError(),i=M?R7(M,Date.now()):"Quota API unavailable";return y$("[quota] blocked: quota API backed off (failClosed)",{nextRetryAt:M?.nextRetryAt,retryCount:M?.retryCount}),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:i}}),{status:429,headers:{"content-type":"application/json","retry-after":String(M?.nextRetryAt?Math.max(1,Math.ceil((M.nextRetryAt-Date.now())/1000)):60)}})}if(r$(S)){if(k.needsRefresh(p4,c0))try{await Promise.all([k.refreshMain(y?.quotaKey,F.access,y?.generation),N1(!1,!0,void 0,"admission")])}catch(i){y$("[quota] killswitch refresh failed",{error:i instanceof Error?i.message:String(i),backedOff:k.isBackedOff()})}R$=_$(y,S)?.quota}if(r$(S)&&!a$(R$,S,void 0,c0)){let i=J0(D,B?.body)?await V$(S,{includeApiRoutes:k$(F.access),modelId:c0}):[];if(i.length>0){y$("[route] skipping main (killswitch), trying fallbacks");let Y$=await K1(D,B,i,S,void 0,E,{onSuccess:(Q$)=>h0(Q$.id,"fallback"),mainAccessToken:F.access,mainQuotaIdentity:y,laneStartRequest:v});if(Y$)return E.done("return_killswitch_fallback",{status:Y$.status}),I(Y$)}let r=Date.now(),z0=(S?.accounts??[]).filter((Y$)=>y0(Y$)&&B0(Y$)).map((Y$)=>({...Y$,quota:Q0(Y$)})),p=f3({mainQuota:R$,requestModelId:c0,storage:S}),e=k7(R$,z0,r,p.isScopedDriven?p.modelId:void 0),i0=x3({retryAfterSeconds:e,...p.isScopedDriven&&{modelName:p.modelName}});return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:i0}}),{status:429,headers:{"content-type":"application/json","retry-after":String(e)}})}if(F.modelDenied){let M=L$(),i=J$?await V$(S,{modelId:X0}):[],r=await K1(D,B,i,S,void 0,E,{onSuccess:(p)=>h0(p.id,"fallback"),fableRequest:W0,laneStartRequest:v,mainAccessToken:F.access,mainQuotaIdentity:y});if(r)return I(r);if(!(e$(S)!=="sticky-balanced"&&A9(R$,X0)&&p1(R$,S)&&a$(R$,S,void 0,X0)))return I(M);return I(await U$(D,B,"",E,"main",S,"main",void 0,W0,v,y))}let u4=await U$(D,B,F.access,E,"main",S,"main",void 0,W0,v,y,d0),f1=!1,p0=await r8(D,B,u4,K$,E,S,F.access,(M)=>{return f1=!0,h0(M.id,"fallback")},c0,W0,v,y);if(!f1)await h0("main","main");return E.done("return_response",{status:p0.status}),I(p0)}}}return{}},get methods(){return[...rY(T9("opencode").tokenPath)?[M8]:[],{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{if(await S1("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.");if(await T.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(Y)=>{let G=await aJ(Y,Z.verifier,Z.redirectUri,Z.state);if(G.type==="failed")return G;G$(),await T.loginOAuth({routeId:"main",replace:!0,credential:{access:G.access,refresh:G.refresh,expires:G.expires}});let K=oJ("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 Q7("console");return{url:Z.url,instructions:"Paste the authorization code here:",method:"code",callback:async(Y)=>{let G=await aJ(Y,Z.verifier,Z.redirectUri,Z.state);if(G.type==="failed")return G;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${G.access}`}}).then((j)=>j.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}},dispose:v8,__primeManager:H1,__quotaManager:k,__cacheKeepManager:t1,__resolveMainQuotaIdentityForTest:s1,__resolveSidebarQuotaAccessForTest:xZ,__refreshSidebarQuotaForTest:x1,__mainProviderAccountUuidForTest:()=>D1,__fallbackRefreshReady:E8,get __scopedRuntime(){return h9(z,$.directory)},__notificationMessageIdBeforeAssistantForTest:j8,__trackDesktopNoticeMessageIdForTest:hZ,__isDesktopNoticeMessageForTest:bZ}},C6=W2;
|
|
42
|
+
export{Y4 as a,_J as b,LJ as c,v1 as d,S0 as e,S3 as f,J9 as g,M3 as h,u3 as i,i3 as j,n3 as k,m1 as l,Q4 as m,_9 as n,D7 as o,C6 as p};
|