@cortexkit/common-auth 0.33.0 → 0.34.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.
Files changed (106) hide show
  1. package/dist/claustrum/consumer.d.ts +12 -0
  2. package/dist/claustrum/consumer.js +36 -0
  3. package/dist/claustrum/custody.d.ts +16 -4
  4. package/dist/claustrum/custody.js +74 -9
  5. package/dist/claustrum/hub.d.ts +3 -2
  6. package/dist/claustrum/hub.js +8 -0
  7. package/dist/claustrum/index.d.ts +1 -0
  8. package/dist/claustrum/roster.d.ts +2 -0
  9. package/dist/claustrum/roster.js +2 -0
  10. package/dist/claustrum/usage.d.ts +41 -0
  11. package/dist/claustrum/usage.js +145 -0
  12. package/dist/commands/builtins.d.ts +5 -0
  13. package/dist/commands/builtins.js +38 -0
  14. package/dist/fs/private-files.d.ts +5 -0
  15. package/dist/fs/private-files.js +7 -0
  16. package/dist/fs/refresh-file-lock.js +142 -47
  17. package/dist/fs/with-lock.js +2 -5
  18. package/dist/limits/activity.d.ts +26 -0
  19. package/dist/limits/activity.js +52 -0
  20. package/dist/limits/axes.d.ts +63 -0
  21. package/dist/limits/axes.js +7 -0
  22. package/dist/limits/bridge.d.ts +4 -0
  23. package/dist/limits/bridge.js +10 -0
  24. package/dist/limits/decide.d.ts +141 -0
  25. package/dist/limits/decide.js +383 -0
  26. package/dist/limits/duration.d.ts +8 -0
  27. package/dist/limits/duration.js +20 -0
  28. package/dist/limits/envelope-loss.d.ts +29 -0
  29. package/dist/limits/envelope-loss.js +150 -0
  30. package/dist/limits/families.d.ts +57 -0
  31. package/dist/limits/families.js +143 -0
  32. package/dist/limits/header-classifier.d.ts +9 -0
  33. package/dist/limits/header-classifier.js +121 -0
  34. package/dist/limits/hold.d.ts +13 -0
  35. package/dist/limits/hold.js +25 -0
  36. package/dist/limits/identity.d.ts +14 -0
  37. package/dist/limits/identity.js +21 -0
  38. package/dist/limits/index.d.ts +44 -0
  39. package/dist/limits/index.js +25 -0
  40. package/dist/limits/jitter.d.ts +2 -0
  41. package/dist/limits/jitter.js +9 -0
  42. package/dist/limits/labels.d.ts +3 -0
  43. package/dist/limits/labels.js +11 -0
  44. package/dist/limits/marker.d.ts +64 -0
  45. package/dist/limits/marker.js +96 -0
  46. package/dist/limits/merge-laws.d.ts +14 -0
  47. package/dist/limits/merge-laws.js +31 -0
  48. package/dist/limits/namespace.d.ts +89 -0
  49. package/dist/limits/namespace.js +183 -0
  50. package/dist/limits/persistence.d.ts +33 -0
  51. package/dist/limits/persistence.js +9 -0
  52. package/dist/limits/pi-wait.d.ts +16 -0
  53. package/dist/limits/pi-wait.js +51 -0
  54. package/dist/limits/pool-adapter.d.ts +16 -0
  55. package/dist/limits/pool-adapter.js +162 -0
  56. package/dist/limits/presets.d.ts +11 -0
  57. package/dist/limits/presets.js +223 -0
  58. package/dist/limits/registry.d.ts +49 -0
  59. package/dist/limits/registry.js +471 -0
  60. package/dist/limits/request-history.d.ts +77 -0
  61. package/dist/limits/request-history.js +117 -0
  62. package/dist/limits/reset.d.ts +21 -0
  63. package/dist/limits/reset.js +44 -0
  64. package/dist/limits/routing-hold.d.ts +16 -0
  65. package/dist/limits/routing-hold.js +23 -0
  66. package/dist/limits/scope.d.ts +12 -0
  67. package/dist/limits/scope.js +10 -0
  68. package/dist/limits/signal.d.ts +41 -0
  69. package/dist/limits/signal.js +1 -0
  70. package/dist/limits/terminal.d.ts +52 -0
  71. package/dist/limits/terminal.js +133 -0
  72. package/dist/limits/vault-adapter.d.ts +16 -0
  73. package/dist/limits/vault-adapter.js +123 -0
  74. package/dist/limits/vault.d.ts +1 -0
  75. package/dist/limits/vault.js +1 -0
  76. package/dist/limits/wake.d.ts +21 -0
  77. package/dist/limits/wake.js +47 -0
  78. package/dist/limits/wording.d.ts +25 -0
  79. package/dist/limits/wording.js +114 -0
  80. package/dist/opencode2/index.d.ts +1 -1
  81. package/dist/opencode2/install.d.ts +2 -2
  82. package/dist/opencode2/install.js +161 -18
  83. package/dist/opencode2/types.d.ts +95 -9
  84. package/dist/routing/admission.d.ts +7 -2
  85. package/dist/routing/admission.js +17 -7
  86. package/dist/routing-accessor/handle.d.ts +1 -0
  87. package/dist/routing-accessor/handle.js +10 -0
  88. package/dist/routing-accessor/index.d.ts +13 -3
  89. package/dist/routing-accessor/index.js +11 -10
  90. package/dist/rpc/port-file.d.ts +12 -3
  91. package/dist/rpc/port-file.js +46 -4
  92. package/dist/store/attribution.js +3 -2
  93. package/dist/store/errors.d.ts +1 -1
  94. package/dist/store/hooks.d.ts +5 -1
  95. package/dist/store/hooks.js +20 -5
  96. package/dist/store/index.d.ts +1 -0
  97. package/dist/store/limits-namespace.d.ts +7 -0
  98. package/dist/store/limits-namespace.js +34 -0
  99. package/dist/store/pool.d.ts +10 -1
  100. package/dist/store/pool.js +2 -0
  101. package/dist/store/provider-state.js +5 -5
  102. package/dist/store/refresh.js +1 -1
  103. package/dist/store/schema.js +9 -4
  104. package/dist/store/settings.d.ts +2 -0
  105. package/dist/store/settings.js +11 -4
  106. package/package.json +10 -2
@@ -1,5 +1,6 @@
1
1
  import type { Plugin } from '@opencode/plugin';
2
2
  import type { SessionRequestKind, SessionRetryDecision } from '@opencode/plugin/promise/session';
3
+ import type { WaitCheckpoint } from '../limits/decide.js';
3
4
  /** The parts of the OpenCode 2 plugin context the installer uses. */
4
5
  export type OpenCode2HookContext = {
5
6
  readonly session: Pick<Plugin.Context['session'], 'hook'>;
@@ -35,6 +36,8 @@ export interface EventVerdict<Q> {
35
36
  readonly outputStarted?: boolean;
36
37
  readonly quota?: Q;
37
38
  readonly limit?: LimitSignal;
39
+ /** Applies only to this attempt, after ownership and attribution checks. */
40
+ readonly hostRetry?: RetryDisposition['hostRetry'];
38
41
  /**
39
42
  * This is the last event of the response (completed or failed); the
40
43
  * attempt ends here. On WebSocket this is the only way an attempt ends
@@ -55,6 +58,16 @@ export type HeaderEdits = Readonly<Record<string, string | null>>;
55
58
  export interface ChooseAccountInput extends RequestScope {
56
59
  /** The retry hook's advance choice (which may hold), or a request's own choice. */
57
60
  readonly phase: 'retry' | 'request';
61
+ /** Retry hook draft's attempt count; also carried by a consumed hold's wake. */
62
+ readonly hostAttempt?: number;
63
+ /** Revalidate the held account before dispatch, even if the target is not due. */
64
+ readonly wake?: RetryWake;
65
+ /**
66
+ * Accounts refused by earlier reroutes of this logical request. Absent means
67
+ * empty. Holds and wakes do not exclude the held account. A snapshot, not a
68
+ * live set; supplied whether or not enforcement is enabled.
69
+ */
70
+ readonly excluded?: readonly string[];
58
71
  /**
59
72
  * The account of the attempt this one retries, when the retry hook just
60
73
  * asked the host to retry an attempt of this session and kind; otherwise
@@ -75,19 +88,43 @@ export interface ChooseAccountInput extends RequestScope {
75
88
  export interface AccountRequest extends RequestScope {
76
89
  readonly accountId: string;
77
90
  }
91
+ /** The held account is ChooseAccountInput.previousAccountId. */
92
+ export interface RetryWake {
93
+ readonly target: number;
94
+ readonly checkpoint?: WaitCheckpoint;
95
+ /** Terminal quota waits do not require the session's provider prompt-cache TTL. */
96
+ readonly kind?: 'hold' | 'terminal';
97
+ }
78
98
  /** An explicit retry on the refused account, without moving its routing pin. */
79
99
  export interface RetryHold {
80
100
  readonly hold: {
81
101
  /**
82
102
  * Adapter-computed wait in milliseconds, including per-session jitter.
83
- * Finite, non-negative values are clamped to MAX_RETRY_HOLD_MS (20 minutes).
84
- * Invalid values keep the host's decision and release the choice.
103
+ * Finite, non-negative values up to MAX_RETRY_HOLD_MS (3_621_000) are
104
+ * accepted. Larger or invalid values keep the host's decision and release
105
+ * the choice rather than dispatching before the requested wait has elapsed.
85
106
  */
86
107
  readonly delayMs: number;
108
+ /** An absolute wake target; its presence forces a request-phase re-check. */
109
+ readonly target?: number;
110
+ readonly checkpoint?: WaitCheckpoint;
111
+ /** Forwarded to wake.kind so terminal quota waits omit the cache bound. */
112
+ readonly kind?: RetryWake['kind'];
87
113
  };
88
114
  }
89
- /** Holds are valid only in phase `retry`, with a recognised account limit. */
90
- export type ChooseAccountResult = string | RetryHold | undefined;
115
+ /** Leave the host's retry decision alone, or forbid replay of this attempt. */
116
+ export interface RetryDisposition {
117
+ readonly hostRetry: 'leave' | 'veto';
118
+ }
119
+ /** Wait through one host retry, then choose afresh without reserving an account. */
120
+ export interface RetryWaitThenReselect {
121
+ readonly waitThenReselect: {
122
+ /** Same finite, non-negative delay bound as RetryHold.hold.delayMs. */
123
+ readonly delayMs: number;
124
+ };
125
+ }
126
+ /** Non-string choices are valid only in phase `retry`, after an account limit. */
127
+ export type ChooseAccountResult = string | RetryHold | RetryDisposition | RetryWaitThenReselect | undefined;
91
128
  /**
92
129
  * One physical send: created when an account is chosen for a request, and
93
130
  * handed back on every hook call and event that belongs to that send, so a
@@ -194,7 +231,7 @@ export interface SameAccountRetryResult {
194
231
  * quota reading type; the installer only carries it to the `quota` event.
195
232
  * `A` is the plugin's per-attempt value (see `Attempt`).
196
233
  * `Choice` defaults to the legacy ID-only result so existing adapters' direct
197
- * callers still see IDs. Opt into holds with `ChooseAccountResult`.
234
+ * callers still see IDs. Opt into retry directives with `ChooseAccountResult`.
198
235
  */
199
236
  export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends ChooseAccountResult = string | undefined> {
200
237
  /** Every hook is scoped to this provider; other providers are untouched. */
@@ -209,11 +246,24 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
209
246
  * After a limit before any output, the retry hook makes this call itself,
210
247
  * with `phase: 'retry'` and `rerouteFrom` set. Every returned account,
211
248
  * including the refused one, is kept for the next attempt of that session
212
- * and kind: it does not choose again. Another account retries at once;
249
+ * and kind: it does not choose again, except for a hold with a target.
250
+ * Another account retries at once;
213
251
  * the refused account keeps the host's decision and wait. `{ hold: { delayMs } }`
214
252
  * commits the refused account without changing its pin and replaces the host's
215
253
  * wait, even its no-retry decision, only for a recognised account limit before
216
- * output in an untainted session. Holds returned in phase `request` cannot
254
+ * output in a session with no foreign transport. A hold with a target releases its queued
255
+ * choice and calls again in phase `request` with `wake` and `hostAttempt`
256
+ * before fetching account headers. The adapter must check that the account
257
+ * is still eligible, still represents the same login, is still available
258
+ * from the credential store and has any required provider prompt-cache TTL
259
+ * remaining, then choose normally if invalid.
260
+ * A hold without a target takes the queued account as before.
261
+ * `{ hostRetry: 'veto' }` forbids replay; `'leave'` preserves the host's decision
262
+ * without reserving an account. `{ waitThenReselect: { delayMs } }` asks for one
263
+ * delayed host retry, then chooses afresh. It commits no account or routing pin.
264
+ * Like holds, its delay must fit MAX_RETRY_HOLD_MS and the host retry budget.
265
+ * These directives obey the same ownership, attribution and output fences.
266
+ * Non-string choices returned in phase `request` cannot
217
267
  * select an account and are treated as undefined. `undefined` or a
218
268
  * throw commits nothing: the host decides, and the next attempt chooses
219
269
  * with `phase: 'request'`, `previousAccountId` and no `rerouteFrom`.
@@ -222,7 +272,8 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
222
272
  /**
223
273
  * Releases a kept retry choice that will not be used: no retry, a changed
224
274
  * model or agent, cancellation of a queued retry (session idle), session forgetting/deletion,
225
- * disposal or record eviction. A hold releases the refused account's choice.
275
+ * disposal, record eviction or a targeted hold's wake re-check. A hold
276
+ * releases the refused account's choice.
226
277
  * Called once with the original choose input plus its returned accountId,
227
278
  * never for a used choice. Awaited before any later chooseAccount for the
228
279
  * same session; errors are logged and swallowed. A model/agent change
@@ -264,6 +315,21 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
264
315
  readonly response: Response;
265
316
  readonly attempt: Attempt<A>;
266
317
  }): Promise<Response | undefined> | Response | undefined;
318
+ /**
319
+ * Optional retry policy for the final HTTP response. Runs immediately after
320
+ * `rewriteResponse` (or on the unchanged response when no rewrite is returned).
321
+ * Return `veto` to forbid host replay of a refusal the adapter formatted,
322
+ * even without a recognised limit. A veto is sticky for this attempt.
323
+ * Ownership and attribution checks still run first: a veto cannot affect a
324
+ * foreign request, a session with mixed ownership, or a retry whose attempt is
325
+ * ambiguous. `leave` or `undefined` preserves the existing retry policy,
326
+ * including an earlier veto.
327
+ */
328
+ responseRetry?(input: AccountRequest & {
329
+ readonly request: Request;
330
+ readonly response: Response;
331
+ readonly attempt: Attempt<A>;
332
+ }): Promise<'leave' | 'veto' | undefined> | 'leave' | 'veto' | undefined;
267
333
  /**
268
334
  * Optional. For an adapter whose own sender can move a request to another
269
335
  * account after `rewriteRequest` (a bridge that answers a 401 or 403 by
@@ -435,6 +501,24 @@ export interface InstallOpenCode2AuthOptions {
435
501
  readonly hostCredentials?: readonly string[];
436
502
  /** Most attempts kept before the oldest is abandoned and dropped. */
437
503
  readonly maxRecords?: number;
504
+ /**
505
+ * Host retry budget, default 10. When hostAttempt leaves no retry available,
506
+ * limit holds and reroutes keep the host's decision and release their choice.
507
+ */
508
+ readonly hostRetryLimit?: number;
509
+ /**
510
+ * Reject chooser results naming a request-excluded account (default false).
511
+ * A rejected choice warns and acts like undefined: the host decides in retry,
512
+ * and request selection stops with no-account. Without this option, chooser
513
+ * results retain their existing meaning.
514
+ *
515
+ * The host supplies no logical request id. The first later attempt of the
516
+ * same session and kind consumes a queued retry's exclusions. If another
517
+ * attempt is in flight, that binding warns but keeps the exclusions. A new
518
+ * concurrent request can therefore inherit them; if it consumes the retry
519
+ * first, the actual retry instead starts a fresh token without them.
520
+ */
521
+ readonly enforceRequestExclusion?: boolean;
438
522
  readonly logger?: OpenCode2AuthLogger;
439
523
  }
440
524
  /**
@@ -449,13 +533,15 @@ export interface InstallOpenCode2AuthOptions {
449
533
  * (its wait, or its refusal to retry) stands and the next attempt may go
450
534
  * to the refused account again;
451
535
  * - `hold`: an explicit adapter wait on the refused account, before output;
536
+ * - `wait-then-reselect`: wait without reserving the next account;
537
+ * - `adapter-veto`: the attributed adapter disposition forbids host replay;
452
538
  * - `same-account`: the adapter requested immediate recovery on the same route,
453
539
  * without account selection, before output;
454
540
  * - `host-decides`: no limit was recognised, or the failing call cannot be
455
541
  * attributed safely (ambiguous attempts or mixed ownership in a gated
456
542
  * session), so the host's decision stands.
457
543
  */
458
- export type RetryReason = 'reroute' | 'hold' | 'same-account' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
544
+ export type RetryReason = 'reroute' | 'hold' | 'wait-then-reselect' | 'adapter-veto' | 'same-account' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
459
545
  /**
460
546
  * The hook that picked an account. Normally `model.request`; a transport hook
461
547
  * picks only when the host skipped `model.request` for that request, which a
@@ -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, once per refusal at gates 2 to 4, with the row id.
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 the refusal.
35
+ * starts from here cannot delay admission or a refusal.
31
36
  */
32
37
  requestPull?: (rowId: string) => void;
33
38
  }
@@ -14,7 +14,7 @@
14
14
  // 3. a required label with no entry is unknown: refused, pull requested;
15
15
  // 4. a reading at or beyond 100% whose reset is missing, unparsable or not
16
16
  // after `now` cannot confirm the exhaustion, so the window is unknown:
17
- // refused, pull requested;
17
+ // refused unless lifted for this wake dispatch; either way, pull requested;
18
18
  // 5. a reading at or beyond 100% with a future reset is exhausted: refused.
19
19
  // Gates 4 and 5 look at every projected limit, not only the required labels.
20
20
  // Stage 2 judges the credit budget across the stage-1 survivors: a row whose
@@ -36,7 +36,7 @@ export function exclusionFor(id, inputs, now) {
36
36
  }
37
37
  return undefined;
38
38
  }
39
- function judgeStageOne(id, projection, requiredLabels, now) {
39
+ function judgeStageOne(id, projection, requiredLabels, now, liftedWindows) {
40
40
  if (projection.limits.length === 0) {
41
41
  return {
42
42
  id,
@@ -60,7 +60,8 @@ function judgeStageOne(id, projection, requiredLabels, now) {
60
60
  }
61
61
  const exhausted = projection.limits.filter(readsExhausted);
62
62
  for (const limit of exhausted) {
63
- if (futureResetAt(limit, now) === undefined) {
63
+ if (futureResetAt(limit, now) === undefined &&
64
+ !liftedWindows.some((window) => window.scope === limit.scope && window.label === limit.label)) {
64
65
  return {
65
66
  id,
66
67
  stage: 1,
@@ -94,6 +95,7 @@ export function admit(input) {
94
95
  const excluded = [];
95
96
  const refused = [];
96
97
  const survivors = [];
98
+ const needsPull = new Set();
97
99
  for (const row of input.rows) {
98
100
  const exclusion = exclusionFor(row.id, input, input.now);
99
101
  if (exclusion) {
@@ -105,7 +107,12 @@ export function admit(input) {
105
107
  continue;
106
108
  }
107
109
  const projection = projectQuota(row.quota, scope);
108
- const refusal = judgeStageOne(row.id, projection, requiredLabels, input.now);
110
+ const lifted = input.liftedWindows?.get(row.id) ?? [];
111
+ if (projection.limits.some((limit) => readsExhausted(limit) &&
112
+ futureResetAt(limit, input.now) === undefined &&
113
+ lifted.some((window) => window.scope === limit.scope && window.label === limit.label)))
114
+ needsPull.add(row.id);
115
+ const refusal = judgeStageOne(row.id, projection, requiredLabels, input.now, lifted);
109
116
  if (refusal) {
110
117
  refused.push(refusal);
111
118
  continue;
@@ -133,9 +140,12 @@ export function admit(input) {
133
140
  const order = new Map(input.rows.map((row, index) => [row.id, index]));
134
141
  const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
135
142
  refused.sort(byInput);
136
- const pulls = refused
137
- .filter((refusal) => 'pullRequested' in refusal)
138
- .map((refusal) => refusal.id);
143
+ for (const refusal of refused)
144
+ if ('pullRequested' in refusal)
145
+ needsPull.add(refusal.id);
146
+ const pulls = input.rows
147
+ .filter((row) => needsPull.has(row.id))
148
+ .map((row) => row.id);
139
149
  for (const id of pulls)
140
150
  input.requestPull?.(id);
141
151
  return { admitted, refused, excluded, pulls };
@@ -0,0 +1 @@
1
+ export declare function routingHandle(sessionId: string): Record<string, unknown> | undefined;
@@ -0,0 +1,10 @@
1
+ export function routingHandle(sessionId) {
2
+ // The bridge can load after the auth plugin, so never cache the accessor.
3
+ const routing = Reflect.get(globalThis, Symbol.for('cortexkit.routing'));
4
+ if (typeof routing !== 'function')
5
+ return undefined;
6
+ const handle = routing(sessionId);
7
+ return typeof handle === 'object' && handle !== null
8
+ ? handle
9
+ : undefined;
10
+ }
@@ -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 `non-gemini`.
43
- * Must be a non-empty string without `:`. Omit to block the whole
44
- * account; include to block only this pool.
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,16 +1,9 @@
1
1
  // Optional THALAMUS routing for vault mode only. Account ids here are vault
2
2
  // account ids; local pool rows are not known to the routing engine.
3
+ import { routingHandle } from './handle.js';
3
4
  function isObject(value) {
4
5
  return typeof value === 'object' && value !== null;
5
6
  }
6
- function routingHandle(sessionId) {
7
- // The bridge can load after the auth plugin, so never cache the accessor.
8
- const routing = Reflect.get(globalThis, Symbol.for('cortexkit.routing'));
9
- if (typeof routing !== 'function')
10
- return undefined;
11
- const handle = routing(sessionId);
12
- return isObject(handle) ? handle : undefined;
13
- }
14
7
  function selectionFor(answer, candidates) {
15
8
  if (!isObject(answer))
16
9
  return undefined;
@@ -56,7 +49,15 @@ export async function askRouting(input) {
56
49
  timer = setTimeout(() => resolve(undefined), deadlineMs);
57
50
  timer.unref();
58
51
  });
59
- const pending = accountFor.call(handle, { provider: input.provider, modelId: input.modelId }, { deadlineMs });
52
+ const request = {
53
+ provider: input.provider,
54
+ modelId: input.modelId,
55
+ };
56
+ const cap = input.holdWaitMaxS;
57
+ if (typeof cap === 'number' && Number.isFinite(cap)) {
58
+ request.hold_wait_max_s = Math.max(0, Math.floor(cap));
59
+ }
60
+ const pending = accountFor.call(handle, request, { deadlineMs });
60
61
  if (!isObject(pending) || typeof pending.then !== 'function')
61
62
  return undefined;
62
63
  const answer = await Promise.race([pending, expired]);
@@ -100,7 +101,7 @@ export function reportRouting(input) {
100
101
  return;
101
102
  // An undefined pool means the whole account, as an omitted one does.
102
103
  if (pool !== undefined &&
103
- (typeof pool !== 'string' || pool.length === 0 || pool.includes(':')))
104
+ (typeof pool !== 'string' || !/^[a-z0-9._-]{1,64}$/.test(pool)))
104
105
  return;
105
106
  payload = {
106
107
  ...identity,
@@ -5,6 +5,11 @@ export interface PortFileEntry {
5
5
  pid: number;
6
6
  startedAt: number;
7
7
  }
8
+ interface PortFileClock {
9
+ /** Internal clock seams for deterministic boot-time checks. */
10
+ now?: () => number;
11
+ uptime?: () => number;
12
+ }
8
13
  export declare function createManagedRpcStateDirPredicate(directoryPrefix: string): (name: string) => boolean;
9
14
  export declare function isManagedRpcStateDir(name: string, directoryPrefix: string): boolean;
10
15
  export declare function getRpcDir(rpcRoot: string, directoryPrefix: string, projectDirectory: string): string;
@@ -18,8 +23,11 @@ export declare function writePortFile(dir: string, entry: {
18
23
  /** Test seam for forcing staging-name collisions; defaults to randomUUID. */
19
24
  stageName?: () => string;
20
25
  }): Promise<string>;
21
- export declare function sweepRpcState(root: string, activeDir: string, isManagedDir: (name: string) => boolean, log?: RpcLogChannel): Promise<void>;
22
- export interface DiscoverPortFileOptions {
26
+ export declare function sweepRpcState(root: string, activeDir: string, isManagedDir: (name: string) => boolean, log?: RpcLogChannel, options?: PortFileClock & {
27
+ /** Internal seam for replacing a stale record before its identity recheck. */
28
+ beforeRemove?: (path: string) => void | Promise<void>;
29
+ }): Promise<void>;
30
+ export interface DiscoverPortFileOptions extends PortFileClock {
23
31
  /**
24
32
  * Return only the expected PID's entry, or null; never fall back to
25
33
  * another live server. Without an expected PID nothing matches, so the
@@ -29,5 +37,6 @@ export interface DiscoverPortFileOptions {
29
37
  exactPid?: boolean;
30
38
  }
31
39
  /** Internal cache validation: probe only the selected file and its PID. */
32
- export declare function portFileIdentity(dir: string, entry: PortFileEntry): Promise<string | null>;
40
+ export declare function portFileIdentity(dir: string, entry: PortFileEntry, options?: PortFileClock): Promise<string | null>;
33
41
  export declare function discoverPortFile(dir: string, expectedPid?: number, options?: DiscoverPortFileOptions): Promise<PortFileEntry | null>;
42
+ export {};
@@ -1,7 +1,36 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { chmod, mkdir, open, readdir, rename, rmdir, stat, unlink, } from 'node:fs/promises';
3
+ import { uptime } from 'node:os';
3
4
  import { join, resolve } from 'node:path';
4
5
  import { ensurePrivateDirectory, PrivateFileError, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from '../fs/private-files.js';
6
+ function staleBefore(clock) {
7
+ // A five-minute margin favors keeping a live record when clocks are uncertain.
8
+ return (clock.now ?? Date.now)() - (clock.uptime ?? uptime)() * 1000 - 300_000;
9
+ }
10
+ function isStalePortFile(entry, info, cutoff) {
11
+ const time = entry.startedAt === undefined ? info?.mtimeMs : entry.startedAt;
12
+ return typeof time === 'number' && Number.isFinite(time) && time < cutoff;
13
+ }
14
+ async function removeStalePortFile(path, raw, info, beforeRemove) {
15
+ if (!info)
16
+ return;
17
+ await beforeRemove?.(path);
18
+ try {
19
+ // A live PID may have replaced its old record while the sweep was reading it.
20
+ const current = await readPrivateText(path);
21
+ const identity = await stat(path);
22
+ if (current === raw &&
23
+ identity.dev === info.dev &&
24
+ identity.ino === info.ino &&
25
+ identity.mtimeMs === info.mtimeMs &&
26
+ identity.size === info.size)
27
+ await unlink(path).catch(() => { });
28
+ }
29
+ catch (error) {
30
+ if (error instanceof PrivateFileError && error.code !== 'ENOENT')
31
+ throw error;
32
+ }
33
+ }
5
34
  /**
6
35
  * A PID a liveness probe may address. `process.kill(0 | negative, 0)` signals
7
36
  * a process group rather than a process, and an unsafe integer cannot name a
@@ -117,7 +146,8 @@ export async function writePortFile(dir, entry, options = {}) {
117
146
  throw error;
118
147
  }
119
148
  }
120
- export async function sweepRpcState(root, activeDir, isManagedDir, log) {
149
+ export async function sweepRpcState(root, activeDir, isManagedDir, log, options = {}) {
150
+ const cutoff = staleBefore(options);
121
151
  let projectDirs;
122
152
  try {
123
153
  projectDirs = await readdir(root, { withFileTypes: true });
@@ -146,6 +176,7 @@ export async function sweepRpcState(root, activeDir, isManagedDir, log) {
146
176
  if (!name.startsWith('port-') || !name.endsWith('.json'))
147
177
  continue;
148
178
  const portFile = join(dir, name);
179
+ const info = await stat(portFile).catch(() => undefined);
149
180
  let raw;
150
181
  try {
151
182
  raw = await readPrivateText(portFile);
@@ -172,13 +203,16 @@ export async function sweepRpcState(root, activeDir, isManagedDir, log) {
172
203
  const entry = parsed;
173
204
  if (!pidAlive(entry.pid))
174
205
  await unlink(portFile).catch(() => { });
206
+ else if (isStalePortFile(entry, info, cutoff))
207
+ await removeStalePortFile(portFile, raw, info, options.beforeRemove);
175
208
  }
176
209
  if (resolve(dir) !== active)
177
210
  await rmdir(dir).catch(() => { });
178
211
  }
179
212
  }
180
213
  /** Internal cache validation: probe only the selected file and its PID. */
181
- export async function portFileIdentity(dir, entry) {
214
+ export async function portFileIdentity(dir, entry, options = {}) {
215
+ const cutoff = staleBefore(options);
182
216
  if (!pidAlive(entry.pid))
183
217
  return null;
184
218
  const path = join(resolve(dir), `port-${entry.pid}.json`);
@@ -186,6 +220,8 @@ export async function portFileIdentity(dir, entry) {
186
220
  if (windowsPrivateFiles)
187
221
  await verifyPrivate(path, 'file');
188
222
  const info = await stat(path);
223
+ if (isStalePortFile(entry, info, cutoff))
224
+ return null;
189
225
  return `${path}:${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`;
190
226
  }
191
227
  catch (error) {
@@ -195,6 +231,7 @@ export async function portFileIdentity(dir, entry) {
195
231
  }
196
232
  }
197
233
  export async function discoverPortFile(dir, expectedPid, options = {}) {
234
+ const cutoff = staleBefore(options);
198
235
  let names;
199
236
  try {
200
237
  if (windowsPrivateFiles)
@@ -213,8 +250,13 @@ export async function discoverPortFile(dir, expectedPid, options = {}) {
213
250
  try {
214
251
  const parsed = JSON.parse(await readPrivateText(join(dir, name)));
215
252
  if (isUsablePortFileEntry(parsed, name)) {
216
- if (pidAlive(parsed.pid))
217
- live.push(parsed);
253
+ if (pidAlive(parsed.pid)) {
254
+ const info = parsed.startedAt === undefined
255
+ ? await stat(join(dir, name)).catch(() => undefined)
256
+ : undefined;
257
+ if (!isStalePortFile(parsed, info, cutoff))
258
+ live.push(parsed);
259
+ }
218
260
  else
219
261
  await unlink(join(dir, name)).catch(() => { });
220
262
  }
@@ -1,4 +1,5 @@
1
1
  import { PoolOperationError } from './errors.js';
2
+ import { runInsideCodec } from './hooks.js';
2
3
  import { toFailure, withTransaction, } from './mutate.js';
3
4
  import { LockStack } from './refresh-lock.js';
4
5
  import { refusal, requireBound, unknownRow, } from './runtime.js';
@@ -31,8 +32,8 @@ export function assertQuotaRow(id, attribution, row) {
31
32
  });
32
33
  }
33
34
  export function mergedQuota(ctx, id, stored, observation) {
34
- const merged = ctx.codec.merge(stored, observation);
35
- if (!ctx.codec.validate(merged))
35
+ const merged = runInsideCodec(() => ctx.codec.merge(stored, observation));
36
+ if (!runInsideCodec(() => ctx.codec.validate(merged)))
36
37
  throw refusal('pull', id, 'invalid-quota', 'the quota codec rejected the merged map');
37
38
  return merged;
38
39
  }
@@ -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
- export declare function runInsideHook<T>(operation: PoolOperation, fn: () => Promise<T> | T): Promise<T>;
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
  }
@@ -1,18 +1,33 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { PoolReentryError } from './errors.js';
3
3
  /**
4
- * Set while a hook of a lock-holding operation runs. Async context is
5
- * inherited by every timer, promise and continuation created inside the hook,
4
+ * Set while a store hook runs, recording whether its store locks are released.
5
+ * Async context is inherited by every timer, promise and continuation inside the hook,
6
6
  * so work a hook schedules is inside the guarded region too.
7
7
  */
8
8
  const insideHook = new AsyncLocalStorage();
9
+ const insideCodec = new AsyncLocalStorage();
9
10
  /** Refuses a row operation or refresh called from inside a hook. */
10
11
  export function assertNotInsideHook(operation) {
11
12
  if (insideHook.getStore() !== undefined)
12
13
  throw new PoolReentryError(operation);
13
14
  }
14
- export function runInsideHook(operation, fn) {
15
- return insideHook.run(operation, async () => await fn());
15
+ /** Namespace writes need only the store locks, not the row lock a hook may retain. */
16
+ export function assertLimitsWriteAllowed() {
17
+ if (insideHook.getStore()?.storeLocksReleased === false ||
18
+ insideCodec.getStore())
19
+ throw new PoolReentryError('updateLimitsNamespace');
20
+ }
21
+ /** Codecs may run under store locks even when no asynchronous hook is active. */
22
+ export function runInsideCodec(fn) {
23
+ return insideCodec.run(true, fn);
24
+ }
25
+ export function runInsideHook(operation, fn, storeLocksReleased = false) {
26
+ return insideHook.run({
27
+ operation,
28
+ storeLocksReleased: storeLocksReleased &&
29
+ insideHook.getStore()?.storeLocksReleased !== false,
30
+ }, async () => await fn());
16
31
  }
17
32
  /**
18
33
  * Runs a failure hook. A hook that throws never replaces the failure it was
@@ -22,7 +37,7 @@ export async function callFailureHook(operation, hook, rowId, error, logger) {
22
37
  if (!hook)
23
38
  return;
24
39
  try {
25
- await runInsideHook(operation, () => hook(rowId, error));
40
+ await runInsideHook(operation, () => hook(rowId, error), true);
26
41
  }
27
42
  catch (hookError) {
28
43
  logger?.warn('store failure hook threw; the original failure stands', {
@@ -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>;
@@ -0,0 +1,34 @@
1
+ import { writeJsonAtomic } from '../fs/atomic-write.js';
2
+ import { assertLimitsWriteAllowed, runInsideHook } from './hooks.js';
3
+ import { notReadyError, readPool, runOperation } from './mutate.js';
4
+ /** A namespace merge and its check of current row bindings share one locked config snapshot. */
5
+ export async function updatePoolLimitsNamespace(rt, mutator) {
6
+ assertLimitsWriteAllowed();
7
+ const { ctx } = rt;
8
+ await runOperation(ctx, 'updateLimitsNamespace', undefined, undefined, async (locks, progress) => {
9
+ for (const spec of ctx.storeLocks)
10
+ await locks.acquire(spec);
11
+ const result = await readPool(ctx);
12
+ if (result.status !== 'ready')
13
+ throw notReadyError(result, 'updateLimitsNamespace', undefined);
14
+ const rows = result.rows.map(({ id, credentialEpoch, identity }) => ({
15
+ id,
16
+ credentialEpoch,
17
+ identity,
18
+ }));
19
+ const envelope = await runInsideHook('updateLimitsNamespace', () => mutator(structuredClone(result.config.commonAuthLimits), rows));
20
+ const config = { ...result.config, commonAuthLimits: envelope };
21
+ const info = {
22
+ operation: 'updateLimitsNamespace',
23
+ rowId: undefined,
24
+ };
25
+ await writeJsonAtomic(ctx.configPath, config, {
26
+ beforeRename: async () => {
27
+ await ctx.onStep?.('before-config-write', info);
28
+ await locks.assertAll();
29
+ },
30
+ });
31
+ progress.writes++;
32
+ await ctx.onStep?.('after-config-write', info);
33
+ });
34
+ }