@cortexkit/common-auth 0.33.0 → 0.35.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.
- package/dist/claustrum/consumer.d.ts +12 -0
- package/dist/claustrum/consumer.js +36 -0
- package/dist/claustrum/custody.d.ts +16 -4
- package/dist/claustrum/custody.js +74 -9
- package/dist/claustrum/hub.d.ts +3 -2
- package/dist/claustrum/hub.js +8 -0
- package/dist/claustrum/index.d.ts +1 -0
- package/dist/claustrum/roster.d.ts +2 -0
- package/dist/claustrum/roster.js +2 -0
- package/dist/claustrum/usage.d.ts +41 -0
- package/dist/claustrum/usage.js +145 -0
- package/dist/commands/builtins.d.ts +5 -0
- package/dist/commands/builtins.js +38 -0
- package/dist/fs/private-files.d.ts +5 -0
- package/dist/fs/private-files.js +7 -0
- package/dist/fs/refresh-file-lock.js +142 -47
- package/dist/fs/with-lock.js +2 -5
- package/dist/limits/activity.d.ts +26 -0
- package/dist/limits/activity.js +52 -0
- package/dist/limits/axes.d.ts +69 -0
- package/dist/limits/axes.js +7 -0
- package/dist/limits/bridge.d.ts +4 -0
- package/dist/limits/bridge.js +10 -0
- package/dist/limits/decide.d.ts +146 -0
- package/dist/limits/decide.js +425 -0
- package/dist/limits/duration.d.ts +8 -0
- package/dist/limits/duration.js +20 -0
- package/dist/limits/envelope-loss.d.ts +29 -0
- package/dist/limits/envelope-loss.js +150 -0
- package/dist/limits/families.d.ts +59 -0
- package/dist/limits/families.js +149 -0
- package/dist/limits/header-classifier.d.ts +9 -0
- package/dist/limits/header-classifier.js +121 -0
- package/dist/limits/hold.d.ts +13 -0
- package/dist/limits/hold.js +25 -0
- package/dist/limits/identity.d.ts +14 -0
- package/dist/limits/identity.js +21 -0
- package/dist/limits/index.d.ts +45 -0
- package/dist/limits/index.js +26 -0
- package/dist/limits/jitter.d.ts +2 -0
- package/dist/limits/jitter.js +9 -0
- package/dist/limits/labels.d.ts +3 -0
- package/dist/limits/labels.js +11 -0
- package/dist/limits/marker.d.ts +69 -0
- package/dist/limits/marker.js +107 -0
- package/dist/limits/merge-laws.d.ts +15 -0
- package/dist/limits/merge-laws.js +31 -0
- package/dist/limits/namespace.d.ts +92 -0
- package/dist/limits/namespace.js +191 -0
- package/dist/limits/persistence.d.ts +33 -0
- package/dist/limits/persistence.js +9 -0
- package/dist/limits/pi-wait.d.ts +16 -0
- package/dist/limits/pi-wait.js +51 -0
- package/dist/limits/pool-adapter.d.ts +16 -0
- package/dist/limits/pool-adapter.js +162 -0
- package/dist/limits/presets.d.ts +11 -0
- package/dist/limits/presets.js +240 -0
- package/dist/limits/registry.d.ts +61 -0
- package/dist/limits/registry.js +478 -0
- package/dist/limits/request-history.d.ts +79 -0
- package/dist/limits/request-history.js +120 -0
- package/dist/limits/reset.d.ts +21 -0
- package/dist/limits/reset.js +44 -0
- package/dist/limits/routing-hold.d.ts +16 -0
- package/dist/limits/routing-hold.js +23 -0
- package/dist/limits/scope.d.ts +12 -0
- package/dist/limits/scope.js +10 -0
- package/dist/limits/signal.d.ts +41 -0
- package/dist/limits/signal.js +1 -0
- package/dist/limits/terminal.d.ts +52 -0
- package/dist/limits/terminal.js +133 -0
- package/dist/limits/unconfirmed-retain-counter.d.ts +13 -0
- package/dist/limits/unconfirmed-retain-counter.js +41 -0
- package/dist/limits/vault-adapter.d.ts +16 -0
- package/dist/limits/vault-adapter.js +123 -0
- package/dist/limits/vault.d.ts +1 -0
- package/dist/limits/vault.js +1 -0
- package/dist/limits/wake.d.ts +21 -0
- package/dist/limits/wake.js +47 -0
- package/dist/limits/wording.d.ts +25 -0
- package/dist/limits/wording.js +114 -0
- package/dist/opencode2/index.d.ts +1 -1
- package/dist/opencode2/install.d.ts +2 -2
- package/dist/opencode2/install.js +161 -18
- package/dist/opencode2/types.d.ts +95 -9
- package/dist/routing/admission.d.ts +7 -2
- package/dist/routing/admission.js +17 -7
- package/dist/routing-accessor/handle.d.ts +1 -0
- package/dist/routing-accessor/handle.js +10 -0
- package/dist/routing-accessor/index.d.ts +13 -3
- package/dist/routing-accessor/index.js +11 -10
- package/dist/rpc/port-file.d.ts +12 -3
- package/dist/rpc/port-file.js +46 -4
- package/dist/store/attribution.js +3 -2
- package/dist/store/errors.d.ts +1 -1
- package/dist/store/hooks.d.ts +5 -1
- package/dist/store/hooks.js +20 -5
- package/dist/store/index.d.ts +1 -0
- package/dist/store/limits-namespace.d.ts +7 -0
- package/dist/store/limits-namespace.js +34 -0
- package/dist/store/pool.d.ts +10 -1
- package/dist/store/pool.js +2 -0
- package/dist/store/provider-state.js +5 -5
- package/dist/store/refresh.js +1 -1
- package/dist/store/schema.js +9 -4
- package/dist/store/settings.d.ts +2 -0
- package/dist/store/settings.js +11 -4
- 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
|
-
|
|
371
|
-
if (
|
|
372
|
-
|
|
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
|
|
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
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
562
|
-
|
|
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 (
|
|
891
|
-
|
|
892
|
-
|
|
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
|
|
904
|
-
|
|
905
|
-
|
|
997
|
+
throw (removalError ??
|
|
998
|
+
new PrivateFileError(lockPath, 'release-not-confirmed', {
|
|
999
|
+
code: 'ETIMEDOUT',
|
|
1000
|
+
}));
|
|
906
1001
|
},
|
|
907
1002
|
};
|
|
908
1003
|
}
|
package/dist/fs/with-lock.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { join, resolve } from 'node:path';
|
|
2
|
-
import {
|
|
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 (!
|
|
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,69 @@
|
|
|
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
|
+
/** Legacy uncounted retention remains unbounded. */
|
|
33
|
+
readonly retainBound: 'none';
|
|
34
|
+
/** Opt-in turn/account budget when the caller supplies unconfirmedRetainCount. */
|
|
35
|
+
readonly unconfirmedRetainLimit?: number;
|
|
36
|
+
readonly poolWaiting: {
|
|
37
|
+
readonly kind: 'off';
|
|
38
|
+
} | {
|
|
39
|
+
readonly kind: 'earliest';
|
|
40
|
+
readonly budgetMs: number;
|
|
41
|
+
readonly requestDeadlineMs: number;
|
|
42
|
+
readonly hardFallbackMs: number;
|
|
43
|
+
readonly singleEligibleSoftExemption: boolean;
|
|
44
|
+
};
|
|
45
|
+
readonly execution: 'host' | 'engine';
|
|
46
|
+
readonly requestExclusion: 'on' | 'off';
|
|
47
|
+
readonly advance: HostValues<{
|
|
48
|
+
readonly statuses: readonly number[];
|
|
49
|
+
readonly attributedLimitOnly: boolean;
|
|
50
|
+
}>;
|
|
51
|
+
readonly markedPool: {
|
|
52
|
+
readonly requestEscape: 'off' | 'ignore-timed-marks-if-all-marked';
|
|
53
|
+
readonly retryExhaustion: 'terminal' | 'same-host-delay' | 'host-delay';
|
|
54
|
+
};
|
|
55
|
+
readonly terminalMetadata: 'setting-capped-fresh' | 'baseline';
|
|
56
|
+
readonly terminalPolicy: 'provided' | 'pool' | 'status-history';
|
|
57
|
+
/** Required when selecting status-history; other terminal policies ignore it. */
|
|
58
|
+
readonly terminalStatusHistory?: {
|
|
59
|
+
readonly minRetryMs: number;
|
|
60
|
+
readonly defaultRetryMs: number;
|
|
61
|
+
readonly paymentBalance?: {
|
|
62
|
+
readonly family: RefusalFamily;
|
|
63
|
+
readonly messageKey: string;
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
readonly refusals: Readonly<Record<RefusalReason, HostValues<RefusalPolicy>>>;
|
|
67
|
+
}
|
|
68
|
+
/** The caller supplies only this account's marks; other models remain blocked. */
|
|
69
|
+
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,146 @@
|
|
|
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
|
+
readonly cause?: import('./marker.js').LimitMarkCause;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Admission includes the caller's minimum quota thresholds, access checks,
|
|
16
|
+
* current identity/credential ownership checks and pending-write fences.
|
|
17
|
+
* Placement and readiness are separate facts.
|
|
18
|
+
*/
|
|
19
|
+
export interface LimitCandidate {
|
|
20
|
+
readonly account: AccountKey;
|
|
21
|
+
readonly admitted: boolean;
|
|
22
|
+
readonly placementEligible: boolean;
|
|
23
|
+
readonly ready: boolean;
|
|
24
|
+
readonly blockers: readonly TimedBlocker[];
|
|
25
|
+
readonly confirmedBlockers?: readonly LimitWindow[];
|
|
26
|
+
}
|
|
27
|
+
export interface ModeSelection {
|
|
28
|
+
readonly account: AccountKey;
|
|
29
|
+
readonly pin: 'pin' | 'preserve' | 'detour';
|
|
30
|
+
}
|
|
31
|
+
export interface WaitCheckpoint {
|
|
32
|
+
readonly accountKey: AccountKey;
|
|
33
|
+
readonly decidedAt: number;
|
|
34
|
+
readonly blockers: readonly {
|
|
35
|
+
readonly window: string;
|
|
36
|
+
readonly resetAt: number;
|
|
37
|
+
}[];
|
|
38
|
+
}
|
|
39
|
+
/** Resolved via sameAccountHoldFacts; expiry uses the caller's epoch clock. */
|
|
40
|
+
export interface HoldFacts {
|
|
41
|
+
readonly cacheExpiresAt: number;
|
|
42
|
+
readonly maxWaitMs: number;
|
|
43
|
+
readonly maxDelayMs?: number;
|
|
44
|
+
}
|
|
45
|
+
/** Resolved metadata for a terminal refusal, not an account-selection instruction. */
|
|
46
|
+
export interface TerminalFacts {
|
|
47
|
+
readonly source: 'pool' | 'vault';
|
|
48
|
+
readonly reason: RefusalReason;
|
|
49
|
+
readonly family?: DecisionFamily;
|
|
50
|
+
readonly messageKey?: string;
|
|
51
|
+
readonly retryable?: boolean;
|
|
52
|
+
readonly hostRetry?: HostRetry;
|
|
53
|
+
readonly retryAfterMs?: number;
|
|
54
|
+
readonly resetAt?: number;
|
|
55
|
+
/** Pool quota refusals require per-field scan evidence to retain a reset. */
|
|
56
|
+
readonly scan?: TerminalScanFacts;
|
|
57
|
+
}
|
|
58
|
+
export interface PolicyFacts {
|
|
59
|
+
readonly phase: 'pre-send' | 'after-limit';
|
|
60
|
+
readonly host: LimitHost;
|
|
61
|
+
readonly hostPhase?: 'request' | 'retry';
|
|
62
|
+
readonly now: number;
|
|
63
|
+
readonly clockNow: number;
|
|
64
|
+
readonly sessionId: string;
|
|
65
|
+
readonly requestScope: Scope;
|
|
66
|
+
readonly history: RequestHistory;
|
|
67
|
+
readonly attempted?: AccountKey;
|
|
68
|
+
readonly signal?: LimitSignal;
|
|
69
|
+
readonly signalApplicable?: boolean;
|
|
70
|
+
readonly status?: number;
|
|
71
|
+
readonly failureRetryable?: boolean;
|
|
72
|
+
readonly delivery: {
|
|
73
|
+
readonly owned: boolean;
|
|
74
|
+
readonly attributable: boolean;
|
|
75
|
+
readonly replayable: boolean;
|
|
76
|
+
};
|
|
77
|
+
readonly candidates: readonly LimitCandidate[];
|
|
78
|
+
readonly selection?: ModeSelection;
|
|
79
|
+
readonly affinity?: 'sticky' | 'broken' | 'none';
|
|
80
|
+
readonly credentialRecovery?: {
|
|
81
|
+
readonly retryMs?: number;
|
|
82
|
+
};
|
|
83
|
+
readonly retryHintsMs?: readonly number[];
|
|
84
|
+
/** Committed unconfirmed retains for the current session, turn and account. */
|
|
85
|
+
readonly unconfirmedRetainCount?: number;
|
|
86
|
+
readonly hold?: HoldFacts;
|
|
87
|
+
readonly wake?: WakeFacts;
|
|
88
|
+
readonly remainingRetries?: number;
|
|
89
|
+
readonly terminal?: TerminalFacts;
|
|
90
|
+
readonly poolWaitBudgetMs?: number;
|
|
91
|
+
}
|
|
92
|
+
interface DecisionBase {
|
|
93
|
+
readonly retryable: boolean;
|
|
94
|
+
readonly hostRetry: HostRetry;
|
|
95
|
+
readonly history: RequestHistory;
|
|
96
|
+
readonly reason: string;
|
|
97
|
+
}
|
|
98
|
+
export type LimitDecision = DecisionBase & ({
|
|
99
|
+
readonly action: 'reroute';
|
|
100
|
+
readonly account: AccountKey;
|
|
101
|
+
readonly pin: ModeSelection['pin'];
|
|
102
|
+
} | {
|
|
103
|
+
readonly action: 'hold';
|
|
104
|
+
readonly account: AccountKey;
|
|
105
|
+
readonly delayMs: number;
|
|
106
|
+
readonly retryAfterMs: number;
|
|
107
|
+
readonly target: number;
|
|
108
|
+
readonly checkpoint: WaitCheckpoint;
|
|
109
|
+
readonly resetAt?: number;
|
|
110
|
+
/** Carry into wake.kind so terminal waits omit the ordinary cache bound. */
|
|
111
|
+
readonly waitKind?: 'terminal';
|
|
112
|
+
} | {
|
|
113
|
+
readonly action: 'retain';
|
|
114
|
+
readonly account: AccountKey;
|
|
115
|
+
readonly retryMs?: number;
|
|
116
|
+
/** Commit once when executing this retain, never when polling the decision. */
|
|
117
|
+
readonly incrementUnconfirmedRetain?: true;
|
|
118
|
+
/** Exhaustion windows waived for this dispatch only, never persisted. */
|
|
119
|
+
readonly liftedWindows?: readonly string[];
|
|
120
|
+
} | {
|
|
121
|
+
readonly action: 'wait-then-reselect';
|
|
122
|
+
readonly delayMs: number;
|
|
123
|
+
readonly resetAt?: number;
|
|
124
|
+
readonly target: number;
|
|
125
|
+
readonly checkpoint: WaitCheckpoint;
|
|
126
|
+
readonly retryAfterMs?: number;
|
|
127
|
+
/** Carry into wake.kind; Pi reselects once and then refuses without another wait. */
|
|
128
|
+
readonly waitKind?: 'terminal';
|
|
129
|
+
} | {
|
|
130
|
+
readonly action: 'exclude-for-request';
|
|
131
|
+
readonly account: AccountKey;
|
|
132
|
+
readonly scope: Scope;
|
|
133
|
+
readonly effects: typeof REQUEST_EXCLUSION_EFFECTS;
|
|
134
|
+
} | {
|
|
135
|
+
readonly action: 'refuse';
|
|
136
|
+
readonly reason: RefusalReason;
|
|
137
|
+
readonly family: DecisionFamily;
|
|
138
|
+
readonly messageKey: string;
|
|
139
|
+
readonly retryAfterMs?: number;
|
|
140
|
+
readonly resetAt?: number;
|
|
141
|
+
} | {
|
|
142
|
+
readonly action: 'pass';
|
|
143
|
+
});
|
|
144
|
+
/** The caller supplies clocks, admission, delivery ownership and parsed evidence. */
|
|
145
|
+
export declare function decideAfterLimit(facts: PolicyFacts, axes: LimitAxes): LimitDecision;
|
|
146
|
+
export {};
|