@cortexkit/pi-anthropic-auth 2.7.1 → 2.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/stream.js +35 -3
  2. package/package.json +2 -2
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, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, 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, } from '@cortexkit/anthropic-auth-core';
1
+ import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, 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, } 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';
@@ -8,6 +8,7 @@ import { registerPiPrimeSender } from './prime.js';
8
8
  import { markPiAccountHold, withPiQuotaWait, } from './quota-wait.js';
9
9
  import { buildPiOAuthMessagesUrl, fetchPiOAuth, requirePiOAuthOrigin, } from './transport.js';
10
10
  const messageThreads = new MessageThreadTracker();
11
+ const dumpResponseObservers = new WeakMap();
11
12
  // Each session owns its lease; storage identifies which host may end it.
12
13
  const primaryTurns = new Map();
13
14
  export function beginPiPrimaryTurn(storagePath, sessionId) {
@@ -377,6 +378,7 @@ export function configureApiRouteHeaders(account, fastMode) {
377
378
  export async function* parseSse(response) {
378
379
  if (!response.body)
379
380
  return;
381
+ const dumpObserver = dumpResponseObservers.get(response);
380
382
  const reader = response.body.getReader();
381
383
  // Core's byte framer ends frames at blank lines with CRLF, LF or CR line
382
384
  // endings and keeps a multibyte character split across reads in one frame,
@@ -396,14 +398,21 @@ export async function* parseSse(response) {
396
398
  streamStart = false;
397
399
  if (!data || data === '[DONE]')
398
400
  continue;
399
- yield JSON.parse(data);
401
+ const event = JSON.parse(data);
402
+ dumpObserver?.observe(event);
403
+ yield event;
400
404
  }
401
405
  }
402
406
  }
407
+ catch (error) {
408
+ dumpObserver?.fail();
409
+ throw error;
410
+ }
403
411
  finally {
404
412
  // Only the lock is released when the consumer stops early: cancelling the
405
413
  // body on abandonment is the consumer's decision, not the parser's.
406
414
  reader.releaseLock();
415
+ await dumpObserver?.finish();
407
416
  }
408
417
  }
409
418
  function buildPiPrimeBody(identity) {
@@ -458,6 +467,7 @@ async function sendAnthropicRequest(options, deps = {}) {
458
467
  const fetchImpl = deps.fetch ?? globalThis.fetch;
459
468
  const keep = deps.cacheKeep ?? cacheKeepManager;
460
469
  const native = deps.native ?? getPiNativeRuntime(options.storagePath);
470
+ let dumpHandle = null;
461
471
  // Capture the serving service while authorization is open. Shutdown rejects
462
472
  // new serving work immediately but drains writes for already-served attempts.
463
473
  const servingRuntime = await native.service();
@@ -721,7 +731,7 @@ async function sendAnthropicRequest(options, deps = {}) {
721
731
  // for a newer credential), end it as cancelled here.
722
732
  if (attempt && response.status === 401)
723
733
  await endIfCancelled(response, init.signal);
724
- await dumpDirectRequest({
734
+ dumpHandle = await dumpDirectRequest({
725
735
  affinity: relayAffinity,
726
736
  route: options.route ??
727
737
  (options.apiAccount ? `api:${options.apiAccount.id}` : 'oauth'),
@@ -759,6 +769,14 @@ async function sendAnthropicRequest(options, deps = {}) {
759
769
  trackAcceptedRequest(attempt);
760
770
  markServed(attempt);
761
771
  }
772
+ if (options.apiAccount && dumpHandle) {
773
+ await dumpResponseArtifact(dumpHandle, {
774
+ status: response.status,
775
+ message: null,
776
+ complete: false,
777
+ });
778
+ dumpResponseObservers.set(response, createDumpResponseObserver(dumpHandle, response.status));
779
+ }
762
780
  return response;
763
781
  };
764
782
  if (options.apiAccount)
@@ -777,6 +795,9 @@ async function sendAnthropicRequest(options, deps = {}) {
777
795
  body: wireBodyText,
778
796
  fallback: directFetch,
779
797
  affinity: relayAffinity,
798
+ onDumpCreated: (handle) => {
799
+ dumpHandle = handle;
800
+ },
780
801
  authorizeAttempt: async () => {
781
802
  const attempt = await takeAttempt();
782
803
  await options.prime?.beforeSend();
@@ -847,6 +868,14 @@ async function sendAnthropicRequest(options, deps = {}) {
847
868
  trackAcceptedRequest(relayAttempt);
848
869
  markServed(relayAttempt);
849
870
  }
871
+ if (dumpHandle) {
872
+ await dumpResponseArtifact(dumpHandle, {
873
+ status: response.status,
874
+ message: null,
875
+ complete: false,
876
+ });
877
+ dumpResponseObservers.set(response, createDumpResponseObserver(dumpHandle, response.status));
878
+ }
850
879
  return response;
851
880
  }
852
881
  /** Exercise one native send with isolated transport and scheduling in tests. */
@@ -983,6 +1012,9 @@ export async function firstStreamingError(response) {
983
1012
  return { response: replay(false), preflight: 'rate_limit_error' };
984
1013
  }
985
1014
  const inspected = replay(true);
1015
+ const dumpObserver = dumpResponseObservers.get(response);
1016
+ if (dumpObserver)
1017
+ dumpResponseObservers.set(inspected, dumpObserver);
986
1018
  return { response: inspected, preflight: inspected };
987
1019
  }
988
1020
  async function executeWithFallback(options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.7.1",
3
+ "version": "2.7.3",
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.7.1"
39
+ "@cortexkit/anthropic-auth-core": "2.7.3"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",