@cortexkit/pi-anthropic-auth 2.9.1 → 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/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 +1 -0
- package/dist/stream.js +142 -46
- package/dist/transport.d.ts +1 -0
- package/dist/transport.js +90 -1
- 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
package/dist/stream.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
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';
|
|
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';
|
|
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';
|
|
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,12 +194,38 @@ 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;
|
|
200
202
|
}
|
|
203
|
+
function piBillingPayer(attempt) {
|
|
204
|
+
return {
|
|
205
|
+
credentialId: attempt.source === 'vault'
|
|
206
|
+
? attempt.receipt.credentialId
|
|
207
|
+
: localMessageThreadCredential(attempt.admission.binding),
|
|
208
|
+
accountId: attempt.accountIdentity,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
201
211
|
const nativePrewarmAttempts = new Map();
|
|
202
212
|
const piCacheKeep = new PiCacheKeep({
|
|
213
|
+
billingRequest(target, attempt) {
|
|
214
|
+
const entry = nativePrewarmAttempts.get(attempt.id);
|
|
215
|
+
if (!entry)
|
|
216
|
+
return undefined;
|
|
217
|
+
return {
|
|
218
|
+
...piBillingPayer(entry.served),
|
|
219
|
+
sessionId: target.policyState?.ownerSessionId ?? target.id,
|
|
220
|
+
model: JSON.parse(target.bodyText).model,
|
|
221
|
+
requestKind: 'keep_warm',
|
|
222
|
+
chargeBasis: 'subscription_included',
|
|
223
|
+
cache: {
|
|
224
|
+
ttlMs: requestCacheLifetimeMs(target.bodyText),
|
|
225
|
+
warming: { on: true },
|
|
226
|
+
},
|
|
227
|
+
};
|
|
228
|
+
},
|
|
203
229
|
fetchImpl: fetchPiOAuth,
|
|
204
230
|
loadStorage: async () => (await getPiNativeRuntime().view()).policyStorage,
|
|
205
231
|
onTrackedSessionsChanged: (sessions) => getPiCacheKeepRegistry().publish(sessions),
|
|
@@ -272,6 +298,15 @@ const piCacheKeep = new PiCacheKeep({
|
|
|
272
298
|
}, {
|
|
273
299
|
storageId: async (storagePath) => (await resolveNativePoolPaths(storagePath, undefined, LEGACY_STATE_LAYOUT)).storageId,
|
|
274
300
|
read: (storagePath) => getPiNativeRuntime(storagePath).view(),
|
|
301
|
+
routing: (storagePath) => {
|
|
302
|
+
const snapshot = peekPiNativeSnapshot(storagePath);
|
|
303
|
+
return {
|
|
304
|
+
snapshot,
|
|
305
|
+
router: snapshot?.routingPath
|
|
306
|
+
? stickyRouters.get(snapshot.routingPath)
|
|
307
|
+
: undefined,
|
|
308
|
+
};
|
|
309
|
+
},
|
|
275
310
|
});
|
|
276
311
|
const cacheKeepManager = piCacheKeep.manager;
|
|
277
312
|
export function startPiCacheKeepSession(storagePath, sessionId) {
|
|
@@ -471,9 +506,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
471
506
|
assertHostAuthorityStable();
|
|
472
507
|
const fetchImpl = deps.fetch ?? globalThis.fetch;
|
|
473
508
|
const fetchResponse = async (input, init) => {
|
|
474
|
-
|
|
475
|
-
const response = await fetchImpl(input, init);
|
|
476
|
-
return copyStreamResponseTiming(response, response, sentAt);
|
|
509
|
+
return fetchPiStreamResponse(input, init, fetchImpl);
|
|
477
510
|
};
|
|
478
511
|
const keep = deps.cacheKeep ?? cacheKeepManager;
|
|
479
512
|
const native = deps.native ?? getPiNativeRuntime(options.storagePath);
|
|
@@ -538,6 +571,45 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
538
571
|
...(options.prime && { requestClass: 'auxiliary' }),
|
|
539
572
|
});
|
|
540
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
|
+
};
|
|
582
|
+
const billingInput = (attempt, apiSubject) => {
|
|
583
|
+
// The session runner matches billing reports to session transcripts, and
|
|
584
|
+
// Prime is account-wide with no session, so it sends no billing report.
|
|
585
|
+
if (options.prime || !relayAffinity || (!attempt && !apiSubject))
|
|
586
|
+
return undefined;
|
|
587
|
+
const credentialId = attempt
|
|
588
|
+
? piBillingPayer(attempt).credentialId
|
|
589
|
+
: apiSubject?.credentialFingerprint;
|
|
590
|
+
if (!credentialId)
|
|
591
|
+
return undefined;
|
|
592
|
+
const ttlMs = requestCacheLifetimeMs(wireBodyText);
|
|
593
|
+
const sessionId = relayAffinity;
|
|
594
|
+
return {
|
|
595
|
+
...(attempt ? piBillingPayer(attempt) : { credentialId }),
|
|
596
|
+
sessionId,
|
|
597
|
+
model: typeof body.model === 'string' ? body.model : options.model.id,
|
|
598
|
+
requestKind: options.requestOrigin === 'direct' ? 'generate' : 'primary',
|
|
599
|
+
chargeBasis: options.apiAccount ? 'metered_api' : 'subscription_included',
|
|
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
|
+
},
|
|
611
|
+
};
|
|
612
|
+
};
|
|
541
613
|
let input = options.apiAccount
|
|
542
614
|
? new URL('https://api.anthropic.com/v1/messages')
|
|
543
615
|
: buildPiOAuthMessagesUrl(options.model.baseUrl);
|
|
@@ -549,6 +621,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
549
621
|
...(!options.apiAccount && { redirect: 'error' }),
|
|
550
622
|
};
|
|
551
623
|
const cacheAccepted = new Set();
|
|
624
|
+
const cacheTracking = new Map();
|
|
552
625
|
const trackAcceptedRequest = (attempt, sentBody = wireBodyText) => {
|
|
553
626
|
if (options.prime || options.apiAccount || init.signal?.aborted)
|
|
554
627
|
return;
|
|
@@ -583,6 +656,8 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
583
656
|
const tracked = deps.cacheKeep
|
|
584
657
|
? Promise.resolve(keep.track(target))
|
|
585
658
|
: piCacheKeep.trackAccepted(target, snapshot);
|
|
659
|
+
cacheTracking.set(attempt, 'pending');
|
|
660
|
+
void tracked.then(() => cacheTracking.set(attempt, 'settled'), () => { });
|
|
586
661
|
let latestUsage = {};
|
|
587
662
|
options.onCacheUsageRecorder?.((usage) => {
|
|
588
663
|
if (!usage || init.signal?.aborted || !relayAffinity)
|
|
@@ -684,7 +759,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
684
759
|
// OAuth bodies go gzipped as Claude Code sends them; `bodyText` stays
|
|
685
760
|
// the signed identity text for dumps and CacheKeep.
|
|
686
761
|
if (options.apiAccount || typeof init.body !== 'string')
|
|
687
|
-
return scope.redactResponse(await fetchResponse(input, init));
|
|
762
|
+
return scope.redactResponse(await physicalFetch(() => fetchResponse(input, init)));
|
|
688
763
|
return scope.redactResponse(await sendWithRequestGzip({
|
|
689
764
|
url: input,
|
|
690
765
|
body: init.body,
|
|
@@ -694,14 +769,23 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
694
769
|
await options.prime?.beforeSend();
|
|
695
770
|
init.signal?.throwIfAborted();
|
|
696
771
|
assertHostAuthorityStable();
|
|
697
|
-
return fetchResponse(input, {
|
|
772
|
+
return physicalFetch(() => fetchResponse(input, {
|
|
698
773
|
...init,
|
|
699
774
|
body: wireBody,
|
|
700
775
|
headers: wireHeaders,
|
|
701
|
-
});
|
|
776
|
+
}));
|
|
702
777
|
},
|
|
703
778
|
}));
|
|
704
779
|
};
|
|
780
|
+
const physicalFetch = async (send) => {
|
|
781
|
+
const billing = billingInput(attempt, apiSubject);
|
|
782
|
+
const response = await (billing
|
|
783
|
+
? withAnthropicBilling(billing, send)
|
|
784
|
+
: send());
|
|
785
|
+
if (attempt)
|
|
786
|
+
reportRoutingHeaders(attempt, response.headers, response.status);
|
|
787
|
+
return response;
|
|
788
|
+
};
|
|
705
789
|
let response;
|
|
706
790
|
try {
|
|
707
791
|
response = await send();
|
|
@@ -797,43 +881,54 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
797
881
|
// The relay scrubs each physical relay attempt's responses and errors with
|
|
798
882
|
// that attempt's own credentials and the relay token; a direct fallback is
|
|
799
883
|
// scrubbed by directFetch.
|
|
800
|
-
const sendRelayAttempt = async () =>
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
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
|
+
};
|
|
837
932
|
let response = await sendRelayAttempt();
|
|
838
933
|
await Promise.all(relayReports);
|
|
839
934
|
if (relay401Attempt &&
|
|
@@ -1630,6 +1725,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1630
1725
|
const completion = createAnthropicStreamCompletion(response);
|
|
1631
1726
|
for await (const event of parseSse(response, completion)) {
|
|
1632
1727
|
if (event.type === 'message_start') {
|
|
1728
|
+
output.responseId = event.message?.id;
|
|
1633
1729
|
recordCacheUsage?.(event.message?.usage);
|
|
1634
1730
|
updateUsage(model, output, event.message?.usage);
|
|
1635
1731
|
}
|
package/dist/transport.d.ts
CHANGED
|
@@ -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 {
|
|
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.
|
|
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.
|
|
39
|
+
"@cortexkit/anthropic-auth-core": "2.10.1"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"@earendil-works/pi-ai": ">=0.86.1 <2",
|