@cortexkit/pi-anthropic-auth 2.8.0 → 2.9.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/native.js CHANGED
@@ -114,6 +114,8 @@ export class PiNativeRuntime {
114
114
  const decision = await decidePiStateLayout({
115
115
  paths,
116
116
  role: 'pi',
117
+ env,
118
+ requireExistingAuthority: true,
117
119
  onLockEvent: options.local?.onLockEvent,
118
120
  });
119
121
  return decision.registration;
package/dist/stream.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type ApiKeyAccount, type CacheKeepManager, type MidConversationEffortTransition, type NativeAccountView, type QuotaManagerOptions } from '@cortexkit/anthropic-auth-core';
1
+ import { type ApiKeyAccount, type CacheKeepManager, createAnthropicStreamCompletion, type MidConversationEffortTransition, type NativeAccountView, type QuotaManagerOptions } from '@cortexkit/anthropic-auth-core';
2
2
  import { type Api, type AssistantMessageEventStream, type Context, type Model, type SimpleStreamOptions } from '@earendil-works/pi-ai';
3
3
  import { type PiNativeAttempt, type PiNativeRuntime } from './native.ts';
4
4
  import { type PiPrimeSendOptions } from './prime.ts';
@@ -28,7 +28,7 @@ type AnthropicEvent = {
28
28
  };
29
29
  export declare function buildExplicitBaseMessagesUrl(baseURL: string): URL;
30
30
  export declare function configureApiRouteHeaders(account: ApiKeyAccount, fastMode: boolean): Headers;
31
- export declare function parseSse(response: Response): AsyncGenerator<AnthropicEvent>;
31
+ export declare function parseSse(response: Response, completion?: ReturnType<typeof createAnthropicStreamCompletion>): AsyncGenerator<AnthropicEvent>;
32
32
  /** Prime uses the model transport without a conversation, thread or cache target. */
33
33
  export declare function sendPiPrimeRequest(options: PiPrimeSendOptions): Promise<Response>;
34
34
  declare function sendAnthropicRequest(options: {
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, 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';
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, } 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';
@@ -375,9 +375,11 @@ export function configureApiRouteHeaders(account, fastMode) {
375
375
  applyCustomHeaders(headers);
376
376
  return headers;
377
377
  }
378
- export async function* parseSse(response) {
379
- if (!response.body)
378
+ export async function* parseSse(response, completion) {
379
+ if (!response.body) {
380
+ completion?.end();
380
381
  return;
382
+ }
381
383
  const dumpObserver = dumpResponseObservers.get(response);
382
384
  const reader = response.body.getReader();
383
385
  // Core's byte framer ends frames at blank lines with CRLF, LF or CR line
@@ -391,8 +393,11 @@ export async function* parseSse(response) {
391
393
  try {
392
394
  while (true) {
393
395
  const { done, value } = await reader.read();
394
- if (done)
396
+ if (done) {
397
+ completion?.end();
395
398
  break;
399
+ }
400
+ completion?.push(value);
396
401
  for (const frame of framer.push(value)) {
397
402
  const data = parseSseFrame(decodeSseFrame(frame, { streamStart })).data;
398
403
  streamStart = false;
@@ -465,6 +470,11 @@ async function sendAnthropicRequest(options, deps = {}) {
465
470
  options.onCacheUsageRecorder?.(() => { });
466
471
  assertHostAuthorityStable();
467
472
  const fetchImpl = deps.fetch ?? globalThis.fetch;
473
+ const fetchResponse = async (input, init) => {
474
+ const sentAt = performance.now();
475
+ const response = await fetchImpl(input, init);
476
+ return copyStreamResponseTiming(response, response, sentAt);
477
+ };
468
478
  const keep = deps.cacheKeep ?? cacheKeepManager;
469
479
  const native = deps.native ?? getPiNativeRuntime(options.storagePath);
470
480
  let dumpHandle = null;
@@ -674,7 +684,7 @@ async function sendAnthropicRequest(options, deps = {}) {
674
684
  // OAuth bodies go gzipped as Claude Code sends them; `bodyText` stays
675
685
  // the signed identity text for dumps and CacheKeep.
676
686
  if (options.apiAccount || typeof init.body !== 'string')
677
- return scope.redactResponse(await fetchImpl(input, init));
687
+ return scope.redactResponse(await fetchResponse(input, init));
678
688
  return scope.redactResponse(await sendWithRequestGzip({
679
689
  url: input,
680
690
  body: init.body,
@@ -684,7 +694,7 @@ async function sendAnthropicRequest(options, deps = {}) {
684
694
  await options.prime?.beforeSend();
685
695
  init.signal?.throwIfAborted();
686
696
  assertHostAuthorityStable();
687
- return fetchImpl(input, {
697
+ return fetchResponse(input, {
688
698
  ...init,
689
699
  body: wireBody,
690
700
  headers: wireHeaders,
@@ -1011,7 +1021,7 @@ export async function firstStreamingError(response) {
1011
1021
  release();
1012
1022
  return { response: replay(false), preflight: 'rate_limit_error' };
1013
1023
  }
1014
- const inspected = replay(true);
1024
+ const inspected = copyStreamResponseTiming(response, replay(true));
1015
1025
  const dumpObserver = dumpResponseObservers.get(response);
1016
1026
  if (dumpObserver)
1017
1027
  dumpResponseObservers.set(inspected, dumpObserver);
@@ -1617,7 +1627,8 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1617
1627
  throw new Error(`Anthropic request failed: HTTP ${response.status} ${await response.text()}`);
1618
1628
  }
1619
1629
  const blocks = output.content;
1620
- for await (const event of parseSse(response)) {
1630
+ const completion = createAnthropicStreamCompletion(response);
1631
+ for await (const event of parseSse(response, completion)) {
1621
1632
  if (event.type === 'message_start') {
1622
1633
  recordCacheUsage?.(event.message?.usage);
1623
1634
  updateUsage(model, output, event.message?.usage);
@@ -1796,6 +1807,13 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1796
1807
  }
1797
1808
  if (options?.signal?.aborted)
1798
1809
  throw new Error('Request was aborted');
1810
+ const incomplete = completion.finish();
1811
+ if (incomplete) {
1812
+ const observer = dumpResponseObservers.get(response);
1813
+ observer?.fail(incomplete.diagnostics);
1814
+ await observer?.finish();
1815
+ throw incomplete;
1816
+ }
1799
1817
  if (output.errorMessage)
1800
1818
  throw new Error(output.errorMessage);
1801
1819
  for (const block of output.content)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.8.0",
3
+ "version": "2.9.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.8.0"
39
+ "@cortexkit/anthropic-auth-core": "2.9.1"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",