@cortexkit/pi-anthropic-auth 2.11.3 → 2.12.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.
@@ -9,12 +9,15 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
9
9
  const native = getPiNativeRuntime(storagePath);
10
10
  const custody = createPiCustodyCommands();
11
11
  const pending = new Map();
12
+ const written = (result, text) => result.outcome === 'refused' || result.outcome === 'failed'
13
+ ? { ok: false, text: result.reason }
14
+ : { ok: true, text };
12
15
  const setSection = async (key, patch) => {
13
- await (await native.service()).updateSettings((settings) => mergeNativeSettingsSection(settings, key, patch));
16
+ return (await native.service()).updateSettings((settings) => mergeNativeSettingsSection(settings, key, patch));
14
17
  };
15
18
  const setLimits = async (entries) => {
16
19
  const snapshot = await native.view();
17
- await (await native.service()).updateSettings((settings) => {
20
+ return (await native.service()).updateSettings((settings) => {
18
21
  const limits = record(settings.killswitch);
19
22
  let accounts = { ...record(limits.accounts) };
20
23
  let main = limits.main;
@@ -22,7 +25,7 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
22
25
  const threshold = {
23
26
  five_hour: entry.fh,
24
27
  seven_day: entry.sd,
25
- ...(entry.scoped !== undefined && { scoped: entry.scoped }),
28
+ scoped: entry.scoped ?? 0,
26
29
  };
27
30
  if (entry.account === 'main' || entry.account === 'all')
28
31
  main = threshold;
@@ -41,6 +44,8 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
41
44
  });
42
45
  };
43
46
  const dispatch = async (request, options) => {
47
+ const runtime = await native.service();
48
+ await runtime.prepareSettingsAction?.();
44
49
  if (isVaultHosted() &&
45
50
  [
46
51
  'enrollment-reset',
@@ -49,7 +54,6 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
49
54
  'add-apikey',
50
55
  ].includes(request.action))
51
56
  return { ok: false, text: VAULT_HOST_CONNECT_REFUSAL };
52
- const runtime = await native.service();
53
57
  switch (request.action) {
54
58
  case 'enable':
55
59
  case 'disable':
@@ -190,13 +194,11 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
190
194
  return { ok: true, text: 'Native OAuth quota and profile refreshed.' };
191
195
  }
192
196
  case 'routing-mode':
193
- await setSection('routing', { mode: request.values.mode });
194
- return { ok: true, text: 'Native routing mode updated.' };
197
+ return written(await setSection('routing', { mode: request.values.mode }), 'Native routing mode updated.');
195
198
  case 'routing-max-same-account-wait':
196
- await setSection('routing', {
199
+ return written(await setSection('routing', {
197
200
  maxSameAccountWait: request.values.maxSameAccountWait,
198
- });
199
- return { ok: true, text: 'Longest wait on the same account updated.' };
201
+ }), 'Longest wait on the same account updated.');
200
202
  case 'routing-reset':
201
203
  await clearPiStickyRoutingSession(storagePath, request.sessionId);
202
204
  return {
@@ -204,7 +206,7 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
204
206
  text: 'This session’s sticky assignment was cleared.',
205
207
  };
206
208
  case 'killswitch-on':
207
- await runtime.updateSettings((settings) => {
209
+ return written(await runtime.updateSettings((settings) => {
208
210
  const limits = record(settings.killswitch);
209
211
  return {
210
212
  ...settings,
@@ -214,64 +216,58 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
214
216
  main: limits.main ?? { ...DEFAULT_KILLSWITCH_THRESHOLDS },
215
217
  },
216
218
  };
217
- });
218
- return { ok: true, text: 'Native killswitch enabled.' };
219
+ }), 'Native killswitch enabled.');
219
220
  case 'killswitch-off':
220
- await setSection('killswitch', { enabled: false });
221
- return { ok: true, text: 'Native killswitch disabled.' };
221
+ return written(await setSection('killswitch', { enabled: false }), 'Native killswitch disabled.');
222
222
  case 'killswitch-set':
223
- await setLimits(request.values.entries);
224
- return { ok: true, text: 'Native killswitch thresholds updated.' };
223
+ return written(await setLimits(request.values.entries), 'Native killswitch thresholds updated.');
225
224
  case 'cache-on':
226
225
  case 'cache-off':
227
- await setSection('claudeCache', {
226
+ return written(await setSection('claudeCache', {
228
227
  enabled: request.action === 'cache-on',
229
- });
230
- return { ok: true, text: 'Native prompt cache setting updated.' };
228
+ }), 'Native prompt cache setting updated.');
231
229
  case 'cache-mode':
232
- await setSection('claudeCache', { mode: request.values.mode });
233
- return { ok: true, text: 'Native prompt cache mode updated.' };
230
+ return written(await setSection('claudeCache', { mode: request.values.mode }), 'Native prompt cache mode updated.');
234
231
  case 'cachekeep-always':
235
- await runtime.updateSettings(nativeCacheKeepAlways);
236
- return { ok: true, text: 'Native CacheKeep is always enabled.' };
232
+ return written(await runtime.updateSettings(nativeCacheKeepAlways), 'Native CacheKeep is always enabled.');
237
233
  case 'cachekeep-off':
238
- await setSection('cacheKeep', { enabled: false });
239
- return { ok: true, text: 'Native CacheKeep disabled.' };
234
+ return written(await setSection('cacheKeep', { enabled: false }), 'Native CacheKeep disabled.');
240
235
  case 'cachekeep-window':
241
- await setSection('cacheKeep', {
236
+ return written(await setSection('cacheKeep', {
242
237
  enabled: true,
243
238
  always: false,
244
239
  startHour: request.values.startHour,
245
240
  endHour: request.values.endHour,
246
- });
247
- return { ok: true, text: 'Native CacheKeep local time window updated.' };
241
+ }), 'Native CacheKeep local time window updated.');
248
242
  case 'cachekeep-subagents':
249
- await setSection('cacheKeep', {
243
+ return written(await setSection('cacheKeep', {
250
244
  subagents: request.values.enabled === 'on',
251
- });
252
- return { ok: true, text: 'Native CacheKeep subagent setting updated.' };
245
+ }), 'Native CacheKeep subagent setting updated.');
253
246
  case 'dump-on':
254
247
  case 'dump-off': {
255
248
  const enabled = request.action === 'dump-on';
256
- await setSection('dump', { enabled });
249
+ const result = written(await setSection('dump', { enabled }), 'Native request dumping setting updated.');
250
+ if (!result.ok)
251
+ return result;
257
252
  setDumpEnabled(enabled);
258
- return { ok: true, text: 'Native request dumping setting updated.' };
253
+ return result;
259
254
  }
260
255
  case 'logging-level':
261
256
  // The native runtime stores the level and applies it to the logger.
262
- await runtime.setLoggingLevel(request.values.level);
263
- return { ok: true, text: 'Native logging level updated.' };
257
+ return written(await runtime.setLoggingLevel(request.values.level), 'Native logging level updated.');
264
258
  case 'fast-on':
265
259
  case 'fast-off':
266
- await setSection('claudeFast', {
260
+ return written(await setSection('claudeFast', {
267
261
  enabled: request.action === 'fast-on',
268
- });
269
- return { ok: true, text: 'Native fast mode setting updated.' };
262
+ }), 'Native fast mode setting updated.');
270
263
  case 'prime-on':
271
- case 'prime-off':
272
- await setSection('prime', { enabled: request.action === 'prime-on' });
264
+ case 'prime-off': {
265
+ const result = written(await setSection('prime', { enabled: request.action === 'prime-on' }), 'Native Prime setting updated.');
266
+ if (!result.ok)
267
+ return result;
273
268
  native.prime?.settingsChanged();
274
- return { ok: true, text: 'Native Prime setting updated.' };
269
+ return result;
270
+ }
275
271
  case 'start-fire':
276
272
  return {
277
273
  ok: false,
@@ -280,14 +276,43 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
280
276
  }
281
277
  };
282
278
  return {
283
- readAccounts: async () => (await native.service()).read(),
279
+ readAccounts: async () => {
280
+ const runtime = await native.service();
281
+ await runtime.prepareSettingsAction?.();
282
+ return runtime.read();
283
+ },
284
284
  dispatch,
285
285
  async readStatus(command) {
286
286
  const runtime = await native.service();
287
+ await runtime.prepareSettingsAction?.();
287
288
  const snapshot = await runtime.read();
288
- if (snapshot.mode === 'claustrum' && !(await runtime.vault.read()))
289
+ if ((command === 'account' || command === 'quota') &&
290
+ snapshot.mode === 'claustrum' &&
291
+ !(await runtime.vault.read()))
289
292
  return 'Claustrum roster is unavailable; no verified account view has been discovered.';
290
293
  const storage = snapshot.policyStorage;
294
+ const settingsStatus = (summary) => {
295
+ const status = runtime.getSettingsStatus?.();
296
+ if (!status)
297
+ return summary;
298
+ const { file } = status;
299
+ return [
300
+ summary,
301
+ `Settings file: ${file.file}`,
302
+ ...(file.missing
303
+ ? ['Settings file is missing; a menu write will recreate it.']
304
+ : [`Settings file state: ${file.state}`]),
305
+ ...(file.recreated
306
+ ? ['Settings file was recreated by a menu write.']
307
+ : []),
308
+ ...file.invalidKeys.map((key) => `Invalid setting: ${key}`),
309
+ ...file.ignoredModelKeys.map(({ setting, model }) => `Ignored model key: ${setting}.${model}`),
310
+ ...file.duplicateKeys.map((key) => `Duplicate setting: ${key}`),
311
+ 'Settings (no model):',
312
+ ...Object.entries(status.values).map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`),
313
+ ...Object.entries(status.modelOverrides).flatMap(([key, rows]) => (rows ?? []).map(({ model, value }) => ` ${key} [${model}]: ${JSON.stringify(value)}`)),
314
+ ].join('\n');
315
+ };
291
316
  switch (command) {
292
317
  case 'account':
293
318
  return [
@@ -313,17 +338,17 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
313
338
  })),
314
339
  });
315
340
  case 'routing':
316
- return `Routing: ${getRoutingMode(storage)}\nLongest wait on the same account: ${getMaxSameAccountWait(storage)}`;
341
+ return settingsStatus(`Routing: ${getRoutingMode(storage)}\nLongest wait on the same account: ${getMaxSameAccountWait(storage)}`);
317
342
  case 'killswitch':
318
- return `Killswitch: ${isKillswitchEnabled(storage) ? 'enabled' : 'disabled'}\n${JSON.stringify(storage.killswitch ?? {})}`;
343
+ return settingsStatus(`Killswitch: ${isKillswitchEnabled(storage) ? 'enabled' : 'disabled'}\n${JSON.stringify(storage.killswitch ?? {})}`);
319
344
  case 'cache':
320
- return [
345
+ return settingsStatus([
321
346
  `1-hour cache: ${isCache1hPersistentlyEnabled(storage) ? 'enabled' : 'disabled'}; mode: ${getCache1hPersistentMode(storage)}`,
322
347
  `- Persisted: ${await runtime.getSettingsPath()}`,
323
- ].join('\n');
348
+ ].join('\n'));
324
349
  case 'cachekeep': {
325
350
  const sessions = await getPiTrackedCacheKeepSessions();
326
- return executeCacheKeepCommand({
351
+ return settingsStatus(executeCacheKeepCommand({
327
352
  argumentsText: '',
328
353
  enabled: isCacheKeepPersistentlyEnabled(storage),
329
354
  always: isCacheKeepAlways(storage),
@@ -334,30 +359,30 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
334
359
  nextPrewarmAt: sessions.length
335
360
  ? Math.min(...sessions.map((session) => session.nextPrewarmAt))
336
361
  : undefined,
337
- });
362
+ }));
338
363
  }
339
364
  case 'dump':
340
- return [
365
+ return settingsStatus([
341
366
  `Request dumping: ${isDumpPersistentlyEnabled(storage) ? 'enabled' : 'disabled'}`,
342
367
  `- Persisted: ${await runtime.getSettingsPath()}`,
343
- ].join('\n');
368
+ ].join('\n'));
344
369
  case 'logging':
345
- return [
370
+ return settingsStatus([
346
371
  `Logging: ${getPersistedLogLevel(storage) ?? 'info'}`,
347
372
  `- Persisted: ${await runtime.getSettingsPath()}`,
348
- ].join('\n');
373
+ ].join('\n'));
349
374
  case 'fast':
350
- return [
375
+ return settingsStatus([
351
376
  `Fast mode: ${isFastModePersistentlyEnabled(storage) ? 'enabled' : 'disabled'}`,
352
377
  `- Persisted: ${await runtime.getSettingsPath()}`,
353
- ].join('\n');
378
+ ].join('\n'));
354
379
  case 'prime':
355
- return executePrimeCommand({
380
+ return settingsStatus(executePrimeCommand({
356
381
  argumentsText: 'status',
357
382
  enabled: isPrimePersistentlyEnabled(storage),
358
383
  accounts: native.prime?.manager.stats(storage) ??
359
384
  buildPrimeAccountStatuses(storage, { now: Date.now() }),
360
- }).text;
385
+ }).text);
361
386
  }
362
387
  },
363
388
  };
package/dist/native.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { type NativeAccountRuntime, type NativeAccountRuntimeOptions, type NativeAccountSnapshot, type NativeCustodyClient, type NativeCustodyReceipt, type NativeCustodyReporterSource, type NativeLocalExternalPolicy, type NativeRefreshResult, type RoutingChoice } from '@cortexkit/anthropic-auth-core';
1
+ import { type AccountStorage, type NativeAccountRuntime, type NativeAccountRuntimeOptions, type NativeAccountSnapshot, type NativeCustodyClient, type NativeCustodyReceipt, type NativeCustodyReporterSource, type NativeLocalExternalPolicy, type NativeRefreshResult, type RoutingChoice } from '@cortexkit/anthropic-auth-core';
2
2
  import { type PiPrimeLease, type PiPrimeOptions } from './prime.ts';
3
+ import { type PiSettingsOptions } from './settings.ts';
3
4
  export type PiNativeAttempt = {
4
5
  source: 'local';
5
6
  accountIdentity: string;
@@ -40,6 +41,7 @@ export declare class PiNativeRuntime {
40
41
  private readonly initialization;
41
42
  private readonly env;
42
43
  private vaultWatch;
44
+ private settings;
43
45
  private closed;
44
46
  private closing;
45
47
  prime: PiPrimeLease | undefined;
@@ -61,10 +63,13 @@ export declare class PiNativeRuntime {
61
63
  local?: NativeAccountRuntimeOptions['local'];
62
64
  vaultPoll?: PiVaultPollOptions;
63
65
  prime?: PiPrimeOptions;
66
+ settings?: PiSettingsOptions;
64
67
  });
65
68
  service(): Promise<NativeAccountRuntime>;
66
69
  /** Inspect only a completed runtime read; initialization is never awaited. */
67
70
  peek(): NativeAccountSnapshot | undefined;
71
+ /** Resolve target settings from the initialized service without request I/O. */
72
+ resolveSettings(stored: AccountStorage, model?: string): AccountStorage;
68
73
  routingPath(): Promise<string>;
69
74
  routingStorage(): Promise<{
70
75
  path: string;
@@ -79,9 +84,9 @@ export declare class PiNativeRuntime {
79
84
  */
80
85
  migrationRefusal(): Promise<Error | undefined>;
81
86
  /** Read the published inventory even when no account can serve, so /claude can show its sign-in remedy. */
82
- view(signal?: AbortSignal): Promise<NativeAccountSnapshot>;
87
+ view(signal?: AbortSignal, model?: string): Promise<NativeAccountSnapshot>;
83
88
  /** Admit a model request without rediscovering a healthy roster. */
84
- requestView(signal?: AbortSignal): Promise<NativeAccountSnapshot>;
89
+ requestView(signal?: AbortSignal, model?: string): Promise<NativeAccountSnapshot>;
85
90
  authorize(routeId: string, signal?: AbortSignal, modelId?: string, intent?: 'serve' | 'cachekeep', routingChoice?: RoutingChoice): Promise<PiNativeAttempt>;
86
91
  retry(routeId: string, served: PiNativeAttempt, signal?: AbortSignal, modelId?: string, routingChoice?: RoutingChoice): Promise<PiNativeAttempt | undefined>;
87
92
  report(served: PiNativeAttempt, status: number, source: NativeCustodyReporterSource): Promise<void>;
@@ -90,11 +95,14 @@ export declare class PiNativeRuntime {
90
95
  }
91
96
  /** Inspect an existing context without creating a runtime or starting its I/O. */
92
97
  export declare function peekPiNativeSnapshot(storagePath?: string): NativeAccountSnapshot | undefined;
98
+ /** When no live runtime exists, resolving settings must not start account I/O. */
99
+ export declare function resolvePiSettingsFromMemory(stored: AccountStorage, model?: string, storagePath?: string): AccountStorage;
93
100
  export declare function getPiNativeRuntime(storagePath?: string, options?: {
94
101
  connect?: () => Promise<NativeCustodyClient>;
95
102
  local?: NativeAccountRuntimeOptions['local'];
96
103
  vaultPoll?: PiVaultPollOptions;
97
104
  prime?: PiPrimeOptions;
105
+ settings?: PiSettingsOptions;
98
106
  }): PiNativeRuntime;
99
107
  export declare function closePiNativeRuntime(storagePath?: string): Promise<void>;
100
108
  export {};
package/dist/native.js CHANGED
@@ -1,7 +1,9 @@
1
+ import { homedir } from 'node:os';
1
2
  import { resolve } from 'node:path';
2
- import { acquireNativeAccountRuntime, createNativeUsagePublisher, decidePiStateLayout, getAccountStatePath, getHostClaustrumEnrollmentPaths, getPersistedLogLevel, isKillswitchEnabled, isVaultHosted, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, logger, NativeAccountRefusal, nativeAccountCanServe, nativeAccountRefusal, nativeLocalAccountRefusal, nativeMigrationAuthorityPhase, nativeRuntimeOptionIdentity, quotaSnapshotHasStandardWindows, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readNativeAccountsForRequest, readNativeMigrationJournal, resolveClaustrumConnectionPath, resolveLocalRoutingDestination, resolveNativePoolPaths, routingChoiceMatches, setLogLevel, } from '@cortexkit/anthropic-auth-core';
3
+ import { acquireNativeAccountRuntime, createNativeUsagePublisher, decidePiStateLayout, getAccountStatePath, getHostClaustrumEnrollmentPaths, getPersistedLogLevel, getSettingsFilePath, isKillswitchEnabled, isVaultHosted, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, logger, NativeAccountRefusal, nativeAccountCanServe, nativeAccountRefusal, nativeLocalAccountRefusal, nativeMigrationAuthorityPhase, nativeRuntimeOptionIdentity, quotaSnapshotHasStandardWindows, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, readNativeAccountsForRequest, readNativeMigrationJournal, resolveClaustrumConnectionPath, resolveLocalRoutingDestination, resolveNativePoolPaths, routingChoiceMatches, setLogLevel, } from '@cortexkit/anthropic-auth-core';
3
4
  import { getPiAccountStoragePath, getPiClaustrumConnectionOptions, getPiConfigDir, requirePiNativeHostAuth, } from './paths.js';
4
5
  import { acquirePiPrime, } from './prime.js';
6
+ import { openPiSettings } from './settings.js';
5
7
  export function piAttemptAccessToken(attempt) {
6
8
  return attempt.source === 'vault'
7
9
  ? attempt.receipt.accessToken
@@ -47,12 +49,13 @@ function closeRuntime(entry) {
47
49
  closingRuntimes.delete(entry.storagePath);
48
50
  }, () => { });
49
51
  }
50
- function runtimeCacheKey(storagePath) {
52
+ function runtimeCacheKey(storagePath, home = homedir()) {
51
53
  const enrollment = getHostClaustrumEnrollmentPaths('pi');
52
54
  return JSON.stringify([
53
55
  resolve(storagePath),
54
56
  resolve(getAccountStatePath(storagePath)),
55
- resolve(getPiConfigDir()),
57
+ resolve(getPiConfigDir(process.env, home)),
58
+ resolve(getSettingsFilePath({ env: process.env, home })),
56
59
  enrollment.tokenPath,
57
60
  enrollment.statePath,
58
61
  getPiClaustrumConnectionOptions(storagePath).identity,
@@ -88,6 +91,7 @@ export class PiNativeRuntime {
88
91
  initialization;
89
92
  env;
90
93
  vaultWatch;
94
+ settings;
91
95
  closed = false;
92
96
  closing;
93
97
  prime;
@@ -103,7 +107,11 @@ export class PiNativeRuntime {
103
107
  ]);
104
108
  }
105
109
  constructor(storagePath, options = {}) {
106
- const env = { ...process.env };
110
+ const env = {
111
+ ...process.env,
112
+ PI_ANTHROPIC_AUTH_FILE: storagePath,
113
+ };
114
+ const home = options.settings?.home ?? homedir();
107
115
  this.env = env;
108
116
  const poll = options.vaultPoll ?? { intervalMs: PI_VAULT_POLL_INTERVAL_MS };
109
117
  const identity = getPiClaustrumConnectionOptions(storagePath).identity;
@@ -126,9 +134,9 @@ export class PiNativeRuntime {
126
134
  return decision.registration;
127
135
  });
128
136
  void this.holderRegistration.catch(() => { });
129
- this.initialization = this.holderRegistration.then(async () => {
137
+ this.initialization = this.holderRegistration.then(async (registration) => {
130
138
  const paths = await this.paths;
131
- const runtime = acquireNativeAccountRuntime({
139
+ const runtimeOptions = {
132
140
  paths,
133
141
  host: 'pi',
134
142
  local: options.local,
@@ -139,7 +147,25 @@ export class PiNativeRuntime {
139
147
  env,
140
148
  identity,
141
149
  },
150
+ };
151
+ const settings = await openPiSettings(runtimeOptions, env, home, registration, options.settings);
152
+ this.settings = settings.service;
153
+ const runtime = acquireNativeAccountRuntime({
154
+ ...runtimeOptions,
155
+ settingsFile: settings.file,
156
+ settingsService: settings.service,
157
+ settingsFallback: settings.fallback,
158
+ settingsReopen: settings.reopen,
159
+ settingsMode: () => settings.mode,
160
+ settingsAuthority: options.settings?.authority,
142
161
  });
162
+ try {
163
+ await runtime.prepareSettingsAction?.();
164
+ }
165
+ catch {
166
+ // A failed settings check must not stop authentication requests.
167
+ logger.warn('settings', 'Pi settings initialization failed; continuing with available settings.');
168
+ }
143
169
  // Apply local or vault preferences before the watcher can log. Match
144
170
  // OpenCode's startup precedence without blocking migration refusals.
145
171
  try {
@@ -148,6 +174,8 @@ export class PiNativeRuntime {
148
174
  setLogLevel(getPersistedLogLevel(initial.policyStorage) ?? 'info');
149
175
  }
150
176
  catch { }
177
+ runtime.applySettingsEffects?.();
178
+ this.publishedRuntime = runtime;
151
179
  if (this.closed)
152
180
  runtime.close();
153
181
  // Refresh returns at once while this host uses local accounts, so the
@@ -171,7 +199,6 @@ export class PiNativeRuntime {
171
199
  // the next poll or a request's bounded refresh retries it.
172
200
  void this.vaultWatch.ready.catch(() => { });
173
201
  }
174
- this.publishedRuntime = runtime;
175
202
  return runtime;
176
203
  });
177
204
  // Initialization is lazy from the host's perspective; a path failure is
@@ -191,6 +218,10 @@ export class PiNativeRuntime {
191
218
  peek() {
192
219
  return this.closed ? undefined : this.publishedRuntime?.peek?.();
193
220
  }
221
+ /** Resolve target settings from the initialized service without request I/O. */
222
+ resolveSettings(stored, model) {
223
+ return this.publishedRuntime?.resolveSettings?.(stored, model) ?? stored;
224
+ }
194
225
  async routingPath() {
195
226
  return (await this.routingStorage()).path;
196
227
  }
@@ -233,15 +264,20 @@ export class PiNativeRuntime {
233
264
  }
234
265
  }
235
266
  /** Read the published inventory even when no account can serve, so /claude can show its sign-in remedy. */
236
- async view(signal) {
267
+ async view(signal, model) {
237
268
  const runtime = await this.service();
238
269
  signal?.throwIfAborted();
239
- return runtime.read();
270
+ return runtime.read(model);
240
271
  }
241
272
  /** Admit a model request without rediscovering a healthy roster. */
242
- async requestView(signal) {
273
+ async requestView(signal, model) {
243
274
  const runtime = await this.service();
244
- return readNativeAccountsForRequest(runtime, signal);
275
+ const snapshot = await readNativeAccountsForRequest(runtime, signal);
276
+ return {
277
+ ...snapshot,
278
+ policyStorage: runtime.resolveSettings?.(snapshot.policyStorage, model) ??
279
+ snapshot.policyStorage,
280
+ };
245
281
  }
246
282
  async authorize(routeId, signal, modelId, intent = 'serve', routingChoice) {
247
283
  const background = intent === 'cachekeep';
@@ -398,19 +434,27 @@ export class PiNativeRuntime {
398
434
  await this.drainReports();
399
435
  await runtime.close();
400
436
  }, () => { });
437
+ await this.settings?.dispose();
401
438
  })();
402
439
  return this.closing;
403
440
  }
404
441
  }
442
+ function cachedPiNativeRuntime(storagePath) {
443
+ const contextKey = runtimeCacheKey(storagePath);
444
+ return [...runtimes.values()].find((entry) => entry.contextKey === contextKey)
445
+ ?.runtime;
446
+ }
405
447
  /** Inspect an existing context without creating a runtime or starting its I/O. */
406
448
  export function peekPiNativeSnapshot(storagePath = getPiAccountStoragePath()) {
407
- const contextKey = runtimeCacheKey(storagePath);
408
- return [...runtimes.values()]
409
- .find((entry) => entry.contextKey === contextKey)
410
- ?.runtime.peek();
449
+ return cachedPiNativeRuntime(storagePath)?.peek();
450
+ }
451
+ /** When no live runtime exists, resolving settings must not start account I/O. */
452
+ export function resolvePiSettingsFromMemory(stored, model, storagePath = getPiAccountStoragePath()) {
453
+ const runtime = cachedPiNativeRuntime(storagePath);
454
+ return runtime?.peek() ? runtime.resolveSettings(stored, model) : stored;
411
455
  }
412
456
  export function getPiNativeRuntime(storagePath = getPiAccountStoragePath(), options = {}) {
413
- const contextKey = runtimeCacheKey(storagePath);
457
+ const contextKey = runtimeCacheKey(storagePath, options.settings?.home);
414
458
  const key = JSON.stringify([
415
459
  contextKey,
416
460
  nativeRuntimeOptionIdentity(options.connect),
package/dist/paths.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare function getPiConfigDir(): string;
1
+ export declare function getPiConfigDir(env?: NodeJS.ProcessEnv, home?: string): string;
2
2
  export declare function getPiAccountStoragePath(): string;
3
3
  export declare function getPiClaustrumConnectionOptions(storagePath?: string): {
4
4
  storagePath: string;
package/dist/paths.js CHANGED
@@ -2,10 +2,10 @@ import { readFile } from 'node:fs/promises';
2
2
  import { homedir } from 'node:os';
3
3
  import { join } from 'node:path';
4
4
  import { ACCOUNT_FILE_NAME, isVaultHosted, nativePiAuthSlotPaths, parseJsonRedacted, primeStorageFingerprint, } from '@cortexkit/anthropic-auth-core';
5
- export function getPiConfigDir() {
6
- return (process.env.PI_CODING_AGENT_DIR?.trim() ||
7
- process.env.PI_AGENT_DIR?.trim() ||
8
- join(homedir(), '.pi', 'agent'));
5
+ export function getPiConfigDir(env = process.env, home = homedir()) {
6
+ return (env.PI_CODING_AGENT_DIR?.trim() ||
7
+ env.PI_AGENT_DIR?.trim() ||
8
+ join(home, '.pi', 'agent'));
9
9
  }
10
10
  export function getPiAccountStoragePath() {
11
11
  return (process.env.PI_ANTHROPIC_AUTH_FILE?.trim() ||
@@ -0,0 +1,11 @@
1
+ import { type NativeAccountRuntimeOptions, type NativeHolderRegistration, type SettingsMoveStartupOptions, type SettingsServiceOptions } from '@cortexkit/anthropic-auth-core';
2
+ export interface PiSettingsOptions {
3
+ home?: string;
4
+ startup?: Pick<SettingsMoveStartupOptions, 'dependencies' | 'readMode'> & {
5
+ fence?: SettingsMoveStartupOptions['fence'];
6
+ };
7
+ service?: Pick<SettingsServiceOptions, 'dependencies' | 'lockTimeoutMs'>;
8
+ authority?: NativeAccountRuntimeOptions['settingsAuthority'];
9
+ }
10
+ /** Complete the settings move and initialize the service before Pi serves requests. */
11
+ export declare function openPiSettings(runtime: NativeAccountRuntimeOptions, env: NodeJS.ProcessEnv, home: string, registration: NativeHolderRegistration | undefined, options?: PiSettingsOptions): Promise<import("@cortexkit/anthropic-auth-core").StartedSettings>;
@@ -0,0 +1,52 @@
1
+ import { createNativeAccountRuntime, legacySettingsProtection, openSettingsService, readPeerLegacySettingsProtection, startSettings, } from '@cortexkit/anthropic-auth-core';
2
+ /** Complete the settings move and initialize the service before Pi serves requests. */
3
+ export async function openPiSettings(runtime, env, home, registration, options = {}) {
4
+ // Create a runtime only if migration must initialize the vault settings file.
5
+ let legacy;
6
+ try {
7
+ const initializeVaultSettings = () => {
8
+ legacy ??= createNativeAccountRuntime(runtime);
9
+ return legacy.vault.initializeSettings();
10
+ };
11
+ return await startSettings({
12
+ ...options.startup,
13
+ host: 'pi',
14
+ env,
15
+ home,
16
+ ownPoolPaths: runtime.paths,
17
+ initializeVaultSettings,
18
+ fence: { registration, ...options.startup?.fence },
19
+ lockTimeoutMs: options.service?.lockTimeoutMs,
20
+ start: options.service && {
21
+ open: (settings) => openSettingsService({ ...options.service, ...settings }),
22
+ },
23
+ protection: {
24
+ readLegacyProtection: async () => {
25
+ // Reopening the settings service can outlive startup. Give each
26
+ // recovery read its own runtime rather than using the closed one.
27
+ const recovery = createNativeAccountRuntime(runtime);
28
+ try {
29
+ const snapshot = await recovery.read();
30
+ return legacySettingsProtection(snapshot.policyStorage, 'pi', snapshot.mode);
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ finally {
36
+ await recovery.close();
37
+ }
38
+ },
39
+ // Recreating a missing settings file needs OpenCode's own protection.
40
+ readPeerLegacyProtection: (host) => readPeerLegacySettingsProtection({
41
+ host,
42
+ env,
43
+ home,
44
+ readMode: options.startup?.readMode,
45
+ }),
46
+ },
47
+ });
48
+ }
49
+ finally {
50
+ await legacy?.close();
51
+ }
52
+ }
package/dist/stream.js CHANGED
@@ -2,7 +2,7 @@ import { applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyCustomHeaders, as
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';
5
- import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, } from './native.js';
5
+ import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, resolvePiSettingsFromMemory, } 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';
@@ -230,6 +230,7 @@ const piCacheKeep = new PiCacheKeep({
230
230
  },
231
231
  fetchImpl: fetchPiOAuth,
232
232
  loadStorage: async () => (await getPiNativeRuntime().view()).policyStorage,
233
+ resolveSettings: resolvePiSettingsFromMemory,
233
234
  onTrackedSessionsChanged: (sessions) => getPiCacheKeepRegistry().publish(sessions),
234
235
  prepareHeaders: async (headers, target, attempt) => {
235
236
  requirePiOAuthOrigin(target.url);
@@ -516,7 +517,7 @@ async function sendAnthropicRequest(options, deps = {}) {
516
517
  // Capture the serving service while authorization is open. Shutdown rejects
517
518
  // new serving work immediately but drains writes for already-served attempts.
518
519
  const servingRuntime = await native.service();
519
- const snapshot = await native.view();
520
+ const snapshot = await native.view(options.streamOptions?.signal, options.model.id);
520
521
  const storage = snapshot.policyStorage;
521
522
  setDumpEnabled(isDumpPersistentlyEnabled(storage));
522
523
  const routeId = options.oauthAccountId ?? STICKY_ROUTING_MAIN_ACCOUNT_ID;
@@ -1135,7 +1136,7 @@ async function executeWithFallback(options) {
1135
1136
  };
1136
1137
  options = { ...options, routingRelay: routingState.relay };
1137
1138
  const native = getPiNativeRuntime(options.storagePath);
1138
- let snapshot = await native.requestView(options.streamOptions?.signal);
1139
+ let snapshot = await native.requestView(options.streamOptions?.signal, options.model.id);
1139
1140
  let storage = snapshot.policyStorage;
1140
1141
  const accountView = (id) => snapshot.accounts.find((account) => account.id === id);
1141
1142
  const vaultAccountIdentities = () => {
@@ -1178,7 +1179,7 @@ async function executeWithFallback(options) {
1178
1179
  (!scopedWindow || Date.now() - scopedWindow.checkedAt < age));
1179
1180
  }
1180
1181
  async function refreshRoutingSnapshot() {
1181
- snapshot = await native.view();
1182
+ snapshot = await native.view(options.streamOptions?.signal, options.model.id);
1182
1183
  storage = snapshot.policyStorage;
1183
1184
  mainAccountId = accountView(STICKY_ROUTING_MAIN_ACCOUNT_ID)?.accountIdentity;
1184
1185
  ({ quotaManager, getUsableFallbackAccounts } = getPiRoutingServices(options.storagePath, snapshot));
@@ -1441,7 +1442,7 @@ async function executeWithFallback(options) {
1441
1442
  const noRouteResponse = async () => {
1442
1443
  if (snapshot.mode === 'claustrum')
1443
1444
  return createNativeVaultNoRouteResponse({
1444
- snapshot: await native.view(),
1445
+ snapshot: await native.view(options.streamOptions?.signal, options.model.id),
1445
1446
  modelId: options.model.id,
1446
1447
  sticky: true,
1447
1448
  sessionId,
@@ -1658,7 +1659,7 @@ async function executeWithFallback(options) {
1658
1659
  }
1659
1660
  if (snapshot.mode === 'claustrum')
1660
1661
  return createNativeVaultNoRouteResponse({
1661
- snapshot: await native.view(),
1662
+ snapshot: await native.view(options.streamOptions?.signal, options.model.id),
1662
1663
  modelId: options.model.id,
1663
1664
  sessionId: options.streamOptions?.sessionId,
1664
1665
  });
@@ -1693,7 +1694,7 @@ async function executeWithFallback(options) {
1693
1694
  if (fallback)
1694
1695
  return fallback;
1695
1696
  }
1696
- const current = await native.view();
1697
+ const current = await native.view(options.streamOptions?.signal, options.model.id);
1697
1698
  return createQuotaRefusalResponse('Killswitch blocked all OAuth routes', quotaRefusalTiming({
1698
1699
  readings: current.accounts
1699
1700
  .filter((account) => account.type === 'oauth' && nativeAccountCanServe(account))
@@ -1771,7 +1772,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
1771
1772
  run: () => executeWithFallback(request),
1772
1773
  resume: async (hold) => {
1773
1774
  const native = getPiNativeRuntime(storagePath);
1774
- const before = await native.requestView(options?.signal);
1775
+ const before = await native.requestView(options?.signal, model.id);
1775
1776
  if (hold &&
1776
1777
  (!hold.accountIdentity ||
1777
1778
  before.accounts.find((account) => account.id === hold.accountId)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-anthropic-auth",
3
- "version": "2.11.3",
3
+ "version": "2.12.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.11.3"
39
+ "@cortexkit/anthropic-auth-core": "2.12.0"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@earendil-works/pi-ai": ">=0.86.1 <2",