@cortexkit/pi-anthropic-auth 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/stream.d.ts CHANGED
@@ -22,6 +22,7 @@ type AnthropicEvent = {
22
22
  delta?: Record<string, unknown>;
23
23
  error?: Record<string, unknown>;
24
24
  message?: {
25
+ id?: string;
25
26
  usage?: Record<string, number>;
26
27
  };
27
28
  usage?: Record<string, number>;
package/dist/stream.js CHANGED
@@ -1,4 +1,4 @@
1
- import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, copyStreamResponseTiming, createAnthropicStreamCompletion, createDumpResponseObserver, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, dumpResponseArtifact, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getCacheKeepRegistryDirectories, getClaudeCodeIdentityForVerifiedAccount, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, localMessageThreadCredential, logger, MessageThreadTracker, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, orderClaudeCodeBody, PROMPT_CACHE_DEFAULT_TTL_MS, parseSseFrame, prepareMessageThreadRequest, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readSessionCachePolicy, reportSessionCacheTouch, requestCacheLifetimeMs, resolveNativePoolPaths, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, stickyRouteFamilyForModel, withAnthropicBilling, } from '@cortexkit/anthropic-auth-core';
1
+ import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ACCEPT_ENCODING, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, copyStreamResponseTiming, createAnthropicStreamCompletion, createDumpResponseObserver, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, dumpResponseArtifact, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getCacheKeepRegistryDirectories, getClaudeCodeIdentityForVerifiedAccount, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, localMessageThreadCredential, logger, MessageThreadTracker, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, orderClaudeCodeBody, PROMPT_CACHE_DEFAULT_TTL_MS, parseSseFrame, prepareMessageThreadRequest, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readSessionCachePolicy, reportRoutingResponse, reportSessionCacheTouch, requestCacheLifetimeMs, resolveNativePoolPaths, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, stickyRouteFamilyForModel, withAnthropicBilling, } from '@cortexkit/anthropic-auth-core';
2
2
  import { calculateCost, createAssistantMessageEventStream, } from '@earendil-works/pi-ai';
3
3
  import { PiCacheKeep } from './cachekeep.js';
4
4
  import { buildAnthropicRequest, fromClaudeCodeToolName } from './convert.js';
@@ -6,7 +6,7 @@ import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, } from
6
6
  import { getPiAccountStoragePath } from './paths.js';
7
7
  import { registerPiPrimeSender } from './prime.js';
8
8
  import { markPiAccountHold, withPiQuotaWait, } from './quota-wait.js';
9
- import { buildPiOAuthMessagesUrl, fetchPiOAuth, requirePiOAuthOrigin, } from './transport.js';
9
+ import { buildPiOAuthMessagesUrl, fetchPiOAuth, fetchPiStreamResponse, requirePiOAuthOrigin, } from './transport.js';
10
10
  const messageThreads = new MessageThreadTracker();
11
11
  const dumpResponseObservers = new WeakMap();
12
12
  // Each session owns its lease; storage identifies which host may end it.
@@ -194,6 +194,8 @@ function applyPiOAuthRequestHeaders(headers, accessToken, options) {
194
194
  extraBetas: options.leadingBetas,
195
195
  requestClass: options.requestClass,
196
196
  });
197
+ // Pi runs on undici, whose default encoding order differs from Claude Code's.
198
+ headers.set('accept-encoding', CLAUDE_CODE_ACCEPT_ENCODING);
197
199
  if (body.speed === 'fast')
198
200
  headers.set('anthropic-beta', mergeAnthropicBetas(headers.get('anthropic-beta'), [FAST_MODE_BETA]));
199
201
  return headers;
@@ -504,9 +506,7 @@ async function sendAnthropicRequest(options, deps = {}) {
504
506
  assertHostAuthorityStable();
505
507
  const fetchImpl = deps.fetch ?? globalThis.fetch;
506
508
  const fetchResponse = async (input, init) => {
507
- const sentAt = performance.now();
508
- const response = await fetchImpl(input, init);
509
- return copyStreamResponseTiming(response, response, sentAt);
509
+ return fetchPiStreamResponse(input, init, fetchImpl);
510
510
  };
511
511
  const keep = deps.cacheKeep ?? cacheKeepManager;
512
512
  const native = deps.native ?? getPiNativeRuntime(options.storagePath);
@@ -571,6 +571,14 @@ async function sendAnthropicRequest(options, deps = {}) {
571
571
  ...(options.prime && { requestClass: 'auxiliary' }),
572
572
  });
573
573
  const relayAffinity = options.streamOptions?.sessionId ?? null;
574
+ const reportRoutingHeaders = (attempt, responseHeaders, status) => {
575
+ if (options.prime || !relayAffinity)
576
+ return;
577
+ const payer = piBillingPayer(attempt);
578
+ reportRoutingResponse(relayAffinity, { accountIdentity: payer.accountId, credentialId: payer.credentialId }, responseHeaders, status, typeof body.model === 'string' ? body.model : options.model.id, status < 400, async () => selected?.accountIdentity === payer.accountId
579
+ ? selected.quota
580
+ : undefined);
581
+ };
574
582
  const billingInput = (attempt, apiSubject) => {
575
583
  // The session runner matches billing reports to session transcripts, and
576
584
  // Prime is account-wide with no session, so it sends no billing report.
@@ -582,13 +590,24 @@ async function sendAnthropicRequest(options, deps = {}) {
582
590
  if (!credentialId)
583
591
  return undefined;
584
592
  const ttlMs = requestCacheLifetimeMs(wireBodyText);
593
+ const sessionId = relayAffinity;
585
594
  return {
586
595
  ...(attempt ? piBillingPayer(attempt) : { credentialId }),
587
- sessionId: relayAffinity,
596
+ sessionId,
588
597
  model: typeof body.model === 'string' ? body.model : options.model.id,
589
598
  requestKind: options.requestOrigin === 'direct' ? 'generate' : 'primary',
590
599
  chargeBasis: options.apiAccount ? 'metered_api' : 'subscription_included',
591
600
  ...(ttlMs > 0 ? { cache: { ttlMs } } : {}),
601
+ // Read when the response finishes. API-key routes are never warmed. An
602
+ // OAuth answer waits for nothing: until this attempt's CacheKeep
603
+ // tracking has settled, the state is left out.
604
+ cacheWarming: () => {
605
+ if (options.apiAccount)
606
+ return { on: false };
607
+ if (!attempt || cacheTracking.get(attempt) !== 'settled')
608
+ return undefined;
609
+ return keep.warming(sessionId);
610
+ },
592
611
  };
593
612
  };
594
613
  let input = options.apiAccount
@@ -602,6 +621,7 @@ async function sendAnthropicRequest(options, deps = {}) {
602
621
  ...(!options.apiAccount && { redirect: 'error' }),
603
622
  };
604
623
  const cacheAccepted = new Set();
624
+ const cacheTracking = new Map();
605
625
  const trackAcceptedRequest = (attempt, sentBody = wireBodyText) => {
606
626
  if (options.prime || options.apiAccount || init.signal?.aborted)
607
627
  return;
@@ -636,6 +656,8 @@ async function sendAnthropicRequest(options, deps = {}) {
636
656
  const tracked = deps.cacheKeep
637
657
  ? Promise.resolve(keep.track(target))
638
658
  : piCacheKeep.trackAccepted(target, snapshot);
659
+ cacheTracking.set(attempt, 'pending');
660
+ void tracked.then(() => cacheTracking.set(attempt, 'settled'), () => { });
639
661
  let latestUsage = {};
640
662
  options.onCacheUsageRecorder?.((usage) => {
641
663
  if (!usage || init.signal?.aborted || !relayAffinity)
@@ -755,9 +777,14 @@ async function sendAnthropicRequest(options, deps = {}) {
755
777
  },
756
778
  }));
757
779
  };
758
- const physicalFetch = (send) => {
780
+ const physicalFetch = async (send) => {
759
781
  const billing = billingInput(attempt, apiSubject);
760
- return billing ? withAnthropicBilling(billing, send) : send();
782
+ const response = await (billing
783
+ ? withAnthropicBilling(billing, send)
784
+ : send());
785
+ if (attempt)
786
+ reportRoutingHeaders(attempt, response.headers, response.status);
787
+ return response;
761
788
  };
762
789
  let response;
763
790
  try {
@@ -854,44 +881,54 @@ async function sendAnthropicRequest(options, deps = {}) {
854
881
  // The relay scrubs each physical relay attempt's responses and errors with
855
882
  // that attempt's own credentials and the relay token; a direct fallback is
856
883
  // scrubbed by directFetch.
857
- const sendRelayAttempt = async () => sendViaRelay({
858
- config: relayConfig,
859
- input,
860
- init,
861
- headers,
862
- body: wireBodyText,
863
- fallback: directFetch,
864
- affinity: relayAffinity,
865
- onDumpCreated: (handle) => {
866
- dumpHandle = handle;
867
- },
868
- authorizeAttempt: async () => {
869
- const attempt = await takeAttempt();
870
- await options.prime?.beforeSend();
871
- init.signal?.throwIfAborted();
872
- assertHostAuthorityStable();
873
- relayAttempt = attempt;
874
- lastTransport = 'relay';
875
- const authorizedHeaders = new Headers(headers);
876
- const sentBody = wireBodyText;
877
- const access = piAttemptAccessToken(attempt);
878
- authorizedHeaders.set('authorization', `Bearer ${access}`);
879
- return {
880
- headers: authorizedHeaders,
881
- billing: billingInput(attempt),
882
- errorSecrets: [access],
883
- onUpstreamStatus: (status) => {
884
- if (status >= 200 && status < 300)
885
- trackAcceptedRequest(attempt, sentBody);
886
- if (status === 401) {
887
- relay401Attempt = attempt;
888
- // The relay can report an upstream 401 after returning the streaming response.
889
- relayReports.push(report(attempt, status, 'relay_status_field'));
890
- }
891
- },
892
- };
893
- },
894
- });
884
+ const sendRelayAttempt = async () => {
885
+ let upstream;
886
+ return sendViaRelay({
887
+ config: relayConfig,
888
+ input,
889
+ init,
890
+ headers,
891
+ body: wireBodyText,
892
+ fallback: directFetch,
893
+ affinity: relayAffinity,
894
+ // Some relay streams start before the provider answers. Report the
895
+ // provider's actual status and headers, not that early placeholder.
896
+ onResponseHeaders: (responseHeaders) => {
897
+ if (upstream)
898
+ reportRoutingHeaders(upstream.attempt, responseHeaders, upstream.status);
899
+ },
900
+ onDumpCreated: (handle) => {
901
+ dumpHandle = handle;
902
+ },
903
+ authorizeAttempt: async () => {
904
+ const attempt = await takeAttempt();
905
+ await options.prime?.beforeSend();
906
+ init.signal?.throwIfAborted();
907
+ assertHostAuthorityStable();
908
+ relayAttempt = attempt;
909
+ lastTransport = 'relay';
910
+ const authorizedHeaders = new Headers(headers);
911
+ const sentBody = wireBodyText;
912
+ const access = piAttemptAccessToken(attempt);
913
+ authorizedHeaders.set('authorization', `Bearer ${access}`);
914
+ return {
915
+ headers: authorizedHeaders,
916
+ billing: billingInput(attempt),
917
+ errorSecrets: [access],
918
+ onUpstreamStatus: (status) => {
919
+ upstream = { attempt, status };
920
+ if (status >= 200 && status < 300)
921
+ trackAcceptedRequest(attempt, sentBody);
922
+ if (status === 401) {
923
+ relay401Attempt = attempt;
924
+ // The relay can report an upstream 401 after returning the streaming response.
925
+ relayReports.push(report(attempt, status, 'relay_status_field'));
926
+ }
927
+ },
928
+ };
929
+ },
930
+ });
931
+ };
895
932
  let response = await sendRelayAttempt();
896
933
  await Promise.all(relayReports);
897
934
  if (relay401Attempt &&
@@ -1688,6 +1725,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1688
1725
  const completion = createAnthropicStreamCompletion(response);
1689
1726
  for await (const event of parseSse(response, completion)) {
1690
1727
  if (event.type === 'message_start') {
1728
+ output.responseId = event.message?.id;
1691
1729
  recordCacheUsage?.(event.message?.usage);
1692
1730
  updateUsage(model, output, event.message?.usage);
1693
1731
  }
@@ -3,3 +3,4 @@ export declare function requirePiOAuthOrigin(value: string): URL;
3
3
  export declare function buildPiOAuthMessagesUrl(baseUrl: string): URL;
4
4
  /** Reject redirects rather than letting an approved OAuth destination forward the request. */
5
5
  export declare const fetchPiOAuth: typeof fetch;
6
+ export declare function fetchPiStreamResponse(input: Parameters<typeof fetch>[0], init: Parameters<typeof fetch>[1], fetchImpl?: typeof fetch): Promise<Response>;
package/dist/transport.js CHANGED
@@ -1,4 +1,5 @@
1
- import { createAnthropicOAuthFetch, requireAnthropicOAuthOrigin, } from '@cortexkit/anthropic-auth-core';
1
+ import { PerformanceObserver, } from 'node:perf_hooks';
2
+ import { copyStreamResponseTiming, createAnthropicOAuthFetch, requireAnthropicOAuthOrigin, } from '@cortexkit/anthropic-auth-core';
2
3
  // Pi keeps its own refusal wording; Core supplies the origin rule itself.
3
4
  const PI_OAUTH_ORIGIN = {
4
5
  refusal: (reason) => new Error(reason === 'unparseable'
@@ -14,3 +15,91 @@ export function buildPiOAuthMessagesUrl(baseUrl) {
14
15
  }
15
16
  /** Reject redirects rather than letting an approved OAuth destination forward the request. */
16
17
  export const fetchPiOAuth = createAnthropicOAuthFetch(PI_OAUTH_ORIGIN);
18
+ export async function fetchPiStreamResponse(input, init, fetchImpl = globalThis.fetch) {
19
+ const sentAt = performance.now();
20
+ let invokedUntil = Infinity;
21
+ const url = input instanceof Request ? input.url : String(input);
22
+ let sizes;
23
+ const collect = (entries) => {
24
+ const entry = entries.find((entry) => entry.name === url &&
25
+ entry.startTime >= sentAt &&
26
+ entry.startTime <= invokedUntil &&
27
+ entry.initiatorType === 'fetch');
28
+ if (!entry)
29
+ return;
30
+ sizes = {
31
+ encoded_body_bytes: entry.encodedBodySize,
32
+ decoded_body_bytes: entry.decodedBodySize,
33
+ };
34
+ observer?.disconnect();
35
+ };
36
+ // Observers have private queues, so concurrent fetches cannot consume each
37
+ // other's timing. Leave the runtime's bounded global timeline untouched.
38
+ const observer = process.versions.bun
39
+ ? undefined
40
+ : new PerformanceObserver((list) => collect(list.getEntries()));
41
+ observer?.observe({ type: 'resource' });
42
+ const settle = () => {
43
+ if (observer)
44
+ collect(observer.takeRecords());
45
+ observer?.disconnect();
46
+ };
47
+ try {
48
+ // Resource startTime is recorded synchronously inside this physical fetch,
49
+ // not while awaiting headers; another same-URL send has a different window.
50
+ let pending;
51
+ try {
52
+ pending = fetchImpl(input, init);
53
+ }
54
+ finally {
55
+ invokedUntil = performance.now();
56
+ }
57
+ const response = await pending;
58
+ copyStreamResponseTiming(response, response, sentAt, 'physical_fetch', () => sizes);
59
+ if (!observer || !response.body) {
60
+ settle();
61
+ return response;
62
+ }
63
+ const reader = response.body.getReader();
64
+ const body = new ReadableStream({
65
+ async pull(controller) {
66
+ try {
67
+ const { done, value } = await reader.read();
68
+ if (done) {
69
+ // Undici publishes resource timing after resolving the final read.
70
+ // Let that end-of-body task run before closing the observed stream.
71
+ await new Promise((resolve) => setImmediate(resolve));
72
+ settle();
73
+ reader.releaseLock();
74
+ controller.close();
75
+ }
76
+ else
77
+ controller.enqueue(value);
78
+ }
79
+ catch (error) {
80
+ settle();
81
+ reader.releaseLock();
82
+ controller.error(error);
83
+ }
84
+ },
85
+ async cancel(reason) {
86
+ try {
87
+ await reader.cancel(reason);
88
+ }
89
+ finally {
90
+ settle();
91
+ reader.releaseLock();
92
+ }
93
+ },
94
+ });
95
+ return copyStreamResponseTiming(response, new Response(body, {
96
+ status: response.status,
97
+ statusText: response.statusText,
98
+ headers: response.headers,
99
+ }));
100
+ }
101
+ catch (error) {
102
+ settle();
103
+ throw error;
104
+ }
105
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.10.0",
3
+ "version": "2.10.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,7 +36,7 @@
36
36
  "prepublishOnly": "bun run build"
37
37
  },
38
38
  "dependencies": {
39
- "@cortexkit/anthropic-auth-core": "2.10.0"
39
+ "@cortexkit/anthropic-auth-core": "2.10.1"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",