@cortexkit/anthropic-auth-core 1.16.0 → 1.18.0

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/relay.js CHANGED
@@ -323,12 +323,12 @@ class PersistentRelaySession {
323
323
  this.serverState = undefined;
324
324
  this.connecting = undefined;
325
325
  }
326
- send(payload, bodyText, optimisticResponse = false) {
326
+ send(payload, bodyText, optimisticResponse = false, onResponseHeaders) {
327
327
  this.touch();
328
328
  const enqueuedAt = perfNowMs();
329
329
  const start = this.queue
330
330
  .catch(() => { })
331
- .then(() => this.startQueued(payload, bodyText, enqueuedAt, optimisticResponse));
331
+ .then(() => this.startQueued(payload, bodyText, enqueuedAt, optimisticResponse, onResponseHeaders));
332
332
  const result = start.then(async ({ response, getPayload }) => ({
333
333
  response: await response,
334
334
  payload: getPayload(),
@@ -339,7 +339,7 @@ class PersistentRelaySession {
339
339
  this.queue = start.then(({ done }) => done.catch(() => { }), () => { });
340
340
  return result;
341
341
  }
342
- async startQueued(payload, bodyText, enqueuedAt, optimisticResponse) {
342
+ async startQueued(payload, bodyText, enqueuedAt, optimisticResponse, onResponseHeaders) {
343
343
  const connectStart = perfNowMs();
344
344
  await this.ensureConnected();
345
345
  const connectedAt = perfNowMs();
@@ -363,7 +363,7 @@ class PersistentRelaySession {
363
363
  }
364
364
  relayLog(`perf websocket send_start session=${shortAffinity(this.affinity)} request=${requestPayload.id} mode=${requestPayload.mode} queueMs=${formatMs(connectedAt - enqueuedAt)} connectMs=${formatMs(connectedAt - connectStart)} bodyBytes=${bodyText.length} relayBytes=${JSON.stringify(requestPayload).length}`);
365
365
  let activePayload = requestPayload;
366
- const first = this.sendPayload(requestPayload, bodyText, optimisticResponse);
366
+ const first = this.sendPayload(requestPayload, bodyText, optimisticResponse, onResponseHeaders);
367
367
  void first.done.catch(() => { });
368
368
  let activeDone = first.done;
369
369
  const response = first.response.catch((error) => {
@@ -376,7 +376,7 @@ class PersistentRelaySession {
376
376
  fullSync.id = createRequestId();
377
377
  fullSync.revision = (this.serverState?.revision ?? 0) + 1;
378
378
  activePayload = fullSync;
379
- const retry = this.sendPayload(fullSync, bodyText, optimisticResponse);
379
+ const retry = this.sendPayload(fullSync, bodyText, optimisticResponse, onResponseHeaders);
380
380
  void retry.done.catch(() => { });
381
381
  activeDone = retry.done;
382
382
  return retry.response;
@@ -457,7 +457,7 @@ class PersistentRelaySession {
457
457
  });
458
458
  await this.connecting;
459
459
  }
460
- sendPayload(payload, bodyText, optimisticResponse) {
460
+ sendPayload(payload, bodyText, optimisticResponse, onResponseHeaders) {
461
461
  const socket = this.socket;
462
462
  if (!socket || socket.readyState !== WebSocket.OPEN) {
463
463
  throw new Error('relay websocket is not connected');
@@ -486,6 +486,9 @@ class PersistentRelaySession {
486
486
  streamByteCount: 0,
487
487
  retryAttempts: 0,
488
488
  retryingBeforeResponse: false,
489
+ onResponseHeaders,
490
+ stagedResponseHeaders: undefined,
491
+ responseHeadersDelivered: false,
489
492
  };
490
493
  this.pending = pending;
491
494
  this.resetPendingTimeout(pending);
@@ -540,6 +543,8 @@ class PersistentRelaySession {
540
543
  pending.accepted = false;
541
544
  pending.acceptedAt = undefined;
542
545
  pending.responseStartedAt = undefined;
546
+ pending.stagedResponseHeaders = undefined;
547
+ pending.responseHeadersDelivered = false;
543
548
  pending.sentAt = perfNowMs();
544
549
  pending.retryingBeforeResponse = false;
545
550
  const socket = this.socket;
@@ -559,10 +564,21 @@ class PersistentRelaySession {
559
564
  return true;
560
565
  }
561
566
  enqueueStreamChunk(pending, chunk) {
567
+ this.deliverResponseHeaders(pending);
562
568
  pending.streamChunkCount += 1;
563
569
  pending.streamByteCount += chunk.byteLength;
564
570
  pending.streamController?.enqueue(chunk);
565
571
  }
572
+ deliverResponseHeaders(pending) {
573
+ if (pending.responseHeadersDelivered ||
574
+ pending.stagedResponseHeaders == null)
575
+ return;
576
+ pending.responseHeadersDelivered = true;
577
+ try {
578
+ pending.onResponseHeaders?.(pending.stagedResponseHeaders);
579
+ }
580
+ catch { }
581
+ }
566
582
  handleBinaryChunk(data) {
567
583
  const pending = this.pending;
568
584
  if (!pending?.responseStarted)
@@ -609,12 +625,17 @@ class PersistentRelaySession {
609
625
  return;
610
626
  }
611
627
  if (message.type === 'response_start') {
628
+ if (pending.responseStartedAt != null)
629
+ return;
612
630
  const responseStartedAt = perfNowMs();
613
631
  pending.responseStartedAt = responseStartedAt;
614
632
  relayLog(`perf websocket response_start session=${shortAffinity(this.affinity)} request=${pending.payload.id} sentMs=${formatMs(responseStartedAt - pending.sentAt)} upstreamMs=${pending.acceptedAt == null ? 'unknown' : formatMs(responseStartedAt - pending.acceptedAt)} status=${message.status}`);
615
633
  clearTimeout(pending.timeout);
634
+ if (message.headers)
635
+ pending.stagedResponseHeaders = new Headers(message.headers);
616
636
  this.resolvePendingResponse(pending, message.status, message.statusText, message.headers);
617
637
  if (pending.optimisticResponse && message.status >= 400) {
638
+ this.deliverResponseHeaders(pending);
618
639
  pending.streamController?.enqueue(new TextEncoder().encode(`event: error\ndata: ${JSON.stringify({ type: 'error', error: { type: 'relay_upstream_error', message: `Relay upstream returned HTTP ${message.status}` } })}\n\n`));
619
640
  this.finishPending();
620
641
  }
@@ -635,6 +656,7 @@ class PersistentRelaySession {
635
656
  // inject an SSE error event and close cleanly.
636
657
  if (pending.optimisticResponse && pending.responseStartedAt != null) {
637
658
  relayLog(`websocket relay error during optimistic response session=${shortAffinity(this.affinity)} request=${pending.payload.id} status=${message.status} message=${message.message || 'unknown'} chunks=${pending.streamChunkCount} bytes=${pending.streamByteCount}`);
659
+ this.deliverResponseHeaders(pending);
638
660
  pending.streamController?.enqueue(new TextEncoder().encode(`event: error\ndata: ${JSON.stringify({ type: 'error', error: { type: 'relay_error', message: message.message || 'relay error' } })}\n\n`));
639
661
  this.finishPending();
640
662
  this.socket?.close();
@@ -661,6 +683,7 @@ class PersistentRelaySession {
661
683
  relayLog(`perf websocket done session=${shortAffinity(this.affinity)} request=${pending.payload.id} sentMs=${formatMs(finishedAt - pending.sentAt)} streamMs=${pending.responseStartedAt == null ? 'unknown' : formatMs(finishedAt - pending.responseStartedAt)} chunks=${pending.streamChunkCount} bytes=${pending.streamByteCount}${workerStats}`);
662
684
  clearTimeout(pending.timeout);
663
685
  if (!pending.streamDone) {
686
+ this.deliverResponseHeaders(pending);
664
687
  pending.streamDone = true;
665
688
  pending.streamController?.close();
666
689
  }
@@ -727,7 +750,7 @@ function getPersistentRelaySession(config, affinity) {
727
750
  return session;
728
751
  }
729
752
  export async function sendViaRelay(options) {
730
- const { config, input, init, headers, body, fallback, affinity: explicitAffinity, optimisticResponse, } = options;
753
+ const { config, input, init, headers, body, fallback, affinity: explicitAffinity, optimisticResponse, onResponseHeaders, } = options;
731
754
  if (!config || !isRelayableAnthropicRequest(input, body))
732
755
  return fallback();
733
756
  const affinity = explicitAffinity ||
@@ -769,7 +792,7 @@ export async function sendViaRelay(options) {
769
792
  if (config.transport === 'websocket') {
770
793
  try {
771
794
  const session = getPersistentRelaySession(config, affinity);
772
- result = await session.send(payload, bodyText, optimisticResponse === true);
795
+ result = await session.send(payload, bodyText, optimisticResponse === true, onResponseHeaders);
773
796
  }
774
797
  catch (error) {
775
798
  relayLog(`websocket relay failed session=${shortAffinity(affinity)}; trying http relay: ${error instanceof Error ? error.message : String(error)}`);
@@ -802,6 +825,12 @@ export async function sendViaRelay(options) {
802
825
  });
803
826
  if (!result.usedRelay)
804
827
  return result.response;
828
+ if (result.transport === 'http') {
829
+ try {
830
+ onResponseHeaders?.(result.response.headers);
831
+ }
832
+ catch { }
833
+ }
805
834
  if (result.transport === 'http') {
806
835
  updateLocalRelayState(affinity, bodyText, result.payload.next_hash, result.payload.revision);
807
836
  }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Stable, non-reversible fingerprint used to bind persisted state to an access
3
+ * token without storing another copy of the credential.
4
+ */
5
+ export declare function tokenFingerprint(token: string): string;
@@ -0,0 +1,8 @@
1
+ import { createHash } from 'node:crypto';
2
+ /**
3
+ * Stable, non-reversible fingerprint used to bind persisted state to an access
4
+ * token without storing another copy of the credential.
5
+ */
6
+ export function tokenFingerprint(token) {
7
+ return createHash('sha256').update(token).digest('hex').slice(0, 16);
8
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/anthropic-auth-core",
3
- "version": "1.16.0",
3
+ "version": "1.18.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",