@cortexkit/common-auth 0.44.0 → 0.46.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 (55) hide show
  1. package/dist/commands/builtins.d.ts +20 -1
  2. package/dist/commands/builtins.js +28 -12
  3. package/dist/commands/index.d.ts +1 -1
  4. package/dist/commands/menu.d.ts +6 -1
  5. package/dist/commands/menu.js +1 -0
  6. package/dist/fs/file-read-cache.d.ts +3 -0
  7. package/dist/fs/file-read-cache.js +9 -5
  8. package/dist/fs/refresh-file-lock.d.ts +11 -0
  9. package/dist/fs/refresh-file-lock.js +159 -11
  10. package/dist/fs/with-lock.d.ts +2 -0
  11. package/dist/fs/with-lock.js +1 -1
  12. package/dist/routing-accessor/index.d.ts +17 -0
  13. package/dist/routing-accessor/index.js +13 -0
  14. package/dist/settings/define.d.ts +35 -0
  15. package/dist/settings/define.js +52 -0
  16. package/dist/settings/descriptors.d.ts +97 -0
  17. package/dist/settings/descriptors.js +81 -0
  18. package/dist/settings/edit.d.ts +24 -0
  19. package/dist/settings/edit.js +229 -0
  20. package/dist/settings/fs.d.ts +6 -0
  21. package/dist/settings/fs.js +19 -0
  22. package/dist/settings/handle.d.ts +30 -0
  23. package/dist/settings/handle.js +228 -0
  24. package/dist/settings/index.d.ts +10 -0
  25. package/dist/settings/index.js +7 -0
  26. package/dist/settings/lock-errors.d.ts +2 -0
  27. package/dist/settings/lock-errors.js +15 -0
  28. package/dist/settings/move.d.ts +76 -0
  29. package/dist/settings/move.js +351 -0
  30. package/dist/settings/parse.d.ts +24 -0
  31. package/dist/settings/parse.js +65 -0
  32. package/dist/settings/paths.d.ts +12 -0
  33. package/dist/settings/paths.js +48 -0
  34. package/dist/settings/refusal.d.ts +7 -0
  35. package/dist/settings/refusal.js +15 -0
  36. package/dist/settings/resolve.d.ts +15 -0
  37. package/dist/settings/resolve.js +51 -0
  38. package/dist/settings/schema.d.ts +29 -0
  39. package/dist/settings/schema.js +81 -0
  40. package/dist/settings/snapshot.d.ts +24 -0
  41. package/dist/settings/snapshot.js +150 -0
  42. package/dist/settings/update.d.ts +6 -0
  43. package/dist/settings/update.js +139 -0
  44. package/dist/settings/write.d.ts +26 -0
  45. package/dist/settings/write.js +88 -0
  46. package/dist/setup/command-error.d.ts +1 -1
  47. package/dist/setup/command-error.js +3 -2
  48. package/dist/setup/command.js +5 -1
  49. package/dist/setup/enroll.js +3 -3
  50. package/dist/setup/enrollment-access.d.ts +1 -1
  51. package/dist/setup/enrollment-access.js +13 -4
  52. package/dist/setup/types.d.ts +4 -0
  53. package/dist/tui-prefs/watcher.d.ts +3 -1
  54. package/dist/tui-prefs/watcher.js +41 -18
  55. package/package.json +5 -1
@@ -1,4 +1,4 @@
1
- import type { AddInput, PoolLockSpec, PoolRow, PoolStore, RemoveOptions } from '../store/index.js';
1
+ import type { AddInput, PoolLockSpec, PoolRow, PoolSettings, PoolStore, RemoveOptions, SettingsMutator } from '../store/index.js';
2
2
  import type { CommandInvocation, KnobValues, MenuChoice, MenuKnob } from './model.js';
3
3
  import { type ResolvedSection } from './seam.js';
4
4
  /**
@@ -98,9 +98,28 @@ export interface LimitsSectionOptions {
98
98
  */
99
99
  labels?: readonly string[];
100
100
  }
101
+ /**
102
+ * Where the Routing and Limits sections read and write the settings they show
103
+ * (`routing.mode`, `routing.maxSameAccountWait`, `killswitch.enabled`,
104
+ * `killswitch.accounts`). Without a port they use the account store's own
105
+ * settings through `readSettings` and `updateSettings`. A plugin that moved
106
+ * its settings to its own file (`./settings`) passes a port that translates
107
+ * this store-shaped view to that file.
108
+ */
109
+ export interface BuiltinSettingsPort {
110
+ /** The current settings, in the store's settings shape. */
111
+ read(): Promise<PoolSettings>;
112
+ /**
113
+ * Apply one menu change. `mutator` gets a private copy in the store's shape
114
+ * and edits it in place or returns the whole next object, as with
115
+ * `updateSettings`. A refusal is thrown and shown as the action's failure.
116
+ */
117
+ update(mutator: SettingsMutator): Promise<void>;
118
+ }
101
119
  export interface BuiltinOptions {
102
120
  store: PoolStore;
103
121
  extraLocks?: readonly PoolLockSpec[];
122
+ settings?: BuiltinSettingsPort;
104
123
  now: () => number;
105
124
  accounts?: AccountsSectionOptions;
106
125
  quota?: QuotaSectionOptions;
@@ -65,15 +65,31 @@ function addedText(name, result) {
65
65
  function failureMessage(error) {
66
66
  return projectFailure(error).text;
67
67
  }
68
+ /** The plugin's settings port, or one over the account store's own settings. */
69
+ function settingsPort(options) {
70
+ if (options.settings)
71
+ return options.settings;
72
+ const { store, extraLocks } = options;
73
+ const locks = extraLocks ? { extraLocks } : {};
74
+ return {
75
+ async read() {
76
+ const read = await store.readSettings();
77
+ return read.status === 'error' ? {} : read.settings;
78
+ },
79
+ async update(mutator) {
80
+ await store.updateSettings(mutator, locks);
81
+ },
82
+ };
83
+ }
68
84
  async function snapshot(options) {
69
85
  const { store } = options;
70
86
  const load = await store.read();
71
- const read = await store.readSettings();
87
+ const settings = await settingsPort(options).read();
72
88
  const vault = await options.routing?.vaultOrder?.();
73
89
  return {
74
90
  load,
75
91
  rows: distinctRows(load),
76
- settings: read.status === 'error' ? {} : read.settings,
92
+ settings,
77
93
  ...(vault ? { vault } : {}),
78
94
  };
79
95
  }
@@ -396,6 +412,7 @@ function vaultNames(vault) {
396
412
  function routingSection(options, snap) {
397
413
  const { store, extraLocks } = options;
398
414
  const locks = extraLocks ? { extraLocks } : {};
415
+ const port = settingsPort(options);
399
416
  const choices = [
400
417
  { value: 'ordered', label: 'Ordered (roster order)' },
401
418
  ...(options.routing?.orderedVariants ?? []),
@@ -428,10 +445,10 @@ function routingSection(options, snap) {
428
445
  ],
429
446
  run: async ({ values }) => {
430
447
  const mode = String(values.mode);
431
- await store.updateSettings((settings) => {
448
+ await port.update((settings) => {
432
449
  settings.routing = { ...record(settings.routing), mode };
433
450
  return undefined;
434
- }, locks);
451
+ });
435
452
  return `Routing mode set to ${choices.find((choice) => choice.value === mode)?.label ?? mode}.`;
436
453
  },
437
454
  },
@@ -495,13 +512,13 @@ function routingSection(options, snap) {
495
512
  run: async ({ values }) => {
496
513
  const value = String(values.maxSameAccountWait);
497
514
  const maxSameAccountWait = value === 'max' ? 'max' : Number(value);
498
- await store.updateSettings((settings) => {
515
+ await port.update((settings) => {
499
516
  settings.routing = {
500
517
  ...record(settings.routing),
501
518
  maxSameAccountWait,
502
519
  };
503
520
  return undefined;
504
- }, locks);
521
+ });
505
522
  return `${waitLabel} set to ${waitName(value)}.`;
506
523
  },
507
524
  });
@@ -541,8 +558,7 @@ function floorNames(options, snap) {
541
558
  return (label) => names.get(label) ?? label;
542
559
  }
543
560
  function limitsSection(options, snap) {
544
- const { store, extraLocks } = options;
545
- const locks = extraLocks ? { extraLocks } : {};
561
+ const port = settingsPort(options);
546
562
  const killswitch = record(snap.settings.killswitch);
547
563
  const enabled = killswitch.enabled === true;
548
564
  const floors = record(killswitch.accounts);
@@ -577,7 +593,7 @@ function limitsSection(options, snap) {
577
593
  : {}),
578
594
  })),
579
595
  run: async ({ values }) => {
580
- await store.updateSettings((settings) => {
596
+ await port.update((settings) => {
581
597
  const next = record(settings.killswitch);
582
598
  const accounts = record(next.accounts);
583
599
  const mine = record(accounts[row.id]);
@@ -598,7 +614,7 @@ function limitsSection(options, snap) {
598
614
  delete next.accounts;
599
615
  settings.killswitch = next;
600
616
  return undefined;
601
- }, locks);
617
+ });
602
618
  return `Floors updated for ${name}.`;
603
619
  },
604
620
  },
@@ -628,13 +644,13 @@ function limitsSection(options, snap) {
628
644
  ],
629
645
  run: async ({ values }) => {
630
646
  const on = values.enabled === true;
631
- await store.updateSettings((settings) => {
647
+ await port.update((settings) => {
632
648
  settings.killswitch = {
633
649
  ...record(settings.killswitch),
634
650
  enabled: on,
635
651
  };
636
652
  return undefined;
637
- }, locks);
653
+ });
638
654
  return `Killswitch ${on ? 'on' : 'off'}.`;
639
655
  },
640
656
  },
@@ -1,4 +1,4 @@
1
- export type { AccountsSectionOptions, LimitsSectionOptions, LoginOutcome, QuotaSectionOptions, RoutingSectionOptions, VaultRoutingOrder, } from './builtins.js';
1
+ export type { AccountsSectionOptions, BuiltinSettingsPort, LimitsSectionOptions, LoginOutcome, QuotaSectionOptions, RoutingSectionOptions, VaultRoutingOrder, } from './builtins.js';
2
2
  export { MENU_DISABLED_REASON } from './builtins.js';
3
3
  export type { CommandMenu, CommandMenuOptions, StoreSectionSlot, } from './menu.js';
4
4
  export { createCommandMenu, parseApplyRequest } from './menu.js';
@@ -1,6 +1,6 @@
1
1
  import { type RedactionOptions } from '../logger/index.js';
2
2
  import type { PoolLockSpec, PoolStore } from '../store/index.js';
3
- import { type AccountsSectionOptions, type LimitsSectionOptions, type QuotaSectionOptions, type RoutingSectionOptions } from './builtins.js';
3
+ import { type AccountsSectionOptions, type BuiltinSettingsPort, type LimitsSectionOptions, type QuotaSectionOptions, type RoutingSectionOptions } from './builtins.js';
4
4
  import type { CommandApplyRequest, CommandApplyResult, CommandDialogPayload, CommandInvocation, PluginExtraSection, PluginSection } from './model.js';
5
5
  import { type SeamLogger } from './seam.js';
6
6
  /** The four slots the library can build from a pool store. */
@@ -25,6 +25,11 @@ export interface CommandMenuOptions {
25
25
  replace?: Partial<Record<StoreSectionSlot, PluginSection>>;
26
26
  /** The plugin's legacy locks, passed to every store write the menu makes. */
27
27
  extraLocks?: readonly PoolLockSpec[];
28
+ /**
29
+ * Where the Routing and Limits sections read and write their settings. Omit
30
+ * it to use the store's own settings, as before.
31
+ */
32
+ settings?: BuiltinSettingsPort;
28
33
  accounts?: AccountsSectionOptions;
29
34
  quota?: QuotaSectionOptions;
30
35
  routing?: RoutingSectionOptions;
@@ -156,6 +156,7 @@ export function createCommandMenu(options) {
156
156
  store,
157
157
  now,
158
158
  ...(options.extraLocks ? { extraLocks: options.extraLocks } : {}),
159
+ ...(options.settings ? { settings: options.settings } : {}),
159
160
  ...(options.accounts ? { accounts: options.accounts } : {}),
160
161
  ...(options.quota ? { quota: options.quota } : {}),
161
162
  ...(options.routing ? { routing: options.routing } : {}),
@@ -1,10 +1,13 @@
1
1
  import type { Stats } from 'node:fs';
2
2
  type FileIdentity = Stats | 'absent';
3
+ type Probe = (path: string) => Promise<Stats>;
3
4
  /** Process-local reads, capped at 64 path sets with one value per resolved set. */
4
5
  export declare class FileReadCache<T> {
5
6
  #private;
6
7
  constructor(options?: {
7
8
  followSymlinks?: boolean;
9
+ stat?: Probe;
10
+ lstat?: Probe;
8
11
  });
9
12
  read(paths: readonly string[], read: (resolvedPaths: string[]) => Promise<T>, validateHit?: (identities: readonly FileIdentity[]) => void): Promise<T>;
10
13
  }
@@ -1,10 +1,10 @@
1
1
  import { lstat, stat } from 'node:fs/promises';
2
2
  import { resolve } from 'node:path';
3
- async function identity(path, followSymlinks) {
3
+ async function identity(path, probe) {
4
4
  try {
5
5
  // Match the reader: private readers reject links, while readFile follows
6
6
  // them and needs the target's identity, not the link's identity.
7
- const metadata = await (followSymlinks ? stat(path) : lstat(path));
7
+ const metadata = await probe(path);
8
8
  return metadata.isFile() ? metadata : undefined;
9
9
  }
10
10
  catch (error) {
@@ -24,15 +24,19 @@ function sameIdentity(left, right) {
24
24
  }
25
25
  /** Process-local reads, capped at 64 path sets with one value per resolved set. */
26
26
  export class FileReadCache {
27
- #followSymlinks;
27
+ #probe;
28
28
  #entries = new Map();
29
29
  constructor(options = {}) {
30
- this.#followSymlinks = options.followSymlinks ?? false;
30
+ // Look the probe up on every call, not once here: tests replace the
31
+ // node:fs/promises functions (and SettingsFs methods) after caches exist.
32
+ this.#probe = options.followSymlinks
33
+ ? (path) => (options.stat ?? stat)(path)
34
+ : (path) => (options.lstat ?? lstat)(path);
31
35
  }
32
36
  async read(paths, read, validateHit) {
33
37
  const resolvedPaths = paths.map((path) => resolve(path));
34
38
  const key = JSON.stringify(resolvedPaths);
35
- const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#followSymlinks)));
39
+ const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#probe)));
36
40
  const identities = probed.every((entry) => entry !== undefined)
37
41
  ? probed
38
42
  : undefined;
@@ -4,6 +4,17 @@ type LeaseCreationTestHooks = {
4
4
  };
5
5
  /** Test-only creation faults; not re-exported from the public fs entry point. */
6
6
  export declare function setLeaseCreationTestHooksForTest(hooks?: LeaseCreationTestHooks): void;
7
+ type StagingSweepTestHooks = {
8
+ readdir?: (directory: string) => Promise<string[]>;
9
+ beforeUnlink?: (path: string) => void | Promise<void>;
10
+ unlink?: (path: string) => Promise<void>;
11
+ };
12
+ /** Test-only sweep faults; not re-exported from the public fs entry point. */
13
+ export declare function setStagingSweepTestHooksForTest(hooks?: StagingSweepTestHooks): void;
14
+ /** Tests only: wait for every staging sweep started so far to finish. */
15
+ export declare function settleStagingSweepsForTest(): Promise<void>;
16
+ /** Tests only: let the next acquisition of every lock path sweep again. */
17
+ export declare function forgetStagingSweepsForTest(): void;
7
18
  export declare function isLostMarkerRaceError(error: unknown): boolean;
8
19
  /** Test-only fault injection between marker mkdir and owner.json write. */
9
20
  export interface EvictionMarkerTestHooks {
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { link, lstat, mkdir, open, readFile, rename, rm, stat, } from 'node:fs/promises';
3
- import { dirname, join } from 'node:path';
2
+ import { link, lstat, mkdir, open, readdir, readFile, rename, rm, stat, unlink, } from 'node:fs/promises';
3
+ import { basename, dirname, join } from 'node:path';
4
+ import { createLogger } from '../logger/index.js';
4
5
  import { DisappearedLockRecordError, isWindowsAccessDeniedCreate, isWindowsAccessDeniedRead, readLockRecord, } from './lock-record.js';
5
6
  import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, isWindowsSharingViolation, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from './private-files.js';
6
7
  import { LockOwnershipError, lockPathFor } from './with-lock.js';
@@ -91,6 +92,149 @@ async function writeExclusiveText(path, text) {
91
92
  await handle.close();
92
93
  }
93
94
  }
95
+ // Lease owner records are staged in sibling files named
96
+ // `<lock file name>.<random UUID>.tmp` before they are linked or renamed into
97
+ // place: by createExclusiveText and by renewal, whose Windows branch uses
98
+ // writePrivateAtomic's default staging name of the same shape. Each writer
99
+ // removes its staging file when it finishes, but a process killed between
100
+ // creating the file and that cleanup leaves it behind for good, since nothing
101
+ // else ever reads that name. The sweep below removes only such leftovers.
102
+ const STAGING_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
103
+ // A staging file records the expiry of the lease it was about to publish,
104
+ // which is always in the future while its writer is alive. Requiring the
105
+ // expiry to be at least a lease TTL in the past, and never less than this
106
+ // floor, keeps a live writer's file safe even if wall clocks disagree.
107
+ const STAGING_SWEEP_MIN_AGE_MS = 10 * 60_000;
108
+ // Bounds the work one sweep does; any remainder is left for a later process.
109
+ const STAGING_SWEEP_MAX_CANDIDATES = 256;
110
+ // A complete owner record is under 100 bytes; anything far larger is not one.
111
+ const STAGING_SWEEP_MAX_BYTES = 4_096;
112
+ // Lock paths already swept by this process. Sweeping once per process keeps
113
+ // the directory listing off the hot path of every later acquisition.
114
+ const sweptLockPaths = new Set();
115
+ const pendingStagingSweeps = new Set();
116
+ let stagingSweepTestHooks;
117
+ /** Test-only sweep faults; not re-exported from the public fs entry point. */
118
+ export function setStagingSweepTestHooksForTest(hooks) {
119
+ stagingSweepTestHooks = hooks;
120
+ }
121
+ /** Tests only: wait for every staging sweep started so far to finish. */
122
+ export async function settleStagingSweepsForTest() {
123
+ while (pendingStagingSweeps.size > 0)
124
+ await Promise.all([...pendingStagingSweeps]);
125
+ }
126
+ /** Tests only: let the next acquisition of every lock path sweep again. */
127
+ export function forgetStagingSweepsForTest() {
128
+ sweptLockPaths.clear();
129
+ }
130
+ function isStagingName(name, lockName) {
131
+ const prefix = `${lockName}.`;
132
+ const suffix = '.tmp';
133
+ if (!name.startsWith(prefix) || !name.endsWith(suffix))
134
+ return false;
135
+ return STAGING_UUID.test(name.slice(prefix.length, -suffix.length));
136
+ }
137
+ function sameStagingFile(a, b) {
138
+ return (a.dev === b.dev &&
139
+ a.ino === b.ino &&
140
+ a.size === b.size &&
141
+ a.mtimeMs === b.mtimeMs &&
142
+ a.birthtimeMs === b.birthtimeMs);
143
+ }
144
+ /**
145
+ * Read the owner record a staging file holds, or undefined when the path is
146
+ * not a plain file holding exactly a complete `{ownerId, expiresAt}` record.
147
+ * Returns the lstat identity the record was read from, for the unlink fence.
148
+ */
149
+ async function readStagedOwner(path) {
150
+ const before = await lstat(path);
151
+ if (!before.isFile() || before.isSymbolicLink())
152
+ return undefined;
153
+ if (before.size > STAGING_SWEEP_MAX_BYTES)
154
+ return undefined;
155
+ const handle = await open(path, 'r');
156
+ let text;
157
+ try {
158
+ // The path could be swapped between the lstat and the open; read only
159
+ // when the opened file is the one the lstat described.
160
+ if (!sameStagingFile(before, await handle.stat()))
161
+ return undefined;
162
+ text = await handle.readFile('utf8');
163
+ }
164
+ finally {
165
+ await handle.close();
166
+ }
167
+ let record;
168
+ try {
169
+ record = JSON.parse(text);
170
+ }
171
+ catch {
172
+ return undefined;
173
+ }
174
+ if (!record || typeof record !== 'object' || Array.isArray(record))
175
+ return undefined;
176
+ const keys = Object.keys(record).sort();
177
+ if (keys.length !== 2 || keys[0] !== 'expiresAt' || keys[1] !== 'ownerId')
178
+ return undefined;
179
+ const { ownerId, expiresAt } = record;
180
+ if (typeof ownerId !== 'string' || !STAGING_UUID.test(ownerId))
181
+ return undefined;
182
+ if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt))
183
+ return undefined;
184
+ return { identity: before, expiresAt };
185
+ }
186
+ async function sweepAbandonedStaging(lockPath, ttlMs, now) {
187
+ const directory = dirname(lockPath);
188
+ const lockName = basename(lockPath);
189
+ const hooks = stagingSweepTestHooks;
190
+ const names = await (hooks?.readdir ?? readdir)(directory);
191
+ const candidates = names
192
+ .filter((name) => isStagingName(name, lockName))
193
+ .slice(0, STAGING_SWEEP_MAX_CANDIDATES);
194
+ const marginMs = Math.max(Number.isFinite(ttlMs) ? ttlMs : 0, STAGING_SWEEP_MIN_AGE_MS);
195
+ for (const name of candidates) {
196
+ const path = join(directory, name);
197
+ try {
198
+ // A file written within the margin belongs to a writer that may be
199
+ // alive, so don't even open it; the record's expiry still decides.
200
+ if (now() - (await lstat(path)).mtimeMs < marginMs)
201
+ continue;
202
+ const staged = await readStagedOwner(path);
203
+ if (!staged || !(staged.expiresAt < now() - marginMs))
204
+ continue;
205
+ if (hooks?.beforeUnlink)
206
+ await hooks.beforeUnlink(path);
207
+ // Remove only the file that was read: a name reused since then keeps
208
+ // its new contents. Inode numbers can be reused at once after an
209
+ // unlink, so the record is read again as well as the identity compared.
210
+ const current = await readStagedOwner(path);
211
+ if (!current ||
212
+ !sameStagingFile(staged.identity, current.identity) ||
213
+ !(current.expiresAt < now() - marginMs))
214
+ continue;
215
+ await (hooks?.unlink ?? unlink)(path);
216
+ }
217
+ catch {
218
+ // Each leftover is independent; a vanished or unreadable one is skipped.
219
+ }
220
+ }
221
+ }
222
+ /**
223
+ * Start a background sweep of abandoned staging files beside `lockPath`, at
224
+ * most once per process per lock path. Called after this process acquires the
225
+ * lock, so no other cooperating process sweeps the same name at that moment.
226
+ * The sweep never delays or fails the acquisition: every error is ignored.
227
+ */
228
+ function startStagingSweep(lockPath, ttlMs, now) {
229
+ if (sweptLockPaths.has(lockPath))
230
+ return;
231
+ sweptLockPaths.add(lockPath);
232
+ const sweep = Promise.resolve()
233
+ .then(() => sweepAbandonedStaging(lockPath, ttlMs, now))
234
+ .catch(() => { });
235
+ pendingStagingSweeps.add(sweep);
236
+ void sweep.finally(() => pendingStagingSweeps.delete(sweep));
237
+ }
94
238
  const setRefreshLockRenewalTimeout = globalThis.setTimeout.bind(globalThis);
95
239
  const clearRefreshLockRenewalTimeout = globalThis.clearTimeout.bind(globalThis);
96
240
  // A concurrent contender renaming the freshly-created eviction-marker directory
@@ -970,6 +1114,7 @@ export async function acquireRefreshFileLockWithClock(options) {
970
1114
  return null;
971
1115
  }
972
1116
  scheduleRenewal();
1117
+ startStagingSweep(lockPath, options.ttlMs, now);
973
1118
  return {
974
1119
  ownerId,
975
1120
  whenLost: () => lostPromise,
@@ -1047,17 +1192,17 @@ export async function acquireRefreshFileLockWithClock(options) {
1047
1192
  removalConfirmed = true;
1048
1193
  }, deadline);
1049
1194
  changingRecordError = undefined;
1050
- if (markerAcquired) {
1051
- if (windowsPrivateFiles && !removalConfirmed)
1052
- throw new PrivateFileError(lockPath, 'release-not-confirmed', {
1053
- code: 'EIO',
1054
- });
1055
- releaseConfirmed = removalConfirmed;
1195
+ // Acquiring the marker does not confirm removal: stale-marker
1196
+ // recovery can take it away after the lease owner was checked.
1197
+ if (markerAcquired && removalConfirmed) {
1198
+ releaseConfirmed = true;
1056
1199
  return;
1057
1200
  }
1058
- if (signal?.aborted)
1059
- return;
1060
- await recoverStaleEvictionMarker(deadline);
1201
+ if (!markerAcquired) {
1202
+ if (signal?.aborted)
1203
+ return;
1204
+ await recoverStaleEvictionMarker(deadline);
1205
+ }
1061
1206
  }
1062
1207
  catch (error) {
1063
1208
  const changingRecord = windowsPrivateFiles &&
@@ -1098,6 +1243,9 @@ export async function acquireRefreshFileLockWithClock(options) {
1098
1243
  new PrivateFileError(lockPath, 'release-not-confirmed', {
1099
1244
  code: 'ETIMEDOUT',
1100
1245
  }));
1246
+ createLogger('fs').warn('File lock release deadline expired', {
1247
+ lockPath,
1248
+ });
1101
1249
  },
1102
1250
  };
1103
1251
  }
@@ -1,3 +1,4 @@
1
+ import { type PrivateFileError } from './private-files.js';
1
2
  import { acquireRefreshFileLock } from './refresh-file-lock.js';
2
3
  export declare function lockPathFor(target: string, name: string): string;
3
4
  export declare class LockContentionError extends Error {
@@ -32,6 +33,7 @@ export interface LockOptions {
32
33
  onStep?: Parameters<typeof acquireRefreshFileLock>[0]['onStep'];
33
34
  onRenewalTimer?: Parameters<typeof acquireRefreshFileLock>[0]['onRenewalTimer'];
34
35
  }
36
+ export declare function isChangingLockRecord(error: unknown, target: string, name: string): error is PrivateFileError;
35
37
  export declare function withLock<T>(target: string, options: LockOptions, fn: (lock: {
36
38
  assertOwned(): Promise<void>;
37
39
  }) => Promise<T>): Promise<T>;
@@ -21,7 +21,7 @@ export class LockOwnershipError extends Error {
21
21
  this.details = details;
22
22
  }
23
23
  }
24
- function isChangingLockRecord(error, target, name) {
24
+ export function isChangingLockRecord(error, target, name) {
25
25
  const path = resolve(lockPathFor(target, name));
26
26
  const paths = [path, join(path, 'owner.json')];
27
27
  return (((isWindowsSharingViolation(error) ||
@@ -77,6 +77,23 @@ export type ReportRoutingInput = (RoutingReportIdentity & ({
77
77
  pool?: string;
78
78
  /** Optional reset time in epoch milliseconds. */
79
79
  resetsAt?: number;
80
+ } | {
81
+ /**
82
+ * A provider's typed refusal that condemns the API key until it is
83
+ * topped up, such as an exhausted prepaid balance. Never use for
84
+ * 401, 403 or short rate limits.
85
+ */
86
+ outcome: 'credential_refused';
87
+ credentialId: string;
88
+ /**
89
+ * What the provider actually sent: its own code from the structured
90
+ * error (OpenRouter's `openrouter_credits`). When the body carries
91
+ * no code, `http_<status>`, but only for a status the provider
92
+ * documents with a single balance meaning (DeepSeek's `http_402`).
93
+ * Never message text, and never a status with several meanings such
94
+ * as 403 or 429. Must match `^[a-z0-9._-]{1,64}$`.
95
+ */
96
+ providerCode: string;
80
97
  })) | {
81
98
  sessionId: string;
82
99
  kind: 'turn_notes_supported';
@@ -334,6 +334,19 @@ export function reportRouting(input) {
334
334
  };
335
335
  break;
336
336
  }
337
+ case 'credential_refused': {
338
+ const { credentialId, providerCode } = input;
339
+ if (!isNonEmptyString(credentialId) ||
340
+ typeof providerCode !== 'string' ||
341
+ !/^[a-z0-9._-]{1,64}$/.test(providerCode))
342
+ return;
343
+ payload = {
344
+ ...identity,
345
+ outcome: 'credential_refused',
346
+ provider_code: providerCode,
347
+ };
348
+ break;
349
+ }
337
350
  default:
338
351
  return;
339
352
  }
@@ -0,0 +1,35 @@
1
+ import { type ValueDescriptor, type ValueOf, type ValueValidationOptions } from './descriptors.js';
2
+ export interface SettingDeclaration<D extends ValueDescriptor = ValueDescriptor> {
3
+ readonly value: D;
4
+ readonly default: ValueDescriptor extends D ? unknown : ValueOf<D>;
5
+ readonly hosts: 'both' | 'opencode' | 'pi' | string;
6
+ readonly overrides?: {
7
+ readonly host?: true;
8
+ readonly model?: true;
9
+ };
10
+ readonly project?: 'user-only' | 'allowed';
11
+ readonly legacy?: readonly {
12
+ readonly source: string;
13
+ readonly path: readonly string[];
14
+ }[];
15
+ }
16
+ type Declarations = Readonly<Record<string, SettingDeclaration>>;
17
+ export interface SettingsDefinition<S extends Declarations = Declarations> {
18
+ readonly plugin: string;
19
+ readonly settings: {
20
+ readonly [K in keyof S]: S[K] & {
21
+ readonly project: S[K] extends {
22
+ readonly project: infer P;
23
+ } ? P : 'project' extends keyof S[K] ? Exclude<S[K]['project'], undefined> | 'user-only' : 'user-only';
24
+ };
25
+ };
26
+ }
27
+ export declare function defineSettings<const S extends Declarations>(definition: {
28
+ readonly plugin: string;
29
+ readonly settings: S;
30
+ }): SettingsDefinition<S>;
31
+ /** Internal helper: host names are reserved and never count as model ids. */
32
+ export declare function isOverrideKeyAllowed(overrides: NonNullable<SettingDeclaration['overrides']>, key: string): boolean;
33
+ /** Validate a file, update or map value, including any permitted override object. */
34
+ export declare function validateSettingValue(declaration: Pick<SettingDeclaration, 'value' | 'overrides'>, value: unknown, options?: ValueValidationOptions): boolean;
35
+ export {};
@@ -0,0 +1,52 @@
1
+ import { deepFreeze, isJsonObject, validateValue, } from './descriptors.js';
2
+ export function defineSettings(definition) {
3
+ for (const [name, declaration] of Object.entries(definition.settings)) {
4
+ if (name === 'schema_version' || name === '$schema') {
5
+ throw new TypeError(`Reserved setting name: ${name}`);
6
+ }
7
+ if (!/^[a-z][a-z0-9_]*$/.test(name) || /\s/.test(name)) {
8
+ throw new TypeError(`Setting name must be snake_case: ${name}`);
9
+ }
10
+ if (name === 'sidebar' && declaration.value.kind !== 'object') {
11
+ throw new TypeError('The sidebar setting must use an object descriptor');
12
+ }
13
+ if (declaration.overrides !== undefined &&
14
+ (declaration.value.kind === 'object' ||
15
+ declaration.value.kind === 'record')) {
16
+ throw new TypeError(`Object and record settings cannot use overrides: ${name}`);
17
+ }
18
+ if (!Object.hasOwn(declaration, 'default') ||
19
+ !validateValue(declaration.value, declaration.default, {
20
+ completeObjects: true,
21
+ })) {
22
+ throw new TypeError(`Invalid default for setting: ${name}`);
23
+ }
24
+ }
25
+ // Copy before freezing so the caller can still use its original default values.
26
+ return deepFreeze({
27
+ plugin: definition.plugin,
28
+ settings: Object.fromEntries(Object.entries(definition.settings).map(([name, declaration]) => [
29
+ name,
30
+ structuredClone({
31
+ ...declaration,
32
+ project: declaration.project ?? 'user-only',
33
+ }),
34
+ ])),
35
+ });
36
+ }
37
+ /** Internal helper: host names are reserved and never count as model ids. */
38
+ export function isOverrideKeyAllowed(overrides, key) {
39
+ if (key === 'default')
40
+ return true;
41
+ if (key === 'opencode' || key === 'pi')
42
+ return overrides.host === true;
43
+ return overrides.model === true;
44
+ }
45
+ /** Validate a file, update or map value, including any permitted override object. */
46
+ export function validateSettingValue(declaration, value, options = {}) {
47
+ if (declaration.overrides !== undefined && isJsonObject(value)) {
48
+ return Object.entries(value).every(([key, entry]) => isOverrideKeyAllowed(declaration.overrides ?? {}, key) &&
49
+ validateValue(declaration.value, entry, options));
50
+ }
51
+ return validateValue(declaration.value, value, options);
52
+ }