@cortexkit/pi-anthropic-auth 2.11.0 → 2.11.2
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/convert.d.ts +2 -0
- package/dist/convert.js +6 -0
- package/dist/quota-wait.js +12 -9
- package/dist/stream.js +24 -6
- package/package.json +2 -2
package/dist/convert.d.ts
CHANGED
|
@@ -40,6 +40,8 @@ export declare function createClaudeCodeToolNameMap(tools: readonly Tool[]): Rea
|
|
|
40
40
|
* executable host tool.
|
|
41
41
|
*/
|
|
42
42
|
export declare function fromClaudeCodeToolName(name: string, requestedToolNames: ReadonlyMap<string, string>): string;
|
|
43
|
+
/** Replace only the system cache marker, preserving the tool and message markers. */
|
|
44
|
+
export declare function piThreadCacheSlot(body: Record<string, unknown>): Record<string, unknown> | undefined;
|
|
43
45
|
export declare function buildAnthropicRequest(modelId: string, context: Context, options: SimpleStreamOptions | undefined, cache: {
|
|
44
46
|
enabled: boolean;
|
|
45
47
|
mode: Cache1hMode;
|
package/dist/convert.js
CHANGED
|
@@ -479,6 +479,12 @@ function applyCacheMode(body, enabled, mode) {
|
|
|
479
479
|
holder.cache_control.ttl = '1h';
|
|
480
480
|
});
|
|
481
481
|
}
|
|
482
|
+
/** Replace only the system cache marker, preserving the tool and message markers. */
|
|
483
|
+
export function piThreadCacheSlot(body) {
|
|
484
|
+
if (body.cache_control || !Array.isArray(body.system))
|
|
485
|
+
return undefined;
|
|
486
|
+
return body.system.findLast((block) => block && typeof block === 'object' && block.cache_control);
|
|
487
|
+
}
|
|
482
488
|
export async function buildAnthropicRequest(modelId, context, options, cache, fastModeEnabled = false, identity, controls = {}) {
|
|
483
489
|
// Pi 0.86 passes a normalized transcript to providers, and later system
|
|
484
490
|
// messages can change the prompt, its named sections and the tool set. Resolve
|
package/dist/quota-wait.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createQuotaRefusalResponse, quotaRefusalDetails, } from '@cortexkit/anthropic-auth-core';
|
|
1
|
+
import { clampHostRetryMs, createQuotaRefusalResponse, hostRetryResponse, quotaRefusalDetails, } from '@cortexkit/anthropic-auth-core';
|
|
2
2
|
const holds = new WeakMap();
|
|
3
3
|
export function markPiAccountHold(response, hold) {
|
|
4
4
|
holds.set(response, hold);
|
|
@@ -9,13 +9,14 @@ async function waitForReset(delayMs, resetAt, signal, options) {
|
|
|
9
9
|
const set = options.setTimeout ?? globalThis.setTimeout;
|
|
10
10
|
const clear = options.clearTimeout ?? globalThis.clearTimeout;
|
|
11
11
|
const when = resetAt ?? (options.now?.() ?? Date.now()) + delayMs;
|
|
12
|
-
const time = new Date(when).toLocaleTimeString(
|
|
12
|
+
const time = new Date(when).toLocaleTimeString('en-GB', {
|
|
13
13
|
hour: '2-digit',
|
|
14
14
|
minute: '2-digit',
|
|
15
15
|
hour12: false,
|
|
16
|
+
timeZone: 'UTC',
|
|
16
17
|
});
|
|
17
18
|
try {
|
|
18
|
-
options.setWorkingMessage?.(`
|
|
19
|
+
options.setWorkingMessage?.(`Checking account availability in ${Math.max(1, Math.ceil(delayMs / 60_000))} min (reset at ${time} UTC) · Esc to cancel`);
|
|
19
20
|
await new Promise((resolve, reject) => {
|
|
20
21
|
const abort = () => {
|
|
21
22
|
clear(timer);
|
|
@@ -36,9 +37,10 @@ async function waitForReset(delayMs, resetAt, signal, options) {
|
|
|
36
37
|
}
|
|
37
38
|
/** Own one bounded wait inside a Pi stream, rather than asking Pi's text-based retry loop. */
|
|
38
39
|
export async function withPiQuotaWait(input) {
|
|
39
|
-
const
|
|
40
|
-
const hold = holds.get(
|
|
41
|
-
const refusal = quotaRefusalDetails(
|
|
40
|
+
const original = await input.run();
|
|
41
|
+
const hold = holds.get(original);
|
|
42
|
+
const refusal = quotaRefusalDetails(original);
|
|
43
|
+
const response = hostRetryResponse(original, input.wait?.now?.() ?? Date.now());
|
|
42
44
|
const delay = Number(response.headers.get('retry-after')) * 1000;
|
|
43
45
|
if ((!hold && !refusal) ||
|
|
44
46
|
!response.headers.has('retry-after') ||
|
|
@@ -54,13 +56,13 @@ export async function withPiQuotaWait(input) {
|
|
|
54
56
|
resetAt: undefined,
|
|
55
57
|
retryAfterSeconds: undefined,
|
|
56
58
|
});
|
|
57
|
-
await waitForReset(delay, hold?.resetAt ?? refusal?.timing.resetAt, input.signal, options);
|
|
59
|
+
await waitForReset(clampHostRetryMs(delay), hold?.resetAt ?? refusal?.timing.resetAt, input.signal, options);
|
|
58
60
|
input.signal?.throwIfAborted();
|
|
59
61
|
let next;
|
|
60
62
|
try {
|
|
61
63
|
next = await input.resume(hold);
|
|
62
64
|
if (next.ok || next.status === 401)
|
|
63
|
-
return next;
|
|
65
|
+
return hostRetryResponse(next, options.now?.() ?? Date.now());
|
|
64
66
|
}
|
|
65
67
|
catch (error) {
|
|
66
68
|
if (input.signal?.aborted)
|
|
@@ -73,6 +75,7 @@ export async function withPiQuotaWait(input) {
|
|
|
73
75
|
refusal?.reason ??
|
|
74
76
|
'The selected OAuth account cannot serve this request. Open /claude to review account availability.', {
|
|
75
77
|
resetAt: latest?.timing.resetAt ?? refusal?.timing.resetAt ?? hold?.resetAt,
|
|
78
|
+
limitName: latest?.timing.limitName ?? refusal?.timing.limitName,
|
|
76
79
|
retryAfterSeconds: undefined,
|
|
77
|
-
}, options.now?.() ?? Date.now());
|
|
80
|
+
}, options.now?.() ?? Date.now(), { retry: 'manual' });
|
|
78
81
|
}
|
package/dist/stream.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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, createRoutingRelay, 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, routingCandidates, routingChoiceMatches, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, stickyRouteFamilyForModel, withAnthropicBilling, } 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, createRoutingRelay, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, dumpResponseArtifact, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getCacheKeepRegistryDirectories, getClaudeCodeIdentityForVerifiedAccount, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, hostRetryHeaders, hostRetryResponse, 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, routingCandidates, routingChoiceMatches, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, stickyRouteCandidateWeight, 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
|
-
import { buildAnthropicRequest, fromClaudeCodeToolName } from './convert.js';
|
|
4
|
+
import { buildAnthropicRequest, fromClaudeCodeToolName, piThreadCacheSlot, } from './convert.js';
|
|
5
5
|
import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, } from './native.js';
|
|
6
6
|
import { getPiAccountStoragePath } from './paths.js';
|
|
7
7
|
import { registerPiPrimeSender } from './prime.js';
|
|
@@ -716,6 +716,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
716
716
|
: localMessageThreadCredential(nextAttempt.admission.binding),
|
|
717
717
|
bodyText,
|
|
718
718
|
replyToolNames: toolNames,
|
|
719
|
+
cacheSlot: piThreadCacheSlot,
|
|
719
720
|
headers,
|
|
720
721
|
signal: init.signal ?? undefined,
|
|
721
722
|
});
|
|
@@ -1431,7 +1432,7 @@ async function executeWithFallback(options) {
|
|
|
1431
1432
|
});
|
|
1432
1433
|
throw error;
|
|
1433
1434
|
}
|
|
1434
|
-
|
|
1435
|
+
const noRouteResponse = async () => {
|
|
1435
1436
|
if (snapshot.mode === 'claustrum')
|
|
1436
1437
|
return createNativeVaultNoRouteResponse({
|
|
1437
1438
|
snapshot: await native.view(),
|
|
@@ -1453,7 +1454,9 @@ async function executeWithFallback(options) {
|
|
|
1453
1454
|
sessionId,
|
|
1454
1455
|
modelId: options.model.id,
|
|
1455
1456
|
});
|
|
1456
|
-
}
|
|
1457
|
+
};
|
|
1458
|
+
if (!resolution)
|
|
1459
|
+
return noRouteResponse();
|
|
1457
1460
|
let route = routes.allRoutes.find((candidate) => candidate.id === resolution?.accountId);
|
|
1458
1461
|
if (resolution && route) {
|
|
1459
1462
|
const sendRoute = (selected) => sendAnthropicRequest({
|
|
@@ -1464,7 +1467,7 @@ async function executeWithFallback(options) {
|
|
|
1464
1467
|
: undefined,
|
|
1465
1468
|
route: `sticky:${selected.id}`,
|
|
1466
1469
|
});
|
|
1467
|
-
const completeRoute = async (_selected, response, _markUsed = true) => response;
|
|
1470
|
+
const completeRoute = async (_selected, response, _markUsed = true) => hostRetryResponse(response);
|
|
1468
1471
|
const heldAccountId = route.id;
|
|
1469
1472
|
const heldAccountIdentity = accountView(route.id)?.accountIdentity;
|
|
1470
1473
|
const holdResponse = (retryAfterSeconds, upstream, routingHold = false) => {
|
|
@@ -1479,7 +1482,7 @@ async function executeWithFallback(options) {
|
|
|
1479
1482
|
type: 'rate_limit_error',
|
|
1480
1483
|
message: 'Sticky OAuth account quota resets shortly; retaining session affinity.',
|
|
1481
1484
|
},
|
|
1482
|
-
}), { status: 429, headers }), {
|
|
1485
|
+
}), { status: 429, headers: hostRetryHeaders(headers) }), {
|
|
1483
1486
|
accountId: heldAccountId,
|
|
1484
1487
|
accountIdentity: heldAccountIdentity,
|
|
1485
1488
|
resetAt: Date.now() + retryAfterSeconds * 1000,
|
|
@@ -1588,8 +1591,23 @@ async function executeWithFallback(options) {
|
|
|
1588
1591
|
clearPiStickyQuotaRetries(options.storagePath, sessionId);
|
|
1589
1592
|
return apiFallback;
|
|
1590
1593
|
}
|
|
1594
|
+
routes = await buildStickyRoutes(options.model.id);
|
|
1591
1595
|
}
|
|
1592
1596
|
}
|
|
1597
|
+
if (primaryResponseAllowsApiFallback(preflight) &&
|
|
1598
|
+
routes.candidates.every((candidate) => stickyRouteCandidateWeight({
|
|
1599
|
+
candidate,
|
|
1600
|
+
family: stickyRouteFamilyForModel(options.model.id),
|
|
1601
|
+
modelId: options.model.id,
|
|
1602
|
+
storage,
|
|
1603
|
+
}) === 0) &&
|
|
1604
|
+
routes.allRoutes.length > 0 &&
|
|
1605
|
+
routes.allRoutes.every((candidate) => quotaObservationIsFresh(candidate.quota, options.model.id))) {
|
|
1606
|
+
void response.body?.cancel().catch(() => { });
|
|
1607
|
+
if (preflight instanceof Response)
|
|
1608
|
+
void preflight.body?.cancel().catch(() => { });
|
|
1609
|
+
return noRouteResponse();
|
|
1610
|
+
}
|
|
1593
1611
|
return completeRoute(route, preflight instanceof Response ? preflight : response);
|
|
1594
1612
|
}
|
|
1595
1613
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/pi-anthropic-auth",
|
|
3
|
-
"version": "2.11.
|
|
3
|
+
"version": "2.11.2",
|
|
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.11.
|
|
39
|
+
"@cortexkit/anthropic-auth-core": "2.11.2"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"@earendil-works/pi-ai": ">=0.86.1 <2",
|