@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,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { lstat, mkdir, open, readFile, rename, rm, stat, } from 'node:fs/promises';
3
3
  import { dirname, join } from 'node:path';
4
- import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from './private-files.js';
4
+ import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, isWindowsSharingViolation, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from './private-files.js';
5
5
  import { LockOwnershipError, lockPathFor } from './with-lock.js';
6
6
  /**
7
7
  * Create a new owner-only file and write `text` into it, failing with EEXIST if
@@ -367,54 +367,109 @@ export async function acquireRefreshFileLockWithClock(options) {
367
367
  else
368
368
  await rm(path, { recursive: true, force: true }).catch(() => { });
369
369
  }
370
- async function releaseEvictionMarker() {
371
- if (await ownsEvictionMarker()) {
372
- await removeLeaseObject(evictPath);
370
+ function isRetryableRemoval(error, path) {
371
+ if (!windowsPrivateFiles ||
372
+ !(error instanceof PrivateFileError) ||
373
+ error.stage !== 'remove' ||
374
+ error.path !== path)
375
+ return false;
376
+ // Native sharing/delete-pending errors use isWindowsSharingViolation.
377
+ // node:fs rm supplies only errno: EBUSY/EPERM can also mean a sharing refusal.
378
+ return (isWindowsSharingViolation(error) ||
379
+ (error.win32Code === undefined &&
380
+ error.reason === undefined &&
381
+ (error.code === 'EBUSY' || error.code === 'EPERM')));
382
+ }
383
+ async function removeOwnedLeaseObject(path, stillOwned, deadline = performance.now() + EVICT_TTL + 1_000) {
384
+ let original;
385
+ let delayMs = 5;
386
+ while (await stillOwned()) {
387
+ try {
388
+ await removeLeaseObject(path);
389
+ return;
390
+ }
391
+ catch (error) {
392
+ if (!isRetryableRemoval(error, path))
393
+ throw error;
394
+ original ??= error;
395
+ }
396
+ const remainingMs = deadline - performance.now();
397
+ if (remainingMs <= 0)
398
+ throw original;
399
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delayMs, remainingMs)));
400
+ if (performance.now() >= deadline)
401
+ throw original;
402
+ delayMs = Math.min(delayMs * 2, 50);
373
403
  }
374
404
  }
405
+ async function releaseEvictionMarker(deadline) {
406
+ let ownedDirectory;
407
+ await removeOwnedLeaseObject(evictPath, async () => {
408
+ if (!windowsPrivateFiles)
409
+ return ownsEvictionMarker();
410
+ const current = await lstat(evictPath).catch((error) => {
411
+ if (error.code !== 'ENOENT')
412
+ throw error;
413
+ return undefined;
414
+ });
415
+ if (!current ||
416
+ (ownedDirectory && !sameMarkerDirectory(ownedDirectory, current)))
417
+ return false;
418
+ if (await ownsEvictionMarker()) {
419
+ ownedDirectory = current;
420
+ return true;
421
+ }
422
+ if (!ownedDirectory)
423
+ return false;
424
+ // Recursive rm can delete owner.json before the directory delete fails.
425
+ // Only that same, now-ownerless directory is still ours to clean up.
426
+ try {
427
+ await stat(evictOwnerPath);
428
+ return false;
429
+ }
430
+ catch (error) {
431
+ if (error.code !== 'ENOENT')
432
+ throw error;
433
+ return true;
434
+ }
435
+ }, deadline);
436
+ }
375
437
  // Returns whether the directory at the marker path was still the one this
376
438
  // process created when its owner write failed. Only then is the failure ours
377
439
  // to report: a gone or replaced directory is a lost race.
378
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
440
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
379
441
  // Best effort only: never throws, so the original owner-write error below
380
442
  // keeps explaining the failure. Removes the directory this process just
381
443
  // created when its owner write failed, and leaves a contender's
382
444
  // replacement alone when the identities differ.
383
445
  if (!created)
384
446
  return false;
385
- let current;
386
- try {
387
- const st = await lstat(evictPath);
388
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
389
- }
390
- catch {
391
- // Renamed away by a contender's steal: nothing of ours left to clean.
392
- return false;
393
- }
394
- if (!sameMarkerDirectory(created, current))
395
- return false;
396
- // Remove only an ownerless directory. An owner file that appeared after
397
- // our failed write belongs to someone: ours goes through
398
- // releaseEvictionMarker in the caller, and a contender's must stay, since
399
- // it may be holding the marker right now.
447
+ let stillOurs = false;
400
448
  try {
401
- await stat(evictOwnerPath);
402
- return true;
403
- }
404
- catch (error) {
405
- if (error.code !== 'ENOENT')
406
- return true;
407
- }
408
- try {
409
- await removeLeaseObject(evictPath);
449
+ await removeOwnedLeaseObject(evictPath, async () => {
450
+ stillOurs = false;
451
+ const st = await lstat(evictPath).catch(() => undefined);
452
+ if (!st || !sameMarkerDirectory(created, st))
453
+ return false;
454
+ stillOurs = true;
455
+ // Recheck both identity and absence of an owner before every attempt;
456
+ // a contender's replacement or newly published owner must stay.
457
+ try {
458
+ await stat(evictOwnerPath);
459
+ return false;
460
+ }
461
+ catch (error) {
462
+ return error.code === 'ENOENT';
463
+ }
464
+ }, deadline);
410
465
  }
411
466
  catch {
412
467
  // A removal failure keeps the stale marker recoverable later; it must
413
468
  // never mask the original owner-write error.
414
469
  }
415
- return true;
470
+ return stillOurs;
416
471
  }
417
- async function tryAcquireEvictionMarker() {
472
+ async function tryAcquireEvictionMarker(deadline) {
418
473
  if (windowsPrivateFiles)
419
474
  await createPrivateDirectoryExclusive(evictPath);
420
475
  else
@@ -455,11 +510,11 @@ export async function acquireRefreshFileLockWithClock(options) {
455
510
  // A race code while our own directory is still in place is not a lost
456
511
  // race but a write that fails here every time: report it, rather than
457
512
  // retrying the same failure until a deadline hides the cause.
458
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
513
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
459
514
  if (isLostMarkerRaceError(error) && !stillOurs)
460
515
  return false;
461
516
  try {
462
- await releaseEvictionMarker();
517
+ await releaseEvictionMarker(deadline);
463
518
  }
464
519
  catch {
465
520
  // Removal must never mask the original owner-write error.
@@ -470,7 +525,7 @@ export async function acquireRefreshFileLockWithClock(options) {
470
525
  await options.onStep('eviction-marker-acquired');
471
526
  return true;
472
527
  }
473
- async function recoverStaleEvictionMarker() {
528
+ async function recoverStaleEvictionMarker(deadline) {
474
529
  let evictStat;
475
530
  try {
476
531
  evictStat = await stat(evictPath);
@@ -529,12 +584,26 @@ export async function acquireRefreshFileLockWithClock(options) {
529
584
  }
530
585
  if (options.onStep)
531
586
  await options.onStep('stale-marker-claimed');
532
- await removeLeaseObject(claimedPath);
587
+ const claimedIdentity = windowsPrivateFiles
588
+ ? await lstat(claimedPath)
589
+ : undefined;
590
+ // The unique renamed claim is ours, not the current marker path where a
591
+ // successor may already be working.
592
+ await removeOwnedLeaseObject(claimedPath, async () => {
593
+ if (!claimedIdentity)
594
+ return true;
595
+ const current = await lstat(claimedPath).catch((error) => {
596
+ if (error.code !== 'ENOENT')
597
+ throw error;
598
+ return undefined;
599
+ });
600
+ return !!current && sameMarkerDirectory(claimedIdentity, current);
601
+ }, deadline);
533
602
  return 'recovered';
534
603
  }
535
- async function withEvictionMarker(action) {
604
+ async function withEvictionMarker(action, deadline) {
536
605
  try {
537
- if (!(await tryAcquireEvictionMarker()))
606
+ if (!(await tryAcquireEvictionMarker(deadline)))
538
607
  return false;
539
608
  }
540
609
  catch (error) {
@@ -555,12 +624,28 @@ export async function acquireRefreshFileLockWithClock(options) {
555
624
  }
556
625
  throw error;
557
626
  }
627
+ let actionFailed = false;
628
+ let actionError;
558
629
  try {
559
630
  await action();
560
631
  }
561
- finally {
562
- await releaseEvictionMarker();
632
+ catch (error) {
633
+ actionFailed = true;
634
+ actionError = error;
635
+ }
636
+ try {
637
+ await releaseEvictionMarker(deadline);
638
+ }
639
+ catch (error) {
640
+ // Cleanup sharing failures must not replace the lock's original
641
+ // sharing refusal when both removals exhaust the same deadline.
642
+ if (isRetryableRemoval(actionError, lockPath) &&
643
+ isRetryableRemoval(error, evictPath))
644
+ throw actionError;
645
+ throw error;
563
646
  }
647
+ if (actionFailed)
648
+ throw actionError;
564
649
  return true;
565
650
  }
566
651
  // Marker loss after a write may mean another contender has taken over.
@@ -847,6 +932,7 @@ export async function acquireRefreshFileLockWithClock(options) {
847
932
  // wall-clock adjustments cannot extend the retry deadline.
848
933
  const deadline = performance.now() + EVICT_TTL + 1_000;
849
934
  let delayMs = 5;
935
+ let removalError;
850
936
  for (;;) {
851
937
  try {
852
938
  let removalConfirmed = false;
@@ -873,7 +959,7 @@ export async function acquireRefreshFileLockWithClock(options) {
873
959
  return;
874
960
  await removeLeaseObject(lockPath);
875
961
  removalConfirmed = true;
876
- });
962
+ }, deadline);
877
963
  if (markerAcquired) {
878
964
  if (windowsPrivateFiles && !removalConfirmed)
879
965
  throw new PrivateFileError(lockPath, 'release-not-confirmed', {
@@ -884,25 +970,34 @@ export async function acquireRefreshFileLockWithClock(options) {
884
970
  }
885
971
  if (signal?.aborted)
886
972
  return;
887
- await recoverStaleEvictionMarker();
973
+ await recoverStaleEvictionMarker(deadline);
888
974
  }
889
975
  catch (error) {
890
- if (windowsPrivateFiles)
891
- throw error;
892
- return;
976
+ if (!isRetryableRemoval(error, lockPath)) {
977
+ if (windowsPrivateFiles)
978
+ throw error;
979
+ return;
980
+ }
981
+ // Like rename, a fenced delete can be refused by a reader's Windows
982
+ // handle without invalidating ownership. Drop the marker, back off,
983
+ // and re-confirm the owner under a new marker before trying again.
984
+ removalError ??= error;
893
985
  }
894
986
  const remainingMs = deadline - performance.now();
895
987
  if (remainingMs <= 0)
896
988
  break;
897
989
  await new Promise((resolve) => setTimeout(resolve, Math.min(delayMs, remainingMs)));
990
+ if (windowsPrivateFiles && performance.now() >= deadline)
991
+ break;
898
992
  delayMs = Math.min(delayMs * 2, 50);
899
993
  }
900
994
  // Do not delete by pathname without the marker: bounded retries leave the
901
995
  // lease to expire rather than risking removal of a successor's lock.
902
996
  if (windowsPrivateFiles)
903
- throw new PrivateFileError(lockPath, 'release-not-confirmed', {
904
- code: 'ETIMEDOUT',
905
- });
997
+ throw (removalError ??
998
+ new PrivateFileError(lockPath, 'release-not-confirmed', {
999
+ code: 'ETIMEDOUT',
1000
+ }));
906
1001
  },
907
1002
  };
908
1003
  }
@@ -1,5 +1,5 @@
1
1
  import { join, resolve } from 'node:path';
2
- import { PrivateFileError, windowsPrivateFiles } from './private-files.js';
2
+ import { isWindowsSharingViolation, } from './private-files.js';
3
3
  import { acquireRefreshFileLock } from './refresh-file-lock.js';
4
4
  export function lockPathFor(target, name) {
5
5
  return `${target}.${name}.lock`;
@@ -21,10 +21,7 @@ export class LockOwnershipError extends Error {
21
21
  }
22
22
  }
23
23
  function isChangingLockRead(error, target, name) {
24
- if (!windowsPrivateFiles ||
25
- !(error instanceof PrivateFileError) ||
26
- error.reason !== 'io-error' ||
27
- (error.win32Code !== 32 && error.win32Code !== 303) ||
24
+ if (!isWindowsSharingViolation(error) ||
28
25
  (error.stage !== 'read' && error.stage !== 'verify'))
29
26
  return false;
30
27
  const path = resolve(lockPathFor(target, name));
@@ -0,0 +1,26 @@
1
+ import type { AccountKey } from './signal.js';
2
+ export interface SessionActivity {
3
+ readonly accountKey: AccountKey;
4
+ readonly lastAcceptedAt: number;
5
+ readonly ttlMs: number;
6
+ }
7
+ export interface AcceptedActivity {
8
+ readonly sessionId: string;
9
+ readonly accountKey: AccountKey;
10
+ /** The authoritative account key at completion, not the key at request start. */
11
+ readonly currentAccountKey: AccountKey;
12
+ readonly lastAcceptedAt: number;
13
+ /** TTLs of prompt segments cached by this response, or their single longest TTL. */
14
+ readonly ttlMs?: number | readonly number[];
15
+ }
16
+ export interface SessionActivityStore {
17
+ readonly size: number;
18
+ /** Call for accepted responses and successful (2xx) keep-warm prewarms. */
19
+ recordAccepted(input: AcceptedActivity): boolean;
20
+ get(sessionId: string): SessionActivity | undefined;
21
+ /** Call both when forgetting a session and when the host deletes it. */
22
+ forgetSession(sessionId: string): void;
23
+ }
24
+ export declare function effectiveCacheTtlMs(ttlMs: number | undefined): number;
25
+ /** One process-local cache record per session; no credential or store I/O. */
26
+ export declare function createSessionActivityStore(): SessionActivityStore;
@@ -0,0 +1,52 @@
1
+ import { sameAccount } from './request-history.js';
2
+ export function effectiveCacheTtlMs(ttlMs) {
3
+ return ttlMs !== undefined && Number.isFinite(ttlMs) && ttlMs >= 0
4
+ ? ttlMs
5
+ : 300000;
6
+ }
7
+ /** One process-local cache record per session; no credential or store I/O. */
8
+ export function createSessionActivityStore() {
9
+ const records = new Map();
10
+ return {
11
+ get size() {
12
+ return records.size;
13
+ },
14
+ recordAccepted(input) {
15
+ if (!sameAccount(input.accountKey, input.currentAccountKey) ||
16
+ !Number.isFinite(input.lastAcceptedAt))
17
+ return false;
18
+ const previous = records.get(input.sessionId);
19
+ // Late completions must not replace more recent accepted cache activity.
20
+ if (previous && previous.lastAcceptedAt > input.lastAcceptedAt)
21
+ return false;
22
+ const ttls = typeof input.ttlMs === 'number' ? [input.ttlMs] : input.ttlMs;
23
+ const ttlMs = ttls?.length
24
+ ? Math.max(...ttls.map(effectiveCacheTtlMs))
25
+ : effectiveCacheTtlMs(undefined);
26
+ records.set(input.sessionId, Object.freeze({
27
+ accountKey: Object.freeze({ ...input.accountKey }),
28
+ lastAcceptedAt: input.lastAcceptedAt,
29
+ ttlMs,
30
+ }));
31
+ if (records.size > 256) {
32
+ let oldest;
33
+ let acceptedAt = Number.POSITIVE_INFINITY;
34
+ for (const [sessionId, record] of records) {
35
+ if (record.lastAcceptedAt < acceptedAt) {
36
+ oldest = sessionId;
37
+ acceptedAt = record.lastAcceptedAt;
38
+ }
39
+ }
40
+ if (oldest !== undefined)
41
+ records.delete(oldest);
42
+ }
43
+ return true;
44
+ },
45
+ get(sessionId) {
46
+ return records.get(sessionId);
47
+ },
48
+ forgetSession(sessionId) {
49
+ records.delete(sessionId);
50
+ },
51
+ };
52
+ }
@@ -0,0 +1,63 @@
1
+ import type { HostRetry, RefusalFamily } from './families.js';
2
+ import type { LimitMark, MarkerAxes } from './marker.js';
3
+ import type { FamilyOf } from './scope.js';
4
+ export type LimitHost = 'opencode1' | 'opencode2' | 'pi';
5
+ export type HostValues<T> = Readonly<Record<LimitHost, T>>;
6
+ export type RefusalReason = 'auth' | 'quota' | 'incomplete' | 'model-unavailable';
7
+ export type DecisionFamily = RefusalFamily | 'local-auth' | 'native-vault-refusal' | 'no-account';
8
+ export interface RefusalPolicy {
9
+ readonly family: DecisionFamily;
10
+ readonly messageKey: string;
11
+ readonly retryable: boolean;
12
+ readonly hostRetry: HostRetry;
13
+ }
14
+ export interface UnknownLimitPolicy {
15
+ readonly action: 'retain' | 'reselect' | 'pass';
16
+ readonly affinity: 'always' | 'sticky';
17
+ readonly hint: 'none' | 'minimum';
18
+ readonly defaultMs: number;
19
+ }
20
+ /** Policies consume already parsed, applicable evidence, never provider names. */
21
+ export interface LimitAxes {
22
+ readonly evidence: 'per-field-overlay' | 'typed' | 'named-window' | 'hints-only';
23
+ readonly markers: HostValues<MarkerAxes>;
24
+ readonly readingClearsCoveredScopes: 'on' | 'off';
25
+ readonly successClearsCoveredScopes: 'on' | 'off';
26
+ readonly unknown: HostValues<UnknownLimitPolicy>;
27
+ readonly shortLimit: {
28
+ readonly holdBound: 'cache-ttl' | 'disabled';
29
+ readonly preference: 'same-account-first' | 'ready-alternative-first';
30
+ readonly jitter: 'session-sha256' | 'none';
31
+ };
32
+ /** Bounded retention is not an adopted policy. */
33
+ readonly retainBound: 'none';
34
+ readonly poolWaiting: {
35
+ readonly kind: 'off';
36
+ } | {
37
+ readonly kind: 'earliest';
38
+ readonly budgetMs: number;
39
+ readonly requestDeadlineMs: number;
40
+ readonly hardFallbackMs: number;
41
+ readonly singleEligibleSoftExemption: boolean;
42
+ };
43
+ readonly execution: 'host' | 'engine';
44
+ readonly requestExclusion: 'on' | 'off';
45
+ readonly advance: HostValues<{
46
+ readonly statuses: readonly number[];
47
+ readonly attributedLimitOnly: boolean;
48
+ }>;
49
+ readonly markedPool: {
50
+ readonly requestEscape: 'off' | 'ignore-timed-marks-if-all-marked';
51
+ readonly retryExhaustion: 'terminal' | 'same-host-delay' | 'host-delay';
52
+ };
53
+ readonly terminalMetadata: 'setting-capped-fresh' | 'baseline';
54
+ readonly terminalPolicy: 'provided' | 'pool' | 'status-history';
55
+ /** Required when selecting status-history; other terminal policies ignore it. */
56
+ readonly terminalStatusHistory?: {
57
+ readonly minRetryMs: number;
58
+ readonly defaultRetryMs: number;
59
+ };
60
+ readonly refusals: Readonly<Record<RefusalReason, HostValues<RefusalPolicy>>>;
61
+ }
62
+ /** The caller supplies only this account's marks; other models remain blocked. */
63
+ export declare function marksAfterSuccess<T extends LimitMark>(marks: readonly T[], axes: Pick<LimitAxes, 'successClearsCoveredScopes'>, model: string, familyOf: FamilyOf): readonly T[];
@@ -0,0 +1,7 @@
1
+ import { scopeCovers } from './scope.js';
2
+ /** The caller supplies only this account's marks; other models remain blocked. */
3
+ export function marksAfterSuccess(marks, axes, model, familyOf) {
4
+ return axes.successClearsCoveredScopes === 'off'
5
+ ? marks
6
+ : marks.filter((mark) => !scopeCovers(mark.scope, model, familyOf));
7
+ }
@@ -0,0 +1,4 @@
1
+ import type { LimitSignal as OpenCode2LimitSignal } from '../opencode2/types.js';
2
+ import type { LimitSignal } from './signal.js';
3
+ /** Pass only reason, status and retryAfterMs to the existing OpenCode 2 adapter. */
4
+ export declare function toOpenCode2LimitSignal(signal: LimitSignal): OpenCode2LimitSignal;
@@ -0,0 +1,10 @@
1
+ /** Pass only reason, status and retryAfterMs to the existing OpenCode 2 adapter. */
2
+ export function toOpenCode2LimitSignal(signal) {
3
+ return {
4
+ reason: signal.reason,
5
+ ...(signal.status === undefined ? {} : { status: signal.status }),
6
+ ...(signal.retryAfterMs === undefined
7
+ ? {}
8
+ : { retryAfterMs: signal.retryAfterMs }),
9
+ };
10
+ }
@@ -0,0 +1,141 @@
1
+ import type { DecisionFamily, LimitAxes, LimitHost, RefusalReason } from './axes.js';
2
+ import type { HostRetry } from './families.js';
3
+ import type { RequestHistory } from './request-history.js';
4
+ import { REQUEST_EXCLUSION_EFFECTS } from './request-history.js';
5
+ import type { Scope } from './scope.js';
6
+ import type { AccountKey, LimitSignal, LimitWindow } from './signal.js';
7
+ import type { TerminalScanFacts } from './terminal.js';
8
+ import type { WakeFacts } from './wake.js';
9
+ export interface TimedBlocker {
10
+ readonly kind: 'hard' | 'cooldown' | 'soft';
11
+ readonly until?: number;
12
+ }
13
+ /**
14
+ * Admission includes the caller's minimum quota thresholds, access checks,
15
+ * current identity/credential ownership checks and pending-write fences.
16
+ * Placement and readiness are separate facts.
17
+ */
18
+ export interface LimitCandidate {
19
+ readonly account: AccountKey;
20
+ readonly admitted: boolean;
21
+ readonly placementEligible: boolean;
22
+ readonly ready: boolean;
23
+ readonly blockers: readonly TimedBlocker[];
24
+ readonly confirmedBlockers?: readonly LimitWindow[];
25
+ }
26
+ export interface ModeSelection {
27
+ readonly account: AccountKey;
28
+ readonly pin: 'pin' | 'preserve' | 'detour';
29
+ }
30
+ export interface WaitCheckpoint {
31
+ readonly accountKey: AccountKey;
32
+ readonly decidedAt: number;
33
+ readonly blockers: readonly {
34
+ readonly window: string;
35
+ readonly resetAt: number;
36
+ }[];
37
+ }
38
+ /** Resolved via sameAccountHoldFacts; expiry uses the caller's epoch clock. */
39
+ export interface HoldFacts {
40
+ readonly cacheExpiresAt: number;
41
+ readonly maxWaitMs: number;
42
+ readonly maxDelayMs?: number;
43
+ }
44
+ /** Resolved metadata for a terminal refusal, not an account-selection instruction. */
45
+ export interface TerminalFacts {
46
+ readonly source: 'pool' | 'vault';
47
+ readonly reason: RefusalReason;
48
+ readonly family?: DecisionFamily;
49
+ readonly messageKey?: string;
50
+ readonly retryable?: boolean;
51
+ readonly hostRetry?: HostRetry;
52
+ readonly retryAfterMs?: number;
53
+ readonly resetAt?: number;
54
+ /** Pool quota refusals require per-field scan evidence to retain a reset. */
55
+ readonly scan?: TerminalScanFacts;
56
+ }
57
+ export interface PolicyFacts {
58
+ readonly phase: 'pre-send' | 'after-limit';
59
+ readonly host: LimitHost;
60
+ readonly hostPhase?: 'request' | 'retry';
61
+ readonly now: number;
62
+ readonly clockNow: number;
63
+ readonly sessionId: string;
64
+ readonly requestScope: Scope;
65
+ readonly history: RequestHistory;
66
+ readonly attempted?: AccountKey;
67
+ readonly signal?: LimitSignal;
68
+ readonly signalApplicable?: boolean;
69
+ readonly status?: number;
70
+ readonly failureRetryable?: boolean;
71
+ readonly delivery: {
72
+ readonly owned: boolean;
73
+ readonly attributable: boolean;
74
+ readonly replayable: boolean;
75
+ };
76
+ readonly candidates: readonly LimitCandidate[];
77
+ readonly selection?: ModeSelection;
78
+ readonly affinity?: 'sticky' | 'broken' | 'none';
79
+ readonly credentialRecovery?: {
80
+ readonly retryMs?: number;
81
+ };
82
+ readonly retryHintsMs?: readonly number[];
83
+ readonly hold?: HoldFacts;
84
+ readonly wake?: WakeFacts;
85
+ readonly remainingRetries?: number;
86
+ readonly terminal?: TerminalFacts;
87
+ readonly poolWaitBudgetMs?: number;
88
+ }
89
+ interface DecisionBase {
90
+ readonly retryable: boolean;
91
+ readonly hostRetry: HostRetry;
92
+ readonly history: RequestHistory;
93
+ readonly reason: string;
94
+ }
95
+ export type LimitDecision = DecisionBase & ({
96
+ readonly action: 'reroute';
97
+ readonly account: AccountKey;
98
+ readonly pin: ModeSelection['pin'];
99
+ } | {
100
+ readonly action: 'hold';
101
+ readonly account: AccountKey;
102
+ readonly delayMs: number;
103
+ readonly retryAfterMs: number;
104
+ readonly target: number;
105
+ readonly checkpoint: WaitCheckpoint;
106
+ readonly resetAt?: number;
107
+ /** Carry into wake.kind so terminal waits omit the ordinary cache bound. */
108
+ readonly waitKind?: 'terminal';
109
+ } | {
110
+ readonly action: 'retain';
111
+ readonly account: AccountKey;
112
+ readonly retryMs?: number;
113
+ /** Exhaustion windows waived for this dispatch only, never persisted. */
114
+ readonly liftedWindows?: readonly string[];
115
+ } | {
116
+ readonly action: 'wait-then-reselect';
117
+ readonly delayMs: number;
118
+ readonly resetAt?: number;
119
+ readonly target: number;
120
+ readonly checkpoint: WaitCheckpoint;
121
+ readonly retryAfterMs?: number;
122
+ /** Carry into wake.kind; Pi reselects once and then refuses without another wait. */
123
+ readonly waitKind?: 'terminal';
124
+ } | {
125
+ readonly action: 'exclude-for-request';
126
+ readonly account: AccountKey;
127
+ readonly scope: Scope;
128
+ readonly effects: typeof REQUEST_EXCLUSION_EFFECTS;
129
+ } | {
130
+ readonly action: 'refuse';
131
+ readonly reason: RefusalReason;
132
+ readonly family: DecisionFamily;
133
+ readonly messageKey: string;
134
+ readonly retryAfterMs?: number;
135
+ readonly resetAt?: number;
136
+ } | {
137
+ readonly action: 'pass';
138
+ });
139
+ /** The caller supplies clocks, admission, delivery ownership and parsed evidence. */
140
+ export declare function decideAfterLimit(facts: PolicyFacts, axes: LimitAxes): LimitDecision;
141
+ export {};