@cortexkit/pi-anthropic-auth 2.9.0 → 2.10.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/cachekeep.d.ts +5 -1
- package/dist/cachekeep.js +12 -1
- package/dist/native.d.ts +5 -0
- package/dist/native.js +13 -0
- package/dist/stream.d.ts +2 -2
- package/dist/stream.js +86 -10
- package/package.json +2 -2
package/dist/cachekeep.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CacheKeepManager, type CacheKeepStoreOptions, type HolderLiveness, type NativeAccountSnapshot } from '@cortexkit/anthropic-auth-core';
|
|
1
|
+
import { CacheKeepManager, type CacheKeepStoreOptions, type HolderLiveness, type NativeAccountSnapshot, type StickySessionRouter } from '@cortexkit/anthropic-auth-core';
|
|
2
2
|
type TrackInput = Parameters<CacheKeepManager['track']>[0];
|
|
3
3
|
type ManagerOptions = ConstructorParameters<typeof CacheKeepManager>[0];
|
|
4
4
|
/** One Pi process owns only the sessions its lifecycle actually opened. */
|
|
@@ -20,6 +20,10 @@ export declare class PiCacheKeep {
|
|
|
20
20
|
constructor(managerOptions: ManagerOptions, options: {
|
|
21
21
|
storageId: (storagePath: string) => Promise<string>;
|
|
22
22
|
read: (storagePath: string) => Promise<NativeAccountSnapshot>;
|
|
23
|
+
routing?: (storagePath: string) => {
|
|
24
|
+
snapshot: NativeAccountSnapshot | undefined;
|
|
25
|
+
router?: StickySessionRouter;
|
|
26
|
+
};
|
|
23
27
|
persistence?: Partial<Pick<CacheKeepStoreOptions, 'root' | 'ownerOnly'>>;
|
|
24
28
|
liveness?: HolderLiveness;
|
|
25
29
|
restoreDelay?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
package/dist/cachekeep.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
-
import { CacheKeepManager, CacheKeepStore, isCacheKeepSubagentsEnabled, logger, nativeAccountCanServe, readSessionCachePolicy, } from '@cortexkit/anthropic-auth-core';
|
|
3
|
+
import { CacheKeepManager, CacheKeepStore, isCacheKeepSubagentsEnabled, logger, nativeAccountCanServe, peekRoutingAccount, readSessionCachePolicy, remapModelId, } from '@cortexkit/anthropic-auth-core';
|
|
4
4
|
import { version as pluginVersion } from '../package.json';
|
|
5
5
|
import { PiCacheKeepClaim } from './cachekeep-claim.js';
|
|
6
6
|
function accountKey(account) {
|
|
@@ -47,6 +47,17 @@ export class PiCacheKeep {
|
|
|
47
47
|
};
|
|
48
48
|
this.manager = new CacheKeepManager({
|
|
49
49
|
...managerOptions,
|
|
50
|
+
peekRoutingAccount: (target, route) => {
|
|
51
|
+
const session = this.sessions.get(route.sessionId);
|
|
52
|
+
const routing = this.options.routing?.(session?.storagePath ?? target.accountStoragePath ?? '');
|
|
53
|
+
return routing
|
|
54
|
+
? peekRoutingAccount({
|
|
55
|
+
...routing,
|
|
56
|
+
...route,
|
|
57
|
+
modelId: route.modelId ? remapModelId(route.modelId) : undefined,
|
|
58
|
+
})
|
|
59
|
+
: managerOptions.peekRoutingAccount?.(target, route);
|
|
60
|
+
},
|
|
50
61
|
setIntervalImpl: ((_callback, ms) => schedule(() => {
|
|
51
62
|
this.ticking = this.manager
|
|
52
63
|
.tick()
|
package/dist/native.d.ts
CHANGED
|
@@ -28,6 +28,7 @@ export interface PiVaultPollOptions {
|
|
|
28
28
|
clearInterval?: typeof globalThis.clearInterval;
|
|
29
29
|
}
|
|
30
30
|
export declare class PiNativeRuntime {
|
|
31
|
+
private publishedRuntime?;
|
|
31
32
|
private readonly pendingReports;
|
|
32
33
|
/** Join started failure reports, never model sends waiting for headers. */
|
|
33
34
|
drainReports(): Promise<void>;
|
|
@@ -59,6 +60,8 @@ export declare class PiNativeRuntime {
|
|
|
59
60
|
prime?: PiPrimeOptions;
|
|
60
61
|
});
|
|
61
62
|
service(): Promise<NativeAccountRuntime>;
|
|
63
|
+
/** Inspect only a completed runtime read; initialization is never awaited. */
|
|
64
|
+
peek(): NativeAccountSnapshot | undefined;
|
|
62
65
|
routingPath(): Promise<string>;
|
|
63
66
|
routingStorage(): Promise<{
|
|
64
67
|
path: string;
|
|
@@ -82,6 +85,8 @@ export declare class PiNativeRuntime {
|
|
|
82
85
|
markUsed(served: PiNativeAttempt, servingRuntime?: NativeAccountRuntime): Promise<void>;
|
|
83
86
|
close(): Promise<void>;
|
|
84
87
|
}
|
|
88
|
+
/** Inspect an existing context without creating a runtime or starting its I/O. */
|
|
89
|
+
export declare function peekPiNativeSnapshot(storagePath?: string): NativeAccountSnapshot | undefined;
|
|
85
90
|
export declare function getPiNativeRuntime(storagePath?: string, options?: {
|
|
86
91
|
connect?: () => Promise<NativeCustodyClient>;
|
|
87
92
|
local?: NativeAccountRuntimeOptions['local'];
|
package/dist/native.js
CHANGED
|
@@ -72,6 +72,7 @@ export function isNativeMigrationRequired(error) {
|
|
|
72
72
|
/** How often Pi asks the vault for account changes, matching OpenCode's default. Model requests no longer rediscover a healthy roster, so this poll is how Pi notices a re-login or a newly added account. */
|
|
73
73
|
export const PI_VAULT_POLL_INTERVAL_MS = 2000;
|
|
74
74
|
export class PiNativeRuntime {
|
|
75
|
+
publishedRuntime;
|
|
75
76
|
pendingReports = new Set();
|
|
76
77
|
/** Join started failure reports, never model sends waiting for headers. */
|
|
77
78
|
async drainReports() {
|
|
@@ -166,6 +167,7 @@ export class PiNativeRuntime {
|
|
|
166
167
|
// the next poll or a request's bounded refresh retries it.
|
|
167
168
|
void this.vaultWatch.ready.catch(() => { });
|
|
168
169
|
}
|
|
170
|
+
this.publishedRuntime = runtime;
|
|
169
171
|
return runtime;
|
|
170
172
|
});
|
|
171
173
|
// Initialization is lazy from the host's perspective; a path failure is
|
|
@@ -181,6 +183,10 @@ export class PiNativeRuntime {
|
|
|
181
183
|
throw new Error('Pi native authentication is closed');
|
|
182
184
|
return runtime;
|
|
183
185
|
}
|
|
186
|
+
/** Inspect only a completed runtime read; initialization is never awaited. */
|
|
187
|
+
peek() {
|
|
188
|
+
return this.closed ? undefined : this.publishedRuntime?.peek?.();
|
|
189
|
+
}
|
|
184
190
|
async routingPath() {
|
|
185
191
|
return (await this.routingStorage()).path;
|
|
186
192
|
}
|
|
@@ -390,6 +396,13 @@ export class PiNativeRuntime {
|
|
|
390
396
|
return this.closing;
|
|
391
397
|
}
|
|
392
398
|
}
|
|
399
|
+
/** Inspect an existing context without creating a runtime or starting its I/O. */
|
|
400
|
+
export function peekPiNativeSnapshot(storagePath = getPiAccountStoragePath()) {
|
|
401
|
+
const contextKey = runtimeCacheKey(storagePath);
|
|
402
|
+
return [...runtimes.values()]
|
|
403
|
+
.find((entry) => entry.contextKey === contextKey)
|
|
404
|
+
?.runtime.peek();
|
|
405
|
+
}
|
|
393
406
|
export function getPiNativeRuntime(storagePath = getPiAccountStoragePath(), options = {}) {
|
|
394
407
|
const contextKey = runtimeCacheKey(storagePath);
|
|
395
408
|
const key = JSON.stringify([
|
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,8 +1,8 @@
|
|
|
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, 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';
|
|
5
|
-
import { getPiNativeRuntime, piAttemptAccessToken, } from './native.js';
|
|
5
|
+
import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, } from './native.js';
|
|
6
6
|
import { getPiAccountStoragePath } from './paths.js';
|
|
7
7
|
import { registerPiPrimeSender } from './prime.js';
|
|
8
8
|
import { markPiAccountHold, withPiQuotaWait, } from './quota-wait.js';
|
|
@@ -198,8 +198,32 @@ function applyPiOAuthRequestHeaders(headers, accessToken, options) {
|
|
|
198
198
|
headers.set('anthropic-beta', mergeAnthropicBetas(headers.get('anthropic-beta'), [FAST_MODE_BETA]));
|
|
199
199
|
return headers;
|
|
200
200
|
}
|
|
201
|
+
function piBillingPayer(attempt) {
|
|
202
|
+
return {
|
|
203
|
+
credentialId: attempt.source === 'vault'
|
|
204
|
+
? attempt.receipt.credentialId
|
|
205
|
+
: localMessageThreadCredential(attempt.admission.binding),
|
|
206
|
+
accountId: attempt.accountIdentity,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
201
209
|
const nativePrewarmAttempts = new Map();
|
|
202
210
|
const piCacheKeep = new PiCacheKeep({
|
|
211
|
+
billingRequest(target, attempt) {
|
|
212
|
+
const entry = nativePrewarmAttempts.get(attempt.id);
|
|
213
|
+
if (!entry)
|
|
214
|
+
return undefined;
|
|
215
|
+
return {
|
|
216
|
+
...piBillingPayer(entry.served),
|
|
217
|
+
sessionId: target.policyState?.ownerSessionId ?? target.id,
|
|
218
|
+
model: JSON.parse(target.bodyText).model,
|
|
219
|
+
requestKind: 'keep_warm',
|
|
220
|
+
chargeBasis: 'subscription_included',
|
|
221
|
+
cache: {
|
|
222
|
+
ttlMs: requestCacheLifetimeMs(target.bodyText),
|
|
223
|
+
warming: { on: true },
|
|
224
|
+
},
|
|
225
|
+
};
|
|
226
|
+
},
|
|
203
227
|
fetchImpl: fetchPiOAuth,
|
|
204
228
|
loadStorage: async () => (await getPiNativeRuntime().view()).policyStorage,
|
|
205
229
|
onTrackedSessionsChanged: (sessions) => getPiCacheKeepRegistry().publish(sessions),
|
|
@@ -272,6 +296,15 @@ const piCacheKeep = new PiCacheKeep({
|
|
|
272
296
|
}, {
|
|
273
297
|
storageId: async (storagePath) => (await resolveNativePoolPaths(storagePath, undefined, LEGACY_STATE_LAYOUT)).storageId,
|
|
274
298
|
read: (storagePath) => getPiNativeRuntime(storagePath).view(),
|
|
299
|
+
routing: (storagePath) => {
|
|
300
|
+
const snapshot = peekPiNativeSnapshot(storagePath);
|
|
301
|
+
return {
|
|
302
|
+
snapshot,
|
|
303
|
+
router: snapshot?.routingPath
|
|
304
|
+
? stickyRouters.get(snapshot.routingPath)
|
|
305
|
+
: undefined,
|
|
306
|
+
};
|
|
307
|
+
},
|
|
275
308
|
});
|
|
276
309
|
const cacheKeepManager = piCacheKeep.manager;
|
|
277
310
|
export function startPiCacheKeepSession(storagePath, sessionId) {
|
|
@@ -375,9 +408,11 @@ export function configureApiRouteHeaders(account, fastMode) {
|
|
|
375
408
|
applyCustomHeaders(headers);
|
|
376
409
|
return headers;
|
|
377
410
|
}
|
|
378
|
-
export async function* parseSse(response) {
|
|
379
|
-
if (!response.body)
|
|
411
|
+
export async function* parseSse(response, completion) {
|
|
412
|
+
if (!response.body) {
|
|
413
|
+
completion?.end();
|
|
380
414
|
return;
|
|
415
|
+
}
|
|
381
416
|
const dumpObserver = dumpResponseObservers.get(response);
|
|
382
417
|
const reader = response.body.getReader();
|
|
383
418
|
// Core's byte framer ends frames at blank lines with CRLF, LF or CR line
|
|
@@ -391,8 +426,11 @@ export async function* parseSse(response) {
|
|
|
391
426
|
try {
|
|
392
427
|
while (true) {
|
|
393
428
|
const { done, value } = await reader.read();
|
|
394
|
-
if (done)
|
|
429
|
+
if (done) {
|
|
430
|
+
completion?.end();
|
|
395
431
|
break;
|
|
432
|
+
}
|
|
433
|
+
completion?.push(value);
|
|
396
434
|
for (const frame of framer.push(value)) {
|
|
397
435
|
const data = parseSseFrame(decodeSseFrame(frame, { streamStart })).data;
|
|
398
436
|
streamStart = false;
|
|
@@ -465,6 +503,11 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
465
503
|
options.onCacheUsageRecorder?.(() => { });
|
|
466
504
|
assertHostAuthorityStable();
|
|
467
505
|
const fetchImpl = deps.fetch ?? globalThis.fetch;
|
|
506
|
+
const fetchResponse = async (input, init) => {
|
|
507
|
+
const sentAt = performance.now();
|
|
508
|
+
const response = await fetchImpl(input, init);
|
|
509
|
+
return copyStreamResponseTiming(response, response, sentAt);
|
|
510
|
+
};
|
|
468
511
|
const keep = deps.cacheKeep ?? cacheKeepManager;
|
|
469
512
|
const native = deps.native ?? getPiNativeRuntime(options.storagePath);
|
|
470
513
|
let dumpHandle = null;
|
|
@@ -528,6 +571,26 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
528
571
|
...(options.prime && { requestClass: 'auxiliary' }),
|
|
529
572
|
});
|
|
530
573
|
const relayAffinity = options.streamOptions?.sessionId ?? null;
|
|
574
|
+
const billingInput = (attempt, apiSubject) => {
|
|
575
|
+
// The session runner matches billing reports to session transcripts, and
|
|
576
|
+
// Prime is account-wide with no session, so it sends no billing report.
|
|
577
|
+
if (options.prime || !relayAffinity || (!attempt && !apiSubject))
|
|
578
|
+
return undefined;
|
|
579
|
+
const credentialId = attempt
|
|
580
|
+
? piBillingPayer(attempt).credentialId
|
|
581
|
+
: apiSubject?.credentialFingerprint;
|
|
582
|
+
if (!credentialId)
|
|
583
|
+
return undefined;
|
|
584
|
+
const ttlMs = requestCacheLifetimeMs(wireBodyText);
|
|
585
|
+
return {
|
|
586
|
+
...(attempt ? piBillingPayer(attempt) : { credentialId }),
|
|
587
|
+
sessionId: relayAffinity,
|
|
588
|
+
model: typeof body.model === 'string' ? body.model : options.model.id,
|
|
589
|
+
requestKind: options.requestOrigin === 'direct' ? 'generate' : 'primary',
|
|
590
|
+
chargeBasis: options.apiAccount ? 'metered_api' : 'subscription_included',
|
|
591
|
+
...(ttlMs > 0 ? { cache: { ttlMs } } : {}),
|
|
592
|
+
};
|
|
593
|
+
};
|
|
531
594
|
let input = options.apiAccount
|
|
532
595
|
? new URL('https://api.anthropic.com/v1/messages')
|
|
533
596
|
: buildPiOAuthMessagesUrl(options.model.baseUrl);
|
|
@@ -674,7 +737,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
674
737
|
// OAuth bodies go gzipped as Claude Code sends them; `bodyText` stays
|
|
675
738
|
// the signed identity text for dumps and CacheKeep.
|
|
676
739
|
if (options.apiAccount || typeof init.body !== 'string')
|
|
677
|
-
return scope.redactResponse(await
|
|
740
|
+
return scope.redactResponse(await physicalFetch(() => fetchResponse(input, init)));
|
|
678
741
|
return scope.redactResponse(await sendWithRequestGzip({
|
|
679
742
|
url: input,
|
|
680
743
|
body: init.body,
|
|
@@ -684,14 +747,18 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
684
747
|
await options.prime?.beforeSend();
|
|
685
748
|
init.signal?.throwIfAborted();
|
|
686
749
|
assertHostAuthorityStable();
|
|
687
|
-
return
|
|
750
|
+
return physicalFetch(() => fetchResponse(input, {
|
|
688
751
|
...init,
|
|
689
752
|
body: wireBody,
|
|
690
753
|
headers: wireHeaders,
|
|
691
|
-
});
|
|
754
|
+
}));
|
|
692
755
|
},
|
|
693
756
|
}));
|
|
694
757
|
};
|
|
758
|
+
const physicalFetch = (send) => {
|
|
759
|
+
const billing = billingInput(attempt, apiSubject);
|
|
760
|
+
return billing ? withAnthropicBilling(billing, send) : send();
|
|
761
|
+
};
|
|
695
762
|
let response;
|
|
696
763
|
try {
|
|
697
764
|
response = await send();
|
|
@@ -811,6 +878,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
811
878
|
authorizedHeaders.set('authorization', `Bearer ${access}`);
|
|
812
879
|
return {
|
|
813
880
|
headers: authorizedHeaders,
|
|
881
|
+
billing: billingInput(attempt),
|
|
814
882
|
errorSecrets: [access],
|
|
815
883
|
onUpstreamStatus: (status) => {
|
|
816
884
|
if (status >= 200 && status < 300)
|
|
@@ -1011,7 +1079,7 @@ export async function firstStreamingError(response) {
|
|
|
1011
1079
|
release();
|
|
1012
1080
|
return { response: replay(false), preflight: 'rate_limit_error' };
|
|
1013
1081
|
}
|
|
1014
|
-
const inspected = replay(true);
|
|
1082
|
+
const inspected = copyStreamResponseTiming(response, replay(true));
|
|
1015
1083
|
const dumpObserver = dumpResponseObservers.get(response);
|
|
1016
1084
|
if (dumpObserver)
|
|
1017
1085
|
dumpResponseObservers.set(inspected, dumpObserver);
|
|
@@ -1617,7 +1685,8 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1617
1685
|
throw new Error(`Anthropic request failed: HTTP ${response.status} ${await response.text()}`);
|
|
1618
1686
|
}
|
|
1619
1687
|
const blocks = output.content;
|
|
1620
|
-
|
|
1688
|
+
const completion = createAnthropicStreamCompletion(response);
|
|
1689
|
+
for await (const event of parseSse(response, completion)) {
|
|
1621
1690
|
if (event.type === 'message_start') {
|
|
1622
1691
|
recordCacheUsage?.(event.message?.usage);
|
|
1623
1692
|
updateUsage(model, output, event.message?.usage);
|
|
@@ -1796,6 +1865,13 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1796
1865
|
}
|
|
1797
1866
|
if (options?.signal?.aborted)
|
|
1798
1867
|
throw new Error('Request was aborted');
|
|
1868
|
+
const incomplete = completion.finish();
|
|
1869
|
+
if (incomplete) {
|
|
1870
|
+
const observer = dumpResponseObservers.get(response);
|
|
1871
|
+
observer?.fail(incomplete.diagnostics);
|
|
1872
|
+
await observer?.finish();
|
|
1873
|
+
throw incomplete;
|
|
1874
|
+
}
|
|
1799
1875
|
if (output.errorMessage)
|
|
1800
1876
|
throw new Error(output.errorMessage);
|
|
1801
1877
|
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.
|
|
3
|
+
"version": "2.10.0",
|
|
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.
|
|
39
|
+
"@cortexkit/anthropic-auth-core": "2.10.0"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"@earendil-works/pi-ai": ">=0.86.1 <2",
|