@cortexkit/pi-anthropic-auth 2.11.4 → 2.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/native-commands.js +86 -58
- package/dist/native.d.ts +15 -3
- package/dist/native.js +68 -16
- package/dist/paths.d.ts +1 -1
- package/dist/paths.js +4 -4
- package/dist/settings.d.ts +11 -0
- package/dist/settings.js +52 -0
- package/dist/stream.js +48 -13
- package/dist/transport.d.ts +13 -2
- package/dist/transport.js +16 -4
- package/package.json +2 -2
package/dist/native-commands.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { authorize, buildClaudeQuotaSummary, buildPrimeAccountStatuses, 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, isPrimePersistentlyEnabled, isVaultHosted, 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';
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
269
|
+
return result;
|
|
270
|
+
}
|
|
275
271
|
case 'start-fire':
|
|
276
272
|
return {
|
|
277
273
|
ok: false,
|
|
@@ -280,14 +276,46 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
|
|
|
280
276
|
}
|
|
281
277
|
};
|
|
282
278
|
return {
|
|
283
|
-
readAccounts: async () =>
|
|
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 (
|
|
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
|
+
const relayNotes = runtime.getRelayStatusNotes?.() ?? [];
|
|
297
|
+
if (!status)
|
|
298
|
+
return [summary, ...relayNotes].join('\n');
|
|
299
|
+
const { file } = status;
|
|
300
|
+
return [
|
|
301
|
+
summary,
|
|
302
|
+
`Settings file: ${file.file}`,
|
|
303
|
+
...(file.missing
|
|
304
|
+
? ['Settings file is missing; a menu write will recreate it.']
|
|
305
|
+
: [`Settings file state: ${file.state}`]),
|
|
306
|
+
...(file.recreated
|
|
307
|
+
? ['Settings file was recreated by a menu write.']
|
|
308
|
+
: []),
|
|
309
|
+
...file.invalidKeys.map((key) => `Invalid setting: ${key}`),
|
|
310
|
+
...file.ignoredModelKeys.map(({ setting, model }) => `Ignored model key: ${setting}.${model}`),
|
|
311
|
+
...file.duplicateKeys.map((key) => `Duplicate setting: ${key}`),
|
|
312
|
+
...claudeGatewayStatusNotes(file.gatewayIgnored, status.values.gateway),
|
|
313
|
+
...relayNotes,
|
|
314
|
+
'Settings (no model):',
|
|
315
|
+
...Object.entries(status.values).map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`),
|
|
316
|
+
...Object.entries(status.modelOverrides).flatMap(([key, rows]) => (rows ?? []).map(({ model, value }) => ` ${key} [${model}]: ${JSON.stringify(value)}`)),
|
|
317
|
+
].join('\n');
|
|
318
|
+
};
|
|
291
319
|
switch (command) {
|
|
292
320
|
case 'account':
|
|
293
321
|
return [
|
|
@@ -313,17 +341,17 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
|
|
|
313
341
|
})),
|
|
314
342
|
});
|
|
315
343
|
case 'routing':
|
|
316
|
-
return `Routing: ${getRoutingMode(storage)}\nLongest wait on the same account: ${getMaxSameAccountWait(storage)}
|
|
344
|
+
return settingsStatus(`Routing: ${getRoutingMode(storage)}\nLongest wait on the same account: ${getMaxSameAccountWait(storage)}`);
|
|
317
345
|
case 'killswitch':
|
|
318
|
-
return `Killswitch: ${isKillswitchEnabled(storage) ? 'enabled' : 'disabled'}\n${JSON.stringify(storage.killswitch ?? {})}
|
|
346
|
+
return settingsStatus(`Killswitch: ${isKillswitchEnabled(storage) ? 'enabled' : 'disabled'}\n${JSON.stringify(storage.killswitch ?? {})}`);
|
|
319
347
|
case 'cache':
|
|
320
|
-
return [
|
|
348
|
+
return settingsStatus([
|
|
321
349
|
`1-hour cache: ${isCache1hPersistentlyEnabled(storage) ? 'enabled' : 'disabled'}; mode: ${getCache1hPersistentMode(storage)}`,
|
|
322
350
|
`- Persisted: ${await runtime.getSettingsPath()}`,
|
|
323
|
-
].join('\n');
|
|
351
|
+
].join('\n'));
|
|
324
352
|
case 'cachekeep': {
|
|
325
353
|
const sessions = await getPiTrackedCacheKeepSessions();
|
|
326
|
-
return executeCacheKeepCommand({
|
|
354
|
+
return settingsStatus(executeCacheKeepCommand({
|
|
327
355
|
argumentsText: '',
|
|
328
356
|
enabled: isCacheKeepPersistentlyEnabled(storage),
|
|
329
357
|
always: isCacheKeepAlways(storage),
|
|
@@ -334,30 +362,30 @@ export function createPiNativeCommands(storagePath = getPiAccountStoragePath())
|
|
|
334
362
|
nextPrewarmAt: sessions.length
|
|
335
363
|
? Math.min(...sessions.map((session) => session.nextPrewarmAt))
|
|
336
364
|
: undefined,
|
|
337
|
-
});
|
|
365
|
+
}));
|
|
338
366
|
}
|
|
339
367
|
case 'dump':
|
|
340
|
-
return [
|
|
368
|
+
return settingsStatus([
|
|
341
369
|
`Request dumping: ${isDumpPersistentlyEnabled(storage) ? 'enabled' : 'disabled'}`,
|
|
342
370
|
`- Persisted: ${await runtime.getSettingsPath()}`,
|
|
343
|
-
].join('\n');
|
|
371
|
+
].join('\n'));
|
|
344
372
|
case 'logging':
|
|
345
|
-
return [
|
|
373
|
+
return settingsStatus([
|
|
346
374
|
`Logging: ${getPersistedLogLevel(storage) ?? 'info'}`,
|
|
347
375
|
`- Persisted: ${await runtime.getSettingsPath()}`,
|
|
348
|
-
].join('\n');
|
|
376
|
+
].join('\n'));
|
|
349
377
|
case 'fast':
|
|
350
|
-
return [
|
|
378
|
+
return settingsStatus([
|
|
351
379
|
`Fast mode: ${isFastModePersistentlyEnabled(storage) ? 'enabled' : 'disabled'}`,
|
|
352
380
|
`- Persisted: ${await runtime.getSettingsPath()}`,
|
|
353
|
-
].join('\n');
|
|
381
|
+
].join('\n'));
|
|
354
382
|
case 'prime':
|
|
355
|
-
return executePrimeCommand({
|
|
383
|
+
return settingsStatus(executePrimeCommand({
|
|
356
384
|
argumentsText: 'status',
|
|
357
385
|
enabled: isPrimePersistentlyEnabled(storage),
|
|
358
386
|
accounts: native.prime?.manager.stats(storage) ??
|
|
359
387
|
buildPrimeAccountStatuses(storage, { now: Date.now() }),
|
|
360
|
-
}).text;
|
|
388
|
+
}).text);
|
|
361
389
|
}
|
|
362
390
|
},
|
|
363
391
|
};
|
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 ClaudeGateway, 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,15 @@ 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;
|
|
73
|
+
/** The user's gateway for OAuth model requests, from memory only. */
|
|
74
|
+
claudeGateway(): ClaudeGateway | undefined;
|
|
68
75
|
routingPath(): Promise<string>;
|
|
69
76
|
routingStorage(): Promise<{
|
|
70
77
|
path: string;
|
|
@@ -79,9 +86,9 @@ export declare class PiNativeRuntime {
|
|
|
79
86
|
*/
|
|
80
87
|
migrationRefusal(): Promise<Error | undefined>;
|
|
81
88
|
/** Read the published inventory even when no account can serve, so /claude can show its sign-in remedy. */
|
|
82
|
-
view(signal?: AbortSignal): Promise<NativeAccountSnapshot>;
|
|
89
|
+
view(signal?: AbortSignal, model?: string): Promise<NativeAccountSnapshot>;
|
|
83
90
|
/** Admit a model request without rediscovering a healthy roster. */
|
|
84
|
-
requestView(signal?: AbortSignal): Promise<NativeAccountSnapshot>;
|
|
91
|
+
requestView(signal?: AbortSignal, model?: string): Promise<NativeAccountSnapshot>;
|
|
85
92
|
authorize(routeId: string, signal?: AbortSignal, modelId?: string, intent?: 'serve' | 'cachekeep', routingChoice?: RoutingChoice): Promise<PiNativeAttempt>;
|
|
86
93
|
retry(routeId: string, served: PiNativeAttempt, signal?: AbortSignal, modelId?: string, routingChoice?: RoutingChoice): Promise<PiNativeAttempt | undefined>;
|
|
87
94
|
report(served: PiNativeAttempt, status: number, source: NativeCustodyReporterSource): Promise<void>;
|
|
@@ -90,11 +97,16 @@ export declare class PiNativeRuntime {
|
|
|
90
97
|
}
|
|
91
98
|
/** Inspect an existing context without creating a runtime or starting its I/O. */
|
|
92
99
|
export declare function peekPiNativeSnapshot(storagePath?: string): NativeAccountSnapshot | undefined;
|
|
100
|
+
/** When no live runtime exists, resolving settings must not start account I/O. */
|
|
101
|
+
export declare function resolvePiSettingsFromMemory(stored: AccountStorage, model?: string, storagePath?: string): AccountStorage;
|
|
93
102
|
export declare function getPiNativeRuntime(storagePath?: string, options?: {
|
|
94
103
|
connect?: () => Promise<NativeCustodyClient>;
|
|
95
104
|
local?: NativeAccountRuntimeOptions['local'];
|
|
96
105
|
vaultPoll?: PiVaultPollOptions;
|
|
97
106
|
prime?: PiPrimeOptions;
|
|
107
|
+
settings?: PiSettingsOptions;
|
|
98
108
|
}): PiNativeRuntime;
|
|
99
109
|
export declare function closePiNativeRuntime(storagePath?: string): Promise<void>;
|
|
110
|
+
/** The gateway for a context's model requests, without starting account I/O. */
|
|
111
|
+
export declare function piClaudeGatewayFromMemory(storagePath?: string): ClaudeGateway | undefined;
|
|
100
112
|
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 = {
|
|
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
|
|
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,14 @@ 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
|
+
}
|
|
225
|
+
/** The user's gateway for OAuth model requests, from memory only. */
|
|
226
|
+
claudeGateway() {
|
|
227
|
+
return this.closed ? undefined : this.publishedRuntime?.getClaudeGateway?.();
|
|
228
|
+
}
|
|
194
229
|
async routingPath() {
|
|
195
230
|
return (await this.routingStorage()).path;
|
|
196
231
|
}
|
|
@@ -233,15 +268,20 @@ export class PiNativeRuntime {
|
|
|
233
268
|
}
|
|
234
269
|
}
|
|
235
270
|
/** Read the published inventory even when no account can serve, so /claude can show its sign-in remedy. */
|
|
236
|
-
async view(signal) {
|
|
271
|
+
async view(signal, model) {
|
|
237
272
|
const runtime = await this.service();
|
|
238
273
|
signal?.throwIfAborted();
|
|
239
|
-
return runtime.read();
|
|
274
|
+
return runtime.read(model);
|
|
240
275
|
}
|
|
241
276
|
/** Admit a model request without rediscovering a healthy roster. */
|
|
242
|
-
async requestView(signal) {
|
|
277
|
+
async requestView(signal, model) {
|
|
243
278
|
const runtime = await this.service();
|
|
244
|
-
|
|
279
|
+
const snapshot = await readNativeAccountsForRequest(runtime, signal);
|
|
280
|
+
return {
|
|
281
|
+
...snapshot,
|
|
282
|
+
policyStorage: runtime.resolveSettings?.(snapshot.policyStorage, model) ??
|
|
283
|
+
snapshot.policyStorage,
|
|
284
|
+
};
|
|
245
285
|
}
|
|
246
286
|
async authorize(routeId, signal, modelId, intent = 'serve', routingChoice) {
|
|
247
287
|
const background = intent === 'cachekeep';
|
|
@@ -398,19 +438,27 @@ export class PiNativeRuntime {
|
|
|
398
438
|
await this.drainReports();
|
|
399
439
|
await runtime.close();
|
|
400
440
|
}, () => { });
|
|
441
|
+
await this.settings?.dispose();
|
|
401
442
|
})();
|
|
402
443
|
return this.closing;
|
|
403
444
|
}
|
|
404
445
|
}
|
|
446
|
+
function cachedPiNativeRuntime(storagePath) {
|
|
447
|
+
const contextKey = runtimeCacheKey(storagePath);
|
|
448
|
+
return [...runtimes.values()].find((entry) => entry.contextKey === contextKey)
|
|
449
|
+
?.runtime;
|
|
450
|
+
}
|
|
405
451
|
/** Inspect an existing context without creating a runtime or starting its I/O. */
|
|
406
452
|
export function peekPiNativeSnapshot(storagePath = getPiAccountStoragePath()) {
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
453
|
+
return cachedPiNativeRuntime(storagePath)?.peek();
|
|
454
|
+
}
|
|
455
|
+
/** When no live runtime exists, resolving settings must not start account I/O. */
|
|
456
|
+
export function resolvePiSettingsFromMemory(stored, model, storagePath = getPiAccountStoragePath()) {
|
|
457
|
+
const runtime = cachedPiNativeRuntime(storagePath);
|
|
458
|
+
return runtime?.peek() ? runtime.resolveSettings(stored, model) : stored;
|
|
411
459
|
}
|
|
412
460
|
export function getPiNativeRuntime(storagePath = getPiAccountStoragePath(), options = {}) {
|
|
413
|
-
const contextKey = runtimeCacheKey(storagePath);
|
|
461
|
+
const contextKey = runtimeCacheKey(storagePath, options.settings?.home);
|
|
414
462
|
const key = JSON.stringify([
|
|
415
463
|
contextKey,
|
|
416
464
|
nativeRuntimeOptionIdentity(options.connect),
|
|
@@ -453,3 +501,7 @@ export function closePiNativeRuntime(storagePath = getPiAccountStoragePath()) {
|
|
|
453
501
|
// must also join those closes, not only the runtimes still in the cache.
|
|
454
502
|
return Promise.all(closingRuntimes.get(resolve(storagePath)) ?? []).then(() => { });
|
|
455
503
|
}
|
|
504
|
+
/** The gateway for a context's model requests, without starting account I/O. */
|
|
505
|
+
export function piClaudeGatewayFromMemory(storagePath = getPiAccountStoragePath()) {
|
|
506
|
+
return cachedPiNativeRuntime(storagePath)?.claudeGateway();
|
|
507
|
+
}
|
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 (
|
|
7
|
-
|
|
8
|
-
join(
|
|
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>;
|
package/dist/settings.js
ADDED
|
@@ -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
|
@@ -1,12 +1,12 @@
|
|
|
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, routingWarmCredential, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, startRoutingWait, stickyQuotaSnapshotIsFresh, stickyRetainRetryHeaders, stickyRetryAfterWithJitter, stickyRouteCandidateWeight, stickyRouteFamilyForModel, withAnthropicBilling, } 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, 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, routingWarmCredential, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, startRoutingWait, stickyQuotaSnapshotIsFresh, stickyRetainRetryHeaders, stickyRetryAfterWithJitter, stickyRouteCandidateWeight, stickyRouteFamilyForModel, warnClaudeGatewayRelayIgnored, 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, piThreadCacheSlot, } from './convert.js';
|
|
5
|
-
import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, } from './native.js';
|
|
5
|
+
import { getPiNativeRuntime, peekPiNativeSnapshot, piAttemptAccessToken, piClaudeGatewayFromMemory, 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';
|
|
9
|
-
import { buildPiOAuthMessagesUrl, fetchPiOAuth, fetchPiStreamResponse, requirePiOAuthOrigin, } from './transport.js';
|
|
9
|
+
import { buildPiOAuthMessagesUrl, createPiOAuthModelFetch, 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.
|
|
@@ -229,7 +229,11 @@ const piCacheKeep = new PiCacheKeep({
|
|
|
229
229
|
};
|
|
230
230
|
},
|
|
231
231
|
fetchImpl: fetchPiOAuth,
|
|
232
|
+
// A keep-warm is a model request, so it follows the current gateway of
|
|
233
|
+
// the target's own runtime.
|
|
234
|
+
fetchForTarget: (target) => createPiOAuthModelFetch(() => piClaudeGatewayFromMemory(target.accountStoragePath ?? getPiAccountStoragePath())),
|
|
232
235
|
loadStorage: async () => (await getPiNativeRuntime().view()).policyStorage,
|
|
236
|
+
resolveSettings: resolvePiSettingsFromMemory,
|
|
233
237
|
onTrackedSessionsChanged: (sessions) => getPiCacheKeepRegistry().publish(sessions),
|
|
234
238
|
prepareHeaders: async (headers, target, attempt) => {
|
|
235
239
|
requirePiOAuthOrigin(target.url);
|
|
@@ -516,7 +520,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
516
520
|
// Capture the serving service while authorization is open. Shutdown rejects
|
|
517
521
|
// new serving work immediately but drains writes for already-served attempts.
|
|
518
522
|
const servingRuntime = await native.service();
|
|
519
|
-
const snapshot = await native.view();
|
|
523
|
+
const snapshot = await native.view(options.streamOptions?.signal, options.model.id);
|
|
520
524
|
const storage = snapshot.policyStorage;
|
|
521
525
|
setDumpEnabled(isDumpPersistentlyEnabled(storage));
|
|
522
526
|
const routeId = options.oauthAccountId ?? STICKY_ROUTING_MAIN_ACCOUNT_ID;
|
|
@@ -618,6 +622,17 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
618
622
|
let input = options.apiAccount
|
|
619
623
|
? new URL('https://api.anthropic.com/v1/messages')
|
|
620
624
|
: buildPiOAuthMessagesUrl(options.model.baseUrl);
|
|
625
|
+
// The user's gateway from their own settings file takes OAuth model
|
|
626
|
+
// requests, Prime included. It is read once, so the relay, thread, gzip and
|
|
627
|
+
// URL choices below agree. `input` stays the Anthropic URL for CacheKeep,
|
|
628
|
+
// which applies the gateway current at each warm.
|
|
629
|
+
const configuredGateway = options.apiAccount
|
|
630
|
+
? undefined
|
|
631
|
+
: servingRuntime.getClaudeGateway?.();
|
|
632
|
+
const gatewayUrl = configuredGateway
|
|
633
|
+
? claudeGatewayModelUrl(input, configuredGateway)
|
|
634
|
+
: undefined;
|
|
635
|
+
const gateway = gatewayUrl ? configuredGateway : undefined;
|
|
621
636
|
const init = {
|
|
622
637
|
method: 'POST',
|
|
623
638
|
headers,
|
|
@@ -699,12 +714,20 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
699
714
|
throw new Error('Pi native OAuth route identity changed');
|
|
700
715
|
return attempt;
|
|
701
716
|
};
|
|
702
|
-
|
|
717
|
+
let relayConfig = options.apiAccount
|
|
703
718
|
? null
|
|
704
719
|
: await (await native.service()).getRelayConfig();
|
|
720
|
+
// A gateway takes the request instead of the relay, with no relay attempt
|
|
721
|
+
// and no fallback to api.anthropic.com.
|
|
722
|
+
if (gateway && relayConfig) {
|
|
723
|
+
warnClaudeGatewayRelayIgnored(gateway);
|
|
724
|
+
relayConfig = null;
|
|
725
|
+
}
|
|
705
726
|
let threadRequest;
|
|
706
727
|
if (!options.apiAccount &&
|
|
707
728
|
!options.prime &&
|
|
729
|
+
// Gateways may refuse the thread route: send full requests.
|
|
730
|
+
!gateway &&
|
|
708
731
|
isPiPrimaryThreadRequest(options.storagePath, options.streamOptions, options.requestOrigin) &&
|
|
709
732
|
(!relayConfig ||
|
|
710
733
|
effectiveRelayTransport(relayConfig.transport, relayConfig.url) !==
|
|
@@ -760,8 +783,18 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
760
783
|
await options.prime?.beforeSend();
|
|
761
784
|
init.signal?.throwIfAborted();
|
|
762
785
|
assertHostAuthorityStable();
|
|
763
|
-
const scope = createProviderErrorResponseScope(
|
|
786
|
+
const scope = createProviderErrorResponseScope(
|
|
787
|
+
// A gateway error may echo the gateway's own header values.
|
|
788
|
+
[secret, ...claudeGatewayHeaderValues(gateway)], 'event-stream');
|
|
764
789
|
physical.scope = scope;
|
|
790
|
+
// Only the destination and the gateway's own headers change; the body
|
|
791
|
+
// goes uncompressed, as Claude Code compresses only to
|
|
792
|
+
// api.anthropic.com.
|
|
793
|
+
if (gateway && gatewayUrl) {
|
|
794
|
+
requirePiOAuthOrigin(gatewayUrl.toString(), gateway);
|
|
795
|
+
const gatewayHeaders = applyClaudeGatewayHeaders(new Headers(headers), gateway);
|
|
796
|
+
return scope.redactResponse(await physicalFetch(() => fetchResponse(gatewayUrl, { ...init, headers: gatewayHeaders })));
|
|
797
|
+
}
|
|
765
798
|
// OAuth bodies go gzipped as Claude Code sends them; `bodyText` stays
|
|
766
799
|
// the signed identity text for dumps and CacheKeep.
|
|
767
800
|
if (options.apiAccount || typeof init.body !== 'string')
|
|
@@ -845,7 +878,9 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
845
878
|
catch (caught) {
|
|
846
879
|
// No response leaves this send, so its credentials retire here.
|
|
847
880
|
physical.scope?.dispose();
|
|
848
|
-
const scope = createProviderErrorResponseScope(
|
|
881
|
+
const scope = createProviderErrorResponseScope(
|
|
882
|
+
// A gateway error may echo the gateway's own header values.
|
|
883
|
+
[secret, ...claudeGatewayHeaderValues(gateway)], 'event-stream');
|
|
849
884
|
const error = scope.redactError(caught);
|
|
850
885
|
scope.dispose();
|
|
851
886
|
await dumpDirectRequest({
|
|
@@ -1135,7 +1170,7 @@ async function executeWithFallback(options) {
|
|
|
1135
1170
|
};
|
|
1136
1171
|
options = { ...options, routingRelay: routingState.relay };
|
|
1137
1172
|
const native = getPiNativeRuntime(options.storagePath);
|
|
1138
|
-
let snapshot = await native.requestView(options.streamOptions?.signal);
|
|
1173
|
+
let snapshot = await native.requestView(options.streamOptions?.signal, options.model.id);
|
|
1139
1174
|
let storage = snapshot.policyStorage;
|
|
1140
1175
|
const accountView = (id) => snapshot.accounts.find((account) => account.id === id);
|
|
1141
1176
|
const vaultAccountIdentities = () => {
|
|
@@ -1178,7 +1213,7 @@ async function executeWithFallback(options) {
|
|
|
1178
1213
|
(!scopedWindow || Date.now() - scopedWindow.checkedAt < age));
|
|
1179
1214
|
}
|
|
1180
1215
|
async function refreshRoutingSnapshot() {
|
|
1181
|
-
snapshot = await native.view();
|
|
1216
|
+
snapshot = await native.view(options.streamOptions?.signal, options.model.id);
|
|
1182
1217
|
storage = snapshot.policyStorage;
|
|
1183
1218
|
mainAccountId = accountView(STICKY_ROUTING_MAIN_ACCOUNT_ID)?.accountIdentity;
|
|
1184
1219
|
({ quotaManager, getUsableFallbackAccounts } = getPiRoutingServices(options.storagePath, snapshot));
|
|
@@ -1441,7 +1476,7 @@ async function executeWithFallback(options) {
|
|
|
1441
1476
|
const noRouteResponse = async () => {
|
|
1442
1477
|
if (snapshot.mode === 'claustrum')
|
|
1443
1478
|
return createNativeVaultNoRouteResponse({
|
|
1444
|
-
snapshot: await native.view(),
|
|
1479
|
+
snapshot: await native.view(options.streamOptions?.signal, options.model.id),
|
|
1445
1480
|
modelId: options.model.id,
|
|
1446
1481
|
sticky: true,
|
|
1447
1482
|
sessionId,
|
|
@@ -1658,7 +1693,7 @@ async function executeWithFallback(options) {
|
|
|
1658
1693
|
}
|
|
1659
1694
|
if (snapshot.mode === 'claustrum')
|
|
1660
1695
|
return createNativeVaultNoRouteResponse({
|
|
1661
|
-
snapshot: await native.view(),
|
|
1696
|
+
snapshot: await native.view(options.streamOptions?.signal, options.model.id),
|
|
1662
1697
|
modelId: options.model.id,
|
|
1663
1698
|
sessionId: options.streamOptions?.sessionId,
|
|
1664
1699
|
});
|
|
@@ -1693,7 +1728,7 @@ async function executeWithFallback(options) {
|
|
|
1693
1728
|
if (fallback)
|
|
1694
1729
|
return fallback;
|
|
1695
1730
|
}
|
|
1696
|
-
const current = await native.view();
|
|
1731
|
+
const current = await native.view(options.streamOptions?.signal, options.model.id);
|
|
1697
1732
|
return createQuotaRefusalResponse('Killswitch blocked all OAuth routes', quotaRefusalTiming({
|
|
1698
1733
|
readings: current.accounts
|
|
1699
1734
|
.filter((account) => account.type === 'oauth' && nativeAccountCanServe(account))
|
|
@@ -1771,7 +1806,7 @@ export function streamCortexKitAnthropic(model, context, options, effortTransiti
|
|
|
1771
1806
|
run: () => executeWithFallback(request),
|
|
1772
1807
|
resume: async (hold) => {
|
|
1773
1808
|
const native = getPiNativeRuntime(storagePath);
|
|
1774
|
-
const before = await native.requestView(options?.signal);
|
|
1809
|
+
const before = await native.requestView(options?.signal, model.id);
|
|
1775
1810
|
if (hold &&
|
|
1776
1811
|
(!hold.accountIdentity ||
|
|
1777
1812
|
before.accounts.find((account) => account.id === hold.accountId)
|
package/dist/transport.d.ts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { type ClaudeGateway } from '@cortexkit/anthropic-auth-core';
|
|
2
|
+
/**
|
|
3
|
+
* Model base URLs and remembered cache-warm URLs must send OAuth tokens only
|
|
4
|
+
* to Anthropic’s HTTPS server. Pass `gateway` only for a model request: it is
|
|
5
|
+
* the user's gateway from their own settings file, never provider config.
|
|
6
|
+
*/
|
|
7
|
+
export declare function requirePiOAuthOrigin(value: string, gateway?: ClaudeGateway): URL;
|
|
3
8
|
export declare function buildPiOAuthMessagesUrl(baseUrl: string): URL;
|
|
4
9
|
/** Reject redirects rather than letting an approved OAuth destination forward the request. */
|
|
5
10
|
export declare const fetchPiOAuth: typeof fetch;
|
|
6
11
|
export declare function fetchPiStreamResponse(input: Parameters<typeof fetch>[0], init: Parameters<typeof fetch>[1], fetchImpl?: typeof fetch): Promise<Response>;
|
|
12
|
+
/**
|
|
13
|
+
* Fetch for OAuth model requests: like fetchPiOAuth, but a model request to
|
|
14
|
+
* api.anthropic.com goes to the user's gateway, read on every call, with its
|
|
15
|
+
* headers. Keep-warm sends use it, so they follow the current settings.
|
|
16
|
+
*/
|
|
17
|
+
export declare function createPiOAuthModelFetch(gateway: () => ClaudeGateway | undefined): typeof fetch;
|
package/dist/transport.js
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import { PerformanceObserver, } from 'node:perf_hooks';
|
|
2
|
-
import { copyStreamResponseTiming, createAnthropicOAuthFetch, requireAnthropicOAuthOrigin, } from '@cortexkit/anthropic-auth-core';
|
|
2
|
+
import { copyStreamResponseTiming, createAnthropicOAuthFetch, createClaudeModelFetch, requireAnthropicOAuthOrigin, } from '@cortexkit/anthropic-auth-core';
|
|
3
3
|
// Pi keeps its own refusal wording; Core supplies the origin rule itself.
|
|
4
4
|
const PI_OAUTH_ORIGIN = {
|
|
5
5
|
refusal: (reason) => new Error(reason === 'unparseable'
|
|
6
6
|
? 'Native OAuth requires the official Anthropic HTTPS origin'
|
|
7
7
|
: 'Native OAuth requires the official Anthropic HTTPS origin without URL userinfo'),
|
|
8
8
|
};
|
|
9
|
-
/**
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Model base URLs and remembered cache-warm URLs must send OAuth tokens only
|
|
11
|
+
* to Anthropic’s HTTPS server. Pass `gateway` only for a model request: it is
|
|
12
|
+
* the user's gateway from their own settings file, never provider config.
|
|
13
|
+
*/
|
|
14
|
+
export function requirePiOAuthOrigin(value, gateway) {
|
|
15
|
+
return requireAnthropicOAuthOrigin(value, gateway ? { ...PI_OAUTH_ORIGIN, gateway } : PI_OAUTH_ORIGIN);
|
|
12
16
|
}
|
|
13
17
|
export function buildPiOAuthMessagesUrl(baseUrl) {
|
|
14
18
|
return new URL('/v1/messages?beta=true', requirePiOAuthOrigin(baseUrl));
|
|
@@ -103,3 +107,11 @@ export async function fetchPiStreamResponse(input, init, fetchImpl = globalThis.
|
|
|
103
107
|
throw error;
|
|
104
108
|
}
|
|
105
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* Fetch for OAuth model requests: like fetchPiOAuth, but a model request to
|
|
112
|
+
* api.anthropic.com goes to the user's gateway, read on every call, with its
|
|
113
|
+
* headers. Keep-warm sends use it, so they follow the current settings.
|
|
114
|
+
*/
|
|
115
|
+
export function createPiOAuthModelFetch(gateway) {
|
|
116
|
+
return createClaudeModelFetch({ origin: PI_OAUTH_ORIGIN, gateway });
|
|
117
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/pi-anthropic-auth",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.13.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"prepublishOnly": "bun run build"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
|
-
"@cortexkit/anthropic-auth-core": "2.
|
|
39
|
+
"@cortexkit/anthropic-auth-core": "2.13.0"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"@earendil-works/pi-ai": ">=0.86.1 <2",
|