@cortexkit/anthropic-auth-core 2.11.0 → 2.11.2

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.
@@ -437,6 +437,7 @@ export declare function quotaRefusalTiming(input: {
437
437
  }): {
438
438
  resetAt: number | undefined;
439
439
  retryAfterSeconds: number | undefined;
440
+ limitName?: string;
440
441
  };
441
442
  /** Compatibility accessor for callers that need only the capped retry delay. */
442
443
  export declare function killswitchRetryAfterSeconds(mainQuota: OAuthQuotaSnapshot | undefined, fallbackAccounts: Array<QuotaResetEvidence>, now: number, scopedModelId?: string, options?: {
@@ -0,0 +1,6 @@
1
+ /** Hosts recheck availability periodically instead of sleeping until a distant quota reset. */
2
+ export declare const MAX_HOST_RETRY_MS: number;
3
+ export declare function clampHostRetryMs(delayMs: number): number;
4
+ /** Keep quota reset headers intact: they are evidence, not instructions to the host. */
5
+ export declare function hostRetryHeaders(upstream: Headers, now?: number): Headers;
6
+ export declare function hostRetryResponse(response: Response, now?: number): Response;
package/dist/index.d.ts CHANGED
@@ -21,6 +21,7 @@ export * from './dump.ts';
21
21
  export * from './fast.ts';
22
22
  export * from './holder-registry.ts';
23
23
  export * from './host-paths.ts';
24
+ export * from './host-retry.ts';
24
25
  export * from './json.ts';
25
26
  export * from './killswitch.ts';
26
27
  export * from './logger.ts';
package/dist/index.js CHANGED
@@ -10234,6 +10234,40 @@ async function exchange(input, verifier, redirectUri, expectedState) {
10234
10234
  return exchangeCode(callback, verifier, redirectUri);
10235
10235
  }
10236
10236
 
10237
+ // src/host-retry.ts
10238
+ var MAX_HOST_RETRY_MS = 15 * 60000;
10239
+ function clampHostRetryMs(delayMs) {
10240
+ return Math.max(0, Math.min(MAX_HOST_RETRY_MS, Number.isNaN(delayMs) ? 0 : delayMs));
10241
+ }
10242
+ function hostRetryHeaders(upstream, now = Date.now()) {
10243
+ const headers = new Headers(upstream);
10244
+ for (const name of ["retry-after", "retry-after-ms"]) {
10245
+ const value = headers.get(name);
10246
+ if (value === null)
10247
+ continue;
10248
+ const numeric = value.trim() ? Number(value) : NaN;
10249
+ const delayMs = name === "retry-after-ms" ? numeric : Number.isNaN(numeric) ? Date.parse(value) - now : numeric * 1000;
10250
+ if (Number.isNaN(delayMs)) {
10251
+ headers.delete(name);
10252
+ continue;
10253
+ }
10254
+ const capped = clampHostRetryMs(delayMs);
10255
+ if (capped !== delayMs)
10256
+ headers.set(name, String(name === "retry-after-ms" ? capped : capped / 1000));
10257
+ }
10258
+ return headers;
10259
+ }
10260
+ function hostRetryResponse(response, now = Date.now()) {
10261
+ const headers = hostRetryHeaders(response.headers, now);
10262
+ if (["retry-after", "retry-after-ms"].every((name) => headers.get(name) === response.headers.get(name)))
10263
+ return response;
10264
+ return new Response(response.body, {
10265
+ status: response.status,
10266
+ statusText: response.statusText,
10267
+ headers
10268
+ });
10269
+ }
10270
+
10237
10271
  // src/routing.ts
10238
10272
  var CLAUDE_ROUTING_COMMAND_NAME = "claude-routing";
10239
10273
  var ROUTING_MODES = [
@@ -11046,32 +11080,44 @@ function quotaRefusalTiming(input) {
11046
11080
  break;
11047
11081
  }
11048
11082
  if (window.remainingPercent <= 0 || window.remainingPercent < Math.max(floors[key], killswitch[key]))
11049
- blockers.push(window);
11083
+ blockers.push({
11084
+ window,
11085
+ name: key === "five_hour" ? "5-hour" : "weekly"
11086
+ });
11050
11087
  }
11051
11088
  if (scoped) {
11052
11089
  if (!Number.isFinite(scoped.remainingPercent))
11053
11090
  unknown = true;
11054
11091
  else if (scoped.remainingPercent <= killswitch.scoped)
11055
- blockers.push(scoped);
11092
+ blockers.push({
11093
+ window: scoped,
11094
+ name: `${scoped.modelName ?? "Model"} weekly`
11095
+ });
11056
11096
  }
11057
11097
  let usableAt;
11058
- for (const window of blockers) {
11098
+ let limitName = "";
11099
+ for (const { window, name } of blockers) {
11059
11100
  const resetAt2 = Date.parse(window?.resetsAt ?? "");
11060
11101
  if (!Number.isFinite(resetAt2) || resetAt2 <= now) {
11061
11102
  unknown = true;
11062
11103
  break;
11063
11104
  }
11064
- usableAt = Math.max(usableAt ?? resetAt2, resetAt2);
11105
+ if (usableAt === undefined || resetAt2 >= usableAt) {
11106
+ usableAt = resetAt2;
11107
+ limitName = name;
11108
+ }
11065
11109
  }
11066
11110
  if (!unknown && usableAt !== undefined)
11067
- resetTimes.push(usableAt);
11111
+ resetTimes.push({ resetAt: usableAt, limitName });
11068
11112
  }
11069
- const resetAt = resetTimes.length ? Math.min(...resetTimes) : undefined;
11113
+ const earliest = resetTimes.sort((a, b) => a.resetAt - b.resetAt)[0];
11114
+ const resetAt = earliest?.resetAt;
11070
11115
  const wait = getMaxSameAccountWait(input.storage ?? null);
11071
11116
  const ttlMs = input.sessionTtlMs && input.sessionTtlMs > 0 && Number.isFinite(input.sessionTtlMs) ? input.sessionTtlMs : 300000;
11072
- const capMs = wait === "max" ? ttlMs : Number(wait) * 60000;
11117
+ const capMs = clampHostRetryMs(wait === "max" ? ttlMs : Number(wait) * 60000);
11073
11118
  return {
11074
11119
  resetAt,
11120
+ ...earliest ? { limitName: earliest.limitName } : {},
11075
11121
  retryAfterSeconds: wait === "0" ? undefined : Math.max(1, Math.ceil(Math.min(resetAt === undefined ? 300000 : resetAt - now, capMs) / 1000))
11076
11122
  };
11077
11123
  }
@@ -24709,21 +24755,39 @@ function mergeHeaderQuotaSnapshot(existing, incoming) {
24709
24755
  // src/quota-refusal.ts
24710
24756
  var details = new WeakMap;
24711
24757
  var quotaRefusalDetails = (response) => details.get(response);
24712
- function createQuotaRefusalResponse(reason, timing, _now) {
24758
+ function retryMinutes(seconds) {
24759
+ const minutes = Math.max(1, Math.ceil(seconds / 60));
24760
+ return minutes === 1 ? "1 minute" : `${minutes} minutes`;
24761
+ }
24762
+ function createQuotaRefusalResponse(reason, timing, now = Date.now(), options = {}) {
24763
+ timing = {
24764
+ ...timing,
24765
+ retryAfterSeconds: timing.retryAfterSeconds === undefined ? undefined : clampHostRetryMs(timing.retryAfterSeconds * 1000) / 1000
24766
+ };
24713
24767
  const reset = timing.resetAt === undefined ? "Reset time is unknown." : `Reset at ${new Intl.DateTimeFormat("en-US", {
24714
24768
  month: "long",
24715
24769
  day: "numeric",
24716
24770
  hour: "2-digit",
24717
24771
  minute: "2-digit",
24718
- timeZoneName: "short"
24772
+ timeZoneName: "short",
24773
+ timeZone: "UTC"
24719
24774
  }).format(timing.resetAt)}.`;
24720
24775
  const seconds = timing.retryAfterSeconds;
24721
24776
  const retry = seconds === undefined ? "" : ` Retry in ${Math.floor(seconds / 60)}m ${seconds % 60}s.`;
24777
+ const resetTime = timing.resetAt === undefined ? undefined : new Intl.DateTimeFormat("en-GB", {
24778
+ hour: "2-digit",
24779
+ minute: "2-digit",
24780
+ timeZone: "UTC",
24781
+ hour12: false
24782
+ }).format(timing.resetAt);
24783
+ const remaining = timing.resetAt === undefined ? 0 : Math.max(0, timing.resetAt - now);
24784
+ const duration = remaining >= 3600000 ? `${Math.ceil(remaining / 3600000)} h` : `${Math.ceil(remaining / 60000)} min`;
24785
+ const message = timing.limitName && resetTime ? `No Claude account has room for this request (${timing.limitName} limit or your quota floor). The earliest reset is ${resetTime} UTC (in ${duration}). ${seconds === undefined || options.retry === "manual" ? "Send the message again after that." : `Retrying every ${retryMinutes(seconds)}.`} ${reason}` : `${reason}${retry} ${reset}`;
24722
24786
  const response = new Response(JSON.stringify({
24723
24787
  type: "error",
24724
24788
  error: {
24725
24789
  type: timing.retryAfterSeconds === undefined ? "FAILED_PRECONDITION" : "rate_limit_error",
24726
- message: `${reason}${retry} ${reset}`
24790
+ message
24727
24791
  }
24728
24792
  }), {
24729
24793
  status: timing.retryAfterSeconds === undefined ? 412 : 429,
@@ -28538,22 +28602,24 @@ function fixedThreadFingerprint(input) {
28538
28602
  betas: input.betas
28539
28603
  }));
28540
28604
  }
28541
- function messageThreadCachePrefix(body, messageIndex, blockIndex) {
28605
+ function messageThreadCachePrefix(body, messageIndex, blockIndex, betas) {
28542
28606
  if (!Array.isArray(body.messages))
28543
28607
  return;
28544
28608
  const message = body.messages[messageIndex];
28545
28609
  if (!isBody(message))
28546
28610
  return;
28547
- const content = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
28548
- if (!Array.isArray(content) || !content[blockIndex])
28611
+ const content = cachePrefixContent(message.content, typeof blockIndex === "number" ? [blockIndex] : blockIndex);
28612
+ if (!content)
28549
28613
  return;
28550
28614
  const messages = body.messages.slice(0, messageIndex).concat({
28551
28615
  ...message,
28552
- content: content.slice(0, blockIndex + 1)
28616
+ content
28553
28617
  });
28554
28618
  const system = Array.isArray(body.system) ? body.system.filter((block) => !(typeof block?.text === "string" && block.text.startsWith("x-anthropic-billing-header:"))).map(withoutOwnCache) : body.system;
28555
28619
  return hash4(canonicalValue({
28556
28620
  model: body.model,
28621
+ speed: body.speed,
28622
+ betas,
28557
28623
  thinking: body.thinking,
28558
28624
  output_config: body.output_config,
28559
28625
  tool_choice: body.tool_choice,
@@ -28564,6 +28630,22 @@ function messageThreadCachePrefix(body, messageIndex, blockIndex) {
28564
28630
  messages: messages.map(withoutMessageCache)
28565
28631
  }));
28566
28632
  }
28633
+ function cachePrefixContent(content, path2) {
28634
+ const blocks = typeof content === "string" ? [{ type: "text", text: content }] : content;
28635
+ const index = path2[0];
28636
+ if (!Array.isArray(blocks) || index === undefined || !Number.isInteger(index) || index < 0 || index >= blocks.length)
28637
+ return;
28638
+ let block = blocks[index];
28639
+ if (path2.length > 1) {
28640
+ if (!isBody(block) || block.type !== "tool_result")
28641
+ return;
28642
+ const nested = cachePrefixContent(block.content, path2.slice(1));
28643
+ if (!nested)
28644
+ return;
28645
+ block = { ...block, content: nested };
28646
+ }
28647
+ return [...blocks.slice(0, index), block];
28648
+ }
28567
28649
  function messageThreadSnapshot(input, identity4 = hash4([input.account, input.credential]), fingerprint = fixedThreadFingerprint(input)) {
28568
28650
  const messages = (Array.isArray(input.body.messages) ? input.body.messages : []).map((message) => hash4(canonicalValue(withoutMessageCache(message))));
28569
28651
  return {
@@ -28607,6 +28689,171 @@ function decideMessageThread(anchor, input, snapshot, now) {
28607
28689
  deltaMessages: messages.slice(anchor.messages.length + 1)
28608
28690
  };
28609
28691
  }
28692
+ function cacheLifetimeSignature(body) {
28693
+ return hash4([
28694
+ ...new Set(tailCacheHolders(body).map((holder) => {
28695
+ const control = holder.cache_control;
28696
+ return JSON.stringify([control.type, control.ttl ?? "5m"]);
28697
+ }))
28698
+ ].sort());
28699
+ }
28700
+ function fixedCacheLayout(body) {
28701
+ let valid = true;
28702
+ const markers = (items) => Array.isArray(items) ? items.flatMap((item, index) => {
28703
+ if (!isBody(item) || !item.cache_control)
28704
+ return [];
28705
+ const control = item.cache_control;
28706
+ if (!isBody(control) || control.type !== "ephemeral" || control.ttl !== undefined && control.ttl !== "1h" && control.ttl !== "5m" || Object.keys(control).some((key) => key !== "type" && key !== "ttl")) {
28707
+ valid = false;
28708
+ return [];
28709
+ }
28710
+ const kept = { ...control };
28711
+ return [{ index, control: kept }];
28712
+ }) : [];
28713
+ const layout = {
28714
+ lifetime: cacheLifetimeSignature(body),
28715
+ system: markers(body.system),
28716
+ tools: markers(body.tools)
28717
+ };
28718
+ return valid ? layout : undefined;
28719
+ }
28720
+ function withFixedCacheLayout(body, layout) {
28721
+ const copy = { ...body };
28722
+ for (const field of ["tools", "system"]) {
28723
+ if (!Array.isArray(body[field]))
28724
+ continue;
28725
+ copy[field] = body[field].map((item, index) => {
28726
+ if (!isBody(item))
28727
+ return item;
28728
+ const marker = layout[field].find((marker2) => marker2.index === index);
28729
+ if (JSON.stringify(item.cache_control) === JSON.stringify(marker?.control))
28730
+ return item;
28731
+ const block = { ...item };
28732
+ if (marker)
28733
+ block.cache_control = { ...marker.control };
28734
+ else
28735
+ delete block.cache_control;
28736
+ return block;
28737
+ });
28738
+ }
28739
+ return copy;
28740
+ }
28741
+ function fullCacheTail(input, acceptedAt) {
28742
+ const tail = messageCacheBoundaries(input.body).at(-1);
28743
+ if (!tail)
28744
+ return;
28745
+ const control = tail.holder.cache_control;
28746
+ if (!isBody(control) || control.type !== "ephemeral" || control.ttl !== undefined && control.ttl !== "1h" && control.ttl !== "5m")
28747
+ return;
28748
+ const prefix = messageThreadCachePrefix(input.body, tail.messageIndex, tail.blockPath, input.betas);
28749
+ return prefix ? {
28750
+ identity: hash4([input.account, input.credential]),
28751
+ messageIndex: tail.messageIndex,
28752
+ blockPath: tail.blockPath,
28753
+ prefix,
28754
+ control: {
28755
+ type: "ephemeral",
28756
+ ...control.ttl ? { ttl: control.ttl } : {}
28757
+ },
28758
+ acceptedAt
28759
+ } : undefined;
28760
+ }
28761
+ function messageCacheBoundaries(body) {
28762
+ const markers = [];
28763
+ const visit = (content, messageIndex, parent) => {
28764
+ if (!Array.isArray(content))
28765
+ return;
28766
+ content.forEach((block, index) => {
28767
+ if (!isBody(block))
28768
+ return;
28769
+ const blockPath = [...parent, index];
28770
+ if (block.type === "tool_result")
28771
+ visit(block.content, messageIndex, blockPath);
28772
+ if (block.cache_control)
28773
+ markers.push({ messageIndex, blockPath, holder: block });
28774
+ });
28775
+ };
28776
+ if (Array.isArray(body.messages))
28777
+ body.messages.forEach((message, index) => {
28778
+ if (isBody(message))
28779
+ visit(message.content, index, []);
28780
+ });
28781
+ return markers;
28782
+ }
28783
+ function cacheBoundaryBlock(body, tail) {
28784
+ const message = Array.isArray(body.messages) ? body.messages[tail.messageIndex] : undefined;
28785
+ let content = isBody(message) ? message.content : undefined;
28786
+ let block;
28787
+ for (const index of tail.blockPath) {
28788
+ if (!Array.isArray(content))
28789
+ return;
28790
+ block = content[index];
28791
+ if (!isBody(block))
28792
+ return;
28793
+ content = block.type === "tool_result" ? block.content : undefined;
28794
+ }
28795
+ return isBody(block) ? block : undefined;
28796
+ }
28797
+ function tailCacheHolders(body) {
28798
+ const fixed = [body.tools, body.system].flatMap((items) => Array.isArray(items) ? items.filter((item) => isBody(item) && Boolean(item.cache_control)) : []);
28799
+ const messages = messageCacheBoundaries(body).map((marker) => marker.holder);
28800
+ return [...fixed, ...messages, ...body.cache_control ? [body] : []];
28801
+ }
28802
+ function restoreFullCacheTail(input, history, now) {
28803
+ if (!history?.hadThread)
28804
+ return { reason: "no_prior_thread" };
28805
+ if (!history.continued)
28806
+ return { reason: "no_continuation" };
28807
+ const tail = history.tail;
28808
+ if (!tail)
28809
+ return { reason: "no_full_tail" };
28810
+ if (tail.identity !== hash4([input.account, input.credential]))
28811
+ return { reason: "account_changed" };
28812
+ if (now < tail.acceptedAt || now >= tail.acceptedAt + (tail.control.ttl === "1h" ? 3600000 : 300000))
28813
+ return { reason: "expired" };
28814
+ if (input.body.cache_control)
28815
+ return { reason: "slot_taken" };
28816
+ const slot = input.cacheSlot?.(input.body);
28817
+ if (!slot)
28818
+ return { reason: "slot_taken" };
28819
+ const holders = tailCacheHolders(input.body);
28820
+ const slotIndex = holders.indexOf(slot);
28821
+ if (slotIndex < 0 || holders.length > 4)
28822
+ return { reason: "slot_taken" };
28823
+ if (tail.prefix !== messageThreadCachePrefix(input.body, tail.messageIndex, tail.blockPath, input.betas))
28824
+ return { reason: "prefix_changed" };
28825
+ const body = structuredClone(input.body);
28826
+ const message = body.messages[tail.messageIndex];
28827
+ if (typeof message?.content === "string" && tail.blockPath.length === 1 && tail.blockPath[0] === 0)
28828
+ message.content = [{ type: "text", text: message.content }];
28829
+ const block = cacheBoundaryBlock(body, tail);
28830
+ if (!block)
28831
+ return { reason: "prefix_changed" };
28832
+ if (block.cache_control)
28833
+ return { reason: "already_marked" };
28834
+ const clonedSlot = tailCacheHolders(body)[slotIndex];
28835
+ if (!clonedSlot)
28836
+ return { reason: "slot_taken" };
28837
+ delete clonedSlot.cache_control;
28838
+ block.cache_control = { ...tail.control };
28839
+ if (!cacheLifetimeOrderValid(body))
28840
+ return { reason: "ttl_order" };
28841
+ if (!fixedCacheLayout(body))
28842
+ return { reason: "layout_unrecordable" };
28843
+ return { body, reason: "tail_marker_added" };
28844
+ }
28845
+ function cacheLifetimeOrderValid(body) {
28846
+ let shortSeen = false;
28847
+ for (const holder of tailCacheHolders(body)) {
28848
+ const control = holder.cache_control;
28849
+ if (control.ttl === "1h") {
28850
+ if (shortSeen)
28851
+ return false;
28852
+ } else
28853
+ shortSeen = true;
28854
+ }
28855
+ return true;
28856
+ }
28610
28857
 
28611
28858
  class MessageThreadTracker {
28612
28859
  capacity;
@@ -28616,12 +28863,15 @@ class MessageThreadTracker {
28616
28863
  messageHashes = 0;
28617
28864
  dispositions = new Map;
28618
28865
  instance = randomUUID18();
28866
+ fullTails = new Map;
28619
28867
  constructor(capacity = MAX_SESSIONS, now = Date.now, hashBudget = MAX_MESSAGE_HASHES) {
28620
28868
  this.capacity = capacity;
28621
28869
  this.now = now;
28622
28870
  this.hashBudget = hashBudget;
28623
28871
  }
28624
28872
  forget(session, disposition = "session_deleted") {
28873
+ if (disposition === "session_deleted" || disposition === "evicted")
28874
+ this.fullTails.delete(session);
28625
28875
  this.messageHashes -= this.sessions.get(session)?.anchor?.messages.length ?? 0;
28626
28876
  this.sessions.delete(session);
28627
28877
  this.dispositions.delete(session);
@@ -28669,48 +28919,80 @@ class MessageThreadTracker {
28669
28919
  const now = this.now();
28670
28920
  const identity4 = anchor && now >= anchor.completedAt && now - anchor.completedAt < MAX_AGE_MS ? hash4([input.account, input.credential]) : undefined;
28671
28921
  let snapshot;
28672
- let reason = continuationBlocker(anchor, input, identity4, now);
28922
+ let threadInput = input;
28923
+ let reason = input.stateless ? "stateless" : continuationBlocker(anchor, input, identity4, now);
28673
28924
  if (!reason && anchor) {
28674
- const fingerprint = fixedThreadFingerprint(input);
28925
+ if (input.cacheSlot && anchor.fixedCacheLayout && anchor.fixedCacheLayout.lifetime === cacheLifetimeSignature(input.body))
28926
+ threadInput = {
28927
+ ...input,
28928
+ body: withFixedCacheLayout(input.body, anchor.fixedCacheLayout)
28929
+ };
28930
+ const fingerprint = fixedThreadFingerprint(threadInput);
28675
28931
  if (fingerprint === anchor.fingerprint)
28676
- snapshot = messageThreadSnapshot(input, identity4, fingerprint);
28932
+ snapshot = messageThreadSnapshot(threadInput, identity4, fingerprint);
28677
28933
  else
28678
28934
  reason = "fixed_changed";
28679
28935
  }
28680
- const decision = snapshot ? decideMessageThread(anchor, input, snapshot, now) : { type: "create" };
28936
+ let decision = snapshot && !input.stateless ? decideMessageThread(anchor, input, snapshot, now) : { type: "create" };
28937
+ let continueBody;
28938
+ let invalidContinue = false;
28939
+ if (decision.type === "continue") {
28940
+ continueBody = {
28941
+ ...threadInput.body,
28942
+ thread: {
28943
+ type: "continue",
28944
+ previous_message_id: decision.previousMessageId
28945
+ },
28946
+ messages: decision.deltaMessages,
28947
+ diagnostics: {
28948
+ ...isBody(threadInput.body.diagnostics) ? threadInput.body.diagnostics : {},
28949
+ previous_message_id: decision.previousMessageId
28950
+ }
28951
+ };
28952
+ placeContinueCache(continueBody, threadInput.body);
28953
+ if (!cacheLifetimeOrderValid(continueBody)) {
28954
+ decision = { type: "create" };
28955
+ reason = "ttl_order";
28956
+ invalidContinue = true;
28957
+ continueBody = undefined;
28958
+ }
28959
+ }
28681
28960
  if (decision.type === "create")
28682
28961
  this.logCreate(input.session, reason ?? "prefix_changed", anchor, input, now);
28962
+ const oldTail = this.fullTails.get(input.session);
28963
+ const tailResult = decision.type === "create" ? invalidContinue ? { reason: "ttl_order" } : restoreFullCacheTail(input, oldTail, now) : undefined;
28964
+ if (tailResult && (oldTail?.hadThread || anchor))
28965
+ logger2.debug("message-threads", "message_thread_tail_marker", {
28966
+ event: "message_thread_tail_marker",
28967
+ session: input.session,
28968
+ request: input.request ?? null,
28969
+ instance: this.instance,
28970
+ reason: tailResult.reason
28971
+ });
28683
28972
  const token2 = {};
28684
28973
  this.forget(input.session, "superseded");
28685
28974
  this.sessions.set(input.session, { token: token2 });
28686
28975
  this.prune();
28687
28976
  const fail = this.failureFor(input.session, token2);
28977
+ let accepted = false;
28688
28978
  let body;
28689
28979
  const outgoingBody = () => {
28980
+ if (continueBody)
28981
+ return continueBody;
28690
28982
  if (body)
28691
28983
  return body;
28692
- const full = input.body;
28984
+ const full = tailResult?.body ?? input.body;
28693
28985
  body = {
28694
28986
  ...full,
28695
- thread: decision.type === "create" ? { type: "create" } : {
28696
- type: "continue",
28697
- previous_message_id: decision.previousMessageId
28698
- }
28987
+ thread: { type: "create" }
28699
28988
  };
28700
- if (decision.type === "continue") {
28701
- Object.assign(body, { messages: decision.deltaMessages });
28702
- placeContinueCache(body, full);
28703
- Object.assign(body, {
28704
- diagnostics: {
28705
- ...isBody(body.diagnostics) ? body.diagnostics : {},
28706
- previous_message_id: decision.previousMessageId
28707
- }
28708
- });
28709
- }
28989
+ if (input.stateless)
28990
+ delete body.thread;
28710
28991
  return body;
28711
28992
  };
28712
28993
  return {
28713
28994
  decision,
28995
+ tailMarkerAdded: Boolean(tailResult?.body),
28714
28996
  get body() {
28715
28997
  return outgoingBody();
28716
28998
  },
@@ -28718,7 +29000,7 @@ class MessageThreadTracker {
28718
29000
  fail,
28719
29001
  complete: (facts) => {
28720
29002
  const current = this.sessions.get(input.session);
28721
- if (current?.token !== token2 || current.anchor)
29003
+ if (current?.token !== token2 || current.anchor || accepted)
28722
29004
  return;
28723
29005
  if (!facts.messageId || !facts.stopped || !facts.stopReason || facts.stopReason === "refusal" || facts.refusal || facts.fallback || facts.rewritten || Array.isArray(input.body.messages) && input.body.messages.length > this.hashBudget) {
28724
29006
  fail(facts.refusal || facts.stopReason === "refusal" ? "response_refusal" : facts.fallback ? "response_fallback" : facts.rewritten ? "response_rewritten" : Array.isArray(input.body.messages) && input.body.messages.length > this.hashBudget ? "evicted" : "invalid_completion");
@@ -28730,7 +29012,31 @@ class MessageThreadTracker {
28730
29012
  return;
28731
29013
  }
28732
29014
  const completedAt = this.now();
28733
- const completedSnapshot = snapshot ?? messageThreadSnapshot(input, identity4);
29015
+ accepted = true;
29016
+ const sentInput = { ...input, body: tailResult?.body ?? input.body };
29017
+ this.fullTails.delete(input.session);
29018
+ if (decision.type === "create") {
29019
+ if (!input.stateless || oldTail?.hadThread)
29020
+ this.fullTails.set(input.session, {
29021
+ hadThread: true,
29022
+ continued: false,
29023
+ tail: fullCacheTail(sentInput, completedAt)
29024
+ });
29025
+ } else
29026
+ this.fullTails.set(input.session, {
29027
+ hadThread: true,
29028
+ continued: true,
29029
+ tail: oldTail?.tail
29030
+ });
29031
+ while (this.fullTails.size > this.capacity) {
29032
+ const oldest = this.fullTails.keys().next().value;
29033
+ if (oldest === undefined)
29034
+ break;
29035
+ this.fullTails.delete(oldest);
29036
+ }
29037
+ if (input.stateless)
29038
+ return;
29039
+ const completedSnapshot = decision.type === "create" ? snapshot ? { ...snapshot, fingerprint: fixedThreadFingerprint(sentInput) } : messageThreadSnapshot(sentInput, identity4) : snapshot ?? messageThreadSnapshot(threadInput, identity4);
28734
29040
  this.messageHashes += completedSnapshot.messages.length;
28735
29041
  this.sessions.set(input.session, {
28736
29042
  token: token2,
@@ -28738,7 +29044,10 @@ class MessageThreadTracker {
28738
29044
  ...completedSnapshot,
28739
29045
  messageId: facts.messageId,
28740
29046
  completedAt,
28741
- replyFingerprint
29047
+ replyFingerprint,
29048
+ ...input.cacheSlot ? {
29049
+ fixedCacheLayout: decision.type === "continue" ? anchor?.fixedCacheLayout : fixedCacheLayout(tailResult?.body ?? input.body)
29050
+ } : {}
28742
29051
  }
28743
29052
  });
28744
29053
  this.prune();
@@ -28868,8 +29177,11 @@ function placeContinueCache(body, full) {
28868
29177
  delete holder.cache_control;
28869
29178
  }
28870
29179
  }
29180
+ function requestHeaderBetas(headers) {
29181
+ return (headers.get("anthropic-beta") ?? "").split(",").map((beta) => beta.trim()).filter(Boolean);
29182
+ }
28871
29183
  function messageThreadBetas(headers) {
28872
- const betas = (headers.get("anthropic-beta") ?? "").split(",").map((beta) => beta.trim()).filter((beta) => beta && beta !== MESSAGE_THREADS_BETA);
29184
+ const betas = requestHeaderBetas(headers).filter((beta) => beta !== MESSAGE_THREADS_BETA);
28873
29185
  betas.push(MESSAGE_THREADS_BETA);
28874
29186
  headers.set("anthropic-beta", betas.join(","));
28875
29187
  return betas;
@@ -28967,14 +29279,17 @@ async function prepareMessageThreadRequest(tracker, input) {
28967
29279
  const fullBody = () => full ??= JSON.parse(fullText);
28968
29280
  const accountKey = input.account;
28969
29281
  let threading = !disabledThreadAccounts.has(accountKey);
28970
- const betas = threading ? messageThreadBetas(input.headers) : [];
29282
+ if (threading)
29283
+ messageThreadBetas(input.headers);
28971
29284
  const prepareForSession = (credential3) => tracker.prepare({
28972
29285
  account: input.account,
28973
29286
  credential: credential3,
28974
29287
  session: input.session ?? "",
28975
29288
  request: input.request ?? input.headers.get("x-client-request-id") ?? undefined,
28976
- betas,
29289
+ betas: requestHeaderBetas(input.headers),
28977
29290
  replyToolNames: input.replyToolNames,
29291
+ cacheSlot: input.cacheSlot,
29292
+ stateless: !threading,
28978
29293
  get body() {
28979
29294
  return fullBody();
28980
29295
  }
@@ -28990,8 +29305,9 @@ async function prepareMessageThreadRequest(tracker, input) {
28990
29305
  credential: input.credential,
28991
29306
  request: input.request ?? input.headers.get("x-client-request-id") ?? undefined
28992
29307
  });
28993
- let prepared = threading && input.session ? prepareForSession(input.credential) : {
29308
+ let prepared = input.session ? prepareForSession(input.credential) : {
28994
29309
  decision: { type: "create" },
29310
+ tailMarkerAdded: false,
28995
29311
  get body() {
28996
29312
  return threading ? { ...fullBody(), thread: { type: "create" } } : fullBody();
28997
29313
  },
@@ -29002,7 +29318,8 @@ async function prepareMessageThreadRequest(tracker, input) {
29002
29318
  fail: ignoreThreadFailure
29003
29319
  };
29004
29320
  const failure = threadFailureState(prepared.fail);
29005
- const outgoing = threading ? prepared.decision.type === "continue" ? JSON.stringify(prepared.body) : serializedCreate(fullText, fullBody) : serializedStateless(fullText, fullBody);
29321
+ const fullOutgoing = () => prepared.tailMarkerAdded ? JSON.stringify(prepared.body) : threading ? serializedCreate(fullText, fullBody) : serializedStateless(fullText, fullBody);
29322
+ const outgoing = threading ? prepared.decision.type === "continue" ? JSON.stringify(prepared.body) : fullOutgoing() : fullOutgoing();
29006
29323
  let bodyText = await signRequestBody(outgoing);
29007
29324
  let recovered = false;
29008
29325
  let credential2 = input.credential;
@@ -29022,7 +29339,11 @@ async function prepareMessageThreadRequest(tracker, input) {
29022
29339
  const prepareStateless = async () => {
29023
29340
  prepared.fail("account_disabled");
29024
29341
  latchStateless();
29025
- bodyText = await signRequestBody(serializedStateless(fullText, fullBody));
29342
+ if (input.session) {
29343
+ prepared = prepareForSession(credential2);
29344
+ failure.replace(prepared.fail);
29345
+ }
29346
+ bodyText = await signRequestBody(fullOutgoing());
29026
29347
  };
29027
29348
  return {
29028
29349
  get bodyText() {
@@ -29030,7 +29351,7 @@ async function prepareMessageThreadRequest(tracker, input) {
29030
29351
  },
29031
29352
  fail: failure.fail,
29032
29353
  observe: (response) => {
29033
- if (!threading || !input.session || disabledThreadAccounts.has(accountKey)) {
29354
+ if (!input.session || threading && disabledThreadAccounts.has(accountKey)) {
29034
29355
  prepared.fail("account_disabled");
29035
29356
  return response;
29036
29357
  }
@@ -29069,7 +29390,7 @@ async function prepareMessageThreadRequest(tracker, input) {
29069
29390
  prepared = prepareForSession(credential2);
29070
29391
  failure.replace(prepared.fail);
29071
29392
  }
29072
- bodyText = await signRequestBody(serializedCreate(fullText, fullBody));
29393
+ bodyText = await signRequestBody(fullOutgoing());
29073
29394
  const created = await send(bodyText);
29074
29395
  if (await isThreadCreateRejection(created)) {
29075
29396
  if (!await mayResend(created, beforeResend)) {
@@ -42918,7 +43239,7 @@ function reportRoutingResponse(sessionId, subject, headers, status, modelId, ser
42918
43239
  }
42919
43240
 
42920
43241
  // src/routing-relay.ts
42921
- var ROUTING_HOLD_LIMIT_MS = 15 * 60000 + 20000;
43242
+ var ROUTING_HOLD_LIMIT_MS = MAX_HOST_RETRY_MS;
42922
43243
  function routingCandidates(accounts) {
42923
43244
  return accounts.filter((account) => account.type === "oauth" && nativeAccountCanServe(account));
42924
43245
  }
@@ -42936,6 +43257,8 @@ class RoutingRefusalError extends Error {
42936
43257
  this.code = refusal2.code;
42937
43258
  this.status = refusal2.code === "account_selection_final" ? 403 : 429;
42938
43259
  this.retryAfterSecs = this.status === 429 ? refusal2.retryAfterSecs ?? (refusal2.resetsAtMs === undefined ? undefined : Math.max(0, Math.ceil((refusal2.resetsAtMs - now) / 1000))) : undefined;
43260
+ if (this.retryAfterSecs !== undefined)
43261
+ this.retryAfterSecs = clampHostRetryMs(this.retryAfterSecs * 1000) / 1000;
42939
43262
  }
42940
43263
  response() {
42941
43264
  return new Response(JSON.stringify({
@@ -45629,6 +45952,8 @@ export {
45629
45952
  isCache1hEnabled,
45630
45953
  isApiKeyAccount,
45631
45954
  inspectNativeHostAuthEntry,
45955
+ hostRetryResponse,
45956
+ hostRetryHeaders,
45632
45957
  homeDefaultConfigDir,
45633
45958
  holderEntryLiveness,
45634
45959
  holderEntryIsLive,
@@ -45780,6 +46105,7 @@ export {
45780
46105
  classifySafeErrorForLog,
45781
46106
  classifyGzipRejection,
45782
46107
  classifyCacheKeepFailure,
46108
+ clampHostRetryMs,
45783
46109
  captureNativeLocalPoolBinding,
45784
46110
  canonicalPath,
45785
46111
  cacheWarmCacheablePrefixFingerprint,
@@ -45907,6 +46233,7 @@ export {
45907
46233
  MESSAGE_THREADS_BETA,
45908
46234
  MAX_UNCONFIRMED_SAME_ACCOUNT_RETRIES,
45909
46235
  MAX_SAME_ACCOUNT_WAITS,
46236
+ MAX_HOST_RETRY_MS,
45910
46237
  LOGGING_LEVELS,
45911
46238
  LEGACY_STATE_LAYOUT,
45912
46239
  KILLSWITCH_COMMAND_NAME,
@@ -9,6 +9,8 @@ export interface MessageThreadInput {
9
9
  session: string;
10
10
  request?: string;
11
11
  replyToolNames?: ReadonlyMap<string, string | null>;
12
+ cacheSlot?: (body: Body) => Body | undefined;
13
+ stateless?: boolean;
12
14
  }
13
15
  export interface MessageThreadSnapshot {
14
16
  identity: string;
@@ -22,6 +24,7 @@ export interface MessageThreadAnchor extends MessageThreadSnapshot {
22
24
  messageId: string;
23
25
  completedAt: number;
24
26
  replyFingerprint: string;
27
+ fixedCacheLayout?: FixedCacheLayout;
25
28
  }
26
29
  export type MessageThreadDecision = {
27
30
  type: 'create';
@@ -30,13 +33,13 @@ export type MessageThreadDecision = {
30
33
  previousMessageId: string;
31
34
  deltaMessages: unknown[];
32
35
  };
33
- export type MessageThreadCreateReason = 'no_anchor' | 'clock_rollback' | 'expired' | 'identity_changed' | 'too_few_messages' | 'assistant_missing' | 'extra_assistant' | 'reply_invalid' | 'reply_changed' | 'fixed_changed' | 'prefix_changed';
36
+ export type MessageThreadCreateReason = 'no_anchor' | 'clock_rollback' | 'expired' | 'identity_changed' | 'too_few_messages' | 'assistant_missing' | 'extra_assistant' | 'reply_invalid' | 'reply_changed' | 'fixed_changed' | 'prefix_changed' | 'ttl_order' | 'stateless';
34
37
  export type MessageThreadDisposition = 'never_seen' | 'superseded' | 'stream_cancelled' | 'stream_error' | 'signal_aborted' | 'invalid_completion' | 'invalid_reply' | 'response_refusal' | 'response_fallback' | 'response_rewritten' | 'thread_rejected' | 'account_disabled' | 'evicted' | 'session_deleted';
35
38
  /** Refresh preserves the local epoch; replacing a login advances it even when the row id is reused. */
36
39
  export declare function localMessageThreadCredential(binding: NativeLocalPoolBinding): string;
37
40
  type ReplyToolName = (name: unknown) => string | undefined;
38
41
  /** Canonical cacheable prefix through one content block, using thread history rules. */
39
- export declare function messageThreadCachePrefix(body: Body, messageIndex: number, blockIndex: number): string | undefined;
42
+ export declare function messageThreadCachePrefix(body: Body, messageIndex: number, blockIndex: number | readonly number[], betas?: readonly string[]): string | undefined;
40
43
  export declare function messageThreadSnapshot(input: MessageThreadInput, identity?: string, fingerprint?: string): MessageThreadSnapshot;
41
44
  /** Decide from immutable request facts; no session state or clock is read here. */
42
45
  export declare function decideMessageThread(anchor: MessageThreadAnchor | undefined, input: MessageThreadInput, snapshot: MessageThreadSnapshot, now: number): MessageThreadDecision;
@@ -50,6 +53,28 @@ export interface MessageThreadCompletion {
50
53
  replyFingerprint?: string;
51
54
  reply?: unknown;
52
55
  }
56
+ interface FullCacheTail {
57
+ identity: string;
58
+ messageIndex: number;
59
+ blockPath: number[];
60
+ prefix: string;
61
+ control: {
62
+ type: 'ephemeral';
63
+ ttl?: '1h' | '5m';
64
+ };
65
+ acceptedAt: number;
66
+ }
67
+ interface FixedCacheLayout {
68
+ lifetime: string;
69
+ system: Array<{
70
+ index: number;
71
+ control: FullCacheTail['control'];
72
+ }>;
73
+ tools: Array<{
74
+ index: number;
75
+ control: FullCacheTail['control'];
76
+ }>;
77
+ }
53
78
  export declare class MessageThreadTracker {
54
79
  private readonly capacity;
55
80
  private readonly now;
@@ -58,6 +83,7 @@ export declare class MessageThreadTracker {
58
83
  private messageHashes;
59
84
  private readonly dispositions;
60
85
  private readonly instance;
86
+ private readonly fullTails;
61
87
  constructor(capacity?: number, now?: () => number, hashBudget?: number);
62
88
  forget(session: string, disposition?: MessageThreadDisposition): void;
63
89
  private prune;
@@ -66,6 +92,7 @@ export declare class MessageThreadTracker {
66
92
  prepare(input: MessageThreadInput): {
67
93
  decision: MessageThreadDecision;
68
94
  body: Body;
95
+ tailMarkerAdded: boolean;
69
96
  normalizeToolName: ReplyToolName;
70
97
  complete: (facts: MessageThreadCompletion) => void;
71
98
  fail: (disposition?: MessageThreadDisposition) => void;
@@ -3,4 +3,6 @@ export declare const quotaRefusalDetails: (response: Response) => {
3
3
  reason: string;
4
4
  timing: ReturnType<typeof quotaRefusalTiming>;
5
5
  } | undefined;
6
- export declare function createQuotaRefusalResponse(reason: string, timing: ReturnType<typeof quotaRefusalTiming>, _now?: number): Response;
6
+ export declare function createQuotaRefusalResponse(reason: string, timing: ReturnType<typeof quotaRefusalTiming>, now?: number, options?: {
7
+ retry?: 'automatic' | 'manual';
8
+ }): Response;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/anthropic-auth-core",
3
- "version": "2.11.0",
3
+ "version": "2.11.2",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",