@cortexkit/anthropic-auth-core 2.10.0 → 2.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/billing.d.ts CHANGED
@@ -2,8 +2,15 @@ import { type BillingUsage, type ReportRoutingInput } from "./internal-types/rou
2
2
  type BillingReport = Extract<ReportRoutingInput, {
3
3
  kind: 'billing';
4
4
  }>;
5
+ export type AnthropicBillingWarming = NonNullable<NonNullable<BillingReport['cache']>['warming']>;
5
6
  export type AnthropicBillingRequest = Omit<BillingReport, 'kind' | 'attemptId' | 'provider' | 'outcome' | 'status' | 'providerRequestId' | 'providerResponseId' | 'usage' | 'usageByModel'> & {
6
7
  attemptId?: string;
8
+ /**
9
+ * Read once a completed response finishes, after the host has let CacheKeep
10
+ * track or refuse it, so the report carries the keep-warm state that request
11
+ * produced. Must not wait or do I/O; `undefined` leaves `cache.warming` out.
12
+ */
13
+ cacheWarming?: () => AnthropicBillingWarming | undefined;
7
14
  };
8
15
  /** Iteration usage is the billed sum; top-level usage can describe only the last model. */
9
16
  export declare function anthropicBillingUsage(raw: Record<string, unknown>): {
@@ -1,6 +1,6 @@
1
- import type { CacheWarmStopReason } from "./internal-types/routing-accessor/index.js";
1
+ import { type CacheWarmStopReason } from "./internal-types/routing-accessor/index.js";
2
2
  import type { AccountStorage } from './accounts.ts';
3
- import { type AnthropicBillingRequest } from './billing.ts';
3
+ import { type AnthropicBillingRequest, type AnthropicBillingWarming } from './billing.ts';
4
4
  import { type CacheKeepFailure } from './cachekeep-failure.ts';
5
5
  import type { CacheKeepStopReason, CacheKeepTrackedSession } from './cachekeep-registry.ts';
6
6
  import { type NativeAccountRefusalReason } from './native-account-refusal.ts';
@@ -187,6 +187,7 @@ export declare class CacheKeepManager {
187
187
  private readonly targets;
188
188
  private readonly immediateTargets;
189
189
  private readonly stoppedSessions;
190
+ private readonly warmingRecords;
190
191
  private timer;
191
192
  private dueTimer;
192
193
  private tickPromise;
@@ -292,6 +293,21 @@ export declare class CacheKeepManager {
292
293
  */
293
294
  trackedPolicyState(id: string): Readonly<CacheKeepPolicyState> | undefined;
294
295
  hasPlannedTarget(id: string): boolean;
296
+ /**
297
+ * Whether keep-warm tracks a session, read from memory only (no lock, no
298
+ * storage). `on: true` means a live target holds the session's cache. A stop
299
+ * carries its reason only when billing reports accept that reason
300
+ * (`isCacheWarmStopReason`); other stops report `on: false` alone.
301
+ * `undefined` means this manager has seen nothing that decides it.
302
+ */
303
+ warming(id: string): AnthropicBillingWarming | undefined;
304
+ /**
305
+ * Record that a session's policy or settings keep warming off, for a host
306
+ * that refuses to track before reaching this manager (an API-key route,
307
+ * local keep-warm disabled, or a subagent without subagent warming).
308
+ */
309
+ recordWarmingOff(id: string): void;
310
+ private setWarmingRecord;
295
311
  updateSubagent(id: string, isSubagent: boolean): void;
296
312
  /** An old response cannot price or reset a newer captured request. */
297
313
  recordAcceptedUsage(id: string, bodyText: string, usage: AcceptedCacheUsage): void;
@@ -26,6 +26,7 @@ export declare const CCH_SALT = "59cf53e54c78";
26
26
  export declare const CCH_POSITIONS: number[];
27
27
  export declare const CLAUDE_CODE_VERSION = "2.1.302";
28
28
  export declare const CLAUDE_CODE_ENTRYPOINT = "cli";
29
+ export declare const CLAUDE_CODE_ACCEPT_ENCODING = "gzip, deflate, br, zstd";
29
30
  export declare const CLAUDE_CODE_STAINLESS_PACKAGE_VERSION = "0.128.0";
30
31
  export declare const CLAUDE_CODE_STAINLESS_RUNTIME_VERSION = "v26.3.0";
31
32
  /**
package/dist/index.d.ts CHANGED
@@ -101,6 +101,7 @@ export * from './request-gzip.ts';
101
101
  export * from './request-history.ts';
102
102
  export * from './routing.ts';
103
103
  export * from './routing-peek.ts';
104
+ export * from './routing-reports.ts';
104
105
  export * from './server-fallback-usage.ts';
105
106
  export * from './session-cache-activity.ts';
106
107
  export * from './session-cache-policy.ts';
package/dist/index.js CHANGED
@@ -9787,6 +9787,7 @@ var CCH_SALT = "59cf53e54c78";
9787
9787
  var CCH_POSITIONS = [4, 7, 20];
9788
9788
  var CLAUDE_CODE_VERSION = "2.1.302";
9789
9789
  var CLAUDE_CODE_ENTRYPOINT = "cli";
9790
+ var CLAUDE_CODE_ACCEPT_ENCODING = "gzip, deflate, br, zstd";
9790
9791
  var CLAUDE_CODE_STAINLESS_PACKAGE_VERSION = "0.128.0";
9791
9792
  var CLAUDE_CODE_STAINLESS_RUNTIME_VERSION = "v26.3.0";
9792
9793
  var CLAUDE_CODE_GZIPS_REQUEST_BODIES = true;
@@ -11653,7 +11654,7 @@ function isSseCandidateFrame(frame) {
11653
11654
 
11654
11655
  // src/stream-completion.ts
11655
11656
  var timings = new WeakMap;
11656
- function copyStreamResponseTiming(source, target, sent, timingSource = "physical_fetch") {
11657
+ function copyStreamResponseTiming(source, target, sent, timingSource = "physical_fetch", bodySizes) {
11657
11658
  const timing = timings.get(source);
11658
11659
  if (timing)
11659
11660
  timings.set(target, timing);
@@ -11662,7 +11663,8 @@ function copyStreamResponseTiming(source, target, sent, timingSource = "physical
11662
11663
  sent,
11663
11664
  headers: performance.now(),
11664
11665
  contentLength: responseHeaders(target.headers)["content-length"],
11665
- source: timingSource
11666
+ source: timingSource,
11667
+ bodySizes
11666
11668
  });
11667
11669
  return target;
11668
11670
  }
@@ -11682,6 +11684,10 @@ function responseHeaders(headers) {
11682
11684
  }
11683
11685
  return result;
11684
11686
  }
11687
+ function bodyByteCounts(input) {
11688
+ const { encoded_body_bytes, decoded_body_bytes } = input ?? {};
11689
+ return typeof encoded_body_bytes === "number" && Number.isSafeInteger(encoded_body_bytes) && encoded_body_bytes >= 0 && typeof decoded_body_bytes === "number" && Number.isSafeInteger(decoded_body_bytes) && decoded_body_bytes >= 0 ? { encoded_body_bytes, decoded_body_bytes } : {};
11690
+ }
11685
11691
  function safeIncompleteStreamDiagnostics(input) {
11686
11692
  const count = (value) => Number.isSafeInteger(value) && value >= 0 ? value : 0;
11687
11693
  return {
@@ -11689,6 +11695,7 @@ function safeIncompleteStreamDiagnostics(input) {
11689
11695
  get: (name) => input.response_headers[name] ?? null
11690
11696
  }),
11691
11697
  response_bytes: count(input.response_bytes),
11698
+ ...bodyByteCounts(input),
11692
11699
  sse_events: count(input.sse_events),
11693
11700
  ...input.send_to_headers_ms !== undefined ? { send_to_headers_ms: count(input.send_to_headers_ms) } : {},
11694
11701
  ...input.timing_source === "physical_fetch" || input.timing_source === "credential_scope" ? { timing_source: input.timing_source } : {},
@@ -11745,6 +11752,7 @@ function createAnthropicStreamCompletion(response) {
11745
11752
  const diagnostics = {
11746
11753
  response_headers: headers,
11747
11754
  response_bytes: bytes,
11755
+ ...bodyByteCounts(timing?.bodySizes?.()),
11748
11756
  sse_events: events,
11749
11757
  ...timing ? {
11750
11758
  send_to_headers_ms: Math.max(0, Math.round(timing.headers - timing.sent)),
@@ -11895,7 +11903,7 @@ function detachReport(report2) {
11895
11903
  } catch {}
11896
11904
  }, 0).unref?.();
11897
11905
  }
11898
- function identity2(input) {
11906
+ function identity2({ cacheWarming: _, ...input }) {
11899
11907
  return {
11900
11908
  ...input,
11901
11909
  kind: "billing",
@@ -11924,11 +11932,21 @@ function createAnthropicBillingObserver(input, status, headers, sse = headers.ge
11924
11932
  const measured = anthropicBillingUsage(rawUsage);
11925
11933
  if (!finalUsage)
11926
11934
  delete measured.usage.output;
11935
+ const outcome = failed ? "failed" : !finalUsage ? "cut" : "completed";
11936
+ let cache = failed ? undefined : base.cache;
11937
+ if (outcome === "completed" && !cache?.warming && input.cacheWarming) {
11938
+ let warming;
11939
+ try {
11940
+ warming = input.cacheWarming();
11941
+ } catch {}
11942
+ if (warming)
11943
+ cache = { ...cache, warming };
11944
+ }
11927
11945
  detachReport({
11928
11946
  ...base,
11929
- cache: failed ? undefined : base.cache,
11947
+ cache,
11930
11948
  providerResponseId,
11931
- outcome: failed ? "failed" : !finalUsage ? "cut" : "completed",
11949
+ outcome,
11932
11950
  ...measured
11933
11951
  });
11934
11952
  };
@@ -17695,6 +17713,7 @@ function cacheKeepSentCredentials(headers) {
17695
17713
  }
17696
17714
  var PLANNED_UNPRICED_MAIN_IDLE_MS = 60 * 60000;
17697
17715
  var PLANNED_UNPRICED_SUBAGENT_IDLE_MS = 30 * 60000;
17716
+ var WARMING_RECORD_LIMIT = 4096;
17698
17717
 
17699
17718
  class CacheKeepWarmRefusal extends Error {
17700
17719
  reason;
@@ -17709,6 +17728,7 @@ class CacheKeepManager2 {
17709
17728
  targets = new Map;
17710
17729
  immediateTargets = new Map;
17711
17730
  stoppedSessions = new Map;
17731
+ warmingRecords = new Map;
17712
17732
  timer = null;
17713
17733
  dueTimer = null;
17714
17734
  tickPromise = null;
@@ -17817,6 +17837,28 @@ class CacheKeepManager2 {
17817
17837
  hasPlannedTarget(id) {
17818
17838
  return this.targets.get(id)?.policyState?.planned === true;
17819
17839
  }
17840
+ warming(id) {
17841
+ const target = this.targets.get(id);
17842
+ if (target && (this.options.now?.() ?? Date.now()) < target.cacheExpiresAt)
17843
+ return { on: true };
17844
+ const record5 = this.warmingRecords.get(id);
17845
+ if (!record5)
17846
+ return;
17847
+ return isCacheWarmStopReason(record5.stopReason) ? { on: false, stopReason: record5.stopReason } : { on: false };
17848
+ }
17849
+ recordWarmingOff(id) {
17850
+ this.setWarmingRecord(id, {});
17851
+ }
17852
+ setWarmingRecord(id, record5) {
17853
+ this.warmingRecords.delete(id);
17854
+ this.warmingRecords.set(id, record5);
17855
+ while (this.warmingRecords.size > WARMING_RECORD_LIMIT) {
17856
+ const oldest = this.warmingRecords.keys().next();
17857
+ if (oldest.done)
17858
+ break;
17859
+ this.warmingRecords.delete(oldest.value);
17860
+ }
17861
+ }
17820
17862
  updateSubagent(id, isSubagent) {
17821
17863
  const target = this.targets.get(id);
17822
17864
  if (!target || target.isSubagent === isSubagent)
@@ -18022,6 +18064,8 @@ class CacheKeepManager2 {
18022
18064
  }
18023
18065
  reportStop(target, reason, at) {
18024
18066
  const state = target.policyState;
18067
+ if (!target.sourceWarm)
18068
+ this.setWarmingRecord(target.id, { stopReason: reportStopReason(reason) });
18025
18069
  if (target.sourceWarm || !state?.hasWarmed || this.reportedStops.has(state))
18026
18070
  return;
18027
18071
  if (reportSessionCacheWarmStopped(state.ownerSessionId, {
@@ -18107,12 +18151,22 @@ class CacheKeepManager2 {
18107
18151
  return retire("unsupported");
18108
18152
  if (!policy && (input.retained?.policyState?.planned || previous?.policyState?.planned))
18109
18153
  return retire("session-ended");
18110
- if (policy?.ttl === "none" || policy?.keep_warm === "off")
18154
+ const sessionId = input.sessionId;
18155
+ const keptOff = () => {
18156
+ if (!previous && !input.sourceWarm)
18157
+ this.recordWarmingOff(sessionId);
18158
+ };
18159
+ if (policy?.ttl === "none" || policy?.keep_warm === "off") {
18160
+ if (policy.keep_warm === "off")
18161
+ keptOff();
18111
18162
  return retire("unsupported");
18163
+ }
18112
18164
  if (!planned && !isCacheKeepPersistentlyEnabled(input.storage)) {
18165
+ keptOff();
18113
18166
  return refuse("cachekeep disabled", "disabled");
18114
18167
  }
18115
18168
  if (!planned && input.cacheMode !== "hybrid") {
18169
+ keptOff();
18116
18170
  return refuse("cache mode is not hybrid", "not-hybrid");
18117
18171
  }
18118
18172
  bodyBytes = Buffer.byteLength(input.bodyText, "utf8");
@@ -18153,6 +18207,7 @@ class CacheKeepManager2 {
18153
18207
  if (this.targets.has(input.sessionId))
18154
18208
  this.targets.delete(input.sessionId);
18155
18209
  this.stoppedSessions.delete(input.sessionId);
18210
+ this.warmingRecords.delete(input.sessionId);
18156
18211
  const headers = {};
18157
18212
  input.headers.forEach((value, key) => {
18158
18213
  headers[key] = value;
@@ -42671,6 +42726,62 @@ function peekRoutingAccount(input) {
42671
42726
  }
42672
42727
  return;
42673
42728
  }
42729
+ // src/routing-reports.ts
42730
+ var ROUTING_POOL_NAME = /^[a-z0-9._-]{1,64}$/;
42731
+ function reportRoutingResponse(sessionId, subject, headers, status, modelId, served = status < 400, quotaFor) {
42732
+ Promise.resolve().then(async () => {
42733
+ if (!subject.accountIdentity || typeof Reflect.get(globalThis, Symbol.for("cortexkit.routing")) !== "function")
42734
+ return;
42735
+ const identity4 = {
42736
+ sessionId,
42737
+ accountId: subject.accountIdentity,
42738
+ ...subject.credentialId ? { credentialId: subject.credentialId } : {}
42739
+ };
42740
+ const reports = [];
42741
+ if (served && status < 400) {
42742
+ const rateHeaders = {};
42743
+ headers.forEach((value, name) => {
42744
+ if (name.toLowerCase().startsWith("anthropic-ratelimit-"))
42745
+ rateHeaders[name.toLowerCase()] = value;
42746
+ });
42747
+ reports.push({ ...identity4, outcome: "served", headers: rateHeaders });
42748
+ }
42749
+ const quota2 = status === 429 ? quotaExhaustionFromHeaders(headers, modelId) : undefined;
42750
+ if (quota2) {
42751
+ for (const [window2, reading2] of [
42752
+ ["5h", quota2.five_hour],
42753
+ ["7d", quota2.seven_day]
42754
+ ]) {
42755
+ if (reading2)
42756
+ reports.push({
42757
+ ...identity4,
42758
+ outcome: "exhausted",
42759
+ window: window2,
42760
+ ...reading2.resetsAt ? { resetsAt: Date.parse(reading2.resetsAt) } : {}
42761
+ });
42762
+ }
42763
+ }
42764
+ for (const report2 of reports)
42765
+ reportRouting(report2);
42766
+ if (quota2?.scoped?.length) {
42767
+ const stored = await quotaFor?.();
42768
+ const scoped = getScopedQuotaWindowForModel({
42769
+ scoped: stored?.scoped?.filter((row) => row.id.startsWith("claude-weekly-scoped-"))
42770
+ }, modelId);
42771
+ const pool = (scoped?.modelId ?? scoped?.modelName)?.trim().toLowerCase();
42772
+ if (!pool || !ROUTING_POOL_NAME.test(pool))
42773
+ return;
42774
+ for (const reading2 of quota2.scoped)
42775
+ reportRouting({
42776
+ ...identity4,
42777
+ outcome: "exhausted",
42778
+ window: "7d",
42779
+ pool,
42780
+ ...reading2.resetsAt ? { resetsAt: Date.parse(reading2.resetsAt) } : {}
42781
+ });
42782
+ }
42783
+ }).catch(() => {});
42784
+ }
42674
42785
  // src/start.ts
42675
42786
  var CLAUDE_START_COMMAND_NAME = "claude-start";
42676
42787
  var START_STATUS_TITLE = "## Claude Lane Start Status";
@@ -45089,6 +45200,7 @@ export {
45089
45200
  requestCacheLifetimeMs,
45090
45201
  reportSessionCacheWarmStopped,
45091
45202
  reportSessionCacheTouch,
45203
+ reportRoutingResponse,
45092
45204
  reportRouting,
45093
45205
  reportAnthropicBillingFailure,
45094
45206
  renameWithWindowsSharingRetry,
@@ -45632,6 +45744,7 @@ export {
45632
45744
  CLAUDE_CODE_FULL_AGENT_BETAS,
45633
45745
  CLAUDE_CODE_ENTRYPOINT,
45634
45746
  CLAUDE_CODE_DEFAULT_BETAS,
45747
+ CLAUDE_CODE_ACCEPT_ENCODING,
45635
45748
  CLAUDE_CACHE_KEEP_COMMAND_NAME,
45636
45749
  CLAUDE_ACCOUNT_COMMAND_NAME,
45637
45750
  CCH_SALT,
@@ -0,0 +1,7 @@
1
+ import { type OAuthQuotaSnapshot } from './accounts.ts';
2
+ export type RoutingReportSubject = {
3
+ accountIdentity?: string;
4
+ credentialId?: string;
5
+ };
6
+ /** Report only the serving response's raw headers, without delaying or failing a send. */
7
+ export declare function reportRoutingResponse(sessionId: string, subject: RoutingReportSubject, headers: Headers, status: number, modelId?: string, served?: boolean, quotaFor?: () => Promise<OAuthQuotaSnapshot | undefined>): void;
@@ -1,6 +1,8 @@
1
1
  export interface IncompleteStreamDiagnostics {
2
2
  response_headers: Record<string, string>;
3
3
  response_bytes: number;
4
+ encoded_body_bytes?: number;
5
+ decoded_body_bytes?: number;
4
6
  sse_events: number;
5
7
  send_to_headers_ms?: number;
6
8
  /**
@@ -11,7 +13,7 @@ export interface IncompleteStreamDiagnostics {
11
13
  headers_to_eof_ms: number;
12
14
  }
13
15
  /** Preserve physical-send timing across wrappers without reading or cloning the body. */
14
- export declare function copyStreamResponseTiming(source: Response, target: Response, sent?: number, timingSource?: 'physical_fetch' | 'credential_scope'): Response;
16
+ export declare function copyStreamResponseTiming(source: Response, target: Response, sent?: number, timingSource?: 'physical_fetch' | 'credential_scope', bodySizes?: () => Pick<IncompleteStreamDiagnostics, 'encoded_body_bytes' | 'decoded_body_bytes'> | undefined): Response;
15
17
  export declare function safeIncompleteStreamDiagnostics(input: IncompleteStreamDiagnostics): IncompleteStreamDiagnostics;
16
18
  /** EOF requires a complete message_stop or an explicit protocol error. */
17
19
  export declare function createAnthropicStreamCompletion(response: Response): {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/anthropic-auth-core",
3
- "version": "2.10.0",
3
+ "version": "2.10.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",