@cortexkit/pi-anthropic-auth 2.15.2 → 2.16.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.
@@ -14,9 +14,8 @@ export interface PiNativeCommands {
14
14
  readMode?: NativeUiOptions['readMode'];
15
15
  readAccounts?: NativeUiOptions['readAccounts'];
16
16
  /**
17
- * Disconnects Pi from the vault. When left out, Core first restores the
18
- * Anthropic sign-in that enrollment set aside in Pi's own auth file, then
19
- * ends Pi's enrollment.
17
+ * Disconnects Pi from the vault. When left out, Core clears the vault
18
+ * placeholder, restores no sign-in, then ends Pi's enrollment.
20
19
  */
21
20
  disconnectVault?: NativeUiOptions['disconnectVault'];
22
21
  }
package/dist/commands.js CHANGED
@@ -4,7 +4,7 @@ import { getAgentDir } from '@earendil-works/pi-coding-agent';
4
4
  /**
5
5
  * Pi's default disconnect. The auth file is the one Pi's SDK uses
6
6
  * (getAgentDir() honours PI_CODING_AGENT_DIR); Core chooses the private
7
- * stash and placeholder, so setup and disconnect always agree on them.
7
+ * legacy stash path and placeholder, so setup and disconnect agree on cleanup.
8
8
  */
9
9
  const disconnectPi = () => disconnectNativeVaultForHost({
10
10
  host: 'pi',
@@ -33,14 +33,14 @@ export function registerCommands(pi, backend) {
33
33
  disconnectVault: async (options) => {
34
34
  const result = await disconnect(options);
35
35
  // Reload after successful or already-inactive enrollment so Pi sees
36
- // any restored sign-in. Reload failure cannot undo the completed
36
+ // the cleared vault placeholder. Reload failure cannot undo the completed
37
37
  // disconnect, so report it separately without exposing the exception.
38
38
  if (result === 'disconnected' || result === 'idle') {
39
39
  try {
40
40
  await ctx.modelRegistry.refresh();
41
41
  }
42
42
  catch {
43
- ctx.ui.notify('Vault enrollment is inactive, but Pi could not reload its saved sign-in. Restart Pi before sending another request.', 'error');
43
+ ctx.ui.notify('Vault enrollment is inactive, but Pi could not reload its authentication. Restart Pi and sign in again before sending another request.', 'error');
44
44
  }
45
45
  }
46
46
  return result;
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { authorize, buildClaudeQuotaSummary, buildPrimeAccountStatuses, claudeGatewayStatusNotes, DEFAULT_KILLSWITCH_THRESHOLDS, exchange, executeCacheKeepCommand, executePrimeCommand, formatEnrollmentStatus, formatNativeAccountState, formatOAuthAccountTier, getCache1hPersistentMode, getCacheKeepWindow, getMaxSameAccountWait, getPersistedLogLevel, getRoutingMode, isCache1hPersistentlyEnabled, isCacheKeepAlways, isCacheKeepHybridActive, isCacheKeepPersistentlyEnabled, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isPrimePersistentlyEnabled, isVaultHosted, nativeAccountCanServe, setDumpEnabled, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from '@cortexkit/anthropic-auth-core';
2
+ import { authorize, buildClaudeQuotaSummary, buildPrimeAccountStatuses, claudeGatewayStatusNotes, DEFAULT_KILLSWITCH_THRESHOLDS, exchange, executeCacheKeepCommand, executePrimeCommand, formatEnrollmentStatus, formatNativeAccountState, formatOAuthAccountTier, getCache1hPersistentMode, getCacheKeepWindow, getMaxSameAccountWait, getPersistedLogLevel, getRoutingMode, isCache1hPersistentlyEnabled, isCacheKeepAlways, isCacheKeepHybridActive, isCacheKeepPersistentlyEnabled, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isPrimePersistentlyEnabled, isVaultHosted, logger, nativeAccountCanServe, setDumpEnabled, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from '@cortexkit/anthropic-auth-core';
3
3
  import { createPiCustodyCommands } from './custody.js';
4
4
  import { getPiNativeRuntime } from './native.js';
5
5
  import { getPiAccountStoragePath } from './paths.js';
@@ -7,6 +7,8 @@ import { clearPiStickyRoutingSession, getPiTrackedCacheKeepSessions, } from './s
7
7
  import { fetchPiOAuth } from './transport.js';
8
8
  export function createPiNativeCommands(storagePath = getPiAccountStoragePath()) {
9
9
  const native = getPiNativeRuntime(storagePath);
10
+ let lastStatusSnapshot;
11
+ let statusReadContended = false;
10
12
  const custody = createPiCustodyCommands();
11
13
  const pending = new Map();
12
14
  const written = (result, text) => result.outcome === 'refused' || result.outcome === 'failed'
@@ -285,7 +287,23 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
285
287
  async readStatus(command) {
286
288
  const runtime = await native.service();
287
289
  await runtime.prepareSettingsAction?.();
288
- const snapshot = await runtime.read();
290
+ let snapshot;
291
+ try {
292
+ snapshot = await runtime.read();
293
+ lastStatusSnapshot = snapshot;
294
+ statusReadContended = false;
295
+ }
296
+ catch (error) {
297
+ if (!isNativeTransientAccountError(error) || !error.poolRead)
298
+ throw error;
299
+ if (!statusReadContended) {
300
+ statusReadContended = true;
301
+ logger.warn('native-auth', 'Account update in progress; keeping status display');
302
+ }
303
+ if (!lastStatusSnapshot)
304
+ return 'Anthropic account update in progress; try status again shortly.';
305
+ snapshot = lastStatusSnapshot;
306
+ }
289
307
  if ((command === 'account' || command === 'quota') &&
290
308
  snapshot.mode === 'claustrum' &&
291
309
  !(await runtime.vault.read()))
@@ -326,6 +344,11 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
326
344
  case 'account':
327
345
  return [
328
346
  `Custody: ${snapshot.mode}`,
347
+ ...(snapshot.mode === 'claustrum'
348
+ ? [
349
+ 'Pi’s previous saved Claude sign-in is not restored on disconnect. Sign in again after disconnecting.',
350
+ ]
351
+ : []),
329
352
  ...snapshot.accounts.map((account) => `${account.id}: ${account.label ?? account.id} (${account.type}, ${account.enabled ? 'enabled' : 'disabled'}, ${account.source}${account.state ? `, ${formatNativeAccountState(account)}` : ''}${formatOAuthAccountTier(account.profile) ? `, ${formatOAuthAccountTier(account.profile)}` : ''}); identity: ${account.accountIdentity ?? 'unverified'}${account.lastRefreshError ? `; refresh: ${account.lastRefreshError.permanent ? 'requires login' : 'backoff'}` : ''}`),
330
353
  ...(isVaultHosted()
331
354
  ? [VAULT_HOST_STATUS]
@@ -11,7 +11,11 @@ export type PiAccountHold = {
11
11
  reason?: 'account_limit' | 'routing_hold';
12
12
  };
13
13
  export declare function markPiAccountHold(response: Response, hold: PiAccountHold): Response;
14
- /** Own one bounded wait inside a Pi stream, rather than asking Pi's text-based retry loop. */
14
+ /**
15
+ * Own one wait inside a Pi stream. Pi's own retry loop decides from an
16
+ * error's message text, with its own short delays, so it can't wait for a
17
+ * quota reset; this waits here, then resends once.
18
+ */
15
19
  export declare function withPiQuotaWait(input: {
16
20
  run: () => Promise<Response>;
17
21
  resume: (hold: PiAccountHold | undefined) => Promise<Response>;
@@ -1,4 +1,4 @@
1
- import { clampHostRetryMs, createQuotaRefusalResponse, hostRetryResponse, quotaRefusalDetails, startRoutingWait, } from '@cortexkit/anthropic-auth-core';
1
+ import { clampHostRetryMs, createQuotaRefusalResponse, hostRetryResponse, quotaRefusalDetails, resetWaitDelayMs, startRoutingWait, } from '@cortexkit/anthropic-auth-core';
2
2
  const holds = new WeakMap();
3
3
  export function markPiAccountHold(response, hold) {
4
4
  holds.set(response, hold);
@@ -35,7 +35,11 @@ async function waitForReset(delayMs, resetAt, signal, options) {
35
35
  options.setWorkingMessage?.();
36
36
  }
37
37
  }
38
- /** Own one bounded wait inside a Pi stream, rather than asking Pi's text-based retry loop. */
38
+ /**
39
+ * Own one wait inside a Pi stream. Pi's own retry loop decides from an
40
+ * error's message text, with its own short delays, so it can't wait for a
41
+ * quota reset; this waits here, then resends once.
42
+ */
39
43
  export async function withPiQuotaWait(input) {
40
44
  const original = await input.run();
41
45
  const hold = holds.get(original);
@@ -48,6 +52,7 @@ export async function withPiQuotaWait(input) {
48
52
  delay <= 0)
49
53
  return response;
50
54
  const options = input.wait ?? {};
55
+ const waitMs = resetWaitDelayMs(original) ?? clampHostRetryMs(delay);
51
56
  void response.body?.cancel().catch(() => { });
52
57
  input.signal?.throwIfAborted();
53
58
  // An unknown reset's retry hint is not evidence that waiting can help this request.
@@ -59,12 +64,12 @@ export async function withPiQuotaWait(input) {
59
64
  const endWait = startRoutingWait({
60
65
  sessionId: input.sessionId,
61
66
  reason: hold?.reason ?? (hold ? 'account_limit' : 'account_free'),
62
- delayMs: clampHostRetryMs(delay),
63
- nextMs: (options.now?.() ?? Date.now()) + clampHostRetryMs(delay),
67
+ delayMs: waitMs,
68
+ nextMs: (options.now?.() ?? Date.now()) + waitMs,
64
69
  });
65
70
  let outcome = 'abandoned';
66
71
  try {
67
- await waitForReset(clampHostRetryMs(delay), hold?.resetAt ?? refusal?.timing.resetAt, input.signal, options);
72
+ await waitForReset(waitMs, hold?.resetAt ?? refusal?.timing.resetAt, input.signal, options);
68
73
  input.signal?.throwIfAborted();
69
74
  let next;
70
75
  try {
package/dist/stream.js CHANGED
@@ -1,4 +1,4 @@
1
- import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyClaudeGatewayHeaders, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ACCEPT_ENCODING, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, claudeGatewayHeaderValues, claudeGatewayModelUrl, copyStreamResponseTiming, createAnthropicStreamCompletion, createDumpResponseObserver, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createRoutingRelay, createSseFramer, createStickyNoRouteResponse, currentCacheKeepRealTurn, 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, raceWithSignal, readSessionCachePolicy, reportRoutingResponse, reportSessionCacheTouch, requestCacheLifetimeMs, requestShortestCacheLifetimeMs, resolveNativePoolPaths, routingCandidates, routingChoiceMatches, routingWarmCredential, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, startRoutingWait, stickyQuotaSnapshotIsFresh, stickyRetainRetryHeaders, stickyRetryAfterWithJitter, stickyRouteCandidateWeight, stickyRouteFamilyForModel, warnClaudeGatewayRelayIgnored, withAnthropicBilling, withCacheKeepRealTurn, } from '@cortexkit/anthropic-auth-core';
1
+ import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyClaudeGatewayHeaders, applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, buildPrimeRequestBody, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, CLAUDE_CODE_ACCEPT_ENCODING, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, claudeGatewayHeaderValues, claudeGatewayModelUrl, copyStreamResponseTiming, createAnthropicStreamCompletion, createDumpResponseObserver, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createRoutingRelay, createSseFramer, createStickyNoRouteResponse, currentCacheKeepRealTurn, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, dumpResponseArtifact, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getCacheKeepRegistryDirectories, getClaudeCodeIdentityForVerifiedAccount, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, getWaitForReset, 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, raceWithSignal, readSessionCachePolicy, reportRoutingResponse, reportSessionCacheTouch, requestCacheLifetimeMs, requestShortestCacheLifetimeMs, resolveNativePoolPaths, routingCandidates, routingChoiceMatches, routingWarmCredential, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, startRoutingWait, stickyQuotaSnapshotIsFresh, stickyRetainRetryHeaders, stickyRetryAfterWithJitter, stickyRouteCandidateWeight, stickyRouteFamilyForModel, warnClaudeGatewayRelayIgnored, withAnthropicBilling, withCacheKeepRealTurn, } 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, piThreadCacheSlot, } from './convert.js';
@@ -1654,6 +1654,7 @@ async function executeWithFallback(options) {
1654
1654
  modelId: options.model.id,
1655
1655
  sticky: true,
1656
1656
  sessionId,
1657
+ waitForReset: getWaitForReset(storage) && !advice,
1657
1658
  });
1658
1659
  return createStickyNoRouteResponse({
1659
1660
  mainRefreshError: storage?.refresh?.mainLastRefreshError,
@@ -1668,6 +1669,7 @@ async function executeWithFallback(options) {
1668
1669
  storage,
1669
1670
  sessionId,
1670
1671
  modelId: options.model.id,
1672
+ waitForReset: getWaitForReset(storage) && !advice,
1671
1673
  });
1672
1674
  };
1673
1675
  if (!resolution)
@@ -1870,6 +1872,7 @@ async function executeWithFallback(options) {
1870
1872
  snapshot: await native.view(options.streamOptions?.signal, options.model.id),
1871
1873
  modelId: options.model.id,
1872
1874
  sessionId: options.streamOptions?.sessionId,
1875
+ waitForReset: getWaitForReset(storage) && !advice,
1873
1876
  });
1874
1877
  return createStickyNoRouteResponse({
1875
1878
  routeQuotas: (storage?.accounts ?? [])
@@ -1886,6 +1889,7 @@ async function executeWithFallback(options) {
1886
1889
  storage,
1887
1890
  sessionId: options.streamOptions?.sessionId,
1888
1891
  modelId: options.model.id,
1892
+ waitForReset: getWaitForReset(storage) && !advice,
1889
1893
  });
1890
1894
  }
1891
1895
  if (isKillswitchEnabled(storage)) {
@@ -1913,6 +1917,8 @@ async function executeWithFallback(options) {
1913
1917
  })),
1914
1918
  storage: current.policyStorage,
1915
1919
  modelId: options.model.id,
1920
+ sessionId: options.streamOptions?.sessionId,
1921
+ waitForReset: getWaitForReset(current.policyStorage) && !advice,
1916
1922
  sessionTtlMs: sessionCacheActivity.ttlMs(options.streamOptions?.sessionId),
1917
1923
  }));
1918
1924
  }
@@ -2248,7 +2254,13 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
2248
2254
  delete block.index;
2249
2255
  output.stopReason = options?.signal?.aborted ? 'aborted' : 'error';
2250
2256
  output.errorMessage =
2251
- error instanceof Error ? error.message : String(error);
2257
+ output.stopReason === 'error' &&
2258
+ isNativeTransientAccountError(error) &&
2259
+ error.poolRead
2260
+ ? 'Anthropic account service unavailable while an update is in progress; retry the request'
2261
+ : error instanceof Error
2262
+ ? error.message
2263
+ : String(error);
2252
2264
  stream.push({ type: 'error', reason: output.stopReason, error: output });
2253
2265
  stream.end();
2254
2266
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.15.2",
3
+ "version": "2.16.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.15.2"
39
+ "@cortexkit/anthropic-auth-core": "2.16.1"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",