@cortexkit/common-auth 0.40.0 → 0.41.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.
@@ -0,0 +1,41 @@
1
+ import type { CacheWarmStopReason, SessionCacheHours, SessionKeepWarmMode } from '../routing-accessor/cache-policy.js';
2
+ export type CacheKeepDecisionInput = {
3
+ /** All times and the cache lifetime are in milliseconds. */
4
+ now: number;
5
+ ttlMs: number;
6
+ lastRealRequestAt: number;
7
+ lastWarmAt?: number;
8
+ /** The caller resets the count and costs on every real request. */
9
+ warmsSinceLastRealRequest: number;
10
+ /** Plugin-priced input-token equivalents; no prices are guessed here. */
11
+ warmCostSoFar?: number;
12
+ nextWarmCost?: number;
13
+ rewriteCost?: number;
14
+ } & ({
15
+ mode: 'hours';
16
+ hours: SessionCacheHours;
17
+ } | {
18
+ mode: Exclude<SessionKeepWarmMode, 'hours'>;
19
+ hours?: never;
20
+ });
21
+ export type CacheKeepDecision = {
22
+ action: 'warm';
23
+ at: number;
24
+ } | {
25
+ action: 'wait';
26
+ until: number;
27
+ } | {
28
+ action: 'stop';
29
+ reason: CacheWarmStopReason;
30
+ };
31
+ /**
32
+ * Decide the next idle or tool-wait warm using a validated mode/window. The
33
+ * caller owns timers, session liveness and resetting counts/costs on real
34
+ * requests. A warm is due before expiry, never in its final safety margin.
35
+ *
36
+ * Auto applies a cost cap only when all three plugin-priced costs are supplied;
37
+ * without them this is timing only, and the plugin must apply its idle bounds.
38
+ * No provider prices are inferred. Off returns unsupported; callers must not
39
+ * report a stop for a session that never warmed.
40
+ */
41
+ export declare function decideCacheKeep(input: CacheKeepDecisionInput): CacheKeepDecision;
@@ -0,0 +1,53 @@
1
+ function withinHours(hours, at) {
2
+ const parts = new Intl.DateTimeFormat('en-GB', {
3
+ timeZone: hours.tz,
4
+ hour: '2-digit',
5
+ minute: '2-digit',
6
+ hourCycle: 'h23',
7
+ }).formatToParts(at);
8
+ const hour = parts.find((part) => part.type === 'hour')?.value;
9
+ const minute = parts.find((part) => part.type === 'minute')?.value;
10
+ const time = `${hour}:${minute}`;
11
+ return hours.from < hours.to
12
+ ? time >= hours.from && time < hours.to
13
+ : time >= hours.from || time < hours.to;
14
+ }
15
+ /**
16
+ * Decide the next idle or tool-wait warm using a validated mode/window. The
17
+ * caller owns timers, session liveness and resetting counts/costs on real
18
+ * requests. A warm is due before expiry, never in its final safety margin.
19
+ *
20
+ * Auto applies a cost cap only when all three plugin-priced costs are supplied;
21
+ * without them this is timing only, and the plugin must apply its idle bounds.
22
+ * No provider prices are inferred. Off returns unsupported; callers must not
23
+ * report a stop for a session that never warmed.
24
+ */
25
+ export function decideCacheKeep(input) {
26
+ const { mode, now, ttlMs, lastRealRequestAt, lastWarmAt, warmsSinceLastRealRequest, warmCostSoFar, nextWarmCost, rewriteCost, } = input;
27
+ if (mode === 'off')
28
+ return { action: 'stop', reason: 'unsupported' };
29
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
30
+ return { action: 'stop', reason: 'unsupported' };
31
+ }
32
+ if ((mode === 'hours' || mode === 'always') &&
33
+ warmsSinceLastRealRequest >= 24)
34
+ return { action: 'stop', reason: 'count-cap' };
35
+ if (mode === 'auto' &&
36
+ warmCostSoFar !== undefined &&
37
+ nextWarmCost !== undefined &&
38
+ rewriteCost !== undefined &&
39
+ warmCostSoFar + nextWarmCost >= rewriteCost)
40
+ return { action: 'stop', reason: 'cost-cap' };
41
+ const last = Math.max(lastRealRequestAt, lastWarmAt ?? lastRealRequestAt);
42
+ const expiresAt = last + ttlMs;
43
+ const due = expiresAt - Math.min(30_000, ttlMs / 2);
44
+ const at = Math.max(now, due);
45
+ // Replaying inside the expiry margin risks paying for a cold cache rewrite.
46
+ if (at >= expiresAt - Math.min(5_000, ttlMs / 10)) {
47
+ return { action: 'stop', reason: 'cost-cap' };
48
+ }
49
+ if (mode === 'hours' &&
50
+ (!withinHours(input.hours, due) || !withinHours(input.hours, at)))
51
+ return { action: 'stop', reason: 'outside-hours' };
52
+ return now < due ? { action: 'wait', until: due } : { action: 'warm', at };
53
+ }
@@ -1,3 +1,5 @@
1
+ export type { CacheKeepDecision, CacheKeepDecisionInput } from './decision.js';
2
+ export { decideCacheKeep } from './decision.js';
1
3
  export type { CacheKeepAdapter, CacheKeepBackoff, CacheKeepLogger, CacheKeepManagerOptions, CacheKeepProfile, CacheKeepSendInput, CacheKeepStatus, CacheKeepTargetStatus, CacheKeepTargetView, CacheKeepTrackInput, CacheKeepTrackResult, } from './manager.js';
2
4
  export { CacheKeepManager } from './manager.js';
3
5
  export type { CacheKeepWindow } from './window.js';
@@ -1,2 +1,3 @@
1
+ export { decideCacheKeep } from './decision.js';
1
2
  export { CacheKeepManager } from './manager.js';
2
3
  export { isWithinCacheKeepWindow, normalizeCacheKeepWindow, } from './window.js';
@@ -6,7 +6,7 @@ export { ClaustrumConsumer, type ClaustrumConsumerOptions, type ClaustrumWatchSt
6
6
  export { type AccountIdentitySource, type ClassifyingClaustrumFamily, type ClaustrumFamily, type ClaustrumFamilyInput, type ClaustrumRosterWatch, type ClaustrumRosterWatchOptions, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, type KeptReceiptState, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, type VaultRowFacts, } from './custody.js';
7
7
  export { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentConnection, type ClaustrumEnrollmentDisconnectResult, ClaustrumEnrollmentManager, type ClaustrumEnrollmentPaths, type ClaustrumEnrollmentResetResult, type ClaustrumEnrollmentStatus, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, type EnrollmentDisposition, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, vaultAuthority, } from './enrollment.js';
8
8
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
9
- export { connectVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from './host.js';
9
+ export { connectVaultHost, hasVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from './host.js';
10
10
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, type HostSlotContent, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
11
11
  export { ClaustrumDiscoveryHub, type ClaustrumDiscoveryHubOptions, type ClaustrumHubMemberOptions, type ClaustrumHubRefusals, type ClaustrumLeasedCustody, type CustodyLease, } from './hub.js';
12
12
  export { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaLookup, type InsulaQuotaMiss, type InsulaQuotaOptions, type InsulaQuotaReading, type InsulaQuotaResult, type InsulaQuotaSource, type InsulaUsageEntry, type InsulaUsageTransport, type InsulaUsageWatch, type InsulaUsageWindow, type InsulaWatchOptions, } from './insula.js';
@@ -12,7 +12,7 @@ export { ClaustrumConsumer, DEFAULT_CONNECT_TIMEOUT_MS, } from './consumer.js';
12
12
  export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, SERVING_MARGIN_MS, } from './custody.js';
13
13
  export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, vaultAuthority, } from './enrollment.js';
14
14
  export { ClaustrumConsumerError, } from './errors.js';
15
- export { connectVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from './host.js';
15
+ export { connectVaultHost, hasVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from './host.js';
16
16
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
17
17
  export { ClaustrumDiscoveryHub, } from './hub.js';
18
18
  export { acquireInsulaQuotaSource, } from './insula.js';
@@ -0,0 +1,51 @@
1
+ export type SessionCacheTtl = 'none' | 'short' | 'long';
2
+ export type SessionKeepWarmMode = 'off' | 'hours' | 'always' | 'auto';
3
+ export interface SessionCacheHours {
4
+ from: string;
5
+ to: string;
6
+ tz: string;
7
+ }
8
+ export interface SessionCachePolicy {
9
+ ttl?: SessionCacheTtl;
10
+ keep_warm?: SessionKeepWarmMode;
11
+ hours?: SessionCacheHours;
12
+ }
13
+ export interface SessionToolWait {
14
+ /** Epoch milliseconds when the oldest running plan tool started. */
15
+ since: number;
16
+ }
17
+ /**
18
+ * The stop reasons the llm-runner contract defines today; any other string is
19
+ * accepted too, for reasons that contract adds later.
20
+ */
21
+ export type CacheWarmStopReason = 'cost-cap' | 'count-cap' | 'outside-hours' | 'session-ended' | 'unsupported' | (string & Record<never, never>);
22
+ export interface CacheTouchInput {
23
+ /** Integer epoch milliseconds when the provider answered. */
24
+ at: number;
25
+ ttlMs: number | 'implicit';
26
+ source: 'response' | 'warm';
27
+ }
28
+ export interface CacheWarmStoppedInput {
29
+ /** Integer epoch milliseconds. */
30
+ at: number;
31
+ reason: CacheWarmStopReason;
32
+ }
33
+ /**
34
+ * Read the session's current plan on every decision; never retain it across
35
+ * requests. Null means the plugin keeps its own settings. No I/O or exceptions.
36
+ */
37
+ export declare function sessionCachePolicy(sessionId: string): SessionCachePolicy | null;
38
+ /** Read the oldest running plan tool afresh, without I/O or exceptions. */
39
+ export declare function sessionToolWait(sessionId: string): SessionToolWait | null;
40
+ /**
41
+ * Call only after the reply has been handed to the host, never on the awaited
42
+ * request path. Synchronous fire-and-forget, with no retries; the bridge owns
43
+ * redelivery of the newest touch. Accessor and report failures are absorbed.
44
+ */
45
+ export declare function reportCacheTouch(sessionId: string, input: CacheTouchInput): void;
46
+ /**
47
+ * Call off the request path, after handing the reply to the host. Report only
48
+ * a session that actually warmed, never one that was off from the start.
49
+ * Synchronous fire-and-forget; failures are absorbed and never retried here.
50
+ */
51
+ export declare function reportCacheWarmStopped(sessionId: string, input: CacheWarmStoppedInput): void;
@@ -0,0 +1,186 @@
1
+ import { routingHandle } from './handle.js';
2
+ const warned = new Set();
3
+ // Inspect descriptors rather than values so warning deduplication cannot invoke
4
+ // a broken bridge's getters a second time. Do not print policy contents.
5
+ function shape(value, seen = new Set()) {
6
+ if (typeof value !== 'object' || value === null) {
7
+ return `${typeof value}:${String(value)}`;
8
+ }
9
+ if (seen.has(value))
10
+ return 'cycle';
11
+ seen.add(value);
12
+ return `${Array.isArray(value) ? 'array' : 'object'}:{${Object.entries(Object.getOwnPropertyDescriptors(value))
13
+ .sort(([a], [b]) => a.localeCompare(b))
14
+ .map(([key, descriptor]) => `${key}:${'value' in descriptor ? shape(descriptor.value, seen) : 'accessor'}`)
15
+ .join(',')}}`;
16
+ }
17
+ function invalid(kind, value) {
18
+ let fingerprint = 'unreadable';
19
+ try {
20
+ fingerprint = shape(value);
21
+ }
22
+ catch {
23
+ // Uninspectable proxies share one diagnostic shape, without invoking getters.
24
+ }
25
+ try {
26
+ const key = `${kind}:${fingerprint}`;
27
+ if (!warned.has(key)) {
28
+ warned.add(key);
29
+ console.warn(`[common-auth] Ignoring invalid session ${kind} policy`);
30
+ }
31
+ }
32
+ catch {
33
+ // A broken warning sink must not break a request either.
34
+ }
35
+ return null;
36
+ }
37
+ function record(value) {
38
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
39
+ }
40
+ function rejectAsync(value) {
41
+ if (typeof value.then !== 'function')
42
+ return false;
43
+ // Absorb a rejected promise from a bridge that broke the synchronous contract.
44
+ void Promise.resolve(value).catch(() => { });
45
+ return true;
46
+ }
47
+ function onlyKeys(value, keys) {
48
+ return Reflect.ownKeys(value).every((key) => typeof key === 'string' && keys.includes(key));
49
+ }
50
+ /**
51
+ * Read the session's current plan on every decision; never retain it across
52
+ * requests. Null means the plugin keeps its own settings. No I/O or exceptions.
53
+ */
54
+ export function sessionCachePolicy(sessionId) {
55
+ let answer;
56
+ try {
57
+ const handle = routingHandle(sessionId);
58
+ if (!handle)
59
+ return null;
60
+ const read = handle.cache;
61
+ if (typeof read !== 'function')
62
+ return null;
63
+ answer = read.call(handle);
64
+ if (answer === null)
65
+ return null;
66
+ if (!record(answer) || rejectAsync(answer))
67
+ return invalid('cache', answer);
68
+ const { ttl, keep_warm, hours } = answer;
69
+ if (!onlyKeys(answer, ['ttl', 'keep_warm', 'hours']) ||
70
+ (ttl !== undefined &&
71
+ ttl !== 'none' &&
72
+ ttl !== 'short' &&
73
+ ttl !== 'long') ||
74
+ (keep_warm !== undefined &&
75
+ keep_warm !== 'off' &&
76
+ keep_warm !== 'hours' &&
77
+ keep_warm !== 'always' &&
78
+ keep_warm !== 'auto') ||
79
+ (ttl === 'none' && keep_warm !== undefined && keep_warm !== 'off') ||
80
+ (keep_warm !== 'hours' && 'hours' in answer)) {
81
+ return invalid('cache', answer);
82
+ }
83
+ const policy = {
84
+ ...(ttl !== undefined ? { ttl } : {}),
85
+ ...(keep_warm !== undefined ? { keep_warm } : {}),
86
+ };
87
+ if (keep_warm === 'hours') {
88
+ if (!record(hours) || !onlyKeys(hours, ['from', 'to', 'tz'])) {
89
+ return invalid('cache', answer);
90
+ }
91
+ const { from, to, tz } = hours;
92
+ const time = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
93
+ if (typeof from !== 'string' ||
94
+ !time.test(from) ||
95
+ typeof to !== 'string' ||
96
+ !time.test(to) ||
97
+ from === to ||
98
+ typeof tz !== 'string' ||
99
+ tz.length === 0) {
100
+ return invalid('cache', answer);
101
+ }
102
+ new Intl.DateTimeFormat('en', { timeZone: tz });
103
+ policy.hours = { from, to, tz };
104
+ }
105
+ return policy;
106
+ }
107
+ catch {
108
+ return invalid('cache', answer);
109
+ }
110
+ }
111
+ /** Read the oldest running plan tool afresh, without I/O or exceptions. */
112
+ export function sessionToolWait(sessionId) {
113
+ let answer;
114
+ try {
115
+ const handle = routingHandle(sessionId);
116
+ if (!handle)
117
+ return null;
118
+ const read = handle.tool_wait;
119
+ if (typeof read !== 'function')
120
+ return null;
121
+ answer = read.call(handle);
122
+ if (answer === null)
123
+ return null;
124
+ if (!record(answer) || rejectAsync(answer))
125
+ return invalid('tool_wait', answer);
126
+ const { since } = answer;
127
+ if (!onlyKeys(answer, ['since']) ||
128
+ typeof since !== 'number' ||
129
+ !Number.isSafeInteger(since) ||
130
+ since < 0) {
131
+ return invalid('tool_wait', answer);
132
+ }
133
+ return { since };
134
+ }
135
+ catch {
136
+ return invalid('tool_wait', answer);
137
+ }
138
+ }
139
+ function report(sessionId, payload) {
140
+ const handle = routingHandle(sessionId);
141
+ if (!handle)
142
+ return;
143
+ const send = handle.report;
144
+ if (typeof send !== 'function')
145
+ return;
146
+ const pending = send.call(handle, payload);
147
+ if (record(pending) && typeof pending.then === 'function') {
148
+ void Promise.resolve(pending).catch(() => { });
149
+ }
150
+ }
151
+ /**
152
+ * Call only after the reply has been handed to the host, never on the awaited
153
+ * request path. Synchronous fire-and-forget, with no retries; the bridge owns
154
+ * redelivery of the newest touch. Accessor and report failures are absorbed.
155
+ */
156
+ export function reportCacheTouch(sessionId, input) {
157
+ try {
158
+ const { at, ttlMs, source } = input;
159
+ if (!Number.isSafeInteger(at) ||
160
+ at < 0 ||
161
+ (ttlMs !== 'implicit' &&
162
+ (typeof ttlMs !== 'number' || !Number.isFinite(ttlMs) || ttlMs < 0)) ||
163
+ (source !== 'response' && source !== 'warm'))
164
+ return;
165
+ report(sessionId, { kind: 'cache_touch', at, ttl_ms: ttlMs, source });
166
+ }
167
+ catch {
168
+ // Optional reporting must never change the result of an auth request.
169
+ }
170
+ }
171
+ /**
172
+ * Call off the request path, after handing the reply to the host. Report only
173
+ * a session that actually warmed, never one that was off from the start.
174
+ * Synchronous fire-and-forget; failures are absorbed and never retried here.
175
+ */
176
+ export function reportCacheWarmStopped(sessionId, input) {
177
+ try {
178
+ const { at, reason } = input;
179
+ if (!Number.isSafeInteger(at) || at < 0 || typeof reason !== 'string')
180
+ return;
181
+ report(sessionId, { kind: 'cache_warm_stopped', at, reason });
182
+ }
183
+ catch {
184
+ // Optional reporting must never change the result of an auth request.
185
+ }
186
+ }
@@ -3,6 +3,8 @@
3
3
  * shaping. Account ids are vault account ids, not local pool rows. Nothing is
4
4
  * persisted here; plugins on routes the runner does not serve get no turn notes.
5
5
  */
6
+ export type { CacheTouchInput, CacheWarmStoppedInput, CacheWarmStopReason, SessionCacheHours, SessionCachePolicy, SessionCacheTtl, SessionKeepWarmMode, SessionToolWait, } from './cache-policy.js';
7
+ export { reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
6
8
  /** An eligible vault route, not a local pool row. */
7
9
  export interface RoutingCandidate {
8
10
  /** Vault account id, not the plugin's route id. */
@@ -94,4 +96,3 @@ export declare function askRouting<Candidate extends RoutingCandidate>(input: As
94
96
  * or redacted here.
95
97
  */
96
98
  export declare function reportRouting(input: ReportRoutingInput): void;
97
- export {};
@@ -4,6 +4,7 @@
4
4
  * persisted here; plugins on routes the runner does not serve get no turn notes.
5
5
  */
6
6
  import { routingHandle } from './handle.js';
7
+ export { reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
7
8
  function isObject(value) {
8
9
  return typeof value === 'object' && value !== null;
9
10
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.40.0",
3
+ "version": "0.41.0",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {