@cortexkit/anthropic-auth-core 2.11.1 → 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.
package/dist/index.js CHANGED
@@ -28602,22 +28602,24 @@ function fixedThreadFingerprint(input) {
28602
28602
  betas: input.betas
28603
28603
  }));
28604
28604
  }
28605
- function messageThreadCachePrefix(body, messageIndex, blockIndex) {
28605
+ function messageThreadCachePrefix(body, messageIndex, blockIndex, betas) {
28606
28606
  if (!Array.isArray(body.messages))
28607
28607
  return;
28608
28608
  const message = body.messages[messageIndex];
28609
28609
  if (!isBody(message))
28610
28610
  return;
28611
- const content = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
28612
- if (!Array.isArray(content) || !content[blockIndex])
28611
+ const content = cachePrefixContent(message.content, typeof blockIndex === "number" ? [blockIndex] : blockIndex);
28612
+ if (!content)
28613
28613
  return;
28614
28614
  const messages = body.messages.slice(0, messageIndex).concat({
28615
28615
  ...message,
28616
- content: content.slice(0, blockIndex + 1)
28616
+ content
28617
28617
  });
28618
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;
28619
28619
  return hash4(canonicalValue({
28620
28620
  model: body.model,
28621
+ speed: body.speed,
28622
+ betas,
28621
28623
  thinking: body.thinking,
28622
28624
  output_config: body.output_config,
28623
28625
  tool_choice: body.tool_choice,
@@ -28628,6 +28630,22 @@ function messageThreadCachePrefix(body, messageIndex, blockIndex) {
28628
28630
  messages: messages.map(withoutMessageCache)
28629
28631
  }));
28630
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
+ }
28631
28649
  function messageThreadSnapshot(input, identity4 = hash4([input.account, input.credential]), fingerprint = fixedThreadFingerprint(input)) {
28632
28650
  const messages = (Array.isArray(input.body.messages) ? input.body.messages : []).map((message) => hash4(canonicalValue(withoutMessageCache(message))));
28633
28651
  return {
@@ -28671,6 +28689,171 @@ function decideMessageThread(anchor, input, snapshot, now) {
28671
28689
  deltaMessages: messages.slice(anchor.messages.length + 1)
28672
28690
  };
28673
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
+ }
28674
28857
 
28675
28858
  class MessageThreadTracker {
28676
28859
  capacity;
@@ -28680,12 +28863,15 @@ class MessageThreadTracker {
28680
28863
  messageHashes = 0;
28681
28864
  dispositions = new Map;
28682
28865
  instance = randomUUID18();
28866
+ fullTails = new Map;
28683
28867
  constructor(capacity = MAX_SESSIONS, now = Date.now, hashBudget = MAX_MESSAGE_HASHES) {
28684
28868
  this.capacity = capacity;
28685
28869
  this.now = now;
28686
28870
  this.hashBudget = hashBudget;
28687
28871
  }
28688
28872
  forget(session, disposition = "session_deleted") {
28873
+ if (disposition === "session_deleted" || disposition === "evicted")
28874
+ this.fullTails.delete(session);
28689
28875
  this.messageHashes -= this.sessions.get(session)?.anchor?.messages.length ?? 0;
28690
28876
  this.sessions.delete(session);
28691
28877
  this.dispositions.delete(session);
@@ -28733,48 +28919,80 @@ class MessageThreadTracker {
28733
28919
  const now = this.now();
28734
28920
  const identity4 = anchor && now >= anchor.completedAt && now - anchor.completedAt < MAX_AGE_MS ? hash4([input.account, input.credential]) : undefined;
28735
28921
  let snapshot;
28736
- let reason = continuationBlocker(anchor, input, identity4, now);
28922
+ let threadInput = input;
28923
+ let reason = input.stateless ? "stateless" : continuationBlocker(anchor, input, identity4, now);
28737
28924
  if (!reason && anchor) {
28738
- 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);
28739
28931
  if (fingerprint === anchor.fingerprint)
28740
- snapshot = messageThreadSnapshot(input, identity4, fingerprint);
28932
+ snapshot = messageThreadSnapshot(threadInput, identity4, fingerprint);
28741
28933
  else
28742
28934
  reason = "fixed_changed";
28743
28935
  }
28744
- 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
+ }
28745
28960
  if (decision.type === "create")
28746
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
+ });
28747
28972
  const token2 = {};
28748
28973
  this.forget(input.session, "superseded");
28749
28974
  this.sessions.set(input.session, { token: token2 });
28750
28975
  this.prune();
28751
28976
  const fail = this.failureFor(input.session, token2);
28977
+ let accepted = false;
28752
28978
  let body;
28753
28979
  const outgoingBody = () => {
28980
+ if (continueBody)
28981
+ return continueBody;
28754
28982
  if (body)
28755
28983
  return body;
28756
- const full = input.body;
28984
+ const full = tailResult?.body ?? input.body;
28757
28985
  body = {
28758
28986
  ...full,
28759
- thread: decision.type === "create" ? { type: "create" } : {
28760
- type: "continue",
28761
- previous_message_id: decision.previousMessageId
28762
- }
28987
+ thread: { type: "create" }
28763
28988
  };
28764
- if (decision.type === "continue") {
28765
- Object.assign(body, { messages: decision.deltaMessages });
28766
- placeContinueCache(body, full);
28767
- Object.assign(body, {
28768
- diagnostics: {
28769
- ...isBody(body.diagnostics) ? body.diagnostics : {},
28770
- previous_message_id: decision.previousMessageId
28771
- }
28772
- });
28773
- }
28989
+ if (input.stateless)
28990
+ delete body.thread;
28774
28991
  return body;
28775
28992
  };
28776
28993
  return {
28777
28994
  decision,
28995
+ tailMarkerAdded: Boolean(tailResult?.body),
28778
28996
  get body() {
28779
28997
  return outgoingBody();
28780
28998
  },
@@ -28782,7 +29000,7 @@ class MessageThreadTracker {
28782
29000
  fail,
28783
29001
  complete: (facts) => {
28784
29002
  const current = this.sessions.get(input.session);
28785
- if (current?.token !== token2 || current.anchor)
29003
+ if (current?.token !== token2 || current.anchor || accepted)
28786
29004
  return;
28787
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) {
28788
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");
@@ -28794,7 +29012,31 @@ class MessageThreadTracker {
28794
29012
  return;
28795
29013
  }
28796
29014
  const completedAt = this.now();
28797
- 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);
28798
29040
  this.messageHashes += completedSnapshot.messages.length;
28799
29041
  this.sessions.set(input.session, {
28800
29042
  token: token2,
@@ -28802,7 +29044,10 @@ class MessageThreadTracker {
28802
29044
  ...completedSnapshot,
28803
29045
  messageId: facts.messageId,
28804
29046
  completedAt,
28805
- replyFingerprint
29047
+ replyFingerprint,
29048
+ ...input.cacheSlot ? {
29049
+ fixedCacheLayout: decision.type === "continue" ? anchor?.fixedCacheLayout : fixedCacheLayout(tailResult?.body ?? input.body)
29050
+ } : {}
28806
29051
  }
28807
29052
  });
28808
29053
  this.prune();
@@ -28932,8 +29177,11 @@ function placeContinueCache(body, full) {
28932
29177
  delete holder.cache_control;
28933
29178
  }
28934
29179
  }
29180
+ function requestHeaderBetas(headers) {
29181
+ return (headers.get("anthropic-beta") ?? "").split(",").map((beta) => beta.trim()).filter(Boolean);
29182
+ }
28935
29183
  function messageThreadBetas(headers) {
28936
- 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);
28937
29185
  betas.push(MESSAGE_THREADS_BETA);
28938
29186
  headers.set("anthropic-beta", betas.join(","));
28939
29187
  return betas;
@@ -29031,14 +29279,17 @@ async function prepareMessageThreadRequest(tracker, input) {
29031
29279
  const fullBody = () => full ??= JSON.parse(fullText);
29032
29280
  const accountKey = input.account;
29033
29281
  let threading = !disabledThreadAccounts.has(accountKey);
29034
- const betas = threading ? messageThreadBetas(input.headers) : [];
29282
+ if (threading)
29283
+ messageThreadBetas(input.headers);
29035
29284
  const prepareForSession = (credential3) => tracker.prepare({
29036
29285
  account: input.account,
29037
29286
  credential: credential3,
29038
29287
  session: input.session ?? "",
29039
29288
  request: input.request ?? input.headers.get("x-client-request-id") ?? undefined,
29040
- betas,
29289
+ betas: requestHeaderBetas(input.headers),
29041
29290
  replyToolNames: input.replyToolNames,
29291
+ cacheSlot: input.cacheSlot,
29292
+ stateless: !threading,
29042
29293
  get body() {
29043
29294
  return fullBody();
29044
29295
  }
@@ -29054,8 +29305,9 @@ async function prepareMessageThreadRequest(tracker, input) {
29054
29305
  credential: input.credential,
29055
29306
  request: input.request ?? input.headers.get("x-client-request-id") ?? undefined
29056
29307
  });
29057
- let prepared = threading && input.session ? prepareForSession(input.credential) : {
29308
+ let prepared = input.session ? prepareForSession(input.credential) : {
29058
29309
  decision: { type: "create" },
29310
+ tailMarkerAdded: false,
29059
29311
  get body() {
29060
29312
  return threading ? { ...fullBody(), thread: { type: "create" } } : fullBody();
29061
29313
  },
@@ -29066,7 +29318,8 @@ async function prepareMessageThreadRequest(tracker, input) {
29066
29318
  fail: ignoreThreadFailure
29067
29319
  };
29068
29320
  const failure = threadFailureState(prepared.fail);
29069
- 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();
29070
29323
  let bodyText = await signRequestBody(outgoing);
29071
29324
  let recovered = false;
29072
29325
  let credential2 = input.credential;
@@ -29086,7 +29339,11 @@ async function prepareMessageThreadRequest(tracker, input) {
29086
29339
  const prepareStateless = async () => {
29087
29340
  prepared.fail("account_disabled");
29088
29341
  latchStateless();
29089
- 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());
29090
29347
  };
29091
29348
  return {
29092
29349
  get bodyText() {
@@ -29094,7 +29351,7 @@ async function prepareMessageThreadRequest(tracker, input) {
29094
29351
  },
29095
29352
  fail: failure.fail,
29096
29353
  observe: (response) => {
29097
- if (!threading || !input.session || disabledThreadAccounts.has(accountKey)) {
29354
+ if (!input.session || threading && disabledThreadAccounts.has(accountKey)) {
29098
29355
  prepared.fail("account_disabled");
29099
29356
  return response;
29100
29357
  }
@@ -29133,7 +29390,7 @@ async function prepareMessageThreadRequest(tracker, input) {
29133
29390
  prepared = prepareForSession(credential2);
29134
29391
  failure.replace(prepared.fail);
29135
29392
  }
29136
- bodyText = await signRequestBody(serializedCreate(fullText, fullBody));
29393
+ bodyText = await signRequestBody(fullOutgoing());
29137
29394
  const created = await send(bodyText);
29138
29395
  if (await isThreadCreateRejection(created)) {
29139
29396
  if (!await mayResend(created, beforeResend)) {
@@ -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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/anthropic-auth-core",
3
- "version": "2.11.1",
3
+ "version": "2.11.2",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",