@cortexkit/pi-anthropic-auth 2.5.5 → 2.5.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cachekeep-claim.d.ts +18 -0
- package/dist/cachekeep-claim.js +120 -0
- package/dist/cachekeep.d.ts +42 -0
- package/dist/cachekeep.js +307 -0
- package/dist/index.js +11 -1
- package/dist/stream.d.ts +3 -1
- package/dist/stream.js +25 -5
- package/package.json +2 -2
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type HolderLiveness, type OwnerOnlyOptions } from '@cortexkit/anthropic-auth-core';
|
|
2
|
+
/** A process-lifetime claim, not a timer lease that can expire during a pause. */
|
|
3
|
+
export declare class PiCacheKeepClaim {
|
|
4
|
+
private readonly directory;
|
|
5
|
+
private readonly options;
|
|
6
|
+
private readonly token;
|
|
7
|
+
private readonly path;
|
|
8
|
+
private held;
|
|
9
|
+
constructor(directory: string, sessionId: string, options?: {
|
|
10
|
+
ownerOnly?: OwnerOnlyOptions;
|
|
11
|
+
liveness?: HolderLiveness;
|
|
12
|
+
sessionHash?: boolean;
|
|
13
|
+
});
|
|
14
|
+
private read;
|
|
15
|
+
acquire(): Promise<boolean>;
|
|
16
|
+
private tryAcquire;
|
|
17
|
+
release(): Promise<void>;
|
|
18
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, open, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
import { createWindowsOwnerOnly, ensureHolderDirectory, holderEntryIsLive, holderEntryLiveness, isOwnerOnly, processIncarnation, readWindowsOwnerOnly, renameWithWindowsSharingRetry, withNativeLock, } from '@cortexkit/anthropic-auth-core';
|
|
7
|
+
/** A process-lifetime claim, not a timer lease that can expire during a pause. */
|
|
8
|
+
export class PiCacheKeepClaim {
|
|
9
|
+
directory;
|
|
10
|
+
options;
|
|
11
|
+
token = randomUUID();
|
|
12
|
+
path;
|
|
13
|
+
held = false;
|
|
14
|
+
constructor(directory, sessionId, options = {}) {
|
|
15
|
+
this.directory = directory;
|
|
16
|
+
this.options = options;
|
|
17
|
+
const hash = options.sessionHash
|
|
18
|
+
? sessionId
|
|
19
|
+
: createHash('sha256').update(sessionId).digest('hex');
|
|
20
|
+
if (!/^[a-f0-9]{64}$/.test(hash))
|
|
21
|
+
throw new Error('Invalid session hash');
|
|
22
|
+
this.path = join(directory, `${hash}.claim.json`);
|
|
23
|
+
}
|
|
24
|
+
async read() {
|
|
25
|
+
try {
|
|
26
|
+
const stat = await lstat(this.path);
|
|
27
|
+
if (!stat.isFile() ||
|
|
28
|
+
stat.isSymbolicLink() ||
|
|
29
|
+
stat.size > 4096 ||
|
|
30
|
+
!(await isOwnerOnly(this.path, () => stat.uid === process.getuid?.() && (stat.mode & 0o777) === 0o600, this.options.ownerOnly)))
|
|
31
|
+
throw new Error('Unsafe CacheKeep claim');
|
|
32
|
+
let bytes = await readWindowsOwnerOnly(this.path, this.options.ownerOnly);
|
|
33
|
+
if (!bytes) {
|
|
34
|
+
const file = await open(this.path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
35
|
+
try {
|
|
36
|
+
bytes = await file.readFile();
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
await file.close();
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const value = JSON.parse(bytes.toString());
|
|
43
|
+
if (!holderEntryLiveness(value) || typeof value.token !== 'string')
|
|
44
|
+
throw new Error('Invalid CacheKeep claim');
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (error.code === 'ENOENT')
|
|
49
|
+
return undefined;
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
async acquire() {
|
|
54
|
+
if (this.held)
|
|
55
|
+
return true;
|
|
56
|
+
await ensureHolderDirectory(this.directory, this.options.ownerOnly);
|
|
57
|
+
for (;;) {
|
|
58
|
+
const result = await this.tryAcquire();
|
|
59
|
+
if (result !== 'sweep')
|
|
60
|
+
return result;
|
|
61
|
+
// A sweep borrows ownership only while reading one record. A resuming
|
|
62
|
+
// session waits in the background instead of mistaking temporary sweep
|
|
63
|
+
// ownership for an active session claim.
|
|
64
|
+
await delay(25);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
tryAcquire() {
|
|
68
|
+
return withNativeLock(this.path, {
|
|
69
|
+
name: 'cachekeep-session',
|
|
70
|
+
ttlMs: 10_000,
|
|
71
|
+
timeoutMs: 2000,
|
|
72
|
+
renew: true,
|
|
73
|
+
}, async (lease) => {
|
|
74
|
+
const existing = await this.read();
|
|
75
|
+
const life = holderEntryLiveness(existing);
|
|
76
|
+
if (life && (await holderEntryIsLive(life, this.options.liveness)))
|
|
77
|
+
return !this.options.sessionHash && existing?.purpose === 'sweep'
|
|
78
|
+
? 'sweep'
|
|
79
|
+
: false;
|
|
80
|
+
const bytes = JSON.stringify({
|
|
81
|
+
pid: process.pid,
|
|
82
|
+
incarnation: await (this.options.liveness?.incarnation ?? processIncarnation)(process.pid),
|
|
83
|
+
registeredAt: Date.now(),
|
|
84
|
+
token: this.token,
|
|
85
|
+
purpose: this.options.sessionHash ? 'sweep' : 'session',
|
|
86
|
+
});
|
|
87
|
+
const temp = `${this.path}.${this.token}.tmp`;
|
|
88
|
+
try {
|
|
89
|
+
if (!(await createWindowsOwnerOnly(temp, bytes, this.options.ownerOnly)))
|
|
90
|
+
await writeFile(temp, bytes, { flag: 'wx', mode: 0o600 });
|
|
91
|
+
await lease.assertOwned();
|
|
92
|
+
await renameWithWindowsSharingRetry(temp, this.path, {
|
|
93
|
+
platform: this.options.ownerOnly?.platform,
|
|
94
|
+
});
|
|
95
|
+
this.held = true;
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
await rm(temp, { force: true });
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
async release() {
|
|
104
|
+
if (!this.held)
|
|
105
|
+
return;
|
|
106
|
+
await withNativeLock(this.path, {
|
|
107
|
+
name: 'cachekeep-session',
|
|
108
|
+
ttlMs: 10_000,
|
|
109
|
+
timeoutMs: 2000,
|
|
110
|
+
renew: true,
|
|
111
|
+
}, async (lease) => {
|
|
112
|
+
const current = await this.read();
|
|
113
|
+
if (current?.token === this.token) {
|
|
114
|
+
await lease.assertOwned();
|
|
115
|
+
await rm(this.path, { force: true });
|
|
116
|
+
}
|
|
117
|
+
this.held = false;
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { CacheKeepManager, type CacheKeepStoreOptions, type HolderLiveness, type NativeAccountSnapshot } from '@cortexkit/anthropic-auth-core';
|
|
2
|
+
type TrackInput = Parameters<CacheKeepManager['track']>[0];
|
|
3
|
+
type ManagerOptions = ConstructorParameters<typeof CacheKeepManager>[0];
|
|
4
|
+
/** One Pi process owns only the sessions its lifecycle actually opened. */
|
|
5
|
+
export declare class PiCacheKeep {
|
|
6
|
+
private readonly options;
|
|
7
|
+
readonly manager: CacheKeepManager;
|
|
8
|
+
private readonly stores;
|
|
9
|
+
private readonly sessions;
|
|
10
|
+
private readonly claims;
|
|
11
|
+
private readonly starts;
|
|
12
|
+
private readonly restored;
|
|
13
|
+
private readonly tracking;
|
|
14
|
+
private stopping;
|
|
15
|
+
private ticking?;
|
|
16
|
+
private cleaning?;
|
|
17
|
+
private cleanupTimer?;
|
|
18
|
+
private readonly schedule;
|
|
19
|
+
private readonly cancel;
|
|
20
|
+
constructor(managerOptions: ManagerOptions, options: {
|
|
21
|
+
storageId: (storagePath: string) => Promise<string>;
|
|
22
|
+
read: (storagePath: string) => Promise<NativeAccountSnapshot>;
|
|
23
|
+
persistence?: Partial<Pick<CacheKeepStoreOptions, 'root' | 'ownerOnly'>>;
|
|
24
|
+
liveness?: HolderLiveness;
|
|
25
|
+
restoreDelay?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
26
|
+
});
|
|
27
|
+
private store;
|
|
28
|
+
private now;
|
|
29
|
+
private managerOptionsNow?;
|
|
30
|
+
private claim;
|
|
31
|
+
private access;
|
|
32
|
+
private startCleanup;
|
|
33
|
+
startSession(storagePath: string, sessionId: string): Promise<void>;
|
|
34
|
+
trackAccepted(input: TrackInput, snapshot: NativeAccountSnapshot): Promise<void | {
|
|
35
|
+
tracked: true;
|
|
36
|
+
} | {
|
|
37
|
+
tracked: false;
|
|
38
|
+
reason: string;
|
|
39
|
+
} | undefined>;
|
|
40
|
+
stop(): Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
export {};
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { CACHE_KEEP_PREWARM_LEAD_MS, CACHE_KEEP_TTL_MS, CacheKeepManager, CacheKeepStore, isCacheKeepHybridActive, isCacheKeepSubagentsEnabled, logger, nativeAccountCanServe, } from '@cortexkit/anthropic-auth-core';
|
|
4
|
+
import { version as pluginVersion } from '../package.json';
|
|
5
|
+
import { PiCacheKeepClaim } from './cachekeep-claim.js';
|
|
6
|
+
function accountKey(account) {
|
|
7
|
+
// Token refresh keeps this key; replacing a login changes its credential epoch.
|
|
8
|
+
return JSON.stringify([
|
|
9
|
+
account.source,
|
|
10
|
+
account.accountIdentity,
|
|
11
|
+
account.credentialId,
|
|
12
|
+
account.binding?.storageId,
|
|
13
|
+
account.binding?.rowId,
|
|
14
|
+
account.binding?.credentialEpoch,
|
|
15
|
+
]);
|
|
16
|
+
}
|
|
17
|
+
/** One Pi process owns only the sessions its lifecycle actually opened. */
|
|
18
|
+
export class PiCacheKeep {
|
|
19
|
+
options;
|
|
20
|
+
manager;
|
|
21
|
+
stores = new Map();
|
|
22
|
+
sessions = new Map();
|
|
23
|
+
claims = new Map();
|
|
24
|
+
starts = new Map();
|
|
25
|
+
restored = new Map();
|
|
26
|
+
tracking = new Set();
|
|
27
|
+
stopping = false;
|
|
28
|
+
ticking;
|
|
29
|
+
cleaning;
|
|
30
|
+
cleanupTimer;
|
|
31
|
+
schedule;
|
|
32
|
+
cancel;
|
|
33
|
+
constructor(managerOptions, options) {
|
|
34
|
+
this.options = options;
|
|
35
|
+
this.managerOptionsNow = managerOptions.now;
|
|
36
|
+
const schedule = managerOptions.setIntervalImpl ?? setInterval;
|
|
37
|
+
this.schedule = schedule;
|
|
38
|
+
this.cancel = managerOptions.clearIntervalImpl ?? clearInterval;
|
|
39
|
+
this.manager = new CacheKeepManager({
|
|
40
|
+
...managerOptions,
|
|
41
|
+
setIntervalImpl: ((_callback, ms) => schedule(() => {
|
|
42
|
+
this.ticking = this.manager
|
|
43
|
+
.tick()
|
|
44
|
+
.catch(() => logger.warn('cachekeep', 'tick failed'));
|
|
45
|
+
return this.ticking;
|
|
46
|
+
}, ms)),
|
|
47
|
+
onTargetChanged: (target) => {
|
|
48
|
+
const session = this.sessions.get(target.id);
|
|
49
|
+
if (session?.identity)
|
|
50
|
+
session.store.changed({
|
|
51
|
+
...target,
|
|
52
|
+
oauthAccountIdentity: session.identity,
|
|
53
|
+
});
|
|
54
|
+
managerOptions.onTargetChanged?.(target);
|
|
55
|
+
},
|
|
56
|
+
onTargetRemoved: (id) => {
|
|
57
|
+
this.restored.delete(id);
|
|
58
|
+
if (!this.stopping)
|
|
59
|
+
this.sessions.get(id)?.store.removed(id);
|
|
60
|
+
managerOptions.onTargetRemoved?.(id);
|
|
61
|
+
},
|
|
62
|
+
prepareHeaders: async (headers, target, attempt) => {
|
|
63
|
+
// Delay the actual first send, not just its due time: minute ticks can
|
|
64
|
+
// coalesce all overdue sessions after many Pi processes restart.
|
|
65
|
+
const stagger = this.restored.get(target.id);
|
|
66
|
+
this.restored.delete(target.id);
|
|
67
|
+
if (stagger !== undefined) {
|
|
68
|
+
if (this.options.restoreDelay)
|
|
69
|
+
await this.options.restoreDelay(stagger, attempt.signal);
|
|
70
|
+
else
|
|
71
|
+
await delay(stagger, undefined, { signal: attempt.signal });
|
|
72
|
+
if (target.cacheExpiresAt <= this.now())
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
if (this.stopping && this.manager.trackedRequest(target.id))
|
|
76
|
+
return undefined;
|
|
77
|
+
const session = this.sessions.get(target.id);
|
|
78
|
+
// One-off prewarmNow probes are not restart targets and have no claim.
|
|
79
|
+
if (session?.identity) {
|
|
80
|
+
const snapshot = await this.options.read(session.storagePath);
|
|
81
|
+
const account = snapshot.accounts.find((row) => accountKey(row) === session.identity);
|
|
82
|
+
if (!account || !nativeAccountCanServe(account))
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
else if (this.manager.trackedRequest(target.id))
|
|
86
|
+
return undefined;
|
|
87
|
+
return managerOptions.prepareHeaders
|
|
88
|
+
? managerOptions.prepareHeaders(headers, target, attempt)
|
|
89
|
+
: headers;
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
store(storagePath) {
|
|
94
|
+
let store = this.stores.get(storagePath);
|
|
95
|
+
if (!store) {
|
|
96
|
+
store = this.options.storageId(storagePath).then((storageId) => new CacheKeepStore({
|
|
97
|
+
storageId,
|
|
98
|
+
host: 'pi',
|
|
99
|
+
pluginVersion,
|
|
100
|
+
...this.options.persistence,
|
|
101
|
+
now: () => this.now(),
|
|
102
|
+
}));
|
|
103
|
+
this.stores.set(storagePath, store);
|
|
104
|
+
}
|
|
105
|
+
return store;
|
|
106
|
+
}
|
|
107
|
+
now() {
|
|
108
|
+
return this.managerOptionsNow?.() ?? Date.now();
|
|
109
|
+
}
|
|
110
|
+
managerOptionsNow;
|
|
111
|
+
claim(storagePath, sessionId) {
|
|
112
|
+
const existing = this.claims.get(sessionId);
|
|
113
|
+
if (existing)
|
|
114
|
+
return existing;
|
|
115
|
+
let claiming;
|
|
116
|
+
claiming = (async () => {
|
|
117
|
+
const store = await this.store(storagePath);
|
|
118
|
+
const claim = new PiCacheKeepClaim(store.directory, sessionId, {
|
|
119
|
+
ownerOnly: this.options.persistence?.ownerOnly,
|
|
120
|
+
liveness: this.options.liveness,
|
|
121
|
+
});
|
|
122
|
+
if (!(await claim.acquire()))
|
|
123
|
+
return undefined;
|
|
124
|
+
const session = { storagePath, claim, store };
|
|
125
|
+
this.sessions.set(sessionId, session);
|
|
126
|
+
return session;
|
|
127
|
+
})()
|
|
128
|
+
.catch(() => {
|
|
129
|
+
logger.warn('cachekeep', 'session claim unavailable; not warming session');
|
|
130
|
+
return undefined;
|
|
131
|
+
})
|
|
132
|
+
.finally(() => {
|
|
133
|
+
if (!this.sessions.has(sessionId) &&
|
|
134
|
+
this.claims.get(sessionId) === claiming)
|
|
135
|
+
this.claims.delete(sessionId);
|
|
136
|
+
});
|
|
137
|
+
this.claims.set(sessionId, claiming);
|
|
138
|
+
return claiming;
|
|
139
|
+
}
|
|
140
|
+
async access(store, hash, restoreOwn = false) {
|
|
141
|
+
for (const [id, owned] of this.sessions) {
|
|
142
|
+
if (owned.store === store &&
|
|
143
|
+
createHash('sha256').update(id).digest('hex') === hash)
|
|
144
|
+
// The manager expires local targets. Cleanup must not race its queued
|
|
145
|
+
// writes; only the initial restore reads a locally claimed record.
|
|
146
|
+
return restoreOwn && !this.manager.trackedRequest(id)
|
|
147
|
+
? async () => { }
|
|
148
|
+
: undefined;
|
|
149
|
+
}
|
|
150
|
+
const cleanup = new PiCacheKeepClaim(store.directory, hash, {
|
|
151
|
+
...this.options.persistence,
|
|
152
|
+
liveness: this.options.liveness,
|
|
153
|
+
sessionHash: true,
|
|
154
|
+
});
|
|
155
|
+
if (!(await cleanup.acquire()))
|
|
156
|
+
return undefined;
|
|
157
|
+
return () => cleanup.release();
|
|
158
|
+
}
|
|
159
|
+
startCleanup() {
|
|
160
|
+
if (this.cleanupTimer || this.stopping)
|
|
161
|
+
return;
|
|
162
|
+
// Unresumed sessions have no manager target or timer. Sweep their expired
|
|
163
|
+
// files without adopting them, and never touch another live owner's files.
|
|
164
|
+
this.cleanupTimer = this.schedule(() => {
|
|
165
|
+
this.cleaning ??= (async () => {
|
|
166
|
+
for (const store of this.stores.values()) {
|
|
167
|
+
const current = await store;
|
|
168
|
+
await current.load(this.now(), () => undefined, (hash) => this.access(current, hash));
|
|
169
|
+
}
|
|
170
|
+
})()
|
|
171
|
+
.catch(() => logger.warn('cachekeep', 'restart cleanup failed'))
|
|
172
|
+
.finally(() => {
|
|
173
|
+
this.cleaning = undefined;
|
|
174
|
+
});
|
|
175
|
+
return this.cleaning;
|
|
176
|
+
}, 60_000);
|
|
177
|
+
this.cleanupTimer.unref?.();
|
|
178
|
+
}
|
|
179
|
+
startSession(storagePath, sessionId) {
|
|
180
|
+
const existing = this.starts.get(sessionId);
|
|
181
|
+
if (existing)
|
|
182
|
+
return existing;
|
|
183
|
+
this.stopping = false;
|
|
184
|
+
let completed = false;
|
|
185
|
+
let starting;
|
|
186
|
+
starting = (async () => {
|
|
187
|
+
const session = await this.claim(storagePath, sessionId);
|
|
188
|
+
// Even a non-owner may clean up expired records, but cannot restore one.
|
|
189
|
+
const store = await this.store(storagePath);
|
|
190
|
+
const snapshot = session
|
|
191
|
+
? await this.options.read(storagePath)
|
|
192
|
+
: undefined;
|
|
193
|
+
const now = this.now();
|
|
194
|
+
await store.load(now, (entry) => {
|
|
195
|
+
if (!session ||
|
|
196
|
+
entry.id !== sessionId ||
|
|
197
|
+
this.stopping ||
|
|
198
|
+
this.manager.trackedRequest(entry.id))
|
|
199
|
+
return undefined;
|
|
200
|
+
if (!snapshot || !isCacheKeepHybridActive(snapshot.policyStorage))
|
|
201
|
+
return 'invalid';
|
|
202
|
+
const account = snapshot.accounts.find((row) => accountKey(row) === entry.oauthAccountIdentity);
|
|
203
|
+
if (!account)
|
|
204
|
+
return 'foreign-identity';
|
|
205
|
+
if (account.type !== 'oauth' || !nativeAccountCanServe(account))
|
|
206
|
+
return 'account-gone';
|
|
207
|
+
if (entry.isSubagent &&
|
|
208
|
+
!isCacheKeepSubagentsEnabled(snapshot.policyStorage))
|
|
209
|
+
return 'invalid';
|
|
210
|
+
session.identity = accountKey(account);
|
|
211
|
+
const result = this.manager.track({
|
|
212
|
+
sessionId,
|
|
213
|
+
url: entry.url,
|
|
214
|
+
headers: new Headers(),
|
|
215
|
+
bodyText: entry.bodyText,
|
|
216
|
+
storage: snapshot.policyStorage,
|
|
217
|
+
cacheMode: 'hybrid',
|
|
218
|
+
oauthAccountId: account.id,
|
|
219
|
+
oauthAccountIdentity: account.accountIdentity,
|
|
220
|
+
accountStoragePath: storagePath,
|
|
221
|
+
isSubagent: entry.isSubagent,
|
|
222
|
+
retained: {
|
|
223
|
+
...entry,
|
|
224
|
+
nextPrewarmAt: Math.max(now, entry.nextPrewarmAt),
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
if (result.tracked && entry.nextPrewarmAt <= now)
|
|
228
|
+
this.restored.set(entry.id, 1000 + Math.floor(Math.random() * 2000));
|
|
229
|
+
return result.tracked ? true : 'invalid';
|
|
230
|
+
}, (hash) => this.access(store, hash, true));
|
|
231
|
+
this.startCleanup();
|
|
232
|
+
completed = !!session;
|
|
233
|
+
})()
|
|
234
|
+
.catch(() => logger.warn('cachekeep', 'failed to restore tracked session'))
|
|
235
|
+
.finally(() => {
|
|
236
|
+
if (!completed && this.starts.get(sessionId) === starting)
|
|
237
|
+
this.starts.delete(sessionId);
|
|
238
|
+
});
|
|
239
|
+
this.starts.set(sessionId, starting);
|
|
240
|
+
return starting;
|
|
241
|
+
}
|
|
242
|
+
trackAccepted(input, snapshot) {
|
|
243
|
+
if (this.stopping || !input.sessionId || !input.accountStoragePath)
|
|
244
|
+
return Promise.resolve();
|
|
245
|
+
const sessionId = input.sessionId;
|
|
246
|
+
const storagePath = input.accountStoragePath;
|
|
247
|
+
const acceptedAt = this.now();
|
|
248
|
+
const tracking = (async () => {
|
|
249
|
+
const session = await this.claim(storagePath, sessionId);
|
|
250
|
+
if (!session)
|
|
251
|
+
return;
|
|
252
|
+
const account = snapshot.accounts.find((row) => row.id === input.oauthAccountId) ??
|
|
253
|
+
snapshot.accounts.find((row) => row.accountIdentity === input.oauthAccountIdentity);
|
|
254
|
+
if (account?.type !== 'oauth' ||
|
|
255
|
+
!nativeAccountCanServe(account) ||
|
|
256
|
+
account.accountIdentity !== input.oauthAccountIdentity)
|
|
257
|
+
return;
|
|
258
|
+
session.identity = accountKey(account);
|
|
259
|
+
// Claim I/O may finish after the response, or even during shutdown. Keep
|
|
260
|
+
// that accepted body, but never grant the cache the time spent waiting.
|
|
261
|
+
const ttlMs = input.ttlMs ?? CACHE_KEEP_TTL_MS;
|
|
262
|
+
const result = this.manager.track({
|
|
263
|
+
...input,
|
|
264
|
+
retained: input.retained ?? {
|
|
265
|
+
cacheExpiresAt: acceptedAt + ttlMs,
|
|
266
|
+
nextPrewarmAt: acceptedAt + ttlMs - CACHE_KEEP_PREWARM_LEAD_MS,
|
|
267
|
+
ttlMs,
|
|
268
|
+
lastTouchAt: acceptedAt,
|
|
269
|
+
lastTouchKind: 'response',
|
|
270
|
+
},
|
|
271
|
+
});
|
|
272
|
+
if (result.tracked)
|
|
273
|
+
this.restored.delete(sessionId);
|
|
274
|
+
if (this.stopping)
|
|
275
|
+
this.manager.stop();
|
|
276
|
+
return result;
|
|
277
|
+
})().catch(() => logger.warn('cachekeep', 'accepted response tracking failed'));
|
|
278
|
+
this.tracking.add(tracking);
|
|
279
|
+
void tracking.then(() => this.tracking.delete(tracking));
|
|
280
|
+
return tracking;
|
|
281
|
+
}
|
|
282
|
+
async stop() {
|
|
283
|
+
this.stopping = true;
|
|
284
|
+
if (this.cleanupTimer)
|
|
285
|
+
this.cancel(this.cleanupTimer);
|
|
286
|
+
this.cleanupTimer = undefined;
|
|
287
|
+
this.manager.stop();
|
|
288
|
+
await Promise.all(this.starts.values());
|
|
289
|
+
await Promise.all(this.claims.values());
|
|
290
|
+
await Promise.all(this.tracking);
|
|
291
|
+
this.manager.stop();
|
|
292
|
+
await this.ticking;
|
|
293
|
+
await this.cleaning;
|
|
294
|
+
// Drain before releasing claims so a successor can never read an older body.
|
|
295
|
+
for (const store of this.stores.values())
|
|
296
|
+
await (await store).drain();
|
|
297
|
+
for (const session of this.manager.trackedSessions())
|
|
298
|
+
this.manager.untrack(session.id);
|
|
299
|
+
for (const session of this.sessions.values())
|
|
300
|
+
await session.claim.release();
|
|
301
|
+
this.sessions.clear();
|
|
302
|
+
this.claims.clear();
|
|
303
|
+
this.starts.clear();
|
|
304
|
+
this.stores.clear();
|
|
305
|
+
this.restored.clear();
|
|
306
|
+
}
|
|
307
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import { collectPiEffortHistory, deriveContextEntries, } from './effort-history.
|
|
|
4
4
|
import { closePiNativeRuntime, getPiNativeRuntime, isNativeMigrationRequired, } from './native.js';
|
|
5
5
|
import { createPiNativeCommands } from './native-commands.js';
|
|
6
6
|
import { getPiAccountStoragePath, requirePiNativeHostAuth } from './paths.js';
|
|
7
|
-
import { beginPiPrimaryTurn, clearPiStickyQuotaRetries, endPiPrimaryTurn, forgetPiMessageThread, streamCortexKitAnthropic, } from './stream.js';
|
|
7
|
+
import { beginPiPrimaryTurn, clearPiStickyQuotaRetries, endPiPrimaryTurn, forgetPiMessageThread, startPiCacheKeepSession, stopPiCacheKeep, streamCortexKitAnthropic, } from './stream.js';
|
|
8
8
|
function textImageInput() {
|
|
9
9
|
return ['text', 'image'];
|
|
10
10
|
}
|
|
@@ -41,8 +41,17 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
|
|
|
41
41
|
registerCommands(pi, createPiNativeCommands(storagePath));
|
|
42
42
|
const effortHistoryBySession = new Map();
|
|
43
43
|
const workingMessageBySession = new Map();
|
|
44
|
+
pi.on('session_start', async (_event, ctx) => {
|
|
45
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
46
|
+
if (sessionId)
|
|
47
|
+
void startPiCacheKeepSession(storagePath, sessionId);
|
|
48
|
+
});
|
|
44
49
|
pi.on('turn_start', async (_event, ctx) => {
|
|
45
50
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
51
|
+
// Older hosts may deliver their first turn before session_start. Both
|
|
52
|
+
// hooks start the same detached restore; bookkeeping never delays a turn.
|
|
53
|
+
if (sessionId)
|
|
54
|
+
void startPiCacheKeepSession(storagePath, sessionId);
|
|
46
55
|
beginPiPrimaryTurn(storagePath, sessionId);
|
|
47
56
|
if (!sessionId)
|
|
48
57
|
return;
|
|
@@ -102,6 +111,7 @@ export default async function cortexKitPiAnthropicAuth(pi, options = {}) {
|
|
|
102
111
|
sessionCacheActivity.forget(sessionId);
|
|
103
112
|
forgetPiMessageThread(sessionId);
|
|
104
113
|
}
|
|
114
|
+
await stopPiCacheKeep();
|
|
105
115
|
await closePiNativeRuntime(storagePath);
|
|
106
116
|
});
|
|
107
117
|
// Keep the catalog chat-only even when Pi also accepts image/classifier models.
|
package/dist/stream.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ApiKeyAccount, CacheKeepManager, type MidConversationEffortTransition, type NativeAccountView, type QuotaManagerOptions } from '@cortexkit/anthropic-auth-core';
|
|
1
|
+
import { type ApiKeyAccount, type CacheKeepManager, type MidConversationEffortTransition, type NativeAccountView, type QuotaManagerOptions } from '@cortexkit/anthropic-auth-core';
|
|
2
2
|
import { type Api, type AssistantMessageEventStream, type Context, type Model, type SimpleStreamOptions } from '@earendil-works/pi-ai';
|
|
3
3
|
import { type PiQuotaWaitOptions } from './quota-wait.ts';
|
|
4
4
|
export declare function beginPiPrimaryTurn(storagePath: string, sessionId?: string): void;
|
|
@@ -8,6 +8,8 @@ export declare function clearPiStickyQuotaRetries(storagePath: string, sessionId
|
|
|
8
8
|
/** Set or clear the test replacement for the wait between quota usage polls. */
|
|
9
9
|
export declare function __setPiQuotaCallPauseForTest(pause: QuotaManagerOptions['pauseBetweenQuotaCalls']): void;
|
|
10
10
|
export declare function clearPiStickyRoutingSession(storagePath: string, sessionId: string): Promise<void>;
|
|
11
|
+
export declare function startPiCacheKeepSession(storagePath: string, sessionId: string): Promise<void>;
|
|
12
|
+
export declare function stopPiCacheKeep(): Promise<void>;
|
|
11
13
|
export declare function getPiTrackedCacheKeepSessions(): Promise<import("@cortexkit/anthropic-auth-core").CacheKeepTrackedSession[]>;
|
|
12
14
|
/** Call prewarmNow directly to exercise its provider request without clock or timer mocks. */
|
|
13
15
|
export declare function __prewarmPiCacheKeepForTest(input: Parameters<CacheKeepManager['prewarmNow']>[0]): Promise<import("@cortexkit/anthropic-auth-core").CacheKeepPrewarmResult>;
|
package/dist/stream.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { applyClaudeCodeHeaders, applyCustomHeaders, CACHE_KEEP_EXTENDED_TTL_BETA,
|
|
1
|
+
import { applyClaudeCodeHeaders, applyCustomHeaders, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepSessionRegistry, createNativeVaultNoRouteResponse, createProviderErrorResponseScope, createQuotaRefusalResponse, createSseFramer, createStickyNoRouteResponse, decideStickyQuotaFailure, decodeSseFrame, dumpDirectRequest, effectiveRelayTransport, FAST_MODE_BETA, getCache1hPersistentMode, getCacheKeepRegistryDirectories, getClaudeCodeIdentityForVerifiedAccount, getFallbackReauthLabels, getMaxSameAccountWait, getQuotaCheckIntervalMs, getRequestGzipLatch, getRequestGzipLatchPath, getRoutingMode, getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isDumpPersistentlyEnabled, isFastModePersistentlyEnabled, isKillswitchEnabled, isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, isValidApiBaseURL, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, logger, MessageThreadTracker, mergeAnthropicBetas, NativeAccountRefusal, nativeAccountCanServe, parseSseFrame, prepareMessageThreadRequest, QuotaManager, quotaBackoffActive, quotaExhaustionFromHeaders, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, resolveNativePoolPaths, runWithRequestSignal, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, StickySessionRouter, sendViaRelay, sendWithRequestGzip, sessionCacheActivity, setDumpEnabled, shouldFallbackStatus, signRequestBody, stickyQuotaSnapshotIsFresh, stickyRetryAfterWithJitter, stickyRouteFamilyForModel, } from '@cortexkit/anthropic-auth-core';
|
|
2
2
|
import { calculateCost, createAssistantMessageEventStream, } from '@earendil-works/pi-ai';
|
|
3
|
+
import { PiCacheKeep } from './cachekeep.js';
|
|
3
4
|
import { buildAnthropicRequest, fromClaudeCodeToolName } from './convert.js';
|
|
4
5
|
import { getPiNativeRuntime, piAttemptAccessToken, } from './native.js';
|
|
5
6
|
import { getPiAccountStoragePath } from './paths.js';
|
|
@@ -195,7 +196,7 @@ function applyPiOAuthRequestHeaders(headers, accessToken, options) {
|
|
|
195
196
|
return headers;
|
|
196
197
|
}
|
|
197
198
|
const nativePrewarmAttempts = new Map();
|
|
198
|
-
const
|
|
199
|
+
const piCacheKeep = new PiCacheKeep({
|
|
199
200
|
fetchImpl: fetchPiOAuth,
|
|
200
201
|
loadStorage: async () => (await getPiNativeRuntime().view()).policyStorage,
|
|
201
202
|
onTrackedSessionsChanged: (sessions) => getPiCacheKeepRegistry().publish(sessions),
|
|
@@ -218,7 +219,11 @@ const cacheKeepManager = new CacheKeepManager({
|
|
|
218
219
|
identity,
|
|
219
220
|
leadingBetas: [CACHE_KEEP_EXTENDED_TTL_BETA],
|
|
220
221
|
});
|
|
221
|
-
nativePrewarmAttempts.set(attempt.id, {
|
|
222
|
+
nativePrewarmAttempts.set(attempt.id, {
|
|
223
|
+
runtime,
|
|
224
|
+
served,
|
|
225
|
+
reported: false,
|
|
226
|
+
});
|
|
222
227
|
return headers;
|
|
223
228
|
},
|
|
224
229
|
retryOnUnauthorized: async ({ target, headers, attempt }) => {
|
|
@@ -260,7 +265,18 @@ const cacheKeepManager = new CacheKeepManager({
|
|
|
260
265
|
onComplete: ({ attempt }) => {
|
|
261
266
|
nativePrewarmAttempts.delete(attempt.id);
|
|
262
267
|
},
|
|
268
|
+
}, {
|
|
269
|
+
storageId: async (storagePath) => (await resolveNativePoolPaths(storagePath, undefined, LEGACY_STATE_LAYOUT)).storageId,
|
|
270
|
+
read: (storagePath) => getPiNativeRuntime(storagePath).view(),
|
|
263
271
|
});
|
|
272
|
+
const cacheKeepManager = piCacheKeep.manager;
|
|
273
|
+
export function startPiCacheKeepSession(storagePath, sessionId) {
|
|
274
|
+
return piCacheKeep.startSession(storagePath, sessionId);
|
|
275
|
+
}
|
|
276
|
+
export async function stopPiCacheKeep() {
|
|
277
|
+
await piCacheKeep.stop();
|
|
278
|
+
await getPiCacheKeepRegistry().dispose();
|
|
279
|
+
}
|
|
264
280
|
export async function getPiTrackedCacheKeepSessions() {
|
|
265
281
|
return getPiCacheKeepRegistry().list(cacheKeepManager.trackedSessions());
|
|
266
282
|
}
|
|
@@ -458,7 +474,7 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
458
474
|
return;
|
|
459
475
|
if (relayAffinity)
|
|
460
476
|
sessionCacheActivity.record(relayAffinity, routeId, cacheTtlMs);
|
|
461
|
-
|
|
477
|
+
const target = {
|
|
462
478
|
sessionId: relayAffinity,
|
|
463
479
|
url: input.toString(),
|
|
464
480
|
headers,
|
|
@@ -469,7 +485,11 @@ async function sendAnthropicRequest(options, deps = {}) {
|
|
|
469
485
|
oauthAccountId: routeId,
|
|
470
486
|
oauthAccountIdentity: verifiedUuid,
|
|
471
487
|
accountStoragePath: options.storagePath,
|
|
472
|
-
}
|
|
488
|
+
};
|
|
489
|
+
if (deps.cacheKeep)
|
|
490
|
+
keep.track(target);
|
|
491
|
+
else
|
|
492
|
+
void piCacheKeep.trackAccepted(target, snapshot);
|
|
473
493
|
};
|
|
474
494
|
const reported = new Set();
|
|
475
495
|
let retried401 = false;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/pi-anthropic-auth",
|
|
3
|
-
"version": "2.5.
|
|
3
|
+
"version": "2.5.7",
|
|
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.5.
|
|
39
|
+
"@cortexkit/anthropic-auth-core": "2.5.7"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"@earendil-works/pi-ai": ">=0.86.1 <2",
|