@cortexkit/anthropic-auth-core 2.4.13 → 2.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cachekeep-failure.d.ts +19 -0
- package/dist/cachekeep.d.ts +8 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +8119 -6771
- package/dist/internal-types/claustrum/consumer.d.ts +12 -0
- package/dist/internal-types/claustrum/custody.d.ts +16 -4
- package/dist/internal-types/claustrum/hub.d.ts +3 -2
- package/dist/internal-types/claustrum/index.d.ts +1 -0
- package/dist/internal-types/claustrum/roster.d.ts +2 -0
- package/dist/internal-types/claustrum/usage.d.ts +41 -0
- package/dist/internal-types/commands/builtins.d.ts +5 -0
- package/dist/internal-types/fs/private-files.d.ts +5 -0
- package/dist/internal-types/routing/admission.d.ts +7 -2
- package/dist/internal-types/routing-accessor/index.d.ts +13 -3
- package/dist/internal-types/store/errors.d.ts +1 -1
- package/dist/internal-types/store/hooks.d.ts +5 -1
- package/dist/internal-types/store/index.d.ts +1 -0
- package/dist/internal-types/store/limits-namespace.d.ts +7 -0
- package/dist/internal-types/store/pool.d.ts +10 -1
- package/dist/internal-types/store/settings.d.ts +2 -0
- package/dist/message-threads.d.ts +82 -0
- package/dist/relay.d.ts +3 -0
- package/dist/sticky-routing.d.ts +16 -1
- package/package.json +2 -2
|
@@ -6,6 +6,7 @@ import { type ClaustrumLogger } from './errors.js';
|
|
|
6
6
|
import type { CustodyLease } from './hub.js';
|
|
7
7
|
import { type InsulaQuotaOptions, type InsulaQuotaResult } from './insula.js';
|
|
8
8
|
import { type AccountMapper, type ProjectionOptions, type QuotaReceipt, type ReorderVaultRosterResult, type VaultRosterFile } from './roster.js';
|
|
9
|
+
import type { ClaustrumUsageReading, ClaustrumUsageReportState } from './usage.js';
|
|
9
10
|
import { type WatchMode } from './watch.js';
|
|
10
11
|
export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
|
|
11
12
|
/**
|
|
@@ -229,6 +230,17 @@ export declare class ClaustrumConsumer<Q = QuotaObservation> {
|
|
|
229
230
|
* poll, and a route whose credential or account changed is refused.
|
|
230
231
|
*/
|
|
231
232
|
authorize(routeId: string, signal?: AbortSignal): Promise<ClaustrumScopedAttempt>;
|
|
233
|
+
/**
|
|
234
|
+
* Queue reply quota metadata without waiting or throwing. Pass rate-limit
|
|
235
|
+
* headers only, never tokens: the library does not filter header names.
|
|
236
|
+
* The credential must have been served by this host and still belong to the route.
|
|
237
|
+
*/
|
|
238
|
+
reportUsage(input: {
|
|
239
|
+
routeId: string;
|
|
240
|
+
credentialId: string;
|
|
241
|
+
reading: ClaustrumUsageReading;
|
|
242
|
+
}): void;
|
|
243
|
+
usageReportState(): ClaustrumUsageReportState;
|
|
232
244
|
reportFailure(attempt: ClaustrumScopedAttempt, status: number, source: ClaustrumReporterSource): Promise<void>;
|
|
233
245
|
/**
|
|
234
246
|
* Send on a vault route. `dispatch` builds and sends the request with the
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { type ClaustrumClient, type ClaustrumReporterSource, type EnrollmentTokenFile } from '@cortexkit/claustrum-client';
|
|
2
2
|
import { type ClaustrumLogger } from './errors.js';
|
|
3
3
|
import type { InsulaUsageTransport } from './insula.js';
|
|
4
|
+
import { type ClaustrumUsageReading, type ClaustrumUsageReportState, type ScopedUsageSource } from './usage.js';
|
|
4
5
|
import { type ScopedWatchSource, type WatchMode } from './watch.js';
|
|
5
6
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
7
|
+
* claustrum-client adds watchScoped in 0.12.0 and reportUsageScoped in 0.14.0.
|
|
8
|
+
* Older clients keep polling and simply do not send reply quota readings.
|
|
8
9
|
*/
|
|
9
10
|
export type ClaustrumScopedClient = Pick<ClaustrumClient, 'listScoped' | 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
|
|
10
11
|
insula?: InsulaUsageTransport;
|
|
11
|
-
} & ScopedWatchSource;
|
|
12
|
+
} & ScopedWatchSource & ScopedUsageSource;
|
|
12
13
|
/** The two credential types a plugin's family can hold; routing differs by type. */
|
|
13
14
|
export type VaultCredentialType = 'oauth' | 'api_key';
|
|
14
15
|
/**
|
|
@@ -332,7 +333,18 @@ export declare class ClaustrumScopedCustody {
|
|
|
332
333
|
* other mode the host keeps its usual list timer.
|
|
333
334
|
*/
|
|
334
335
|
watchRoster(options: ClaustrumRosterWatchOptions): ClaustrumRosterWatch;
|
|
336
|
+
/**
|
|
337
|
+
* Queue reply quota metadata and return synchronously. Pass rate-limit
|
|
338
|
+
* headers only, never tokens: the library does not filter header names.
|
|
339
|
+
* Only credentials served by this custody and retained in its roster report.
|
|
340
|
+
* Hosts managing their own roster must call retain() when that roster changes.
|
|
341
|
+
*/
|
|
342
|
+
reportUsage(input: {
|
|
343
|
+
credentialId: string;
|
|
344
|
+
reading: ClaustrumUsageReading;
|
|
345
|
+
}): void;
|
|
346
|
+
usageReportState(): ClaustrumUsageReportState;
|
|
335
347
|
close(): void;
|
|
336
|
-
/** Stop
|
|
348
|
+
/** Stop accepting work; give token reads and reply reports one shared 2 s drain. */
|
|
337
349
|
dispose(onTimeout?: (pendingOperations: number) => void): Promise<void>;
|
|
338
350
|
}
|
|
@@ -107,11 +107,12 @@ export interface ClaustrumHubMemberOptions<_Q = QuotaObservation> {
|
|
|
107
107
|
logger?: ClaustrumLogger;
|
|
108
108
|
}
|
|
109
109
|
/** What a lease may do with the shared custody. */
|
|
110
|
-
export type ClaustrumLeasedCustody = Pick<ClaustrumScopedCustody, 'authorize' | 'reportFailure' | 'forget' | 'keptReceiptState'>;
|
|
110
|
+
export type ClaustrumLeasedCustody = Pick<ClaustrumScopedCustody, 'authorize' | 'reportFailure' | 'reportUsage' | 'usageReportState' | 'forget' | 'keptReceiptState'>;
|
|
111
111
|
/**
|
|
112
112
|
* One acquisition of the hub's shared custody. `custody` throws `closed`
|
|
113
113
|
* after `release()`, and once the connection it belongs to ended for any
|
|
114
|
-
* reason, vault mode going off included. `
|
|
114
|
+
* reason, vault mode going off included. Best-effort `reportUsage` instead
|
|
115
|
+
* ignores reports through an ended lease. `release()` is idempotent.
|
|
115
116
|
*/
|
|
116
117
|
export interface CustodyLease {
|
|
117
118
|
readonly custody: ClaustrumLeasedCustody;
|
|
@@ -12,6 +12,7 @@ export { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaLook
|
|
|
12
12
|
export { acceptAccount, type DeclinedAccount, declineAccount, isDeclined, } from './interlock.js';
|
|
13
13
|
export { drainVaultQuota } from './quota-writer.js';
|
|
14
14
|
export { type AccountMapper, acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, type MutateVaultRosterOptions, mutateVaultRoster, type ProjectionOptions, projectVaultRoster, type QuotaReceipt, type ReorderVaultRosterOptions, type ReorderVaultRosterResult, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, resolveVaultPrimary, type VaultPrimary, type VaultPrimaryBinding, type VaultPrimaryUnavailableReason, type VaultRosterFile, type VaultRosterLockContext, type VaultRosterRow, type VaultRosterSeed, vaultRosterSeed, vaultRoutingRows, } from './roster.js';
|
|
15
|
+
export type { ClaustrumUsageReading, ClaustrumUsageReportState, } from './usage.js';
|
|
15
16
|
export { type ChangeNotice, ChangeNoticeReader, RESUBSCRIBE_BACKOFF_MS, SAFETY_POLL_MS, ScopedRosterWatch, type ScopedRosterWatchOptions, type ScopedWatchEnd, type ScopedWatchHandle, type ScopedWatchNoticeShape, type ScopedWatchSource, WATCH_RETRY_MS, type WatchMode, } from './watch.js';
|
|
16
17
|
/** How long `connectClaustrumScopedClient` waits by default. */
|
|
17
18
|
export declare const SCOPED_CONNECT_TIMEOUT_MS = 10000;
|
|
@@ -48,6 +48,8 @@ export interface VaultRosterFile {
|
|
|
48
48
|
complete: boolean;
|
|
49
49
|
/** The unusable records of an incomplete reply: a safe id and a fixed reason. */
|
|
50
50
|
rejected?: SkippedVaultRecord[];
|
|
51
|
+
/** Opaque limits data; roster-only writers preserve even newer schemas. */
|
|
52
|
+
limits?: unknown;
|
|
51
53
|
rows: VaultRosterRow[];
|
|
52
54
|
declined: DeclinedAccount[];
|
|
53
55
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { ClaustrumLogger } from './errors.js';
|
|
2
|
+
/** Reply quota metadata, never authorization headers or bearer material. */
|
|
3
|
+
export interface ClaustrumUsageReading {
|
|
4
|
+
provider: string;
|
|
5
|
+
observedAtMs: number;
|
|
6
|
+
headers?: Record<string, string>;
|
|
7
|
+
frame?: unknown;
|
|
8
|
+
account?: string;
|
|
9
|
+
}
|
|
10
|
+
/** Structural to also typecheck with the claustrum-client 0.6.2 peer minimum. */
|
|
11
|
+
export interface ScopedUsageSource {
|
|
12
|
+
reportUsageScoped?(input: {
|
|
13
|
+
credentialId: string;
|
|
14
|
+
reading: Record<string, unknown>;
|
|
15
|
+
enrollmentToken?: string;
|
|
16
|
+
}): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
export interface ClaustrumUsageReportState {
|
|
19
|
+
readonly pending: number;
|
|
20
|
+
readonly inFlight: boolean;
|
|
21
|
+
readonly dropped: number;
|
|
22
|
+
}
|
|
23
|
+
/** One queue per custody connection, shared by every hub member on it. */
|
|
24
|
+
export declare class ScopedUsageReporter {
|
|
25
|
+
#private;
|
|
26
|
+
private readonly options;
|
|
27
|
+
constructor(options: {
|
|
28
|
+
client: ScopedUsageSource;
|
|
29
|
+
owns: (credentialId: string) => boolean;
|
|
30
|
+
token: () => Promise<string>;
|
|
31
|
+
logger: ClaustrumLogger;
|
|
32
|
+
setTimeout: typeof setTimeout;
|
|
33
|
+
clearTimeout: typeof clearTimeout;
|
|
34
|
+
});
|
|
35
|
+
state(): ClaustrumUsageReportState;
|
|
36
|
+
report(credentialId: string, reading: ClaustrumUsageReading): void;
|
|
37
|
+
forget(credentialId: string): void;
|
|
38
|
+
/** Start the final flush; the custody's existing shutdown drain bounds it. */
|
|
39
|
+
close(): Promise<void> | undefined;
|
|
40
|
+
drop(): void;
|
|
41
|
+
}
|
|
@@ -41,6 +41,11 @@ export interface QuotaSectionOptions {
|
|
|
41
41
|
check?(ids: readonly string[], invocation: CommandInvocation): Promise<void>;
|
|
42
42
|
}
|
|
43
43
|
export interface RoutingSectionOptions {
|
|
44
|
+
/**
|
|
45
|
+
* Show how long the plugin may wait for the current account's limit to
|
|
46
|
+
* reset before switching. Opt in only when the plugin supports that policy.
|
|
47
|
+
*/
|
|
48
|
+
sameAccountWait?: boolean;
|
|
44
49
|
/**
|
|
45
50
|
* Further `routing.mode` values the plugin routes as `ordered` with the
|
|
46
51
|
* former main row moved (`main-first`, `fallback-first`), offered between
|
|
@@ -21,6 +21,11 @@ export declare class PrivateFileError extends Error {
|
|
|
21
21
|
orphanPath?: string;
|
|
22
22
|
constructor(path: string, stage: string, cause: unknown);
|
|
23
23
|
}
|
|
24
|
+
/** Native sharing and delete-pending errors reveal neither ownership nor expiry. */
|
|
25
|
+
export declare function isWindowsSharingViolation(error: unknown): error is PrivateFileError & {
|
|
26
|
+
reason: 'io-error';
|
|
27
|
+
win32Code: 32 | 303;
|
|
28
|
+
};
|
|
24
29
|
export declare function privateOperation<T>(path: string, stage: string, operation: () => Promise<T>): Promise<T>;
|
|
25
30
|
/** Tests only: policy options used by safe-parent checks that pass none. */
|
|
26
31
|
export declare function setSafeParentOptionsForTest(options?: PosixOwnerOnlyPathAsyncOptions): void;
|
|
@@ -23,11 +23,16 @@ export interface AdmissionInput extends ExclusionInputs {
|
|
|
23
23
|
scope?: string;
|
|
24
24
|
/** Labels the scope requires an entry for; defaults to `['primary']`. */
|
|
25
25
|
requiredLabels?: readonly string[];
|
|
26
|
+
/**
|
|
27
|
+
* One-dispatch exemptions keyed by row; waive only gate 4. The caller first
|
|
28
|
+
* validates the current account incarnation and checkpointed reset times.
|
|
29
|
+
*/
|
|
30
|
+
liftedWindows?: ReadonlyMap<string, readonly WindowRef[]>;
|
|
26
31
|
now: number;
|
|
27
32
|
/**
|
|
28
|
-
* Called synchronously
|
|
33
|
+
* Called synchronously once per row needing a pull, including lifted windows.
|
|
29
34
|
* Its return value is ignored and never awaited, so a pull the caller
|
|
30
|
-
* starts from here cannot delay
|
|
35
|
+
* starts from here cannot delay admission or a refusal.
|
|
31
36
|
*/
|
|
32
37
|
requestPull?: (rowId: string) => void;
|
|
33
38
|
}
|
|
@@ -12,6 +12,14 @@ export interface AskRoutingInput<Candidate extends RoutingCandidate = RoutingCan
|
|
|
12
12
|
candidates: readonly Candidate[];
|
|
13
13
|
/** Defaults to 500 ms, clamped to 1–2000 ms. */
|
|
14
14
|
deadlineMs?: number;
|
|
15
|
+
/**
|
|
16
|
+
* Longest same-account hold, in seconds, that routing may advise. The
|
|
17
|
+
* holdWaitMaxS helper from `./limits` caps it by the setting and the current
|
|
18
|
+
* account's cache expiry, returning 0 when there is no accepted prompt cache
|
|
19
|
+
* worth waiting for. Fractions are floored and negatives become 0. Omit it to leave
|
|
20
|
+
* routing's default cap in force.
|
|
21
|
+
*/
|
|
22
|
+
holdWaitMaxS?: number;
|
|
15
23
|
}
|
|
16
24
|
export interface RoutingHold {
|
|
17
25
|
/** Uncapped advice from routing. The plugin must apply its own hold cap. */
|
|
@@ -39,9 +47,11 @@ export type ReportRoutingInput = RoutingReportIdentity & ({
|
|
|
39
47
|
/** The exhausted quota window; keep scoped quota groups in `pool`. */
|
|
40
48
|
window: '5h' | '7d';
|
|
41
49
|
/**
|
|
42
|
-
* Scoped quota group, such as `
|
|
43
|
-
* Must
|
|
44
|
-
*
|
|
50
|
+
* Scoped quota group, such as Antigravity's `3p` or `gemini`.
|
|
51
|
+
* Must match `^[a-z0-9._-]{1,64}$`. Routing compares names exactly, so
|
|
52
|
+
* callers must lowercase names from elsewhere (e.g. `Fable` to `fable`).
|
|
53
|
+
* Names are never rewritten here. Omit or pass `undefined` to block the
|
|
54
|
+
* whole account; include to block only this pool.
|
|
45
55
|
*/
|
|
46
56
|
pool?: string;
|
|
47
57
|
/** Optional reset time in epoch milliseconds. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { StoredCredential } from './schema.js';
|
|
2
2
|
/** Every library operation that can fail, as named in the failure value. */
|
|
3
|
-
export type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
|
|
3
|
+
export type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'updateLimitsNamespace' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
|
|
4
4
|
/**
|
|
5
5
|
* How far an operation got before it failed.
|
|
6
6
|
*
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { type PoolOperation } from './errors.js';
|
|
2
2
|
/** Refuses a row operation or refresh called from inside a hook. */
|
|
3
3
|
export declare function assertNotInsideHook(operation: PoolOperation): void;
|
|
4
|
-
|
|
4
|
+
/** Namespace writes need only the store locks, not the row lock a hook may retain. */
|
|
5
|
+
export declare function assertLimitsWriteAllowed(): void;
|
|
6
|
+
/** Codecs may run under store locks even when no asynchronous hook is active. */
|
|
7
|
+
export declare function runInsideCodec<T>(fn: () => T): T;
|
|
8
|
+
export declare function runInsideHook<T>(operation: PoolOperation, fn: () => Promise<T> | T, storeLocksReleased?: boolean): Promise<T>;
|
|
5
9
|
export interface PoolLogger {
|
|
6
10
|
warn(message: string, data?: unknown): void;
|
|
7
11
|
}
|
|
@@ -3,6 +3,7 @@ export type { PoolFailureKind, PoolFailurePhase, PoolOperation, } from './errors
|
|
|
3
3
|
export { PoolOperationError, PoolReentryError } from './errors.js';
|
|
4
4
|
export type { PoolLogger } from './hooks.js';
|
|
5
5
|
export { countUnknownIdentityRows, DUPLICATE_IDENTITY_REASON, } from './identity.js';
|
|
6
|
+
export type { PoolLimitsMutator, PoolLimitsRow } from './limits-namespace.js';
|
|
6
7
|
export type { HoldPoint, InitializeOutcome, WriteStep } from './mutate.js';
|
|
7
8
|
export type { OpenPoolStoreOptions, PoolLoad, PoolStore, } from './pool.js';
|
|
8
9
|
export { openPoolStore } from './pool.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { StoreRuntime } from './runtime.js';
|
|
2
|
+
import type { PoolRow } from './schema.js';
|
|
3
|
+
/** Row IDs, credential epochs and identities only; mutators never receive credentials. */
|
|
4
|
+
export type PoolLimitsRow = Pick<PoolRow, 'id' | 'credentialEpoch' | 'identity'>;
|
|
5
|
+
export type PoolLimitsMutator = (envelope: unknown, rows: readonly PoolLimitsRow[]) => unknown | Promise<unknown>;
|
|
6
|
+
/** A namespace merge and its check of current row bindings share one locked config snapshot. */
|
|
7
|
+
export declare function updatePoolLimitsNamespace(rt: StoreRuntime, mutator: PoolLimitsMutator): Promise<void>;
|
|
@@ -2,6 +2,7 @@ import type { QuotaCommitTimer } from '../quota/commit-interval.js';
|
|
|
2
2
|
import { type Attribution } from './attribution.js';
|
|
3
3
|
import type { PoolOperationError } from './errors.js';
|
|
4
4
|
import type { PoolLogger } from './hooks.js';
|
|
5
|
+
import { type PoolLimitsMutator } from './limits-namespace.js';
|
|
5
6
|
import { type HoldPoint, type InitializeOutcome, type StoreContext } from './mutate.js';
|
|
6
7
|
import { type ProviderStateMutator, type UpdateProviderStateResult } from './provider-state.js';
|
|
7
8
|
import { type PublicationReceipt, type PublishOptions, type PublishPlan, type PublishResult } from './publication.js';
|
|
@@ -191,9 +192,17 @@ export interface PoolStore {
|
|
|
191
192
|
/**
|
|
192
193
|
* One locked write of the plugin's settings (since 0.2.6) beside the pool,
|
|
193
194
|
* in the config file. Refuses a result that sets a pool-owned key
|
|
194
|
-
* (`invalid-input`).
|
|
195
|
+
* (`invalid-input`). Carries commonAuthLimits through unchanged and refuses
|
|
196
|
+
* an explicit alteration to it. Takes `extraLocks`, then the store locks.
|
|
195
197
|
*/
|
|
196
198
|
updateSettings(mutator: SettingsMutator, options?: UpdateSettingsOptions): Promise<UpdateSettingsResult>;
|
|
199
|
+
/**
|
|
200
|
+
* Merges commonAuthLimits with current row bindings in one config write.
|
|
201
|
+
* Requires a ready pool and takes only the store locks. May run in an
|
|
202
|
+
* onPersisted/onFailure hook or a pull, but not in a lock-held mutator.
|
|
203
|
+
* Optional so existing structural implementations remain compatible.
|
|
204
|
+
*/
|
|
205
|
+
updateLimitsNamespace?(mutator: PoolLimitsMutator): Promise<void>;
|
|
197
206
|
/**
|
|
198
207
|
* Records the identity a lookup found for the row's credential. Since
|
|
199
208
|
* 0.3.1 it takes the credential epoch the lookup was issued for, and
|
|
@@ -59,5 +59,7 @@ export declare function readPoolSettings(rt: StoreRuntime): Promise<SettingsRead
|
|
|
59
59
|
* pool-owned key refuses (`invalid-input`) with nothing written; a result
|
|
60
60
|
* equal to the current settings writes nothing. The state file is never
|
|
61
61
|
* touched, and the pool-owned keys are written back exactly as read.
|
|
62
|
+
* commonAuthLimits is also carried through unchanged, even when omitted by
|
|
63
|
+
* the mutator; an explicit change to it refuses before writing anything.
|
|
62
64
|
*/
|
|
63
65
|
export declare function updatePoolSettings(rt: StoreRuntime, mutator: SettingsMutator, options?: UpdateSettingsOptions): Promise<UpdateSettingsResult>;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
export declare const MESSAGE_THREADS_BETA = "message-threads-2026-08-12";
|
|
2
|
+
type Body = Record<string, unknown>;
|
|
3
|
+
export interface MessageThreadInput {
|
|
4
|
+
body: Body;
|
|
5
|
+
betas: string[];
|
|
6
|
+
account: string;
|
|
7
|
+
credential: string;
|
|
8
|
+
session: string;
|
|
9
|
+
replyToolNames?: ReadonlyMap<string, string | null>;
|
|
10
|
+
}
|
|
11
|
+
export interface MessageThreadSnapshot {
|
|
12
|
+
identity: string;
|
|
13
|
+
fingerprint: string;
|
|
14
|
+
messages: string[];
|
|
15
|
+
prefix: string;
|
|
16
|
+
}
|
|
17
|
+
export interface MessageThreadAnchor extends MessageThreadSnapshot {
|
|
18
|
+
messageId: string;
|
|
19
|
+
completedAt: number;
|
|
20
|
+
replyFingerprint: string;
|
|
21
|
+
}
|
|
22
|
+
export type MessageThreadDecision = {
|
|
23
|
+
type: 'create';
|
|
24
|
+
} | {
|
|
25
|
+
type: 'continue';
|
|
26
|
+
previousMessageId: string;
|
|
27
|
+
deltaMessages: unknown[];
|
|
28
|
+
};
|
|
29
|
+
type ReplyToolName = (name: unknown) => string | undefined;
|
|
30
|
+
export declare function messageThreadSnapshot(input: MessageThreadInput, identity?: string, fingerprint?: string): MessageThreadSnapshot;
|
|
31
|
+
/** Decide from immutable request facts; no session state or clock is read here. */
|
|
32
|
+
export declare function decideMessageThread(anchor: MessageThreadAnchor | undefined, input: MessageThreadInput, snapshot: MessageThreadSnapshot, now: number): MessageThreadDecision;
|
|
33
|
+
export interface MessageThreadCompletion {
|
|
34
|
+
messageId?: string;
|
|
35
|
+
stopReason?: string | null;
|
|
36
|
+
stopped: boolean;
|
|
37
|
+
refusal?: boolean;
|
|
38
|
+
fallback?: boolean;
|
|
39
|
+
rewritten?: boolean;
|
|
40
|
+
replyFingerprint?: string;
|
|
41
|
+
reply?: unknown;
|
|
42
|
+
}
|
|
43
|
+
export declare class MessageThreadTracker {
|
|
44
|
+
private readonly capacity;
|
|
45
|
+
private readonly now;
|
|
46
|
+
private readonly hashBudget;
|
|
47
|
+
private readonly sessions;
|
|
48
|
+
private messageHashes;
|
|
49
|
+
constructor(capacity?: number, now?: () => number, hashBudget?: number);
|
|
50
|
+
forget(session: string): void;
|
|
51
|
+
private prune;
|
|
52
|
+
private failureFor;
|
|
53
|
+
prepare(input: MessageThreadInput): {
|
|
54
|
+
decision: MessageThreadDecision;
|
|
55
|
+
body: Body;
|
|
56
|
+
normalizeToolName: ReplyToolName;
|
|
57
|
+
complete: (facts: MessageThreadCompletion) => void;
|
|
58
|
+
fail: () => void;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** Observe without teeing or buffering the response; cancellation cannot publish an anchor. */
|
|
62
|
+
export declare function observeMessageThreadResponse(response: Response, prepared: Pick<ReturnType<MessageThreadTracker['prepare']>, 'complete' | 'fail'> & Partial<Pick<ReturnType<MessageThreadTracker['prepare']>, 'normalizeToolName'>>): Response;
|
|
63
|
+
export declare function messageThreadBetas(headers: Headers): string[];
|
|
64
|
+
/** The HTTP protocol uses error.details.error_code, not the SDK's error.code. */
|
|
65
|
+
export declare function isMessageThreadRejection(response: Response): Promise<boolean>;
|
|
66
|
+
export declare function prepareMessageThreadRequest(tracker: MessageThreadTracker, input: Omit<MessageThreadInput, 'body' | 'betas' | 'session'> & {
|
|
67
|
+
session?: string;
|
|
68
|
+
bodyText: string;
|
|
69
|
+
headers: Headers;
|
|
70
|
+
signal?: AbortSignal;
|
|
71
|
+
}): Promise<{
|
|
72
|
+
readonly bodyText: string;
|
|
73
|
+
fail: () => void;
|
|
74
|
+
observe: (response: Response) => Response;
|
|
75
|
+
recover(response: Response, send: (body: string) => Promise<Response>, beforeResend?: (rejected: Response) => Promise<boolean | {
|
|
76
|
+
credential: string;
|
|
77
|
+
}> | boolean | {
|
|
78
|
+
credential: string;
|
|
79
|
+
}): Promise<Response>;
|
|
80
|
+
}>;
|
|
81
|
+
export type MessageThreadRequest = Awaited<ReturnType<typeof prepareMessageThreadRequest>>;
|
|
82
|
+
export {};
|
package/dist/relay.d.ts
CHANGED
|
@@ -31,6 +31,7 @@ export type RelayPatch = {
|
|
|
31
31
|
deleteCount: number;
|
|
32
32
|
insert: string;
|
|
33
33
|
};
|
|
34
|
+
type RelayPatchSet = RelayPatch | RelayPatch[];
|
|
34
35
|
export type RelayAttemptAuthorization = {
|
|
35
36
|
headers: Headers;
|
|
36
37
|
/** Called only for a genuine upstream response, never optimistic/transport status. */
|
|
@@ -48,6 +49,7 @@ export declare function getRelayConfig(storage: AccountStorage | null): RelayCon
|
|
|
48
49
|
export declare function generateRelayToken(): string;
|
|
49
50
|
export declare function hashBody(body: string): string;
|
|
50
51
|
export declare function createStringPatch(previous: string, next: string): RelayPatch;
|
|
52
|
+
export declare function createRelayPatch(previous: string, next: string): RelayPatchSet;
|
|
51
53
|
export declare function sendViaRelay(options: {
|
|
52
54
|
config: RelayConfig | null;
|
|
53
55
|
input: string | URL | Request;
|
|
@@ -84,3 +86,4 @@ export declare function sendViaRelay(options: {
|
|
|
84
86
|
requireUpstreamUrl?: (url: string) => unknown;
|
|
85
87
|
}): Promise<Response>;
|
|
86
88
|
export declare const WORKER_SCRIPT = "\nasync function hashBody(body) {\n const bytes = new TextEncoder().encode(body)\n const digest = await crypto.subtle.digest('SHA-256', bytes)\n const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')\n return 'sha256:' + hex\n}\n\nfunction applyPatch(base, patch) {\n return base.slice(0, patch.start) + patch.insert + base.slice(patch.start + patch.deleteCount)\n}\n\nfunction applyPatchSet(base, patch) {\n if (!Array.isArray(patch)) return applyPatch(base, patch)\n if (patch.length === 0) return base\n\n let result = ''\n let cursor = 0\n for (const item of patch) {\n if (item.start < cursor) return { error: 'overlapping patch', status: 400 }\n result += base.slice(cursor, item.start)\n result += item.insert\n cursor = item.start + item.deleteCount\n }\n return result + base.slice(cursor)\n}\n\nasync function readState(env, affinity) {\n const raw = await env.RELAY_STATE.get('session:' + affinity)\n return raw ? JSON.parse(raw) : null\n}\n\nasync function writeState(env, affinity, state) {\n await env.RELAY_STATE.put('session:' + affinity, JSON.stringify(state), { expirationTtl: 86400 })\n}\n\nasync function resolveBody(env, payload) {\n if (payload.mode === 'full_sync') return payload.body\n if (payload.mode === 'patch') {\n const state = await readState(env, payload.affinity)\n if (!state || state.hash !== payload.base_hash) {\n return { error: 'state mismatch', status: 409 }\n }\n return applyPatchSet(state.body, payload.patch)\n }\n return { error: 'unknown mode', status: 400 }\n}\n\nasync function prepareUpstream(env, payload) {\n if ((payload.protocol !== 1 && payload.protocol !== 2) || payload.type !== 'request' || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {\n return { error: 'invalid payload', status: 400 }\n }\n\n const body = await resolveBody(env, payload)\n if (body && typeof body === 'object' && 'error' in body) return body\n\n if (typeof body !== 'string' || (await hashBody(body)) !== payload.next_hash) {\n return { error: 'hash mismatch', status: 409 }\n }\n\n const stateWrite = writeState(env, payload.affinity, { body, hash: payload.next_hash, revision: payload.revision }).catch(() => {})\n console.log(JSON.stringify({\n relay: 'opencode-anthropic-auth',\n transport: 'relay',\n mode: payload.mode,\n revision: payload.revision,\n affinity: String(payload.affinity).slice(0, 12),\n bodyBytes: body.length,\n }))\n\n return { body, stateWrite }\n}\n\nfunction resolveBodyFromState(state, payload) {\n if (payload.mode === 'full_sync') return payload.body\n if (payload.mode === 'patch') {\n if (!state || state.hash !== payload.base_hash) {\n return { error: 'state mismatch', status: 409 }\n }\n return applyPatchSet(state.body, payload.patch)\n }\n return { error: 'unknown mode', status: 400 }\n}\n\nfunction deferWorkerTask(task) {\n return new Promise((resolve) => setTimeout(resolve, 0)).then(task)\n}\n\nconst WEBSOCKET_STREAM_FLUSH_BYTES = 1024\nconst WEBSOCKET_STREAM_FLUSH_MS = 20\n\nfunction createWebSocketStreamCoalescer(socket, options = {}) {\n const flushBytes = options.flushBytes || WEBSOCKET_STREAM_FLUSH_BYTES\n const flushMs = options.flushMs ?? WEBSOCKET_STREAM_FLUSH_MS\n let chunks = []\n let byteLength = 0\n let flushTimer = null\n const stats = {\n upstreamChunks: 0,\n upstreamBytes: 0,\n frames: 0,\n frameBytes: 0,\n }\n\n const clearFlushTimer = () => {\n if (flushTimer === null) return\n clearTimeout(flushTimer)\n flushTimer = null\n }\n\n const mergeChunks = () => {\n if (chunks.length === 1) return chunks[0]\n const frame = new Uint8Array(byteLength)\n let offset = 0\n for (const chunk of chunks) {\n frame.set(chunk, offset)\n offset += chunk.byteLength\n }\n return frame\n }\n\n const flush = () => {\n clearFlushTimer()\n if (byteLength === 0) return\n const frame = mergeChunks()\n chunks = []\n byteLength = 0\n socket.send(frame)\n stats.frames += 1\n stats.frameBytes += frame.byteLength\n }\n\n const scheduleFlush = () => {\n if (flushTimer !== null) return\n flushTimer = setTimeout(flush, flushMs)\n }\n\n return {\n push(value) {\n const chunk = value instanceof Uint8Array ? value : new Uint8Array(value)\n if (chunk.byteLength === 0) return\n stats.upstreamChunks += 1\n stats.upstreamBytes += chunk.byteLength\n chunks.push(chunk)\n byteLength += chunk.byteLength\n if (byteLength >= flushBytes) flush()\n else scheduleFlush()\n },\n flush,\n stats() {\n return { ...stats, pendingBytes: byteLength }\n },\n }\n}\n\nfunction checkpointWebSocketState(env, payload, body, nextState) {\n return deferWorkerTask(async () => {\n try {\n if ((await hashBody(body)) !== payload.next_hash) {\n throw new Error('hash mismatch')\n }\n await writeState(env, payload.affinity, nextState)\n } catch {\n console.log(JSON.stringify({\n relay: 'opencode-anthropic-auth',\n transport: 'websocket',\n event: 'checkpoint_write_failed',\n affinity: String(payload.affinity).slice(0, 12),\n code: 'checkpoint_write_error',\n }))\n }\n })\n}\n\nasync function prepareWebSocketUpstream(env, state, payload) {\n if (payload.protocol !== 2 || payload.type !== 'request' || !payload.id || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {\n return { error: 'invalid payload', status: 400 }\n }\n\n const body = resolveBodyFromState(state, payload)\n if (body && typeof body === 'object' && 'error' in body) return body\n if (typeof body !== 'string') return { error: 'invalid body', status: 400 }\n if ((await hashBody(body)) !== payload.next_hash) {\n return { error: 'hash mismatch', status: 409 }\n }\n\n const nextState = { body, hash: payload.next_hash, revision: payload.revision }\n const checkpoint = checkpointWebSocketState(env, payload, body, nextState)\n const logAccepted = () => console.log(JSON.stringify({\n relay: 'opencode-anthropic-auth',\n transport: 'websocket',\n mode: payload.mode,\n revision: payload.revision,\n affinity: String(payload.affinity).slice(0, 12),\n bodyBytes: body.length,\n }))\n\n return { body, state: nextState, checkpoint, logAccepted }\n}\n\nfunction headersToObject(headers) {\n const result = {}\n for (const [key, value] of headers.entries()) result[key] = value\n return result\n}\n\nasync function handleRelayPayload(env, payload) {\n const prepared = await prepareUpstream(env, payload)\n if (prepared.error) return prepared\n const upstream = await fetch(payload.upstream.url, {\n method: payload.upstream.method || 'POST',\n headers: payload.upstream.headers,\n body: prepared.body,\n })\n return { upstream, stateWrite: prepared.stateWrite }\n}\n\nasync function handleWebSocket(socket, env, ctx, payload, getState, setState) {\n const heartbeat = setInterval(() => {\n try {\n socket.send(JSON.stringify({ protocol: 2, type: 'keepalive' }))\n } catch {\n clearInterval(heartbeat)\n }\n }, 15000)\n let streamCoalescer = null\n try {\n const result = await prepareWebSocketUpstream(env, getState(), payload)\n if (result.error) {\n socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: result.status, message: result.error }))\n return\n }\n\n setState(result.state)\n socket.send(JSON.stringify({ protocol: 2, type: 'accepted', id: payload.id, hash: result.state.hash, revision: result.state.revision }))\n ctx?.waitUntil?.(deferWorkerTask(result.logAccepted))\n\n const upstreamPromise = fetch(payload.upstream.url, {\n method: payload.upstream.method || 'POST',\n headers: payload.upstream.headers,\n body: result.body,\n })\n ctx?.waitUntil?.(result.checkpoint)\n const upstream = await upstreamPromise\n socket.send(JSON.stringify({\n protocol: 2,\n type: 'response_start',\n id: payload.id,\n status: upstream.status,\n statusText: upstream.statusText,\n headers: headersToObject(upstream.headers),\n }))\n\n const reader = upstream.body?.getReader()\n if (reader) {\n streamCoalescer = createWebSocketStreamCoalescer(socket)\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n streamCoalescer.push(value)\n }\n streamCoalescer.flush()\n }\n const stats = streamCoalescer?.stats?.() || {}\n socket.send(JSON.stringify({ protocol: 2, type: 'done', id: payload.id, ...stats }))\n } catch (error) {\n try {\n streamCoalescer?.flush?.()\n } catch {}\n socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: 500, message: error instanceof Error ? error.message : String(error) }))\n } finally {\n clearInterval(heartbeat)\n }\n}\n\nexport default {\n async fetch(request, env, ctx) {\n if (request.headers.get('Upgrade') === 'websocket') {\n const url = new URL(request.url)\n const token = url.searchParams.get('token')\n const affinity = url.searchParams.get('affinity')\n if (token !== env.RELAY_TOKEN) return new Response('unauthorized', { status: 401 })\n if (!affinity) return new Response('missing affinity', { status: 400 })\n const pair = new WebSocketPair()\n const client = pair[0]\n const server = pair[1]\n server.binaryType = 'arraybuffer'\n let state = null\n let ready = false\n server.accept()\n const loadState = readState(env, affinity).then((loadedState) => {\n state = loadedState\n ready = true\n server.send(JSON.stringify({\n protocol: 2,\n type: 'ready',\n state: state ? { hash: state.hash, revision: state.revision } : null,\n }))\n }).catch((error) => {\n server.send(JSON.stringify({ protocol: 2, type: 'error', status: 500, message: error instanceof Error ? error.message : String(error) }))\n server.close(1011, 'state load failed')\n })\n ctx?.waitUntil?.(loadState)\n if (!ctx?.waitUntil) void loadState\n let busy = false\n server.addEventListener('message', (event) => {\n if (!ready) {\n server.send(JSON.stringify({ protocol: 2, type: 'error', status: 425, message: 'relay state is not ready' }))\n return\n }\n if (busy) {\n server.send(JSON.stringify({ protocol: 2, type: 'error', status: 429, message: 'request already in flight' }))\n return\n }\n let payload\n try {\n payload = JSON.parse(event.data)\n } catch {\n server.send(JSON.stringify({ protocol: 2, type: 'error', status: 400, message: 'invalid JSON payload' }))\n return\n }\n payload.affinity = affinity\n busy = true\n const run = handleWebSocket(server, env, ctx, payload, () => state, (nextState) => { state = nextState }).finally(() => { busy = false })\n ctx?.waitUntil?.(run)\n if (!ctx?.waitUntil) void run\n })\n return new Response(null, { status: 101, webSocket: client })\n }\n\n if (request.method === 'GET') {\n return Response.json({ status: 'ok', transports: ['http', 'websocket'] })\n }\n if (request.method !== 'POST') return new Response('method not allowed', { status: 405 })\n if (request.headers.get('x-relay-token') !== env.RELAY_TOKEN) {\n return new Response('unauthorized', { status: 401 })\n }\n\n try {\n const payload = await request.json()\n const result = await handleRelayPayload(env, payload)\n if (result.error) return Response.json({ error: result.error }, { status: result.status })\n\n if (result.stateWrite) ctx.waitUntil(result.stateWrite)\n\n const upstream = result.upstream\n return new Response(upstream.body, {\n status: upstream.status,\n statusText: upstream.statusText,\n headers: upstream.headers,\n })\n } catch (error) {\n return Response.json(\n { error: error instanceof Error ? error.message : 'internal relay error' },\n { status: 502 },\n )\n }\n },\n}\n";
|
|
89
|
+
export {};
|
package/dist/sticky-routing.d.ts
CHANGED
|
@@ -49,8 +49,17 @@ export type StickyQuotaFailureDecision = {
|
|
|
49
49
|
retryAfterSeconds: number;
|
|
50
50
|
} | {
|
|
51
51
|
action: 'migrate';
|
|
52
|
-
reason: 'five-hour' | 'seven-day' | 'model-scoped';
|
|
52
|
+
reason: 'five-hour' | 'seven-day' | 'model-scoped' | 'unconfirmed-retry-limit';
|
|
53
53
|
};
|
|
54
|
+
export declare const MAX_UNCONFIRMED_SAME_ACCOUNT_RETRIES = 2;
|
|
55
|
+
/** Process-local retry budgets; only the current turn and account survive per session. */
|
|
56
|
+
export declare class StickyQuotaRetryCounter {
|
|
57
|
+
private readonly maxSessions;
|
|
58
|
+
private readonly sessions;
|
|
59
|
+
constructor(maxSessions?: number);
|
|
60
|
+
retain(sessionId: string, turnId: string, accountId: string): boolean;
|
|
61
|
+
clear(sessionId: string): void;
|
|
62
|
+
}
|
|
54
63
|
/**
|
|
55
64
|
* Build the terminal response for a complete sticky quota pool that has no
|
|
56
65
|
* eligible route. This prevents callers from silently falling through to the
|
|
@@ -101,6 +110,12 @@ export declare function decideStickyQuotaFailure(input: {
|
|
|
101
110
|
now?: number;
|
|
102
111
|
sessionId?: string;
|
|
103
112
|
holdUntil?: number;
|
|
113
|
+
unconfirmedRetry?: {
|
|
114
|
+
counter: StickyQuotaRetryCounter;
|
|
115
|
+
sessionId: string;
|
|
116
|
+
turnId: string;
|
|
117
|
+
accountId: string;
|
|
118
|
+
};
|
|
104
119
|
}): StickyQuotaFailureDecision;
|
|
105
120
|
/** Bound an unconfirmed 429's host retry while preserving any shorter upstream wait. */
|
|
106
121
|
export declare function stickyRetainRetryHeaders(upstream: Headers, now?: number): Headers;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/anthropic-auth-core",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.5.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"prepublishOnly": "bun run build"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
|
-
"@cortexkit/common-auth": "0.
|
|
33
|
+
"@cortexkit/common-auth": "0.34.0"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"@cortexkit/claustrum-client": "0.13.0",
|