@cortexkit/opencode-anthropic-auth 2.4.2 → 2.4.3
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 +44 -44
- package/dist/{index-nbwx1dph.js → index-42r4bnpm.js} +1 -1
- package/dist/{index-a1k6z503.js → index-hbk67489.js} +1 -1
- package/dist/{index-12km9x91.js → index-t4aky73k.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/sidebar-state.d.ts +1 -0
- package/dist/sidebar-state.js +1 -1
- package/dist/v2/cachekeep.d.ts +6 -1
- package/dist/v2/server.js +7 -7
- package/dist/v2/tui.js +1 -1
- package/package.json +3 -3
- package/src/sidebar-state.ts +9 -0
- package/src/tui/claude-sidebar.tsx +22 -32
- package/src/tui-compiled/sidebar-state.ts +9 -0
- package/src/tui-compiled/tui/claude-sidebar.tsx +155 -184
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as Q8}from"./index-sg0knfec.js";import{t as B8}from"./index-hc7bm3yf.js";import{D as F8}from"./index-naff9h33.js";import{H as w8,M as y9,O as T8,P as E8}from"./index-12km9x91.js";import{ga as Z7}from"./index-gvswxab8.js";import{randomUUID as XZ}from"node:crypto";import{existsSync as UW,readFileSync as QW}from"node:fs";import{dirname as BW,join as FW}from"node:path";import{fileURLToPath as wW}from"node:url";import{ANTHROPIC_OAUTH_ORIGIN_REFUSAL as TW,acquireNativeAccountRuntime as EW,applyCustomHeaders as k7,assertNotCustodyTombstone as SW,authorize as v7,buildAccountList as p$,buildClaudeQuotaSummary as CW,buildFallbackQuotaSummaries as AW,buildPrimeRequestBody as PW,CACHE_KEEP_EXTENDED_TTL_BETA as qW,CacheKeepManager as RW,CacheKeepSessionRegistry as MW,CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS as IW,CLAUDE_HAIKU_4_5_MODEL_ID as h7,CLAUDE_HAIKU_5_5_CONTEXT_WINDOW as xW,CLAUDE_HAIKU_5_5_LONG_CONTEXT_PRICING as T9,CLAUDE_HAIKU_5_5_LONG_CONTEXT_THRESHOLD as fW,CLAUDE_HAIKU_5_5_MAX_OUTPUT_TOKENS as kW,CLAUDE_HAIKU_5_5_MODEL_ID as E9,CLAUDE_HAIKU_5_5_PRICING as S9,CLAUDE_HAIKU_5_5_RELEASE_DATE as vW,CLAUDE_OPUS_5_5_CONTEXT_WINDOW as hW,CLAUDE_OPUS_5_5_MAX_OUTPUT_TOKENS as bW,CLAUDE_OPUS_5_5_MODEL_ID as C9,CLAUDE_OPUS_5_5_PRICING as A9,CLAUDE_OPUS_5_5_RELEASE_DATE as gW,CLAUDE_SONNET_5_5_CONTEXT_WINDOW as yW,CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS as mW,CLAUDE_SONNET_5_5_MODEL_ID as P9,CLAUDE_SONNET_5_5_PRICING as q9,CLAUDE_SONNET_5_5_RELEASE_DATE as cW,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as WZ,computeXxhash64Hex as pW,configuredAnthropicOAuthAccountCount as lW,createEmptyStorage as a$,createNativeUsagePublisher as uW,createProviderErrorResponseScope as R9,createSseFramer as dW,createStickyNoRouteResponse as iW,custodyTombstoneOAuth as GZ,decideOpenCodeStateLayoutOnce as nW,decideStickyQuotaFailure as zZ,decodeSseFrame as oW,detectClaustrumConnection as b7,dumpDirectRequest as M9,dumpResponseArtifact as VZ,effectiveRelayStatus as rW,exchange as KZ,executeAccountCommand as sW,executeCache1hCommand as jZ,executeCacheKeepCommand as aW,executeDumpCommand as g7,executeFastModeCommand as y7,executeKillswitchCommand as m7,executeLaneStartCommand as c7,executeLoggingCommand as p7,executePrimeCommand as tW,executeRoutingCommand as l7,FALLBACK_BACKGROUND_TICK_MS as eW,fallbackAccountUuidForLineage as $2,formatEnrollmentStatus as u7,formatNativeAccountState as _Z,formatOAuthAccountTier as C4,formatQuotaBackoffMessage as d7,formatRefreshBackoffMessage as J2,getAccountStoragePath as Z2,getCache1hMode as A4,getCache1hPersistentMode as P4,getCacheKeepWindow as i7,getClaudeCodeIdentityForVerifiedAccount as Y2,getClaudeModelCatalogue as X2,getClaustrumMode as q4,getDefaultCacheKeepRegistryDirectory as W2,getFallbackReauthLabels as G2,getHostClaustrumEnrollmentPaths as I9,getKillswitchConfig as OZ,getPersistedLogLevel as LZ,getQuotaCheckIntervalMs as n7,getQuotaNextRefreshAt as T1,getRequestGzipLatch as z2,getRequestGzipLatchPath as V2,getRoutingMode as Z1,getScopedQuotaWindowForModel as K2,getThinkingPrefixMismatchBehavior as j2,inspectNativeHostAuthEntry as _2,isApiKeyAccount as p1,isCache1hEnabled as R4,isCache1hPersistentlyEnabled as x9,isCacheKeepAlways as o7,isCacheKeepHybridActive as r7,isCacheKeepPersistentlyEnabled as O2,isCacheKeepSubagentsEnabled as L2,isClaudeFableOrMythos51Model as N2,isClaudeOpus5Model as D2,isClaudeOpus55Model as H2,isCostZeroingEnabled as U2,isCustodyTombstoneOAuth as NZ,isDumpPersistentlyEnabled as DZ,isFastModeEnabled as HZ,isFastModePersistentlyEnabled as UZ,isFastModeSupportedModel as s7,isKillswitchEnabled as t$,isNativeTransientAccountError as E1,isOAuthAccount as w0,isPermanentRefreshError as e$,isPrimePersistentlyEnabled as f9,isQuotaBearingHeaderFrame as Q2,isValidApiBaseURL as QZ,killswitchPassesPolicy as $1,killswitchRetryAfterSeconds as a7,log as l$,logger as b,mergeAnthropicBetas as t7,mergeHeaderQuotaForPersistence as e7,NativeCustodyError as B2,NativeRuntimeError as F2,NativeVaultNoAccountError as BZ,nativeAccountCanServe as m0,nativeLocalQuotaLineage as w2,nativeMigrationAuthorityPhase as $8,normalizeQuotaHeaders as T2,oauthProfileIsFresh as k9,oauthProfileMatchesIdentity as E2,PARALLEL_TOOL_CALLS_SYSTEM_PROMPT as S2,PrimeManager as C2,parseAccountCommandAction as A2,parseCache1hCommandAction as P2,parseCacheKeepCommandAction as q2,parseDumpCommandAction as R2,parseFastModeCommandAction as M2,parseLaneStartCommandAction as I2,parseLoggingCommandAction as x2,parsePrimeCommandAction as f2,parseRoutingCommandAction as k2,parseSseFrame as v2,QUOTA_HEADER_FEED_SCHEMA_VERSION as v9,QuotaHeaderFeedRegistry as h2,QuotaManager as b2,quotaSnapshotCheckedAt as S1,quotaSnapshotHasStandardWindows as FZ,quotaSnapshotModelScopeIsExhausted as h9,quotaSnapshotPassesModelScope as b9,quotaSnapshotPassesPolicy as l1,readClaustrumEnrollmentStatus as J8,readNativeAccountsForRequest as g2,readNativeEnrollmentMode as C1,readNativeHostAuthKind as y2,readNativeMigrationJournal as Z8,refreshBackoffActive as A1,remapRequestBodyModel as m2,resetClaustrumEnrollmentState as c2,resolveClaudeModelCapabilities as p2,resolveNativePoolPaths as l2,STICKY_ROUTING_MAIN_ACCOUNT_ID as $$,StickySessionRouter as u2,sendViaRelay as d2,sendWithRequestGzip as i2,setCache1hState as g9,setDumpEnabled as wZ,setFastModeEnabled as TZ,setLogLevel as n2,shouldFallbackStatus as o2,snapshotHasServableLocalOAuth as Y8,stateRefusalPublicMessage as r2,stickyQuotaSnapshotIsFresh as P1,stickyRouteFamilyForModel as s2,TrailingAssistantHistoryError as X8,tokenFingerprint as J1}from"@cortexkit/anthropic-auth-core";import{randomUUID as V3}from"node:crypto";import{isValidAnthropicRequestId as K3,isValidBillingPromptId as LY}from"@cortexkit/anthropic-auth-core";var j4="x-cortexkit-billing-lineage",NY=4096,DY=4096,HY=1024,j3=new Set(["title","summary","compaction"]),UY="[lane start] — automated cache warm; no response needed.";function QY($){let J=$.info?.sessionID??$.info?.sessionId;return typeof J==="string"&&J.length>0?J:void 0}function BY($){if($.info?.synthetic===!0||$.info?.ignored===!0||typeof $.info?.agent==="string"&&j3.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===UY)return!0}return!1}function B1($,J){while($.size>J){let Y=$.keys().next().value;if(Y===void 0)return;$.delete(Y)}}function wJ($){let J=$.get("request-id")??$.get("x-request-id");return J&&K3(J)?J:void 0}class TJ{#$;#_;#K;#O;#X;#J=new Map;#Y=new Map;#Z=new Map;#W=new Map;#G=new Map;#z=new Map;#V=new Map;constructor($={}){this.#$=$.createPromptId??V3,this.#_=$.createRequestToken??V3,this.#K=$.maxPrompts??NY,this.#O=$.maxRequests??DY,this.#X=$.maxSessions??HY}observeMessages($){let J;for(let D=$.length-1;D>=0;D-=1)if($[D]?.info?.role==="user"){J=$[D];break}if(!J)return;let Y=QY(J),X=J.info?.id;if(!Y||typeof X!=="string"||X.length===0)return;let z=this.#j(Y,X);if(BY(J)){this.#Y.delete(z),this.#Y.set(z,!0),B1(this.#Y,this.#K),this.#J.delete(z);return}this.#Y.delete(z);let V=this.#J.get(z);if(V){this.#J.delete(z),this.#J.set(z,V);return}let K=this.#$();if(!LY(K))return;this.#J.set(z,K),B1(this.#J,this.#K)}markHeaders($){let J=this.#j($.sessionId,$.messageId);if(j3.has($.agent??"")||this.#Y.has(J))return!1;let Y=this.#J.get(J);if(!Y)return!1;let X=this.#_();if(!X||/[\r\n]/.test(X))return!1;let z={sessionId:$.sessionId,messageId:$.messageId,promptId:Y,requestToken:X,generation:this.#G.get($.sessionId)??0,sequence:0};return this.#Z.set(X,z),B1(this.#Z,this.#O),$.headers[j4]=X,!0}resolveHeader($){if(!$)return;let J=this.#Z.get($);if(!J)return;this.#Z.delete($),this.#Z.set($,J);let Y=(this.#z.get(J.sessionId)??0)+1;this.#z.delete(J.sessionId),this.#z.set(J.sessionId,Y),B1(this.#z,this.#X);let X={...J,previousRequestId:this.#W.get(J.sessionId),sequence:Y};if(X.previousRequestId===void 0)delete X.previousRequestId;return X}commit($,J){if(!$||!J||!K3(J))return!1;if((this.#G.get($.sessionId)??0)!==$.generation)return!1;let Y=this.#Z.get($.requestToken);if(!Y||Y.sessionId!==$.sessionId||Y.messageId!==$.messageId||Y.promptId!==$.promptId||Y.generation!==$.generation)return!1;if(this.#J.get(this.#j($.sessionId,$.messageId))!==$.promptId)return!1;if($.sequence<(this.#V.get($.sessionId)??0))return!1;return this.#V.delete($.sessionId),this.#V.set($.sessionId,$.sequence),B1(this.#V,this.#X),this.#W.delete($.sessionId),this.#W.set($.sessionId,J),B1(this.#W,this.#X),!0}clearSession($){this.#G.set($,(this.#G.get($)??0)+1),this.#W.delete($),this.#z.delete($),this.#V.delete($);let J=`${$}\x00`;for(let Y of this.#J.keys())if(Y.startsWith(J))this.#J.delete(Y);for(let Y of this.#Y.keys())if(Y.startsWith(J))this.#Y.delete(Y);for(let[Y,X]of this.#Z)if(X.sessionId===$)this.#Z.delete(Y);B1(this.#G,this.#X)}#j($,J){return`${$}\x00${J}`}}import{setBounded as O3,stickyRetryAfterWithJitter as FY}from"@cortexkit/anthropic-auth-core";var O4="cache-diagnosis-2026-04-07",wY="MC-CACHE-DIAG ",TY=1000,EY=300000,SY={turn:!1,start:!0,prewarm_cachekeep:!0},CY=1000;class EJ{entries=new Map;previousFor($){return this.entries.get($)??null}capture($,J,Y){O3(this.entries,$,{messageId:J,receivedAt:Y},TY)}}class SJ{hashes=new Map;capture($,J){if(this.hashes.has($))return null;return O3(this.hashes,$,!0,CY),`MC-CACHE-DIAG-BETAS ${JSON.stringify({hash:$,betas:[...J].sort()})}`}}function e4($,J,Y){let X=$.get(J);if(X)$.set(Y,X)}async function CJ($,J,Y,X,z){let V=new Headers($.headers);if(V.set("retry-after",String(FY(J,Y))),X)return await $.body?.cancel().catch(()=>{}),V.set("content-type","application/json"),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account quota resets shortly; retaining session affinity."}}),{status:429,headers:V});let K=new Response($.body,{status:$.status,statusText:$.statusText,headers:V});return e4(z,$,K),K}function $9($,J){$.diagnostics={previous_message_id:J}}function r$($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function AY($){return r$($)&&$.type==="ephemeral"}function L3($,J){if(!AY($))return;J.push($.ttl==="1h"?"1h":"5m")}function _3($,J){if(!Array.isArray($))return;for(let Y of $)if(r$(Y))L3(Y.cache_control,J)}function J9($){if(!r$($))return null;let J=[];if(L3($.cache_control,J),_3($.system,J),Array.isArray($.messages)){for(let Y of $.messages)if(r$(Y))_3(Y.content,J)}return J.at(-1)??null}function PY($){if(!Object.hasOwn($,"diagnostics"))return{state:"absent"};let J=$.diagnostics;if(J===null)return{state:"server_null"};if(!r$(J))return null;if(!Object.hasOwn(J,"cache_miss_reason"))return null;let Y=J.cache_miss_reason;if(Y===null)return{state:"pending"};if(!r$(Y)||typeof Y.type!=="string"||!Y.type)return null;let X=Y.cache_missed_input_tokens;if(X!==void 0&&typeof X!=="number")return null;return{state:"populated",missReason:Y.type,cacheMissedInputTokens:X}}function _4($,J){let Y=$[J];return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function N3($){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=SY[$.source];if(J!==void 0&&J!==$.synthetic)$.onWarning?.(`cache diagnostics source/synthetic mismatch: source=${$.source} expected=${J} actual=${$.synthetic}`);let Y=Math.trunc($.receivedAt);if(!Number.isFinite($.receivedAt)||Y!==$.receivedAt)return{};if(!r$($.message))return{};let X=$.message.id,z=$.message.model,V=$.message.usage;if(typeof X!=="string"||X.length===0)return{};if(typeof z!=="string"||z.length===0||!r$(V))return{};let K=_4(V,"input_tokens"),D=_4(V,"cache_read_input_tokens"),F=_4(V,"cache_creation_input_tokens"),P=V.cache_creation;if(K===null||D===null||F===null||!r$(P))return{};let q=_4(P,"ephemeral_5m_input_tokens"),x=_4(P,"ephemeral_1h_input_tokens");if(q===null||x===null)return{};let o=PY($.message);if(!o)return{};let i={v:2,source:$.source,account_id:$.accountId,synthetic:$.synthetic,betas_hash:$.betasHash,session_id:$.request.sessionId,ts_ms_received:Y,model:z,is_subagent:$.request.isSubagent,ttl_sent:$.request.ttlSent,cache_read:D,cache_creation:F,input_tokens:K,ephemeral_5m_tokens:q,ephemeral_1h_tokens:x,message_id:X,previous_message_id:$.request.previousMessageId,diag_state:o.state};if(o.missReason!==void 0)i.miss_reason=o.missReason;if(o.cacheMissedInputTokens!==void 0)i.cache_missed_input_tokens=o.cacheMissedInputTokens;if($.requestedModel!==void 0&&$.requestedModel!==z)i.requested_model=$.requestedModel;let O0=o.missReason==="previous_message_not_found"&&$.request.previousMessageId!==null&&$.request.previousMessageReceivedAt!==void 0&&$.receivedAt-$.request.previousMessageReceivedAt<EY&&$.receivedAt>=$.request.previousMessageReceivedAt?{messageId:X,previousMessageId:$.request.previousMessageId}:void 0;return{record:i,messageId:X,...O0?{canary:O0}:{}}}function D3($){return`${wY}${JSON.stringify($)}`}import{getClaustrumMode as Z9,hasNoLocalCredential as AJ,isCustodyTombstoneOAuth as qY,isOAuthAccount as PJ,nativeAccountCanServe as qJ}from"@cortexkit/anthropic-auth-core";function L4($,J){if(Z9(J)!=="claustrum"||!J?.claustrum?.scopedRoster)return!1;let Y=J.accounts.find((X)=>X.id===$);return Boolean(Y&&PJ(Y)&&qJ(Y)&&Y.claustrumScopedCredentialId&&Y.anthropicAccountUuid&&AJ(Y))}function H3($){if(Z9($)!=="claustrum")return{fallbacks:"R",evidence:"V"};if(!$?.claustrum?.scopedRoster)return{fallbacks:"M",evidence:"N"};return{fallbacks:$.accounts.filter((Y)=>qJ(Y)&&PJ(Y)).every((Y)=>Boolean(Y.claustrumScopedCredentialId&&Y.anthropicAccountUuid&&AJ(Y)))?"T":"R",evidence:"V"}}function RJ($){if(qY($,"anthropic"))return"T";if($.type==="oauth"&&$.access&&$.refresh)return"R";return"X"}function MJ($,J){if($.role==="main"){if(Z9(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 qJ(X)?"on-vault-served":"on-cold"}if(Z9(J)!=="claustrum")return"off";let Y=J?.accounts.find((X)=>X.id===$.id);if(!Y||!PJ(Y)||!Y.claustrumScopedCredentialId||!Y.anthropicAccountUuid||!AJ(Y))return"off";if(Y.claustrumScopedState==="needs_reauth")return"on-vault-reauth";return L4($.id,J)?"on-vault-served":"on-cold"}class N4 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 U3($){if($.authority!=="committed"&&$.authority!=="retired")throw new N4("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 N4("FAIL_CLOSED",$)}import{createHash as RY}from"node:crypto";import{defaultAdaptiveEffort as MY,logger as IY,normalizeAdaptiveEffort as xY,pinsEffortOnEveryRequest as Q3,resolveClaudeModelCapabilities as fY,supportsPerMessageEffort as kY}from"@cortexkit/anthropic-auth-core";var E3=512,vY=1024,hY=4096,D4=32,H4=32,X9="[A-Za-z0-9_-]{1,128}",bY="<cortexkit-internal-effort ",gY="<cortexkit-internal-effort-plan ",S3=/^\s*(?:§[0-9]+§\s*)+$/,U4={low:"l",medium:"m",high:"h",xhigh:"x",max:"z"},kJ=Object.fromEntries(Object.entries(U4).map(([$,J])=>[J,$])),vJ="<cortexkit-internal-effort-v2 ",hJ="<cortexkit-internal-effort-anchor-v1 ",b1="x-cortexkit-effort-plan";class E0 extends Error{check;details;constructor($,J="unspecified",Y={}){super($);this.check=J;this.details=Y;this.name="EffortMarkerCorrelationError"}}function o0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function yY($){let J=fY($);if(!J||J.effortMarkers==="none")return;return J.id.replace(/^claude-/,"")}function IJ($){if($?.info?.role!=="user")return;if($.info.model?.providerID!=="anthropic")return;return yY($.info.model.modelID)}function B3($){return xY($.info?.model?.variant)??MY($.info?.model?.modelID)}function F3($){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 y$($){return RY("sha256").update($).digest("hex")}function mY($){return y$(`scope:${$}`).slice(0,H4)}function W9($){return y$(`cortexkit-effort-v2:${$}`).slice(0,D4)}function cY($,J,Y){let X=U4[Y],z=`transition:${$}:${J}:${X}`;return`${vJ}scope="${$}" boundary="${J}" effort="${X}" check="${W9(z)}"/>`}function C3($){let J=$.match(new RegExp(`^${vJ}scope="([0-9a-f]{${H4}})" boundary="(${X9})" effort="([lmhxz])" check="([0-9a-f]{${D4}})"/>$`));if(!J)return null;let[,Y,X,z,V]=J,K=kJ[z??""];if(!Y||!X||!z||!V||!K)return null;let D=`transition:${Y}:${X}:${z}`;if(W9(D)!==V)return null;return{scope:Y,boundary:X,effort:K,token:$}}function pY($,J,Y,X){let z=U4[Y],V=`anchor:${$}:${J}:${z}:${X}`;return`${hJ}scope="${$}" boundary="${J}" effort="${z}" digest="${X}" check="${W9(V)}"/>`}function A3($){let J=$.match(new RegExp(`^${hJ}scope="([0-9a-f]{${H4}})" boundary="(${X9})" effort="([lmhxz])" digest="([0-9a-f]{64})" check="([0-9a-f]{${D4}})"/>$`));if(!J)return null;let[,Y,X,z,V,K]=J,D=kJ[z??""];if(!Y||!X||!z||!V||!K||!D)return null;let F=`anchor:${Y}:${X}:${z}:${V}`;if(W9(F)!==K)return null;return{scope:Y,boundary:X,effort:D,digest:V,token:$}}function xJ($){return $.trim()===""||S3.test($)}function w3(){return new RegExp(`(?:${gY}nonce="[^"]+" baseline="[^"]+" count="[^"]+" sig="[0-9a-f]+"/>|${bY}nonce="[^"]+" effort="[^"]+" sig="[0-9a-f]+"/>)`,"g")}function lY(){return new RegExp(`${vJ}scope="[0-9a-f]{${H4}}" boundary="${X9}" effort="[lmhxz]" check="[0-9a-f]{${D4}}"/>`,"g")}function uY(){return new RegExp(`${hJ}scope="[0-9a-f]{${H4}}" boundary="${X9}" effort="[lmhxz]" digest="[0-9a-f]{64}" check="[0-9a-f]{${D4}}"/>`,"g")}function P3($,J,Y){let X=0,z=$,V=$.replace(w3(),"");if(V!==$&&S3.test(V))X+=[...$.matchAll(w3())].length,z=V;return z=z.replace(lY(),(K)=>{let D=C3(K);if(!D)return K;return J?.(D),X++,""}),z=z.replace(uY(),(K)=>{let D=A3(K);if(!D)return K;return Y?.(D),X++,""}),{text:z,removed:X}}function dY($){for(let J of $){if(!Array.isArray(J.parts))continue;J.parts=J.parts.flatMap((Y)=>{if(Y.type!=="text"||typeof Y.text!=="string"||!Y.text.includes("<cortexkit-internal-effort"))return[Y];let X=P3(Y.text);if(X.removed===0)return[Y];if(xJ(X.text))return[];return Y.text=X.text,[Y]})}}function Y9($,J,Y,X,z){let V=z?`:${z}`:"",K=`plan:${$}:${U4[J]}:${Y.toString(36)}${V}`;return y$([K,...X].join(`
|
|
1
|
+
import{r as Q8}from"./index-sg0knfec.js";import{t as B8}from"./index-hc7bm3yf.js";import{D as F8}from"./index-naff9h33.js";import{H as w8,M as y9,O as T8,P as E8}from"./index-t4aky73k.js";import{ga as Z7}from"./index-gvswxab8.js";import{randomUUID as XZ}from"node:crypto";import{existsSync as UW,readFileSync as QW}from"node:fs";import{dirname as BW,join as FW}from"node:path";import{fileURLToPath as wW}from"node:url";import{ANTHROPIC_OAUTH_ORIGIN_REFUSAL as TW,acquireNativeAccountRuntime as EW,applyCustomHeaders as k7,assertNotCustodyTombstone as SW,authorize as v7,buildAccountList as p$,buildClaudeQuotaSummary as CW,buildFallbackQuotaSummaries as AW,buildPrimeRequestBody as PW,CACHE_KEEP_EXTENDED_TTL_BETA as qW,CacheKeepManager as RW,CacheKeepSessionRegistry as MW,CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS as IW,CLAUDE_HAIKU_4_5_MODEL_ID as h7,CLAUDE_HAIKU_5_5_CONTEXT_WINDOW as xW,CLAUDE_HAIKU_5_5_LONG_CONTEXT_PRICING as T9,CLAUDE_HAIKU_5_5_LONG_CONTEXT_THRESHOLD as fW,CLAUDE_HAIKU_5_5_MAX_OUTPUT_TOKENS as kW,CLAUDE_HAIKU_5_5_MODEL_ID as E9,CLAUDE_HAIKU_5_5_PRICING as S9,CLAUDE_HAIKU_5_5_RELEASE_DATE as vW,CLAUDE_OPUS_5_5_CONTEXT_WINDOW as hW,CLAUDE_OPUS_5_5_MAX_OUTPUT_TOKENS as bW,CLAUDE_OPUS_5_5_MODEL_ID as C9,CLAUDE_OPUS_5_5_PRICING as A9,CLAUDE_OPUS_5_5_RELEASE_DATE as gW,CLAUDE_SONNET_5_5_CONTEXT_WINDOW as yW,CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS as mW,CLAUDE_SONNET_5_5_MODEL_ID as P9,CLAUDE_SONNET_5_5_PRICING as q9,CLAUDE_SONNET_5_5_RELEASE_DATE as cW,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as WZ,computeXxhash64Hex as pW,configuredAnthropicOAuthAccountCount as lW,createEmptyStorage as a$,createNativeUsagePublisher as uW,createProviderErrorResponseScope as R9,createSseFramer as dW,createStickyNoRouteResponse as iW,custodyTombstoneOAuth as GZ,decideOpenCodeStateLayoutOnce as nW,decideStickyQuotaFailure as zZ,decodeSseFrame as oW,detectClaustrumConnection as b7,dumpDirectRequest as M9,dumpResponseArtifact as VZ,effectiveRelayStatus as rW,exchange as KZ,executeAccountCommand as sW,executeCache1hCommand as jZ,executeCacheKeepCommand as aW,executeDumpCommand as g7,executeFastModeCommand as y7,executeKillswitchCommand as m7,executeLaneStartCommand as c7,executeLoggingCommand as p7,executePrimeCommand as tW,executeRoutingCommand as l7,FALLBACK_BACKGROUND_TICK_MS as eW,fallbackAccountUuidForLineage as $2,formatEnrollmentStatus as u7,formatNativeAccountState as _Z,formatOAuthAccountTier as C4,formatQuotaBackoffMessage as d7,formatRefreshBackoffMessage as J2,getAccountStoragePath as Z2,getCache1hMode as A4,getCache1hPersistentMode as P4,getCacheKeepWindow as i7,getClaudeCodeIdentityForVerifiedAccount as Y2,getClaudeModelCatalogue as X2,getClaustrumMode as q4,getDefaultCacheKeepRegistryDirectory as W2,getFallbackReauthLabels as G2,getHostClaustrumEnrollmentPaths as I9,getKillswitchConfig as OZ,getPersistedLogLevel as LZ,getQuotaCheckIntervalMs as n7,getQuotaNextRefreshAt as T1,getRequestGzipLatch as z2,getRequestGzipLatchPath as V2,getRoutingMode as Z1,getScopedQuotaWindowForModel as K2,getThinkingPrefixMismatchBehavior as j2,inspectNativeHostAuthEntry as _2,isApiKeyAccount as p1,isCache1hEnabled as R4,isCache1hPersistentlyEnabled as x9,isCacheKeepAlways as o7,isCacheKeepHybridActive as r7,isCacheKeepPersistentlyEnabled as O2,isCacheKeepSubagentsEnabled as L2,isClaudeFableOrMythos51Model as N2,isClaudeOpus5Model as D2,isClaudeOpus55Model as H2,isCostZeroingEnabled as U2,isCustodyTombstoneOAuth as NZ,isDumpPersistentlyEnabled as DZ,isFastModeEnabled as HZ,isFastModePersistentlyEnabled as UZ,isFastModeSupportedModel as s7,isKillswitchEnabled as t$,isNativeTransientAccountError as E1,isOAuthAccount as w0,isPermanentRefreshError as e$,isPrimePersistentlyEnabled as f9,isQuotaBearingHeaderFrame as Q2,isValidApiBaseURL as QZ,killswitchPassesPolicy as $1,killswitchRetryAfterSeconds as a7,log as l$,logger as b,mergeAnthropicBetas as t7,mergeHeaderQuotaForPersistence as e7,NativeCustodyError as B2,NativeRuntimeError as F2,NativeVaultNoAccountError as BZ,nativeAccountCanServe as m0,nativeLocalQuotaLineage as w2,nativeMigrationAuthorityPhase as $8,normalizeQuotaHeaders as T2,oauthProfileIsFresh as k9,oauthProfileMatchesIdentity as E2,PARALLEL_TOOL_CALLS_SYSTEM_PROMPT as S2,PrimeManager as C2,parseAccountCommandAction as A2,parseCache1hCommandAction as P2,parseCacheKeepCommandAction as q2,parseDumpCommandAction as R2,parseFastModeCommandAction as M2,parseLaneStartCommandAction as I2,parseLoggingCommandAction as x2,parsePrimeCommandAction as f2,parseRoutingCommandAction as k2,parseSseFrame as v2,QUOTA_HEADER_FEED_SCHEMA_VERSION as v9,QuotaHeaderFeedRegistry as h2,QuotaManager as b2,quotaSnapshotCheckedAt as S1,quotaSnapshotHasStandardWindows as FZ,quotaSnapshotModelScopeIsExhausted as h9,quotaSnapshotPassesModelScope as b9,quotaSnapshotPassesPolicy as l1,readClaustrumEnrollmentStatus as J8,readNativeAccountsForRequest as g2,readNativeEnrollmentMode as C1,readNativeHostAuthKind as y2,readNativeMigrationJournal as Z8,refreshBackoffActive as A1,remapRequestBodyModel as m2,resetClaustrumEnrollmentState as c2,resolveClaudeModelCapabilities as p2,resolveNativePoolPaths as l2,STICKY_ROUTING_MAIN_ACCOUNT_ID as $$,StickySessionRouter as u2,sendViaRelay as d2,sendWithRequestGzip as i2,setCache1hState as g9,setDumpEnabled as wZ,setFastModeEnabled as TZ,setLogLevel as n2,shouldFallbackStatus as o2,snapshotHasServableLocalOAuth as Y8,stateRefusalPublicMessage as r2,stickyQuotaSnapshotIsFresh as P1,stickyRouteFamilyForModel as s2,TrailingAssistantHistoryError as X8,tokenFingerprint as J1}from"@cortexkit/anthropic-auth-core";import{randomUUID as V3}from"node:crypto";import{isValidAnthropicRequestId as K3,isValidBillingPromptId as LY}from"@cortexkit/anthropic-auth-core";var j4="x-cortexkit-billing-lineage",NY=4096,DY=4096,HY=1024,j3=new Set(["title","summary","compaction"]),UY="[lane start] — automated cache warm; no response needed.";function QY($){let J=$.info?.sessionID??$.info?.sessionId;return typeof J==="string"&&J.length>0?J:void 0}function BY($){if($.info?.synthetic===!0||$.info?.ignored===!0||typeof $.info?.agent==="string"&&j3.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===UY)return!0}return!1}function B1($,J){while($.size>J){let Y=$.keys().next().value;if(Y===void 0)return;$.delete(Y)}}function wJ($){let J=$.get("request-id")??$.get("x-request-id");return J&&K3(J)?J:void 0}class TJ{#$;#_;#K;#O;#X;#J=new Map;#Y=new Map;#Z=new Map;#W=new Map;#G=new Map;#z=new Map;#V=new Map;constructor($={}){this.#$=$.createPromptId??V3,this.#_=$.createRequestToken??V3,this.#K=$.maxPrompts??NY,this.#O=$.maxRequests??DY,this.#X=$.maxSessions??HY}observeMessages($){let J;for(let D=$.length-1;D>=0;D-=1)if($[D]?.info?.role==="user"){J=$[D];break}if(!J)return;let Y=QY(J),X=J.info?.id;if(!Y||typeof X!=="string"||X.length===0)return;let z=this.#j(Y,X);if(BY(J)){this.#Y.delete(z),this.#Y.set(z,!0),B1(this.#Y,this.#K),this.#J.delete(z);return}this.#Y.delete(z);let V=this.#J.get(z);if(V){this.#J.delete(z),this.#J.set(z,V);return}let K=this.#$();if(!LY(K))return;this.#J.set(z,K),B1(this.#J,this.#K)}markHeaders($){let J=this.#j($.sessionId,$.messageId);if(j3.has($.agent??"")||this.#Y.has(J))return!1;let Y=this.#J.get(J);if(!Y)return!1;let X=this.#_();if(!X||/[\r\n]/.test(X))return!1;let z={sessionId:$.sessionId,messageId:$.messageId,promptId:Y,requestToken:X,generation:this.#G.get($.sessionId)??0,sequence:0};return this.#Z.set(X,z),B1(this.#Z,this.#O),$.headers[j4]=X,!0}resolveHeader($){if(!$)return;let J=this.#Z.get($);if(!J)return;this.#Z.delete($),this.#Z.set($,J);let Y=(this.#z.get(J.sessionId)??0)+1;this.#z.delete(J.sessionId),this.#z.set(J.sessionId,Y),B1(this.#z,this.#X);let X={...J,previousRequestId:this.#W.get(J.sessionId),sequence:Y};if(X.previousRequestId===void 0)delete X.previousRequestId;return X}commit($,J){if(!$||!J||!K3(J))return!1;if((this.#G.get($.sessionId)??0)!==$.generation)return!1;let Y=this.#Z.get($.requestToken);if(!Y||Y.sessionId!==$.sessionId||Y.messageId!==$.messageId||Y.promptId!==$.promptId||Y.generation!==$.generation)return!1;if(this.#J.get(this.#j($.sessionId,$.messageId))!==$.promptId)return!1;if($.sequence<(this.#V.get($.sessionId)??0))return!1;return this.#V.delete($.sessionId),this.#V.set($.sessionId,$.sequence),B1(this.#V,this.#X),this.#W.delete($.sessionId),this.#W.set($.sessionId,J),B1(this.#W,this.#X),!0}clearSession($){this.#G.set($,(this.#G.get($)??0)+1),this.#W.delete($),this.#z.delete($),this.#V.delete($);let J=`${$}\x00`;for(let Y of this.#J.keys())if(Y.startsWith(J))this.#J.delete(Y);for(let Y of this.#Y.keys())if(Y.startsWith(J))this.#Y.delete(Y);for(let[Y,X]of this.#Z)if(X.sessionId===$)this.#Z.delete(Y);B1(this.#G,this.#X)}#j($,J){return`${$}\x00${J}`}}import{setBounded as O3,stickyRetryAfterWithJitter as FY}from"@cortexkit/anthropic-auth-core";var O4="cache-diagnosis-2026-04-07",wY="MC-CACHE-DIAG ",TY=1000,EY=300000,SY={turn:!1,start:!0,prewarm_cachekeep:!0},CY=1000;class EJ{entries=new Map;previousFor($){return this.entries.get($)??null}capture($,J,Y){O3(this.entries,$,{messageId:J,receivedAt:Y},TY)}}class SJ{hashes=new Map;capture($,J){if(this.hashes.has($))return null;return O3(this.hashes,$,!0,CY),`MC-CACHE-DIAG-BETAS ${JSON.stringify({hash:$,betas:[...J].sort()})}`}}function e4($,J,Y){let X=$.get(J);if(X)$.set(Y,X)}async function CJ($,J,Y,X,z){let V=new Headers($.headers);if(V.set("retry-after",String(FY(J,Y))),X)return await $.body?.cancel().catch(()=>{}),V.set("content-type","application/json"),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account quota resets shortly; retaining session affinity."}}),{status:429,headers:V});let K=new Response($.body,{status:$.status,statusText:$.statusText,headers:V});return e4(z,$,K),K}function $9($,J){$.diagnostics={previous_message_id:J}}function r$($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function AY($){return r$($)&&$.type==="ephemeral"}function L3($,J){if(!AY($))return;J.push($.ttl==="1h"?"1h":"5m")}function _3($,J){if(!Array.isArray($))return;for(let Y of $)if(r$(Y))L3(Y.cache_control,J)}function J9($){if(!r$($))return null;let J=[];if(L3($.cache_control,J),_3($.system,J),Array.isArray($.messages)){for(let Y of $.messages)if(r$(Y))_3(Y.content,J)}return J.at(-1)??null}function PY($){if(!Object.hasOwn($,"diagnostics"))return{state:"absent"};let J=$.diagnostics;if(J===null)return{state:"server_null"};if(!r$(J))return null;if(!Object.hasOwn(J,"cache_miss_reason"))return null;let Y=J.cache_miss_reason;if(Y===null)return{state:"pending"};if(!r$(Y)||typeof Y.type!=="string"||!Y.type)return null;let X=Y.cache_missed_input_tokens;if(X!==void 0&&typeof X!=="number")return null;return{state:"populated",missReason:Y.type,cacheMissedInputTokens:X}}function _4($,J){let Y=$[J];return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function N3($){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=SY[$.source];if(J!==void 0&&J!==$.synthetic)$.onWarning?.(`cache diagnostics source/synthetic mismatch: source=${$.source} expected=${J} actual=${$.synthetic}`);let Y=Math.trunc($.receivedAt);if(!Number.isFinite($.receivedAt)||Y!==$.receivedAt)return{};if(!r$($.message))return{};let X=$.message.id,z=$.message.model,V=$.message.usage;if(typeof X!=="string"||X.length===0)return{};if(typeof z!=="string"||z.length===0||!r$(V))return{};let K=_4(V,"input_tokens"),D=_4(V,"cache_read_input_tokens"),F=_4(V,"cache_creation_input_tokens"),P=V.cache_creation;if(K===null||D===null||F===null||!r$(P))return{};let q=_4(P,"ephemeral_5m_input_tokens"),x=_4(P,"ephemeral_1h_input_tokens");if(q===null||x===null)return{};let o=PY($.message);if(!o)return{};let i={v:2,source:$.source,account_id:$.accountId,synthetic:$.synthetic,betas_hash:$.betasHash,session_id:$.request.sessionId,ts_ms_received:Y,model:z,is_subagent:$.request.isSubagent,ttl_sent:$.request.ttlSent,cache_read:D,cache_creation:F,input_tokens:K,ephemeral_5m_tokens:q,ephemeral_1h_tokens:x,message_id:X,previous_message_id:$.request.previousMessageId,diag_state:o.state};if(o.missReason!==void 0)i.miss_reason=o.missReason;if(o.cacheMissedInputTokens!==void 0)i.cache_missed_input_tokens=o.cacheMissedInputTokens;if($.requestedModel!==void 0&&$.requestedModel!==z)i.requested_model=$.requestedModel;let O0=o.missReason==="previous_message_not_found"&&$.request.previousMessageId!==null&&$.request.previousMessageReceivedAt!==void 0&&$.receivedAt-$.request.previousMessageReceivedAt<EY&&$.receivedAt>=$.request.previousMessageReceivedAt?{messageId:X,previousMessageId:$.request.previousMessageId}:void 0;return{record:i,messageId:X,...O0?{canary:O0}:{}}}function D3($){return`${wY}${JSON.stringify($)}`}import{getClaustrumMode as Z9,hasNoLocalCredential as AJ,isCustodyTombstoneOAuth as qY,isOAuthAccount as PJ,nativeAccountCanServe as qJ}from"@cortexkit/anthropic-auth-core";function L4($,J){if(Z9(J)!=="claustrum"||!J?.claustrum?.scopedRoster)return!1;let Y=J.accounts.find((X)=>X.id===$);return Boolean(Y&&PJ(Y)&&qJ(Y)&&Y.claustrumScopedCredentialId&&Y.anthropicAccountUuid&&AJ(Y))}function H3($){if(Z9($)!=="claustrum")return{fallbacks:"R",evidence:"V"};if(!$?.claustrum?.scopedRoster)return{fallbacks:"M",evidence:"N"};return{fallbacks:$.accounts.filter((Y)=>qJ(Y)&&PJ(Y)).every((Y)=>Boolean(Y.claustrumScopedCredentialId&&Y.anthropicAccountUuid&&AJ(Y)))?"T":"R",evidence:"V"}}function RJ($){if(qY($,"anthropic"))return"T";if($.type==="oauth"&&$.access&&$.refresh)return"R";return"X"}function MJ($,J){if($.role==="main"){if(Z9(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 qJ(X)?"on-vault-served":"on-cold"}if(Z9(J)!=="claustrum")return"off";let Y=J?.accounts.find((X)=>X.id===$.id);if(!Y||!PJ(Y)||!Y.claustrumScopedCredentialId||!Y.anthropicAccountUuid||!AJ(Y))return"off";if(Y.claustrumScopedState==="needs_reauth")return"on-vault-reauth";return L4($.id,J)?"on-vault-served":"on-cold"}class N4 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 U3($){if($.authority!=="committed"&&$.authority!=="retired")throw new N4("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 N4("FAIL_CLOSED",$)}import{createHash as RY}from"node:crypto";import{defaultAdaptiveEffort as MY,logger as IY,normalizeAdaptiveEffort as xY,pinsEffortOnEveryRequest as Q3,resolveClaudeModelCapabilities as fY,supportsPerMessageEffort as kY}from"@cortexkit/anthropic-auth-core";var E3=512,vY=1024,hY=4096,D4=32,H4=32,X9="[A-Za-z0-9_-]{1,128}",bY="<cortexkit-internal-effort ",gY="<cortexkit-internal-effort-plan ",S3=/^\s*(?:§[0-9]+§\s*)+$/,U4={low:"l",medium:"m",high:"h",xhigh:"x",max:"z"},kJ=Object.fromEntries(Object.entries(U4).map(([$,J])=>[J,$])),vJ="<cortexkit-internal-effort-v2 ",hJ="<cortexkit-internal-effort-anchor-v1 ",b1="x-cortexkit-effort-plan";class E0 extends Error{check;details;constructor($,J="unspecified",Y={}){super($);this.check=J;this.details=Y;this.name="EffortMarkerCorrelationError"}}function o0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function yY($){let J=fY($);if(!J||J.effortMarkers==="none")return;return J.id.replace(/^claude-/,"")}function IJ($){if($?.info?.role!=="user")return;if($.info.model?.providerID!=="anthropic")return;return yY($.info.model.modelID)}function B3($){return xY($.info?.model?.variant)??MY($.info?.model?.modelID)}function F3($){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 y$($){return RY("sha256").update($).digest("hex")}function mY($){return y$(`scope:${$}`).slice(0,H4)}function W9($){return y$(`cortexkit-effort-v2:${$}`).slice(0,D4)}function cY($,J,Y){let X=U4[Y],z=`transition:${$}:${J}:${X}`;return`${vJ}scope="${$}" boundary="${J}" effort="${X}" check="${W9(z)}"/>`}function C3($){let J=$.match(new RegExp(`^${vJ}scope="([0-9a-f]{${H4}})" boundary="(${X9})" effort="([lmhxz])" check="([0-9a-f]{${D4}})"/>$`));if(!J)return null;let[,Y,X,z,V]=J,K=kJ[z??""];if(!Y||!X||!z||!V||!K)return null;let D=`transition:${Y}:${X}:${z}`;if(W9(D)!==V)return null;return{scope:Y,boundary:X,effort:K,token:$}}function pY($,J,Y,X){let z=U4[Y],V=`anchor:${$}:${J}:${z}:${X}`;return`${hJ}scope="${$}" boundary="${J}" effort="${z}" digest="${X}" check="${W9(V)}"/>`}function A3($){let J=$.match(new RegExp(`^${hJ}scope="([0-9a-f]{${H4}})" boundary="(${X9})" effort="([lmhxz])" digest="([0-9a-f]{64})" check="([0-9a-f]{${D4}})"/>$`));if(!J)return null;let[,Y,X,z,V,K]=J,D=kJ[z??""];if(!Y||!X||!z||!V||!K||!D)return null;let F=`anchor:${Y}:${X}:${z}:${V}`;if(W9(F)!==K)return null;return{scope:Y,boundary:X,effort:D,digest:V,token:$}}function xJ($){return $.trim()===""||S3.test($)}function w3(){return new RegExp(`(?:${gY}nonce="[^"]+" baseline="[^"]+" count="[^"]+" sig="[0-9a-f]+"/>|${bY}nonce="[^"]+" effort="[^"]+" sig="[0-9a-f]+"/>)`,"g")}function lY(){return new RegExp(`${vJ}scope="[0-9a-f]{${H4}}" boundary="${X9}" effort="[lmhxz]" check="[0-9a-f]{${D4}}"/>`,"g")}function uY(){return new RegExp(`${hJ}scope="[0-9a-f]{${H4}}" boundary="${X9}" effort="[lmhxz]" digest="[0-9a-f]{64}" check="[0-9a-f]{${D4}}"/>`,"g")}function P3($,J,Y){let X=0,z=$,V=$.replace(w3(),"");if(V!==$&&S3.test(V))X+=[...$.matchAll(w3())].length,z=V;return z=z.replace(lY(),(K)=>{let D=C3(K);if(!D)return K;return J?.(D),X++,""}),z=z.replace(uY(),(K)=>{let D=A3(K);if(!D)return K;return Y?.(D),X++,""}),{text:z,removed:X}}function dY($){for(let J of $){if(!Array.isArray(J.parts))continue;J.parts=J.parts.flatMap((Y)=>{if(Y.type!=="text"||typeof Y.text!=="string"||!Y.text.includes("<cortexkit-internal-effort"))return[Y];let X=P3(Y.text);if(X.removed===0)return[Y];if(xJ(X.text))return[];return Y.text=X.text,[Y]})}}function Y9($,J,Y,X,z){let V=z?`:${z}`:"",K=`plan:${$}:${U4[J]}:${Y.toString(36)}${V}`;return y$([K,...X].join(`
|
|
2
2
|
`))}function iY($){return["v2",$.scope,U4[$.baseline],$.markerCount.toString(36),$.digest].join(".")}function nY($){if(!$)return null;let J=$.match(/^v2\.([0-9a-f]{32})\.([lmhxz])\.([0-9a-z]+)\.([0-9a-f]{64})$/);if(!J)return null;let[,Y,X,z,V]=J,K=kJ[X??""],D=Number.parseInt(z??"",36);if(!Y||!K||!V||!Number.isSafeInteger(D)||D<0||D>E3)return null;return{scope:Y,baseline:K,markerCount:D,digest:V}}function q3($){let J=$.findLast((i)=>i.info?.role==="user"),Y=IJ(J);if(!J||!Y)return null;if(dY($),!Array.isArray(J.parts)||!F3(J))return null;let X=J.info?.sessionID,z=J.info?.id;if(typeof X!=="string"||typeof z!=="string")throw new E0("Cannot correlate per-message effort markers without session and message IDs");let V=mY(X),K=$.findLast((i)=>i.info?.role==="user"&&i.parts?.some((O0)=>O0.type==="compaction")),D=typeof K?.info?.id==="string"?K.info.id:void 0,F,P;if(K&&IJ(K)===Y)F=B3(K),P=F;let q=[];for(let i of $){let O0=i.info;if(O0?.role!=="user")continue;if(D&&typeof O0.id==="string"&&O0.id<=D)continue;if(IJ(i)!==Y||!F3(i))continue;let g=B3(i);if(!F){F=g,P=g;continue}if(g===P)continue;if(q.length>=E3)throw new E0("Too many per-message effort changes in the active context");if(!Array.isArray(i.parts)||typeof O0.id!=="string")throw new E0("Cannot mark a per-message effort change without message identity");let z0=cY(V,O0.id,g);i.parts.push({type:"text",text:z0}),q.push(z0),P=g}if(!F)return null;let x=Y9(V,F,q.length,q,q.length>0?z:void 0),o=q.length>0?pY(V,z,P??F,x):void 0;if(o)J.parts.push({type:"text",text:o});return{scope:V,baseline:F,markerCount:q.length,digest:x,transitionTokens:q,anchorToken:o,sessionId:X,messageId:z}}function oY($){let J=Array.isArray($.messages)?$.messages:[],Y=[];for(let X of J){let z=[],V=[];if(!o0(X)||X.role!=="user"){Y.push({value:X,transitions:z,anchors:V});continue}let K=(D)=>P3(D,(F)=>z.push(F),(F)=>V.push(F));if(typeof X.content==="string"){let D=K(X.content);X.content=D.removed>0&&xJ(D.text)?"":D.text}else if(Array.isArray(X.content))X.content=X.content.flatMap((D)=>{if(!o0(D)||D.type!=="text"||typeof D.text!=="string")return[D];let F=K(D.text);if(F.removed>0&&xJ(F.text))return[];return[{...D,text:F.text}]});Y.push({value:X,transitions:z,anchors:V})}return $.messages=Y.map((X)=>X.value),{messages:Y}}function rY($,J){let Y=$[J]?.value,X=$[J-1]?.value;if(!o0(Y)||Y.role!=="user"||!Array.isArray(Y.content)||Y.content.length===0||!o0(X)||X.role!=="assistant"||!Array.isArray(X.content))return!1;let z=new Set(X.content.flatMap((V)=>o0(V)&&V.type==="tool_use"&&typeof V.id==="string"?[V.id]:[]));return Y.content.every((V)=>o0(V)&&V.type==="tool_result"&&typeof V.tool_use_id==="string"&&z.has(V.tool_use_id))}function sY($,J){if(J<0)return!1;let Y=$.flatMap((X,z)=>z>J&&o0(X.value)&&X.value.role==="user"?[z]:[]);return Y.length>0&&Y.every((X)=>rY($,X))}function T3($){if(!o0($))return null;if(typeof $.id==="string")return $.id;return typeof $.message_id==="string"?$.message_id:null}function R3($,J){if(!J)return null;if(J.scope!==$.scope||J.baseline!==$.baseline||J.markerCount!==$.markerCount||J.digest!==$.digest||J.transitionTokens.length!==$.markerCount)throw new E0("Per-message effort marker request plan mismatch");let Y=J.transitionTokens.map((V)=>C3(V)),X=J.anchorToken?A3(J.anchorToken):null,z=Y.at(-1)?.effort??$.baseline;if(Y.some((V)=>V===null)||Y.some((V)=>V?.scope!==$.scope)||$.markerCount>0&&(!X||X.scope!==$.scope||X.boundary!==J.messageId||X.effort!==z||X.digest!==$.digest)||$.markerCount===0&&X!==null||$.digest!==Y9($.scope,$.baseline,$.markerCount,J.transitionTokens,J.markerCount>0?J.messageId:void 0))throw new E0("Per-message effort marker request plan mismatch");return{transitions:Y,anchor:X}}function fJ($,J,Y,X){let z=Y.flatMap((x)=>x.transitions),V=z.length,K=$.length-V;if(K<0)throw new E0(`Per-message effort marker correlation failed: expected ${$.length}, found ${V}`);let D=$.slice(K);if(z.some((x,o)=>x.token!==D[o]?.token))throw new E0("Per-message effort marker non-prefix loss");let F=$.slice(0,K);if(X&&F.some((x)=>x.boundary===X.boundary))throw new E0("Per-message effort marker non-prefix loss");let P=[],q=0;return Y.forEach((x,o)=>{if(x.transitions.length===0)return;q+=x.transitions.length,P.push(`${o}:${D[q-1]?.effort}`)}),{effectiveBaseline:F.at(-1)?.effort??J,systemMarkers:P}}function aY($,J){let[Y,X]=$.transitions.length>=J.transitions.length?[$,J]:[J,$],z=Y.transitions.length-X.transitions.length;if(X.transitions.some((K,D)=>K.token!==Y.transitions[z+D]?.token))return!1;let V=z>0?Y.transitions[z-1]?.effort:Y.baseline;return X.baseline===V}function tY($){let{anchor:J,headerPlan:Y,headerAnchor:X}=$;if($.anchorCount!==1||J.scope!==X.scope||J.boundary!==X.boundary)return null;let z=$.recordedVersions.find((V)=>V.sessionId===Y.sessionId&&V.messageId===Y.messageId&&V.digest!==Y.digest&&V.anchorToken===J.token);if(!z)return null;try{let V=R3({scope:z.scope,baseline:z.baseline,markerCount:z.markerCount,digest:z.digest},z);if(!V?.anchor||V.anchor.token!==J.token||V.anchor.effort!==X.effort||!aY({baseline:Y.baseline,transitions:$.headerTransitions},{baseline:z.baseline,transitions:V.transitions}))return null;let K=fJ($.headerTransitions,Y.baseline,$.messages,J),D=fJ(V.transitions,z.baseline,$.messages,J);if(K.effectiveBaseline!==D.effectiveBaseline||K.systemMarkers.join(`
|
|
3
3
|
`)!==D.systemMarkers.join(`
|
|
4
4
|
`))return null}catch(V){if(V instanceof E0)return null;throw V}return z}function M3($,J,Y,X,z=[]){if(!Array.isArray($.messages))return{found:0,inserted:0};let V=nY(Y);if(Y&&!V)throw new E0("Missing or invalid internal per-message effort request plan");let K=V?R3(V,X):null,D=K?.transitions??null;if(!$.messages.some((u)=>{if(!o0(u)||u.role!=="user")return!1;if(typeof u.content==="string"&&u.content.includes("<cortexkit-internal-effort"))return!0;return Array.isArray(u.content)&&u.content.some((q0)=>o0(q0)&&q0.type==="text"&&typeof q0.text==="string"&&q0.text.includes("<cortexkit-internal-effort"))})){if(!V)return{found:0,inserted:0};if(V.markerCount!==0){let u=$.messages.findLastIndex((M0)=>o0(M0)&&M0.role==="user"),q0=$.messages[u],J$=o0(q0)&&Array.isArray(q0.content)?q0.content:[];throw new E0(`Per-message effort marker correlation failed: expected ${V.markerCount}, found 0`,"missing_all_markers",{markerCount:V.markerCount,resolvedPlan:K!==null,plannedBoundaryId:K?.anchor?.boundary??null,expectedAnchorHash:K?.anchor?y$(K.anchor.token):null,retainedMessageCount:$.messages.length,retainedUserMessageCount:$.messages.filter((M0)=>o0(M0)&&M0.role==="user").length,lastUserMessageIndex:u,lastUserTextBlockCount:J$.filter((M0)=>o0(M0)&&M0.type==="text").length,lastUserToolResultBlockCount:J$.filter((M0)=>o0(M0)&&M0.type==="tool_result").length})}if(!D&&V.digest!==Y9(V.scope,V.baseline,0,[]))throw new E0("Per-message effort marker request plan mismatch");if(J&&Q3($.model)){let u=o0($.output_config)?{...$.output_config}:{};u.effort=D?.at(-1)?.effort??V.baseline,$.output_config=u}return{found:0,inserted:0}}let P=oY($),q=P.messages.flatMap((u)=>u.transitions),x=P.messages.flatMap((u)=>u.anchors),o=q.length;if(!V){if(o===0)return{found:0,inserted:0};throw new E0("Missing or invalid internal per-message effort request plan")}for(let u of P.messages){for(let q0 of u.transitions)if(q0.scope!==V.scope)throw new E0("Per-message effort marker scope mismatch");if(u.anchors.length>1)throw new E0("Multiple internal per-message effort anchors on one user boundary")}let i=P.messages.findIndex((u)=>u.anchors.length===1),O0=P.messages.findLastIndex((u)=>o0(u.value)&&u.value.role==="user"),g=x[0],z0=P.messages[O0]?.value,S=sY(P.messages,i);if(V.markerCount>0&&(x.length!==1||i!==O0&&!S||!g||g.scope!==V.scope))throw new E0("Missing or invalid internal per-message effort anchor placement","anchor_placement",{anchorBoundaryId:g?.boundary??null,plannedBoundaryId:K?.anchor?.boundary??null,lastUserMessageId:T3(z0),anchorMessageIndex:i,lastUserMessageIndex:O0,validToolContinuationSuffix:S,anchorsFound:x.length,markerCount:V.markerCount,scope:V.scope,foundScope:g?.scope??null,expectedAnchorHash:K?.anchor?y$(K.anchor.token):null,foundAnchorHash:g?y$(g.token):null,anchorMatchesExpected:K?.anchor!=null&&g?.token===K.anchor.token});if(V.markerCount===0&&x.length!==0)throw new E0("Unexpected internal per-message effort anchor");if(K?.anchor&&g?.token!==K.anchor.token){let u=g&&X&&D?tY({anchor:g,anchorCount:x.length,headerPlan:X,headerTransitions:D,headerAnchor:K.anchor,recordedVersions:z,messages:P.messages}):null;if(!u)throw new E0("Mismatched internal per-message effort anchor token","anchor_token",{anchorBoundaryId:g?.boundary??null,plannedBoundaryId:K.anchor.boundary,lastUserMessageId:T3(z0),anchorMessageIndex:i,lastUserMessageIndex:O0,anchorsFound:x.length,markerCount:V.markerCount,scope:V.scope,foundScope:g?.scope??null,expectedAnchorHash:y$(K.anchor.token),foundAnchorHash:g?y$(g.token):null,anchorMatchesExpected:!1});IY.warn("effort-history","accepted an earlier effort anchor whose plan gives the same efforts",{check:"anchor_token_equivalent_plan",plannedBoundaryId:K.anchor.boundary,markerCount:V.markerCount,foundPlanMarkerCount:u.markerCount,markersFound:o,expectedAnchorHash:y$(K.anchor.token),foundAnchorHash:g?y$(g.token):null})}let t=V.baseline;if(D)t=fJ(D,V.baseline,P.messages,g).effectiveBaseline;else{if(o!==V.markerCount)throw new E0(`Per-message effort marker correlation failed: expected ${V.markerCount}, found ${o}`);let u=Y9(V.scope,V.baseline,V.markerCount,q.map((J$)=>J$.token),g?.boundary);if(V.digest!==u)throw new E0("Per-message effort marker request plan mismatch");let q0=q.at(-1)?.effort??V.baseline;if(g&&(g.effort!==q0||g.digest!==V.digest))throw new E0("Missing or invalid internal per-message effort anchor")}let x0=J&&kY($),_0=0,U0=[];for(let u of P.messages){let q0=u.transitions.at(-1);if(q0&&x0)U0.push({role:"system",content:[],output_config:{effort:q0.effort}}),_0++;U0.push(u.value)}if($.messages=U0,x0&&(_0>0||Q3($.model))){let u=o0($.output_config)?{...$.output_config}:{};u.effort=t,$.output_config=u}return{found:o,inserted:_0}}class bJ{plans=new Map;history=new Map;historyByMessage=new Map;record($){let J=this.key($.sessionId,$.messageId),Y={...$,transitionTokens:[...$.transitionTokens]};this.remember(J,Y),this.plans.delete(J),this.plans.set(J,Y);while(this.plans.size>vY){let X=this.plans.keys().next().value;if(typeof X!=="string")break;this.plans.delete(X)}}clear($,J){let Y=this.key($,J);this.plans.delete(Y);for(let X of this.historyByMessage.get(Y)??[])this.history.delete(X);this.historyByMessage.delete(Y)}markHeaders($){let J=this.key($.sessionId,$.messageId),Y=this.plans.get(J);if(!Y)return!1;return $.headers[b1]=this.remember(J,Y),this.plans.delete(J),this.plans.set(J,Y),!0}resolveHeader($){return $?this.history.get($):void 0}versionsFor($,J){return[...this.historyByMessage.get(this.key($,J))??[]].flatMap((X)=>{let z=this.history.get(X);return z?[z]:[]})}remember($,J){let Y=iY(J),X=this.history.get(Y);if(X&&this.key(X.sessionId,X.messageId)!==$){if(X.markerCount!==0||J.markerCount!==0||X.sessionId!==J.sessionId)throw new E0("Per-message effort plan header collision");let V=this.key(X.sessionId,X.messageId),K=this.historyByMessage.get(V);if(K?.delete(Y),K?.size===0)this.historyByMessage.delete(V)}this.history.delete(Y),this.history.set(Y,J);let z=this.historyByMessage.get($)??new Set;z.add(Y),this.historyByMessage.set($,z);while(this.history.size>hY){let V=this.history.entries().next().value;if(!V)break;let[K,D]=V;this.history.delete(K);let F=this.key(D.sessionId,D.messageId),P=this.historyByMessage.get(F);if(P?.delete(K),P?.size===0)this.historyByMessage.delete(F)}return Y}key($,J){return`${$}\x00${J}`}}import{resolveClaudeModelCapabilities as eY}from"@cortexkit/anthropic-auth-core";var I3="claude-opus-4-8",gJ=10,x3=128,$5=86400000;function m$($){return eY($)?.refusalRecoveryFamily??null}function G9($){return m$($)!==null}function J5($,J){let Y=m$(J);return Y?`${$}\x00${Y}`:null}function Z5($){try{let J=JSON.parse($);return typeof J.model==="string"?{body:J,model:J.model}:null}catch{return null}}class yJ{now;recoveries=new Map;selectedModels=new Map;nextCycle=1;constructor($=Date.now){this.now=$}prune(){let $=this.now();for(let[J,Y]of this.recoveries)if($-Y.updatedAt>=$5)this.recoveries.delete(J);while(this.recoveries.size>x3){let J=this.recoveries.keys().next().value;if(typeof J!=="string")break;this.recoveries.delete(J)}}clearSession($){this.selectedModels.delete($);for(let J of this.recoveries.keys())if(J.startsWith(`${$}\x00`))this.recoveries.delete(J)}resetForModelChange($,J){let Y=this.selectedModels.get($),X=Y!==void 0&&Y!==J;if(X)this.clearSession($);this.selectedModels.delete($),this.selectedModels.set($,J);while(this.selectedModels.size>x3){let z=this.selectedModels.keys().next().value;if(z===void 0)break;this.selectedModels.delete(z)}return X}plan($,J){if(!$||typeof J!=="string")return null;this.prune();for(let[V,K]of[...this.recoveries]){if(!V.startsWith(`${$}\x00`))continue;K.updatedAt=this.now(),this.recoveries.delete(V),this.recoveries.set(V,K)}let Y=Z5(J);if(!Y||!G9(Y.model))return null;let X=J5($,Y.model);if(!X)return null;let z=this.recoveries.get(X);if(z)z.nextRequestSequence++;if(!z||z.remaining<=0)return{sessionId:$,recoveryKey:X,requestedModel:Y.model,effectiveModel:Y.model,bodyText:J,downgraded:!1,cycle:z?.cycle,standbyCacheAnchor:z?.standbyCacheAnchor};return z.updatedAt=this.now(),this.recoveries.delete(X),this.recoveries.set(X,z),Y.body.model=I3,{sessionId:$,recoveryKey:X,requestedModel:z.model,effectiveModel:I3,bodyText:JSON.stringify(Y.body),downgraded:!0,cycle:z.cycle,cacheAccountId:z.cacheAccountId,standbyCacheAnchor:z.standbyCacheAnchor,requestSequence:z.nextRequestSequence}}recoveryAccount($){if($.cycle===void 0)return $.cacheAccountId;let J=this.recoveries.get($.recoveryKey);return J?.cycle===$.cycle?J.cacheAccountId:$.cacheAccountId}bindRecoveryAccount($,J){if(!$.downgraded||$.cycle===void 0)return!1;let Y=this.recoveries.get($.recoveryKey);if(!Y||Y.cycle!==$.cycle)return!1;if(Y.cacheAccountId===J)return!1;return Y.cacheAccountId=J,Y.standbyCacheAnchor=void 0,Y.standbyAnchorSequence=0,Y.updatedAt=this.now(),$.cacheAccountId=J,$.standbyCacheAnchor=void 0,!0}activate($,J){if($.downgraded||!G9($.requestedModel))return this.remaining($);let Y=this.recoveries.get($.recoveryKey),X=Y&&Y.sourceSuccesses<gJ?Y.reRefusals+1:0,z={model:$.requestedModel,remaining:gJ*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,z),this.prune(),z.remaining}completeSource($,J=!0){if($.downgraded||$.cycle==null||$.completed)return!1;$.completed=!0;let Y=this.recoveries.get($.recoveryKey);if(!Y||Y.cycle!==$.cycle||Y.remaining>0)return!1;if(!J)return Y.sourceSuccesses=0,!1;return Y.sourceSuccesses=Math.min(Y.sourceSuccesses+1,gJ),Y.updatedAt=this.now(),!0}complete($,J){if(!$.downgraded||$.cycle==null||$.completed)return{counted:!1,remaining:this.remaining($)};$.completed=!0;let Y=this.recoveries.get($.recoveryKey);if(!Y||Y.cycle!==$.cycle||Y.remaining<=0)return{counted:!1,remaining:Y?.remaining??0};if(Y.remaining--,J&&(!Y.cacheAccountId||J.oauthAccountId===Y.cacheAccountId)&&$.requestSequence!=null&&$.requestSequence>=Y.standbyAnchorSequence)Y.standbyCacheAnchor=J,Y.standbyAnchorSequence=$.requestSequence;return Y.updatedAt=this.now(),this.recoveries.delete($.recoveryKey),this.recoveries.set($.recoveryKey,Y),{counted:!0,remaining:Y.remaining}}remaining($){return this.prune(),this.recoveries.get($.recoveryKey)?.remaining??0}}function s$($){return typeof $==="object"&&$!==null}function Y5($){if(Array.isArray($))return $;if(s$($)&&Array.isArray($.data))return $.data;return[]}function v3($){if(!s$($)||!s$($.info))return;return $.info}function f3($){let J=v3($);return typeof J?.role==="string"?J.role:void 0}function X5($){let J=v3($);return typeof J?.id==="string"?J.id:void 0}function mJ($){if(!s$($)||!s$($.info))return null;let J=$.info,Y=s$(J.model)?J.model:void 0,X=typeof J.agent==="string"?J.agent:void 0,z=typeof Y?.providerID==="string"?Y.providerID:typeof J.providerID==="string"?J.providerID:void 0,V=typeof Y?.modelID==="string"?Y.modelID:typeof Y?.id==="string"?Y.id:typeof J.modelID==="string"?J.modelID:void 0,K=typeof Y?.variant==="string"?Y.variant:typeof J.variant==="string"?J.variant:void 0;if(!X&&(!z||!V)&&!K)return null;let D={};if(X)D.agent=X;if(z&&V)D.model={providerID:z,modelID:V};if(K)D.variant=K;return D}function cJ($,J){return{agent:$.agent??J.agent,model:$.model??J.model,variant:$.variant??J.variant,latestAssistantMessageId:$.latestAssistantMessageId??J.latestAssistantMessageId,latestUserMessageId:$.latestUserMessageId??J.latestUserMessageId}}function k3($){return Boolean($.agent&&$.model&&$.variant)}async function z9($,J){if(!$||!J)return null;let Y=$,X=[];if(typeof Y.session?.messages==="function")try{X=Y5(await Promise.resolve(Y.session.messages({path:{id:J},query:{limit:100}})))}catch{X=[]}let z,V;for(let D of X){let F=X5(D);if(!F)continue;let P=f3(D);if(P==="assistant"&&(!z||F>z))z=F;if(P==="user"&&(!V||F>V))V=F}let K={latestAssistantMessageId:z,latestUserMessageId:V};for(let D=X.length-1;D>=0;D--){if(f3(X[D])!=="assistant")continue;let F=mJ(X[D]);if(!F)continue;if(K=cJ(K,F),k3(K))return K}for(let D=X.length-1;D>=0;D--){let F=mJ(X[D]);if(!F)continue;if(K=cJ(K,F),k3(K))return K}if(typeof Y.session?.get==="function")try{let D=await Promise.resolve(Y.session.get({path:{id:J}})),F=s$(D)&&s$(D.data)?D.data:s$(D)?D:void 0,P=F?mJ({info:F}):null;if(P)K=cJ(K,P)}catch{}if(!K.agent&&!K.model&&!K.variant&&!K.latestAssistantMessageId&&!K.latestUserMessageId)return null;return K}var h3="[lane start] — automated cache warm; no response needed.",V9="x-cortexkit-lane-start",W5=1000;function G5($){if(!$||typeof $!=="object")return!1;let J=$;return J.type==="text"&&J.text===h3&&J.synthetic===!0}async function b3($,J){let Y=$?.session;if(typeof Y?.promptAsync!=="function")throw Error("OpenCode plugin client does not support session.promptAsync");let X=await z9($,J),z={noReply:!1,parts:[{type:"text",text:h3,synthetic:!0}]};if(X?.agent)z.agent=X.agent;if(X?.model)z.model=X.model;if(X?.variant)z.variant=X.variant;await Promise.resolve(Y.promptAsync({path:{id:J},body:z}))}class pJ{#$=new Map;observeSyntheticMessage($){if(!$.parts.some(G5))return!1;let J=`${$.sessionId}\x00${$.messageId}`;if(!this.#$.has(J)&&this.#$.size>=W5){let Y=this.#$.keys().next().value;if(Y!==void 0)this.#$.delete(Y)}return this.#$.set(J,$.sessionId),!0}markHeaders($){let J=`${$.sessionId}\x00${$.messageId}`;if(!this.#$.has(J))return!1;return this.#$.delete(J),$.headers[V9]="1",!0}clearSession($){for(let[J,Y]of this.#$)if(Y===$)this.#$.delete(J)}}import{createNativeUi as z5,disconnectNativeVaultForHost as V5,readNativeEnrollmentMode as K5}from"@cortexkit/anthropic-auth-core";function g3($){if(!$?.trim())throw TypeError("sessionId is required");return $}function y3($){if($.host!=="opencode")throw TypeError("OpenCode host is required");let J=z5({...$,readMode:$.readMode??(()=>K5("opencode",process.env)),disconnectVault:$.disconnectVault??(()=>V5({host:"opencode",env:process.env}))});return{menu:J,open(Y){return J.open({sessionId:g3(Y),notify(){}})},apply(Y){return J.apply(Y,{sessionId:g3(Y.sessionId),notify(){}})}}}import{createAnthropicOAuthFetch as j5,logger as m3,requireAnthropicOAuthOrigin as _5}from"@cortexkit/anthropic-auth-core";var lJ="ANTHROPIC_AUTH_TEST_OAUTH_LOOPBACK_ORIGIN",O5=new Set(["127.0.0.1","[::1]","localhost"]),c3;function L5(){let $=process.env[lJ];if(!$)return;let J=N5($);if(c3!==$)if(c3=$,J)m3.warn("oauth-destination","test-only loopback origin is allowed for Claude OAuth requests",{env:lJ});else m3.warn("oauth-destination","ignored an invalid test-only loopback origin; Claude OAuth requests stay limited to https://api.anthropic.com",{env:lJ});return J}function N5($){let J;try{J=new URL($)}catch{return}if(J.protocol!=="http:"&&J.protocol!=="https:")return;if(J.username||J.password||J.search||J.hash)return;if(!O5.has(J.hostname))return;if(!J.port)return;if($!==J.origin)return;return J.origin}function p3(){let $=L5();return $?{extraOrigin:$}:{}}function K9($){return _5($,p3())}function uJ($){try{return K9($),!0}catch{return!1}}var Q4=j5(p3);var l3;import{primeStorageFingerprint as D5}from"@cortexkit/anthropic-auth-core";var j9=new Map,_9=new Map;function u3($,J){let Y=_9.get($);if(Y?.fingerprint!==J.fingerprint||Y.marker!==J.marker)return;let X=j9.get(J.fingerprint);if(X?.slots.delete($),X?.slots.size===0)X.manager.stop(),j9.delete(J.fingerprint);_9.delete($)}function d3($,J,Y){let X=D5($),z=j9.get(X),V=z?.manager??J();if(z)Y.rebind(V);let K=_9.get(Y.slot);if(K&&K.fingerprint!==X)u3(Y.slot,K);let D=z??{manager:V,slots:new Set};if(!z)j9.set(X,D);let F={fingerprint:X,marker:Symbol(Y.slot)};return D.slots.add(Y.slot),_9.set(Y.slot,F),{manager:V,release:()=>u3(Y.slot,F)}}import{classifySafeErrorForLog as H5,logger as U5}from"@cortexkit/anthropic-auth-core";function i3($,J,Y){U5.warn("quota","fallback quota preflight could not obtain a reading",{accountId:$,requiredByPolicy:J,...H5(Y)})}var dJ="x-cortexkit-request-class",Q5=new Set(["title","summary","prime"]);function n3($){return typeof $==="string"&&Q5.has($)}function o3($){let J=$.get("x-cortexkit-request-class");return $.delete("x-cortexkit-request-class"),J==="auxiliary"?"auxiliary":"main"}import{getKillswitchThresholdsForAccount as B5,getScopedQuotaWindowForModel as F5,killswitchPassesPolicy as w5}from"@cortexkit/anthropic-auth-core";function r3($){let J=Math.floor($.retryAfterSeconds/60),Y=$.retryAfterSeconds%60,X=`Retry in ${J}m ${Y}s.`;return $.modelName?`${$.modelName} weekly limit reached, no routable accounts. ${X}`:`Killswitch: no routable accounts. ${X}`}function s3($){if(!$.requestModelId)return{isScopedDriven:!1};if(!w5($.mainQuota,$.storage))return{isScopedDriven:!1};let J=F5($.mainQuota,$.requestModelId);if(!J)return{isScopedDriven:!1};if(!Number.isFinite(J.remainingPercent))return{isScopedDriven:!1};let Y=B5($.storage);if(J.remainingPercent<=Y.scoped)return{isScopedDriven:!0,modelName:J.modelName,modelId:$.requestModelId};return{isScopedDriven:!1}}var I$=[],T5=1,a3=new Map,O9=new Map,F1=new Set,E5=1000;function t3($){if(typeof $!=="string"||$.length===0)throw TypeError("sessionId is required")}function iJ($,J){t3(J);let Y=T5++;if("menu"in $){if($.command!=="claude"||$.menu.command!=="claude")throw TypeError("Only the claude menu is supported");I$.push({id:Y,type:"open-menu",payload:$,sessionId:J})}else I$.push({id:Y,type:"open-dialog",payload:$,sessionId:J});if(I$.length>100)I$=I$.slice(I$.length-100);return Y}function e3($,J,Y){let X=iJ($,J);return new Promise((z)=>{let V;O9.set(X,{picked(){if(V!==void 0)Y.clearTimeout(V);z(!0)},cancel(){if(V!==void 0)Y.clearTimeout(V);z(!1)}}),V=Y.setTimeout(()=>{if(!O9.delete(X))return;if(I$=I$.filter((K)=>K.id!==X),F1.delete(J),F1.add(J),F1.size>E5){let K=F1.values().next().value;if(K!==void 0)F1.delete(K)}z(!1)},Y.timeoutMs)})}function $7($){return F1.has($)}function J7($,J){if(t3(J),a3.set(J,Date.now()),F1.delete(J),$>0)I$=I$.filter((X)=>X.id>$||X.sessionId!==J);let Y=I$.filter((X)=>X.id>$&&X.sessionId===J);for(let X of Y){let z=O9.get(X.id);if(!z)continue;O9.delete(X.id),z.picked()}return Y}function L9($){let J=Date.now(),Y=a3.get($)??0;return Y>0&&J-Y<3000}import{randomBytes as S5,timingSafeEqual as C5}from"node:crypto";import{readFile as A5,unlink as P5}from"node:fs/promises";import{createServer as q5}from"node:http";import{join as R5}from"node:path";import{parseApplyRequest as M5}from"@cortexkit/anthropic-auth-core";function I5($){return new Promise((J,Y)=>{let X=[],z=0;$.on("data",(V)=>{if(z+=V.length,z>1e6){$.destroy(),Y(Error("body too large"));return}X.push(V)}),$.on("end",()=>J(Buffer.concat(X).toString("utf8"))),$.on("error",Y)})}function x5($,J){if(!$?.startsWith("Bearer "))return!1;let Y=Buffer.from($.slice(7)),X=Buffer.from(J);return Y.length===X.length&&C5(Y,X)}async function Y7($){let J=S5(32).toString("hex"),Y=q5((V,K)=>{X(V,K)});async function X(V,K){let D=(F,P)=>{K.writeHead(F,{"content-type":"application/json"}),K.end(JSON.stringify(P))};try{let F=V.url??"";if(V.method==="GET"&&F==="/health")return D(200,{ok:!0});if(V.method!=="POST"||!F.startsWith("/rpc/"))return D(404,{error:"not found"});if(!x5(V.headers.authorization,J))return D(401,{error:"unauthorized"});let P=F.slice(5),q=JSON.parse(await I5(V)||"{}");if(P==="pending-notifications"){if(typeof q.sessionId!=="string"||q.sessionId.length===0)return D(400,{error:"sessionId is required"});let x=$.drain(Number(q.lastReceivedId??0),q.sessionId);return D(200,{messages:x})}if(P==="apply"){if(!$.apply)return D(501,{error:"text apply unavailable"});let x=await $.apply(q);return D(200,x)}if(P==="apply-menu"){let x=M5(q);if(x?.command!=="claude"||!x.sessionId?.trim())return D(400,{error:"invalid menu request"});if(!$.applyMenu)return D(501,{error:"menu unavailable"});return D(200,await $.applyMenu(x))}return D(404,{error:"unknown method"})}catch{if(!K.headersSent&&!K.writableEnded&&!K.destroyed)D(500,{error:"RPC request failed"})}}let z=await new Promise((V,K)=>{Y.on("error",K),Y.listen(0,"127.0.0.1",()=>{let D=Y.address();if(D&&typeof D==="object")V(D.port);else K(Error("no port"))})});Y.unref();try{await Z7($.dir,{port:z,token:J,pid:process.pid})}catch(V){throw await new Promise((K)=>Y.close(()=>K())),V}return{port:z,token:J,async stop(){await new Promise((V)=>Y.close(()=>V()));try{let V=R5($.dir,`port-${process.pid}.json`),K=JSON.parse(await A5(V,"utf8"));if(K.port===z&&K.pid===process.pid)await P5(V)}catch{}}}}async function X7($,J){let Y=globalThis,X=Y.__anthropicAuthRpcServers??new Map,z=Y.__anthropicAuthRpcServersPending??new Map;Y.__anthropicAuthRpcServers=X,Y.__anthropicAuthRpcServersPending=z;let V=z.get($)??Promise.resolve(),K,D=V.catch(()=>{}).then(async()=>{let P=X.get($);if(P){if(await P.stop(),X.get($)===P)X.delete($)}K=await J(),X.set($,K)});z.set($,D);try{await D}finally{if(z.get($)===D)z.delete($)}let F=K;if(!F)throw Error("RPC server failed to start");return{server:F,release:async()=>{if(X.get($)!==F)return;if(await F.stop(),X.get($)===F)X.delete($)}}}import{resolveClaudeModelCapabilities as f5}from"@cortexkit/anthropic-auth-core";var z7="server-side-fallback-2026-07-01",V7="",N9="cortexkit-server-fallback-v1:";function x$($){return $!==null&&typeof $==="object"&&!Array.isArray($)?$:void 0}function g1($,J){let Y=$?.[J];return typeof Y==="string"?Y:void 0}function y1($){return typeof $==="string"&&$.length>0&&$.length<=128&&/^claude-[a-z0-9-]+$/i.test($)}function k5($){return`${N9}${$.fromModel}|${$.toModel}`}function v5($){if(typeof $!=="string"||!$.startsWith(N9))return null;let J=$.slice(N9.length),Y=J.indexOf("|");if(Y<=0||Y!==J.lastIndexOf("|"))return null;let X=J.slice(0,Y),z=J.slice(Y+1);if(!y1(X)||!y1(z))return null;return{fromModel:X,toModel:z}}function h5($){if($.type!=="fallback")return null;let J=g1(x$($.from),"model"),Y=g1(x$($.to),"model");if(!y1(J)||!y1(Y))return null;return{fromModel:J,toModel:Y}}function b5($){return{type:"fallback",from:{model:$.fromModel},to:{model:$.toModel}}}function g5($,J){let Y=0,X=0;if(!Array.isArray($.messages))return{restoredMarkers:Y,droppedMarkers:X};for(let z of $.messages){let V=x$(z);if(V?.role!=="assistant"||!Array.isArray(V.content))continue;let K=[];for(let D of V.content){let F=x$(D);if(!(F?.type==="thinking"&&(F.thinking===V7||F.thinking==="")&&typeof F.signature==="string"&&F.signature.startsWith(N9))){K.push(D);continue}let q=v5(F.signature);if(J&&q)K.push(b5(q)),Y++;else X++}V.content=K}return{restoredMarkers:Y,droppedMarkers:X}}function K7($){return $?.trim().toLowerCase()==="legacy"?"legacy":"server"}function j7($,J){let Y=J&&f5($.model)?.serverSideFallback===!0,X=g5($,Y);if(Y)$.fallbacks="default";else if($.fallbacks==="default")delete $.fallbacks;return{enabled:Y,...X}}function y5($){let J,Y=[];for(let z of $.split(/\r?\n/))if(z.startsWith("event:"))J=z.slice(6).trim();else if(z.startsWith("data:")){let V=z.slice(5);Y.push(V.startsWith(" ")?V.slice(1):V)}let X=Y.join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{I as P,J as k}from"./index-
|
|
1
|
+
import{I as P,J as k}from"./index-t4aky73k.js";var G=(f)=>f!==null&&typeof f==="object"&&!Array.isArray(f),K=(f)=>G(f)&&typeof f.sessionId==="string"&&f.sessionId.length>0,D=(f)=>{if(!K(f)||!G(f)||f.command!=="claude"||typeof f.sectionId!=="string"||typeof f.actionId!=="string")return!1;if(f.itemId!==void 0&&typeof f.itemId!=="string")return!1;if(f.confirmed!==void 0&&typeof f.confirmed!=="boolean")return!1;if(f.values!==void 0&&(!G(f.values)||!Object.values(f.values).every((q)=>q===null||typeof q==="string"||typeof q==="boolean"||typeof q==="number"&&Number.isFinite(q))))return!1;return!0};function H(f){return{"~standard":{version:1,vendor:"cortexkit-native",validate:(q)=>f(q)?{value:q}:{issues:[{message:"Invalid native menu payload"}]}}}}var M=(f)=>G(f)&&f.command==="claude"&&G(f.menu)&&f.menu.command==="claude"&&typeof f.menu.title==="string"&&Array.isArray(f.menu.sections),L=(f)=>G(f)&&f.command==="claude"&&typeof f.ok==="boolean"&&typeof f.text==="string"&&(f.authorizationUrl===void 0||typeof f.authorizationUrl==="string")&&G(f.menu)&&Array.isArray(f.menu.sections),Z=(f)=>{if(f===null||typeof f==="string"||typeof f==="boolean")return!0;if(typeof f==="number")return Number.isFinite(f);if(Array.isArray(f))return f.every(Z);if(G(f))return Object.values(f).every(Z);return!1},N={"~standard":{version:1,vendor:"cortexkit-native",validate:(f)=>{let q=k(f);return{value:Z(q)?q:{...P}}}}},O={id:"cortexkit-anthropic-native",methods:{open:{input:H(K),output:H(M)},apply:{input:H(D),output:H(L)},sidebar:{input:H(K),output:N}},events:{opened:{schema:H((f)=>K(f)&&M(f.payload))},notification:{schema:H((f)=>K(f)&&typeof f.message==="string"&&["info","warning","error"].includes(String(f.kind)))}}};async function U(f,q,$){let z=new AbortController,X=(j)=>({sessionId:j,notify(W,Y="info"){Q.events.emit("notification",{sessionId:j,message:W,kind:Y}).catch(()=>{})}}),Q=await f.rpc.register(O,{open:(j)=>q.open(X(j.sessionId)),apply:(j)=>q.apply(j,X(j.sessionId)),sidebar:(j)=>$.readSidebar(j.sessionId)}),B;try{B=await f.command.transform((j)=>j.add({name:"claude",description:"Native Claude accounts and settings",async execute(W){let Y=await q.open(X(W.sessionID));await Q.events.emit("opened",{sessionId:W.sessionID,payload:Y})}}))}catch(j){throw await Q.dispose(),j}let w=(async()=>{try{for await(let j of f.event.subscribe({signal:z.signal}))if(j.type==="session.deleted")$.forgetSession(j.data.sessionID)}catch{}})(),F=!1;return{async dispose(){if(F)return;F=!0,z.abort(),await Promise.all([Q.dispose(),B.dispose(),w])}}}
|
|
2
2
|
export{O as u,U as v};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{randomUUID as E}from"node:crypto";import{mkdir as g,readFile as y,rename as S,rm as O,rmdir as w,stat as D,unlink as m,writeFile as b}from"node:fs/promises";import{tmpdir as d}from"node:os";import{dirname as v,join as f}from"node:path";import{formatQuota as c,isQuotaStale as u,logger as C,quotaDisplayProjection as I,quotaWindowParts as s}from"@cortexkit/anthropic-auth-core";var n="OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE",i=f(d(),"opencode-anthropic-auth"),l=f(i,"sidebar-state.json");function P(){return process.env[n]||l}var H={main:{quota:null},fallbacks:[],route:"main",relay:null,fastMode:!1,lastUpdated:0};function Q(J){return J!==null&&typeof J==="object"&&!Array.isArray(J)}function z(J){return typeof J==="number"&&Number.isFinite(J)}function o(J){if(!Q(J))return;let Z=Number(J.count),V=Number(J.inputTokens),X=Number(J.outputTokens),x=Number(J.since);if(![Z,V,X,x].every(Number.isFinite)||Z<0||V<0||X<0||x<0)return;return{count:Math.floor(Z),inputTokens:Math.floor(V),outputTokens:Math.floor(X),since:Math.floor(x)}}function r(J){if(!Q(J))return;if(typeof J.id!=="string"||!J.id.trim())return;if(typeof J.label!=="string"||!J.label.trim())return;let Z={id:J.id.trim(),label:J.label.trim()};if(J.nextDueAt===null)Z.nextDueAt=null;else if(z(J.nextDueAt))Z.nextDueAt=J.nextDueAt;if(J.lastPrimedAt===null)Z.lastPrimedAt=null;else if(z(J.lastPrimedAt))Z.lastPrimedAt=J.lastPrimedAt;if(J.lastResult==="ok"||J.lastResult==="error"||J.lastResult==="skipped")Z.lastResult=J.lastResult;let V=o(J.usage);if(V)Z.usage=V;if(z(J.estimatedCostUsd))Z.estimatedCostUsd=J.estimatedCostUsd;return Z}function a(J){if(!Q(J))return;if(typeof J.enabled!=="boolean")return;let Z=Array.isArray(J.accounts)?J.accounts.map(r).filter((V)=>V!=null):[];return{enabled:J.enabled,accounts:Z}}function q(J){if(!Q(J))return;let Z=Number(J.usedPercent),V=Number(J.remainingPercent);if(!Number.isFinite(Z)||!Number.isFinite(V))return;return{usedPercent:Z,remainingPercent:V,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0,...z(J.checkedAt)&&{checkedAt:J.checkedAt}}}function R(J){if(!Q(J))return null;let Z={};if(z(J.checkedAt))Z.checkedAt=J.checkedAt;let V=q(J.five_hour),X=q(J.seven_day);if(V)Z.five_hour=V;if(X)Z.seven_day=X;if(Array.isArray(J.scoped)){let x=J.scoped.map((Y)=>{if(!Q(Y))return;let G=q(Y);if(!G)return;if(typeof Y.id!=="string"||!Y.id.trim())return;if(typeof Y.title!=="string"||!Y.title.trim())return;if(typeof Y.modelName!=="string"||!Y.modelName.trim())return;let $=typeof Y.modelId==="string"&&Y.modelId.trim()?Y.modelId.trim():void 0;return{...G,id:Y.id.trim(),title:Y.title.trim(),...$&&{modelId:$},modelName:Y.modelName.trim()}}).filter((Y)=>Y!=null);Z.scoped=x}if(Q(J.extraUsage)){let x=A(J.extraUsage.used),Y=A(J.extraUsage.limit);if(x&&Y&&typeof J.extraUsage.exhausted==="boolean")Z.extraUsage={used:x,limit:Y,...typeof J.extraUsage.utilizationPercent==="number"&&Number.isFinite(J.extraUsage.utilizationPercent)&&{utilizationPercent:J.extraUsage.utilizationPercent},...typeof J.extraUsage.severity==="string"&&{severity:J.extraUsage.severity},exhausted:J.extraUsage.exhausted}}if(typeof J.bindingWindow==="string"&&J.bindingWindow.trim())Z.bindingWindow=J.bindingWindow.trim();if(typeof J.fallbackAdvised==="boolean")Z.fallbackAdvised=J.fallbackAdvised;return Object.keys(Z).length?Z:null}function A(J){if(!Q(J))return;if(!Number.isInteger(J.amountMinor)||typeof J.currency!=="string"||!/^[A-Za-z]{3}$/.test(J.currency.trim())||!Number.isInteger(J.exponent)||J.exponent<0||J.exponent>20)return;return{amountMinor:J.amountMinor,currency:J.currency.trim(),exponent:J.exponent}}function k(J){if(!Q(J))return{...H};let Z={quota:null};if(Q(J.main)){let $=J.main;if(Z.quota=R($.quota),typeof $.enabled==="boolean")Z.enabled=$.enabled;if(typeof $.stateLine==="string")Z.stateLine=$.stateLine;if($.quotaDated===!0)Z.quotaDated=!0;if(typeof $.tierLabel==="string"&&$.tierLabel.trim())Z.tierLabel=$.tierLabel.trim();if(typeof $.quotaBackedOff==="boolean")Z.quotaBackedOff=$.quotaBackedOff;if(z($.quotaBackoffUntil))Z.quotaBackoffUntil=$.quotaBackoffUntil;if(typeof $.refreshBackedOff==="boolean")Z.refreshBackedOff=$.refreshBackedOff;if(z($.refreshBackoffUntil))Z.refreshBackoffUntil=$.refreshBackoffUntil}let V=Array.isArray(J.fallbacks)?J.fallbacks.filter(Q).filter(($)=>typeof $.id==="string").map(($)=>({id:$.id,...typeof $.label==="string"&&{label:$.label},quota:R($.quota),enabled:typeof $.enabled==="boolean"?$.enabled:!1,...typeof $.stateLine==="string"&&{stateLine:$.stateLine},...$.quotaDated===!0&&{quotaDated:!0},needsReauth:typeof $.needsReauth==="boolean"?$.needsReauth:!1,...$.vaultReauth===!0&&{vaultReauth:!0},...$.vaultServed===!0&&{vaultServed:!0},...typeof $.custodyState==="string"&&{custodyState:$.custodyState},...typeof $.tierLabel==="string"&&$.tierLabel.trim()&&{tierLabel:$.tierLabel.trim()}})):[],X=null;if(Q(J.relay)){let $=J.relay;if(typeof $.enabled==="boolean"&&typeof $.transport==="string")X={enabled:$.enabled,transport:$.transport}}let x;if(Q(J.cacheKeep)){let $=J.cacheKeep;if(typeof $.enabled==="boolean")x={enabled:$.enabled,...typeof $.window==="string"&&{window:$.window},...z($.trackedSessions)&&{trackedSessions:$.trackedSessions}}}let Y=Array.isArray(J.fableRecoveries)?J.fableRecoveries.filter(Q).flatMap(($)=>{if(typeof $.sessionId!=="string"||$.mode!=="opus"&&$.mode!=="fable"&&$.mode!=="server"||typeof $.remaining!=="number"||!Number.isFinite($.remaining)||typeof $.changedAt!=="number"||!Number.isFinite($.changedAt))return[];return[{sessionId:$.sessionId,mode:$.mode,remaining:Math.max(0,Math.floor($.remaining)),changedAt:$.changedAt,...typeof $.requestedModelId==="string"&&{requestedModelId:$.requestedModelId},...typeof $.targetModelId==="string"&&{targetModelId:$.targetModelId}}]}):[],G=a(J.prime);return{main:Z,fallbacks:V,...typeof J.activeId==="string"&&{activeId:J.activeId},route:typeof J.route==="string"?J.route:H.route,relay:X,fastMode:typeof J.fastMode==="boolean"?J.fastMode:H.fastMode,cacheKeep:x,...G&&{prime:G},...Y.length>0&&{fableRecoveries:Y},lastUpdated:z(J.lastUpdated)?J.lastUpdated:0}}var W=Promise.resolve(),t=1000,e=2000,JJ=5,ZJ=15,M=new Map;function HJ(J,Z=P()){if(J)M.set(Z,J);else M.delete(Z)}function U(J){return M.get(J)}var p=null;function WJ(J){p=J}function UJ(){return p}function $J(J){return new Promise((Z)=>setTimeout(Z,J))}async function F(J){let Z=`${J}.lock`,V=U(J),X=V?.lockBudgetMs??t,x=V?.lockRetryMinMs??JJ,Y=V?.lockRetryMaxMs??ZJ,G=Date.now()+X;while(!0){try{await g(Z);let K=E(),j=f(Z,K);return await b(j,"",{encoding:"utf8",mode:384,flag:"wx"}),await V?.onLockAcquired?.(Z),{ownsLock:async()=>{try{return await D(j),!0}catch{return!1}},release:async()=>{try{await m(j)}catch{return}await V?.beforeReleaseDirectoryRemoval?.(Z),await w(Z).catch(()=>{})}}}catch(K){if(K.code!=="EEXIST")return C.trace("sidebar","state lock unavailable; write skipped",{stateFile:J,error:K instanceof Error?K.message:String(K)}),null}try{let K=await D(Z);if(Date.now()-K.mtimeMs>e){await V?.afterStaleLockStat?.(Z);let j=`${Z}.evict-${process.pid}-${E()}`;try{await S(Z,j)}catch(N){if(N.code==="ENOENT")continue;throw N}await V?.onStaleLockClaimed?.(Z),await O(j,{recursive:!0,force:!0}).catch(()=>{});continue}}catch(K){if(K.code==="ENOENT")continue;return C.trace("sidebar","state lock inspection failed; write skipped",{stateFile:J,error:K instanceof Error?K.message:String(K)}),null}let $=G-Date.now();if($<=0)return C.warn("sidebar","lock budget exhausted, write skipped",{stateFile:J,budgetMs:X}),null;let B=x+Math.floor(Math.random()*(Y-x+1));await $J(Math.min(B,$))}}async function qJ(J){return(await F(J))?.release??null}async function VJ(J,Z,V){let X=U(J),x=`${J}.${process.pid}.${E()}.tmp`;await b(x,JSON.stringify(Z),{encoding:"utf8",mode:384});try{if(!await V())return C.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await O(x,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await X?.beforeRename?.(J,x),!await V())return C.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await O(x,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await S(x,J),await U(J)?.afterRename?.(J),!await V())return"lock-lost-after-rename";return"written"}catch(Y){throw await O(x,{force:!0}).catch(()=>{}),Y}}async function T(J=P()){try{let Z=await y(J,"utf8");return k(JSON.parse(Z))}catch{return H}}async function LJ(J,Z=P(),V={}){return W=W.then(async()=>{await g(v(Z),{recursive:!0});for(let X=0;X<2;X++){let x=X===1,Y=await F(Z);if(!Y){if(x)C.warn("sidebar","post-rename repair lock unavailable; write skipped",{stateFile:Z});return}let G=J,$;try{if(V.routingAuthoritative===!1){let B=await T(Z),K=await V.resolvePreservedRouting?.(B);if(K){let j=K.state??J;G={...j,activeId:K.activeId,route:K.route,lastUpdated:Math.max(j.lastUpdated,B.lastUpdated)}}await U(Z)?.afterMergeRead?.(Z)}else if(x){let B=await T(Z);G={...B,activeId:J.activeId,route:J.route,relay:J.relay,fastMode:J.fastMode,cacheKeep:J.cacheKeep,lastUpdated:Math.max(B.lastUpdated,J.lastUpdated)}}G=k(G),$=await VJ(Z,G,Y.ownsLock)}finally{await Y.release()}if($==="lock-lost-after-rename"){if(x){C.warn("sidebar","post-rename repair lost lock; write skipped",{stateFile:Z});return}C.warn("sidebar","state lock lost after rename; repairing write",{stateFile:Z});continue}if($==="lock-lost-before-rename")return;V.onRoutingResolved?.({activeId:G.activeId,route:G.route});return}}).catch(()=>{}),W}async function EJ(){return W}function XJ(J){let Z=J.activeId;if(Z&&Z!=="main"){let V=J.fallbacks?.find((X)=>X.enabled&&X.id===Z);if(V)return{id:V.id,name:V.label??V.id,quota:V.quota,...V.stateLine&&{stateLine:V.stateLine,quotaDated:V.quotaDated}}}return{id:"main",name:"main",quota:J.main?.quota??null,...J.main?.stateLine&&{stateLine:J.main.stateLine,quotaDated:J.main.quotaDated}}}function L(J){if(J==="claude-mythos-5-1"||J?.startsWith("claude-mythos-5-1-"))return"Mythos 5.1";if(J==="claude-fable-5-1"||J?.startsWith("claude-fable-5-1-"))return"Fable 5.1";if(J==="claude-fable-5"||J?.startsWith("claude-fable-5-"))return"Fable 5";if(J==="claude-opus-5-5"||J?.startsWith("claude-opus-5-5-"))return"Opus 5.5";if(J==="claude-opus-5"||J?.startsWith("claude-opus-5-"))return"Opus 5";if(J==="claude-opus-4-8"||J?.startsWith("claude-opus-4-8-"))return"Opus 4.8";return J??"Fable 5"}function h(J){return new Date(J).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function YJ(J){if(J===0)return"0";if(J<0.0001)return J.toExponential(2);return J.toFixed(Math.min(6,Math.max(0,4)))}function MJ(J,Z=Date.now()){if(J.lastResult==="error")return{text:"err",hasError:!0};if(J.lastResult==="skipped")return{text:"skip",hasError:!1};if(J.nextDueAt&&J.nextDueAt>Z)return{text:h(J.nextDueAt),hasError:!1};if(J.lastPrimedAt)return{text:`primed ${h(J.lastPrimedAt)} ✓`,hasError:!1};if(J.usage?.count)return{text:`✓ ${J.usage.count} ≈ $${YJ(J.estimatedCostUsd??0)}`,hasError:!1};return{text:"—",hasError:!1}}function fJ(J,Z){let V=J.fableRecoveries?.find((X)=>X.sessionId===Z);if(!V)return;if(V.mode==="fable")return`${L(V.requestedModelId)} · restored`;if(V.mode==="server")return`${L(V.requestedModelId)}→${L(V.targetModelId)} · safety`;return`Opus 4.8 · ${V.remaining} left`}function PJ(J,Z=10){if(Z<=0)return"";let V=J;if(Bun.stringWidth(V)>Z){V="";for(let X of J){if(Bun.stringWidth(V+X)>Z-1)break;V+=X}V+="…"}return V+" ".repeat(Math.max(0,Z-Bun.stringWidth(V)))}function xJ(J,Z=Date.now()){let V=J?.scoped??[];if(!V.length)return[];let{windows:X}=s(I({scoped:V},Z),{now:Z});return V.map((x)=>X.find((Y)=>Y.kind==="window"&&Y.name===x.title)?.short||x.title)}function _J(J,Z=Date.now()){return Math.max(2,...J.flatMap((V)=>xJ(V,Z).map((X)=>Bun.stringWidth(X))))}var GJ=3;function DJ(J){let{width:Z,labelWidth:V,barWidth:X,figure:x,reset:Y}=J,G={barCells:X,reset:Y||void 0};if(Z===void 0)return G;let $=(j)=>V+1+(j.barCells>0?j.barCells+1:0)+Bun.stringWidth(x)+(j.reset?1+Bun.stringWidth(j.reset):0),B=Math.min(GJ,X),K=[G];for(let j=X;j>=B;j--)K.push({barCells:j});return K.find((j)=>$(j)<=Z)??{barCells:B}}function RJ(J,Z,V,X,x){if(!J||J.state==="on-pace")return null;let Y=x!==void 0&&x<=0,G=V==="now"||V==="0m"?"<1m":V,$=`${J.state} ${Math.round(Math.abs(J.deltaPercent))}%`,B=Y?X?`used up · resets in ${X}`:"used up":G?`${$} · out in ${G}`:`${$} · lasts to reset`;if(Z===void 0||Bun.stringWidth(B)<=Z)return B;if(Z<=0)return"";let K="";for(let j of B){if(Bun.stringWidth(K+j)>Z-1)break;K+=j}return`${K.trimEnd()}…`}function AJ(J,Z=Date.now()){let V=J?.five_hour?.usedPercent??null,X=J?.seven_day?.usedPercent??null,x=J?.scoped??[],Y=x.map(($)=>$.usedPercent);if(!J||V==null&&X==null&&x.length===0&&!J.extraUsage)return{fiveHourUsedPercent:V,sevenDayUsedPercent:X,scopedUsedPercents:Y,text:null,stale:!1};let G=I(J,Z);return{fiveHourUsedPercent:V,sevenDayUsedPercent:X,scopedUsedPercents:Y,text:c(G,{now:Z,form:"narrow"}),stale:u(G,{now:Z})}}function TJ(J,Z=!0){let V=J.activeId===void 0?void 0:XJ(J).id;return[{id:"main",name:"main",quota:J.main?.quota??null,quotaDated:J.main?.quotaDated,active:V==="main"},...Z?(J.fallbacks??[]).filter((X)=>X.enabled||X.custodyState&&X.custodyState!=="off").map((X)=>({id:X.id,name:X.label??X.id,quota:X.quota,quotaDated:X.quotaDated,active:V===X.id})):[]]}var hJ=18000000,gJ=604800000,KJ=300000,jJ=0.01,BJ=1;function SJ(J,Z,V){if(!J.resetsAt)return null;let X=new Date(J.resetsAt).getTime();if(!Number.isFinite(X))return null;let x=X-Z,Y=V-x;if(Y<KJ)return null;if(Y<Z*jJ)return null;if(Y>=Z)return null;let G=J.usedPercent,$=Math.min(Math.max(Y/Z*100,0),100),B=G-$,K=Math.abs(B)<BJ?"on-pace":B>0?"deficit":"reserve",j=null;if(G>0){let N=Y*100/G,_=x+N;if(_<X)j=new Date(_).toISOString()}return{pacePercent:$,deltaPercent:B,state:K,runsOutAt:j}}
|
|
1
|
+
import{randomUUID as E}from"node:crypto";import{mkdir as g,readFile as y,rename as S,rm as O,rmdir as w,stat as D,unlink as m,writeFile as b}from"node:fs/promises";import{tmpdir as d}from"node:os";import{dirname as v,join as f}from"node:path";import{formatQuota as c,isQuotaStale as s,logger as C,quotaDisplayProjection as I,quotaWindowParts as u}from"@cortexkit/anthropic-auth-core";var i="OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE",l=f(d(),"opencode-anthropic-auth"),n=f(l,"sidebar-state.json");function P(){return process.env[i]||n}var H={main:{quota:null},fallbacks:[],route:"main",relay:null,fastMode:!1,lastUpdated:0};function Q(J){return J!==null&&typeof J==="object"&&!Array.isArray(J)}function z(J){return typeof J==="number"&&Number.isFinite(J)}function o(J){if(!Q(J))return;let Z=Number(J.count),V=Number(J.inputTokens),X=Number(J.outputTokens),x=Number(J.since);if(![Z,V,X,x].every(Number.isFinite)||Z<0||V<0||X<0||x<0)return;return{count:Math.floor(Z),inputTokens:Math.floor(V),outputTokens:Math.floor(X),since:Math.floor(x)}}function r(J){if(!Q(J))return;if(typeof J.id!=="string"||!J.id.trim())return;if(typeof J.label!=="string"||!J.label.trim())return;let Z={id:J.id.trim(),label:J.label.trim()};if(J.nextDueAt===null)Z.nextDueAt=null;else if(z(J.nextDueAt))Z.nextDueAt=J.nextDueAt;if(J.lastPrimedAt===null)Z.lastPrimedAt=null;else if(z(J.lastPrimedAt))Z.lastPrimedAt=J.lastPrimedAt;if(J.lastResult==="ok"||J.lastResult==="error"||J.lastResult==="skipped")Z.lastResult=J.lastResult;let V=o(J.usage);if(V)Z.usage=V;if(z(J.estimatedCostUsd))Z.estimatedCostUsd=J.estimatedCostUsd;return Z}function a(J){if(!Q(J))return;if(typeof J.enabled!=="boolean")return;let Z=Array.isArray(J.accounts)?J.accounts.map(r).filter((V)=>V!=null):[];return{enabled:J.enabled,accounts:Z}}function q(J){if(!Q(J))return;let Z=Number(J.usedPercent),V=Number(J.remainingPercent);if(!Number.isFinite(Z)||!Number.isFinite(V))return;return{usedPercent:Z,remainingPercent:V,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0,...z(J.checkedAt)&&{checkedAt:J.checkedAt}}}function R(J){if(!Q(J))return null;let Z={};if(z(J.checkedAt))Z.checkedAt=J.checkedAt;let V=q(J.five_hour),X=q(J.seven_day);if(V)Z.five_hour=V;if(X)Z.seven_day=X;if(Array.isArray(J.scoped)){let x=J.scoped.map((Y)=>{if(!Q(Y))return;let G=q(Y);if(!G)return;if(typeof Y.id!=="string"||!Y.id.trim())return;if(typeof Y.title!=="string"||!Y.title.trim())return;if(typeof Y.modelName!=="string"||!Y.modelName.trim())return;let $=typeof Y.modelId==="string"&&Y.modelId.trim()?Y.modelId.trim():void 0;return{...G,id:Y.id.trim(),title:Y.title.trim(),...$&&{modelId:$},modelName:Y.modelName.trim()}}).filter((Y)=>Y!=null);Z.scoped=x}if(Q(J.extraUsage)){let x=A(J.extraUsage.used),Y=A(J.extraUsage.limit);if(x&&Y&&typeof J.extraUsage.exhausted==="boolean")Z.extraUsage={used:x,limit:Y,...typeof J.extraUsage.utilizationPercent==="number"&&Number.isFinite(J.extraUsage.utilizationPercent)&&{utilizationPercent:J.extraUsage.utilizationPercent},...typeof J.extraUsage.severity==="string"&&{severity:J.extraUsage.severity},exhausted:J.extraUsage.exhausted}}if(typeof J.bindingWindow==="string"&&J.bindingWindow.trim())Z.bindingWindow=J.bindingWindow.trim();if(typeof J.fallbackAdvised==="boolean")Z.fallbackAdvised=J.fallbackAdvised;return Object.keys(Z).length?Z:null}function A(J){if(!Q(J))return;if(!Number.isInteger(J.amountMinor)||typeof J.currency!=="string"||!/^[A-Za-z]{3}$/.test(J.currency.trim())||!Number.isInteger(J.exponent)||J.exponent<0||J.exponent>20)return;return{amountMinor:J.amountMinor,currency:J.currency.trim(),exponent:J.exponent}}function k(J){if(!Q(J))return{...H};let Z={quota:null};if(Q(J.main)){let $=J.main;if(Z.quota=R($.quota),typeof $.enabled==="boolean")Z.enabled=$.enabled;if(typeof $.stateLine==="string")Z.stateLine=$.stateLine;if($.quotaDated===!0)Z.quotaDated=!0;if(typeof $.tierLabel==="string"&&$.tierLabel.trim())Z.tierLabel=$.tierLabel.trim();if(typeof $.quotaBackedOff==="boolean")Z.quotaBackedOff=$.quotaBackedOff;if(z($.quotaBackoffUntil))Z.quotaBackoffUntil=$.quotaBackoffUntil;if(typeof $.refreshBackedOff==="boolean")Z.refreshBackedOff=$.refreshBackedOff;if(z($.refreshBackoffUntil))Z.refreshBackoffUntil=$.refreshBackoffUntil}let V=Array.isArray(J.fallbacks)?J.fallbacks.filter(Q).filter(($)=>typeof $.id==="string").map(($)=>({id:$.id,...typeof $.label==="string"&&{label:$.label},quota:R($.quota),enabled:typeof $.enabled==="boolean"?$.enabled:!1,...typeof $.stateLine==="string"&&{stateLine:$.stateLine},...$.quotaDated===!0&&{quotaDated:!0},needsReauth:typeof $.needsReauth==="boolean"?$.needsReauth:!1,...$.vaultReauth===!0&&{vaultReauth:!0},...$.vaultServed===!0&&{vaultServed:!0},...typeof $.custodyState==="string"&&{custodyState:$.custodyState},...typeof $.tierLabel==="string"&&$.tierLabel.trim()&&{tierLabel:$.tierLabel.trim()}})):[],X=null;if(Q(J.relay)){let $=J.relay;if(typeof $.enabled==="boolean"&&typeof $.transport==="string")X={enabled:$.enabled,transport:$.transport}}let x;if(Q(J.cacheKeep)){let $=J.cacheKeep;if(typeof $.enabled==="boolean")x={enabled:$.enabled,...typeof $.window==="string"&&{window:$.window},...z($.trackedSessions)&&{trackedSessions:$.trackedSessions}}}let Y=Array.isArray(J.fableRecoveries)?J.fableRecoveries.filter(Q).flatMap(($)=>{if(typeof $.sessionId!=="string"||$.mode!=="opus"&&$.mode!=="fable"&&$.mode!=="server"||typeof $.remaining!=="number"||!Number.isFinite($.remaining)||typeof $.changedAt!=="number"||!Number.isFinite($.changedAt))return[];return[{sessionId:$.sessionId,mode:$.mode,remaining:Math.max(0,Math.floor($.remaining)),changedAt:$.changedAt,...typeof $.requestedModelId==="string"&&{requestedModelId:$.requestedModelId},...typeof $.targetModelId==="string"&&{targetModelId:$.targetModelId}}]}):[],G=a(J.prime);return{main:Z,fallbacks:V,...typeof J.activeId==="string"&&{activeId:J.activeId},route:typeof J.route==="string"?J.route:H.route,relay:X,fastMode:typeof J.fastMode==="boolean"?J.fastMode:H.fastMode,cacheKeep:x,...G&&{prime:G},...Y.length>0&&{fableRecoveries:Y},lastUpdated:z(J.lastUpdated)?J.lastUpdated:0}}var W=Promise.resolve(),t=1000,e=2000,JJ=5,ZJ=15,M=new Map;function HJ(J,Z=P()){if(J)M.set(Z,J);else M.delete(Z)}function U(J){return M.get(J)}var p=null;function WJ(J){p=J}function UJ(){return p}function $J(J){return new Promise((Z)=>setTimeout(Z,J))}async function F(J){let Z=`${J}.lock`,V=U(J),X=V?.lockBudgetMs??t,x=V?.lockRetryMinMs??JJ,Y=V?.lockRetryMaxMs??ZJ,G=Date.now()+X;while(!0){try{await g(Z);let K=E(),j=f(Z,K);return await b(j,"",{encoding:"utf8",mode:384,flag:"wx"}),await V?.onLockAcquired?.(Z),{ownsLock:async()=>{try{return await D(j),!0}catch{return!1}},release:async()=>{try{await m(j)}catch{return}await V?.beforeReleaseDirectoryRemoval?.(Z),await w(Z).catch(()=>{})}}}catch(K){if(K.code!=="EEXIST")return C.trace("sidebar","state lock unavailable; write skipped",{stateFile:J,error:K instanceof Error?K.message:String(K)}),null}try{let K=await D(Z);if(Date.now()-K.mtimeMs>e){await V?.afterStaleLockStat?.(Z);let j=`${Z}.evict-${process.pid}-${E()}`;try{await S(Z,j)}catch(N){if(N.code==="ENOENT")continue;throw N}await V?.onStaleLockClaimed?.(Z),await O(j,{recursive:!0,force:!0}).catch(()=>{});continue}}catch(K){if(K.code==="ENOENT")continue;return C.trace("sidebar","state lock inspection failed; write skipped",{stateFile:J,error:K instanceof Error?K.message:String(K)}),null}let $=G-Date.now();if($<=0)return C.warn("sidebar","lock budget exhausted, write skipped",{stateFile:J,budgetMs:X}),null;let B=x+Math.floor(Math.random()*(Y-x+1));await $J(Math.min(B,$))}}async function qJ(J){return(await F(J))?.release??null}async function VJ(J,Z,V){let X=U(J),x=`${J}.${process.pid}.${E()}.tmp`;await b(x,JSON.stringify(Z),{encoding:"utf8",mode:384});try{if(!await V())return C.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await O(x,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await X?.beforeRename?.(J,x),!await V())return C.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await O(x,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await S(x,J),await U(J)?.afterRename?.(J),!await V())return"lock-lost-after-rename";return"written"}catch(Y){throw await O(x,{force:!0}).catch(()=>{}),Y}}async function T(J=P()){try{let Z=await y(J,"utf8");return k(JSON.parse(Z))}catch{return H}}async function LJ(J,Z=P(),V={}){return W=W.then(async()=>{await g(v(Z),{recursive:!0});for(let X=0;X<2;X++){let x=X===1,Y=await F(Z);if(!Y){if(x)C.warn("sidebar","post-rename repair lock unavailable; write skipped",{stateFile:Z});return}let G=J,$;try{if(V.routingAuthoritative===!1){let B=await T(Z),K=await V.resolvePreservedRouting?.(B);if(K){let j=K.state??J;G={...j,activeId:K.activeId,route:K.route,lastUpdated:Math.max(j.lastUpdated,B.lastUpdated)}}await U(Z)?.afterMergeRead?.(Z)}else if(x){let B=await T(Z);G={...B,activeId:J.activeId,route:J.route,relay:J.relay,fastMode:J.fastMode,cacheKeep:J.cacheKeep,lastUpdated:Math.max(B.lastUpdated,J.lastUpdated)}}G=k(G),$=await VJ(Z,G,Y.ownsLock)}finally{await Y.release()}if($==="lock-lost-after-rename"){if(x){C.warn("sidebar","post-rename repair lost lock; write skipped",{stateFile:Z});return}C.warn("sidebar","state lock lost after rename; repairing write",{stateFile:Z});continue}if($==="lock-lost-before-rename")return;V.onRoutingResolved?.({activeId:G.activeId,route:G.route});return}}).catch(()=>{}),W}async function EJ(){return W}function XJ(J){let Z=J.activeId;if(Z&&Z!=="main"){let V=J.fallbacks?.find((X)=>X.enabled&&X.id===Z);if(V)return{id:V.id,name:V.label??V.id,quota:V.quota,...V.stateLine&&{stateLine:V.stateLine,quotaDated:V.quotaDated}}}return{id:"main",name:"main",quota:J.main?.quota??null,...J.main?.stateLine&&{stateLine:J.main.stateLine,quotaDated:J.main.quotaDated}}}function L(J){if(J==="claude-mythos-5-1"||J?.startsWith("claude-mythos-5-1-"))return"Mythos 5.1";if(J==="claude-fable-5-1"||J?.startsWith("claude-fable-5-1-"))return"Fable 5.1";if(J==="claude-fable-5"||J?.startsWith("claude-fable-5-"))return"Fable 5";if(J==="claude-opus-5-5"||J?.startsWith("claude-opus-5-5-"))return"Opus 5.5";if(J==="claude-opus-5"||J?.startsWith("claude-opus-5-"))return"Opus 5";if(J==="claude-opus-4-8"||J?.startsWith("claude-opus-4-8-"))return"Opus 4.8";return J??"Fable 5"}function h(J){return new Date(J).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function YJ(J){if(J===0)return"0";if(J<0.0001)return J.toExponential(2);return J.toFixed(Math.min(6,Math.max(0,4)))}function MJ(J,Z=Date.now()){if(J.lastResult==="error")return{text:"err",hasError:!0};if(J.lastResult==="skipped")return{text:"skip",hasError:!1};if(J.nextDueAt&&J.nextDueAt>Z)return{text:h(J.nextDueAt),hasError:!1};if(J.lastPrimedAt)return{text:`primed ${h(J.lastPrimedAt)} ✓`,hasError:!1};if(J.usage?.count)return{text:`✓ ${J.usage.count} ≈ $${YJ(J.estimatedCostUsd??0)}`,hasError:!1};return{text:"—",hasError:!1}}function fJ(J,Z){let V=J.fableRecoveries?.find((X)=>X.sessionId===Z);if(!V)return;if(V.mode==="fable")return`${L(V.requestedModelId)} · restored`;if(V.mode==="server")return`${L(V.requestedModelId)}→${L(V.targetModelId)} · safety`;return`Opus 4.8 · ${V.remaining} left`}function PJ(J,Z=10){if(Z<=0)return"";let V=J;if(Bun.stringWidth(V)>Z){V="";for(let X of J){if(Bun.stringWidth(V+X)>Z-1)break;V+=X}V+="…"}return V+" ".repeat(Math.max(0,Z-Bun.stringWidth(V)))}function xJ(J,Z=Date.now()){let V=J?.scoped??[];if(!V.length)return[];let{windows:X}=u(I({scoped:V},Z),{now:Z});return V.map((x)=>X.find((Y)=>Y.kind==="window"&&Y.name===x.title)?.short||x.title)}function _J(J,Z=Date.now()){return Math.max(2,...J.flatMap((V)=>xJ(V,Z).map((X)=>Bun.stringWidth(X))))}var GJ=3;function DJ(J){let{width:Z,labelWidth:V,barWidth:X,figure:x,reset:Y}=J,G={barCells:X,reset:Y||void 0};if(Z===void 0)return G;let $=(j)=>V+1+(j.barCells>0?j.barCells+1:0)+Bun.stringWidth(x)+(j.reset?1+Bun.stringWidth(j.reset):0),B=Math.min(GJ,X),K=[G];for(let j=X;j>=B;j--)K.push({barCells:j});return K.find((j)=>$(j)<=Z)??{barCells:B}}function RJ(J,Z,V,X,x){if(!J||J.state==="on-pace")return null;let Y=x!==void 0&&x<=0,G=V==="now"||V==="0m"?"<1m":V,$=`${J.state} ${Math.round(Math.abs(J.deltaPercent))}%`,B=Y?X?`used up · resets in ${X}`:"used up":G?`${$} · out in ${G}`:`${$} · lasts to reset`;if(Z===void 0||Bun.stringWidth(B)<=Z)return B;if(Z<=0)return"";let K="";for(let j of B){if(Bun.stringWidth(K+j)>Z-1)break;K+=j}return`${K.trimEnd()}…`}function AJ(J,Z=Date.now()){let V=J?.five_hour?.usedPercent??null,X=J?.seven_day?.usedPercent??null,x=J?.scoped??[],Y=x.map(($)=>$.usedPercent);if(!J||V==null&&X==null&&x.length===0&&!J.extraUsage)return{fiveHourUsedPercent:V,sevenDayUsedPercent:X,scopedUsedPercents:Y,text:null,stale:!1};let G=I(J,Z);return{fiveHourUsedPercent:V,sevenDayUsedPercent:X,scopedUsedPercents:Y,text:c(G,{now:Z,form:"narrow"}),stale:s(G,{now:Z})}}function TJ(J,Z=!0){let V=J.activeId===void 0?void 0:XJ(J).id;return[{id:"main",name:"main",quota:J.main?.quota??null,quotaDated:J.main?.quotaDated,active:V==="main",blocked:J.main?.enabled===!1||Boolean(J.main?.stateLine)},...Z?(J.fallbacks??[]).filter((X)=>X.enabled||X.custodyState&&X.custodyState!=="off").map((X)=>({id:X.id,name:X.label??X.id,quota:X.quota,quotaDated:X.quotaDated,active:V===X.id,blocked:!X.enabled||Boolean(X.stateLine)||X.needsReauth||X.vaultReauth===!0||X.custodyState!=null&&X.custodyState!=="off"&&X.custodyState!=="on-vault-served"})):[]]}var hJ=18000000,gJ=604800000,KJ=300000,jJ=0.01,BJ=1;function SJ(J,Z,V){if(!J.resetsAt)return null;let X=new Date(J.resetsAt).getTime();if(!Number.isFinite(X))return null;let x=X-Z,Y=V-x;if(Y<KJ)return null;if(Y<Z*jJ)return null;if(Y>=Z)return null;let G=J.usedPercent,$=Math.min(Math.max(Y/Z*100,0),100),B=G-$,K=Math.abs(B)<BJ?"on-pace":B>0?"deficit":"reserve",j=null;if(G>0){let N=Y*100/G,_=x+N;if(_<X)j=new Date(_).toISOString()}return{pacePercent:$,deltaPercent:B,state:K,runsOutAt:j}}
|
|
2
2
|
export{P as H,H as I,k as J,HJ as K,WJ as L,UJ as M,qJ as N,T as O,LJ as P,EJ as Q,XJ as R,L as S,h as T,YJ as U,MJ as V,fJ as W,PJ as X,xJ as Y,_J as Z,GJ as _,DJ as $,RJ as aa,AJ as ba,TJ as ca,hJ as da,gJ as ea,SJ as fa};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{q as a}from"./index-
|
|
1
|
+
import{q as a}from"./index-42r4bnpm.js";import"./index-sg0knfec.js";import"./index-hc7bm3yf.js";import"./index-naff9h33.js";import"./index-t4aky73k.js";import"./index-gvswxab8.js";import"./index-71temqvq.js";export{a as AnthropicAuthPlugin};
|
package/dist/sidebar-state.d.ts
CHANGED
|
@@ -234,6 +234,7 @@ export declare function getCollapsedAccounts(state: SidebarState, showFallbacks?
|
|
|
234
234
|
quota: AccountQuota | null;
|
|
235
235
|
quotaDated: boolean | undefined;
|
|
236
236
|
active: boolean;
|
|
237
|
+
blocked: boolean;
|
|
237
238
|
}[];
|
|
238
239
|
export declare const FIVE_HOUR_MS: number;
|
|
239
240
|
export declare const SEVEN_DAY_MS: number;
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as u,H as a,I as b,J as c,K as d,L as e,M as f,N as g,O as h,P as i,Q as j,R as k,S as l,T as m,U as n,V as o,W as p,X as q,Y as r,Z as s,_ as t,aa as v,ba as w,ca as x,da as y,ea as z,fa as A}from"./index-
|
|
1
|
+
import{$ as u,H as a,I as b,J as c,K as d,L as e,M as f,N as g,O as h,P as i,Q as j,R as k,S as l,T as m,U as n,V as o,W as p,X as q,Y as r,Z as s,_ as t,aa as v,ba as w,ca as x,da as y,ea as z,fa as A}from"./index-t4aky73k.js";import"./index-71temqvq.js";export{i as setSidebarState,r as scopedQuotaShortNames,k as resolveActiveAccount,s as quotaLabelColumnWidth,c as normalizeSidebarState,a as getSidebarStateFile,h as getSidebarState,f as getInitialSidebarRoutingTestHooks,p as getFableRecoverySummary,w as getCollapsedQuotaSummary,x as getCollapsedAccounts,q as formatQuotaRowLabel,m as formatPrimeTime,n as formatPrimeCost,o as formatPrimeAccountValue,l as formatFallbackModelLabel,u as fitQuotaRow,v as fitPaceLine,j as drainSidebarWrites,A as computeQuotaPacing,d as __setSidebarStateWriteTestHooks,e as __setInitialSidebarRoutingTestHooks,g as __acquireSidebarStateLockForTest,z as SEVEN_DAY_MS,t as QUOTA_BAR_MIN_CELLS,y as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
|
package/dist/v2/cachekeep.d.ts
CHANGED
|
@@ -22,7 +22,12 @@ export declare function createNativeCacheKeep(options: NativeCacheKeepOptions &
|
|
|
22
22
|
fetch?: typeof fetch;
|
|
23
23
|
isSubagent?: (sessionID: string) => Promise<boolean>;
|
|
24
24
|
}): {
|
|
25
|
-
track(input: Parameters<NonNullable<NativeSource['onRequestPrepared']>>[0]): Promise<void
|
|
25
|
+
track(input: Parameters<NonNullable<NativeSource['onRequestPrepared']>>[0]): Promise<void | {
|
|
26
|
+
tracked: true;
|
|
27
|
+
} | {
|
|
28
|
+
tracked: false;
|
|
29
|
+
reason: string;
|
|
30
|
+
}>;
|
|
26
31
|
registry: CacheKeepSessionRegistry;
|
|
27
32
|
dispose(): Promise<void>;
|
|
28
33
|
};
|