@cortexkit/opencode-antigravity-auth 3.0.29 → 3.0.30

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 (173) hide show
  1. package/dist/cli.js +689 -183
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +130 -67
  4. package/dist/index.js +734 -191
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +159 -72
  7. package/dist/server.js +734 -194
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/cli.d.ts +1 -0
  11. package/dist/src/cli.d.ts.map +1 -1
  12. package/dist/src/cli.js +22 -2
  13. package/dist/src/cli.js.map +1 -1
  14. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  15. package/dist/src/common-auth-embedded/claustrum/consumer.js +36 -0
  16. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  17. package/dist/src/common-auth-embedded/claustrum/custody.js +74 -9
  18. package/dist/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  19. package/dist/src/common-auth-embedded/claustrum/hub.js +8 -0
  20. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  21. package/dist/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  22. package/dist/src/common-auth-embedded/claustrum/roster.js +2 -0
  23. package/dist/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  24. package/dist/src/common-auth-embedded/claustrum/usage.js +145 -0
  25. package/dist/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  26. package/dist/src/common-auth-embedded/commands/builtins.js +38 -0
  27. package/dist/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  28. package/dist/src/common-auth-embedded/fs/private-files.js +7 -0
  29. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  30. package/dist/src/common-auth-embedded/fs/with-lock.js +2 -5
  31. package/dist/src/common-auth-embedded/limits/activity.d.ts +26 -0
  32. package/dist/src/common-auth-embedded/limits/axes.d.ts +63 -0
  33. package/dist/src/common-auth-embedded/limits/decide.d.ts +141 -0
  34. package/dist/src/common-auth-embedded/limits/duration.d.ts +8 -0
  35. package/dist/src/common-auth-embedded/limits/families.d.ts +57 -0
  36. package/dist/src/common-auth-embedded/limits/marker.d.ts +64 -0
  37. package/dist/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  38. package/dist/src/common-auth-embedded/limits/scope.d.ts +12 -0
  39. package/dist/src/common-auth-embedded/limits/signal.d.ts +41 -0
  40. package/dist/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  41. package/dist/src/common-auth-embedded/limits/wake.d.ts +21 -0
  42. package/dist/src/common-auth-embedded/limits/wording.d.ts +25 -0
  43. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  44. package/dist/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  45. package/dist/src/common-auth-embedded/opencode2/install.js +161 -18
  46. package/dist/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  47. package/dist/src/common-auth-embedded/routing/admission.d.ts +7 -2
  48. package/dist/src/common-auth-embedded/routing/admission.js +17 -7
  49. package/dist/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  50. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  51. package/dist/src/common-auth-embedded/routing-accessor/index.js +11 -10
  52. package/dist/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  53. package/dist/src/common-auth-embedded/rpc/port-file.js +46 -4
  54. package/dist/src/common-auth-embedded/source-output.json +254 -118
  55. package/dist/src/common-auth-embedded/store/attribution.js +3 -2
  56. package/dist/src/common-auth-embedded/store/errors.d.ts +1 -1
  57. package/dist/src/common-auth-embedded/store/hooks.d.ts +5 -1
  58. package/dist/src/common-auth-embedded/store/hooks.js +20 -5
  59. package/dist/src/common-auth-embedded/store/index.d.ts +1 -0
  60. package/dist/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  61. package/dist/src/common-auth-embedded/store/limits-namespace.js +34 -0
  62. package/dist/src/common-auth-embedded/store/pool.d.ts +10 -1
  63. package/dist/src/common-auth-embedded/store/pool.js +2 -0
  64. package/dist/src/common-auth-embedded/store/provider-state.js +5 -5
  65. package/dist/src/common-auth-embedded/store/refresh.js +1 -1
  66. package/dist/src/common-auth-embedded/store/schema.js +9 -4
  67. package/dist/src/common-auth-embedded/store/settings.d.ts +2 -0
  68. package/dist/src/common-auth-embedded/store/settings.js +11 -4
  69. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  70. package/dist/src/runtime-layout.d.ts +9 -2
  71. package/dist/src/runtime-layout.d.ts.map +1 -1
  72. package/dist/src/runtime-layout.js +8 -8
  73. package/dist/src/runtime-layout.js.map +1 -1
  74. package/dist/src/setup.d.ts.map +1 -1
  75. package/dist/src/setup.js +29 -40
  76. package/dist/src/setup.js.map +1 -1
  77. package/dist/tui-build-map.json +9 -9
  78. package/dist/tui-ga-build-map.json +1 -1
  79. package/dist/types/src/cli.d.ts +1 -0
  80. package/dist/types/src/cli.d.ts.map +1 -1
  81. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  82. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  83. package/dist/types/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  84. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  85. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  86. package/dist/types/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  87. package/dist/types/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  88. package/dist/types/src/common-auth-embedded/limits/activity.d.ts +26 -0
  89. package/dist/types/src/common-auth-embedded/limits/axes.d.ts +63 -0
  90. package/dist/types/src/common-auth-embedded/limits/decide.d.ts +141 -0
  91. package/dist/types/src/common-auth-embedded/limits/duration.d.ts +8 -0
  92. package/dist/types/src/common-auth-embedded/limits/families.d.ts +57 -0
  93. package/dist/types/src/common-auth-embedded/limits/marker.d.ts +64 -0
  94. package/dist/types/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  95. package/dist/types/src/common-auth-embedded/limits/scope.d.ts +12 -0
  96. package/dist/types/src/common-auth-embedded/limits/signal.d.ts +41 -0
  97. package/dist/types/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  98. package/dist/types/src/common-auth-embedded/limits/wake.d.ts +21 -0
  99. package/dist/types/src/common-auth-embedded/limits/wording.d.ts +25 -0
  100. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  101. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  102. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  103. package/dist/types/src/common-auth-embedded/routing/admission.d.ts +7 -2
  104. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  105. package/dist/types/src/common-auth-embedded/store/errors.d.ts +1 -1
  106. package/dist/types/src/common-auth-embedded/store/hooks.d.ts +5 -1
  107. package/dist/types/src/common-auth-embedded/store/index.d.ts +1 -0
  108. package/dist/types/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  109. package/dist/types/src/common-auth-embedded/store/pool.d.ts +10 -1
  110. package/dist/types/src/common-auth-embedded/store/settings.d.ts +2 -0
  111. package/dist/types/src/runtime-layout.d.ts +9 -2
  112. package/dist/types/src/runtime-layout.d.ts.map +1 -1
  113. package/dist/types/src/setup.d.ts.map +1 -1
  114. package/package.json +2 -2
  115. package/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  116. package/src/common-auth-embedded/claustrum/consumer.js +36 -0
  117. package/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  118. package/src/common-auth-embedded/claustrum/custody.js +74 -9
  119. package/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  120. package/src/common-auth-embedded/claustrum/hub.js +8 -0
  121. package/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  122. package/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  123. package/src/common-auth-embedded/claustrum/roster.js +2 -0
  124. package/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  125. package/src/common-auth-embedded/claustrum/usage.js +145 -0
  126. package/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  127. package/src/common-auth-embedded/commands/builtins.js +38 -0
  128. package/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  129. package/src/common-auth-embedded/fs/private-files.js +7 -0
  130. package/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  131. package/src/common-auth-embedded/fs/with-lock.js +2 -5
  132. package/src/common-auth-embedded/limits/activity.d.ts +26 -0
  133. package/src/common-auth-embedded/limits/axes.d.ts +63 -0
  134. package/src/common-auth-embedded/limits/decide.d.ts +141 -0
  135. package/src/common-auth-embedded/limits/duration.d.ts +8 -0
  136. package/src/common-auth-embedded/limits/families.d.ts +57 -0
  137. package/src/common-auth-embedded/limits/marker.d.ts +64 -0
  138. package/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  139. package/src/common-auth-embedded/limits/scope.d.ts +12 -0
  140. package/src/common-auth-embedded/limits/signal.d.ts +41 -0
  141. package/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  142. package/src/common-auth-embedded/limits/wake.d.ts +21 -0
  143. package/src/common-auth-embedded/limits/wording.d.ts +25 -0
  144. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  145. package/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  146. package/src/common-auth-embedded/opencode2/install.js +161 -18
  147. package/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  148. package/src/common-auth-embedded/routing/admission.d.ts +7 -2
  149. package/src/common-auth-embedded/routing/admission.js +17 -7
  150. package/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  151. package/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  152. package/src/common-auth-embedded/routing-accessor/index.js +11 -10
  153. package/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  154. package/src/common-auth-embedded/rpc/port-file.js +46 -4
  155. package/src/common-auth-embedded/source-output.json +254 -118
  156. package/src/common-auth-embedded/store/attribution.js +3 -2
  157. package/src/common-auth-embedded/store/errors.d.ts +1 -1
  158. package/src/common-auth-embedded/store/hooks.d.ts +5 -1
  159. package/src/common-auth-embedded/store/hooks.js +20 -5
  160. package/src/common-auth-embedded/store/index.d.ts +1 -0
  161. package/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  162. package/src/common-auth-embedded/store/limits-namespace.js +34 -0
  163. package/src/common-auth-embedded/store/pool.d.ts +10 -1
  164. package/src/common-auth-embedded/store/pool.js +2 -0
  165. package/src/common-auth-embedded/store/provider-state.js +5 -5
  166. package/src/common-auth-embedded/store/refresh.js +1 -1
  167. package/src/common-auth-embedded/store/schema.js +9 -4
  168. package/src/common-auth-embedded/store/settings.d.ts +2 -0
  169. package/src/common-auth-embedded/store/settings.js +11 -4
  170. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +7 -0
  171. package/src/tui-compiled/common-auth-embedded/rpc/port-file.js +46 -4
  172. package/src/tui-raw/common-auth-embedded/fs/private-files.js +7 -0
  173. package/src/tui-raw/common-auth-embedded/rpc/port-file.js +46 -4
@@ -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,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,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 {};
@@ -0,0 +1,8 @@
1
+ /** Compact durations keep every numeric component below the hosts' retry codes. */
2
+ export declare function formatDuration(ms: number): string;
3
+ export interface ResetFormatInput {
4
+ readonly resetAt: number;
5
+ readonly now: number;
6
+ }
7
+ export type ResetFormatter = (input: ResetFormatInput) => string;
8
+ export declare const formatReset: ResetFormatter;
@@ -0,0 +1,57 @@
1
+ import { type LimitMessages } from './wording.js';
2
+ export type OpenCode1Family = 'openai-429' | 'claude-429' | 'json-412' | 'claustrum-429' | 'claude-econnreset';
3
+ export type RefusalFamily = OpenCode1Family | 'pi-final';
4
+ export type HostRetry = 'leave' | 'veto';
5
+ export interface RefusalInput {
6
+ readonly family: RefusalFamily;
7
+ readonly messageKey: string;
8
+ readonly messages?: LimitMessages;
9
+ readonly parameters?: {
10
+ readonly labels?: readonly string[];
11
+ };
12
+ /**
13
+ * Set only for re-login guidance, where the user needs to know which account to sign in again.
14
+ * Ordinary refusals omit labels, even when the caller supplies them.
15
+ */
16
+ readonly labelPolicy?: 'relogin';
17
+ readonly now: number;
18
+ /** A retained reset, already filtered for freshness by the decision layer. */
19
+ readonly resetAt?: number;
20
+ readonly retryAfterMs?: number;
21
+ /** Time already spent presenting a notice, not an instruction to sleep. */
22
+ readonly noticeDelayMs?: number;
23
+ /** Additional provider headers are preserved by the JSON 412 family only. */
24
+ readonly extraHeaders?: ConstructorParameters<typeof Headers>[0];
25
+ }
26
+ interface RefusalAttributes {
27
+ readonly family: RefusalFamily;
28
+ readonly disposition: 'refuse';
29
+ readonly retryable: boolean;
30
+ readonly hostRetry: HostRetry;
31
+ }
32
+ export interface HttpRefusal extends RefusalAttributes {
33
+ readonly kind: 'http';
34
+ readonly status: 412 | 429;
35
+ readonly headers: Headers;
36
+ readonly body: string;
37
+ }
38
+ export interface TextRefusal extends RefusalAttributes {
39
+ readonly kind: 'text';
40
+ readonly body: string;
41
+ }
42
+ export declare class ClaudeIncompleteError extends Error {
43
+ readonly code = "ECONNRESET";
44
+ readonly syscall = "sticky-routing";
45
+ readonly isRetryable = true;
46
+ constructor(message: string);
47
+ }
48
+ export interface ThrownRefusal extends RefusalAttributes {
49
+ readonly kind: 'throw';
50
+ readonly error: ClaudeIncompleteError;
51
+ }
52
+ export type BuiltRefusal = HttpRefusal | TextRefusal | ThrownRefusal;
53
+ /** Compute metadata at delivery time, after time spent showing a notice. */
54
+ export declare function retryAfterSeconds(retryAfterMs: number | undefined, noticeDelayMs?: number): number | undefined;
55
+ /** Pure wire construction: the caller sends the response, emits text, or throws the error. */
56
+ export declare function buildRefusal(input: RefusalInput): BuiltRefusal;
57
+ export {};
@@ -0,0 +1,64 @@
1
+ import type { Scope } from './scope.js';
2
+ import type { AccountKey, LimitKind, LimitSignal } from './signal.js';
3
+ export type MergeLaw = 'latest-evidence' | 'max-until' | 'overwrite';
4
+ export interface LimitMark {
5
+ readonly scope: Scope;
6
+ readonly until: number;
7
+ readonly mergeLaw: MergeLaw;
8
+ }
9
+ export interface FailureLadderAxes {
10
+ readonly kind: 'failure-ladder';
11
+ readonly mergeLaw: MergeLaw;
12
+ readonly hintFloorMs: number;
13
+ readonly quotaSteps: readonly number[];
14
+ readonly byKind: Readonly<Partial<Record<LimitKind, number>>>;
15
+ readonly byReason: Readonly<Record<string, number>>;
16
+ readonly capacity: {
17
+ readonly baseMs: number;
18
+ /** Maximum displacement on either side of baseMs. */
19
+ readonly spreadMs: number;
20
+ };
21
+ readonly defaultMs: number;
22
+ }
23
+ export declare const ANTIGRAVITY_FAILURE_LADDER: FailureLadderAxes;
24
+ export type MarkerAxes = {
25
+ readonly kind: 'off';
26
+ } | {
27
+ readonly kind: 'hint';
28
+ readonly mergeLaw: MergeLaw;
29
+ readonly defaultMs: number;
30
+ readonly minimumMs: number;
31
+ readonly zero: 'accept' | 'skip';
32
+ /** Core absolute dates and host event-relative hints use different samples. */
33
+ readonly hintClock: 'signal' | 'marker';
34
+ } | {
35
+ readonly kind: 'reset';
36
+ readonly mergeLaw: MergeLaw;
37
+ readonly defaultMs: number;
38
+ } | FailureLadderAxes;
39
+ export interface FailureStreak {
40
+ readonly count: number;
41
+ readonly lastFailureAt: number;
42
+ }
43
+ /** Owned by the process, not a persisted registry snapshot. */
44
+ export type FailureHistory = ReadonlyMap<string, FailureStreak>;
45
+ export type FailureEvent = {
46
+ readonly type: 'failure';
47
+ readonly account: AccountKey;
48
+ readonly at: number;
49
+ } | {
50
+ readonly type: 'success';
51
+ readonly account: AccountKey;
52
+ };
53
+ /** Feed committed marker events, not repeated reducer evaluations, into history. */
54
+ export declare function reduceFailureHistory(history: FailureHistory, event: FailureEvent, ttlMs?: number): FailureHistory;
55
+ export interface MarkerHistory {
56
+ readonly now: number;
57
+ /** Includes the current failure event; success removes only that account's streak. */
58
+ readonly failures?: FailureHistory;
59
+ /** Uniform sample in [0, 1] for the capacity fallback duration; omitted means midpoint. */
60
+ readonly random?: number;
61
+ }
62
+ /** No clocks, random draws, state updates or I/O occur while producing a mark. */
63
+ export declare function markFromSignal(signal: LimitSignal | undefined, axes: MarkerAxes, history: MarkerHistory): LimitMark | undefined;
64
+ export declare function markIsActive(mark: LimitMark, now: number): boolean;