@cortexkit/common-auth 0.26.0 → 0.27.1

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 (43) hide show
  1. package/README.md +0 -16
  2. package/dist/claustrum/consumer.d.ts +77 -2
  3. package/dist/claustrum/consumer.js +320 -35
  4. package/dist/claustrum/custody.d.ts +36 -1
  5. package/dist/claustrum/custody.js +95 -11
  6. package/dist/claustrum/enrollment.js +37 -12
  7. package/dist/claustrum/hub.d.ts +195 -0
  8. package/dist/claustrum/hub.js +988 -0
  9. package/dist/claustrum/index.d.ts +13 -3
  10. package/dist/claustrum/index.js +37 -4
  11. package/dist/claustrum/quota-writer.d.ts +8 -1
  12. package/dist/claustrum/quota-writer.js +34 -12
  13. package/dist/claustrum/roster.d.ts +49 -1
  14. package/dist/claustrum/roster.js +187 -12
  15. package/dist/claustrum/shutdown.d.ts +8 -0
  16. package/dist/claustrum/shutdown.js +42 -0
  17. package/dist/fs/file-read-cache.d.ts +8 -0
  18. package/dist/fs/file-read-cache.js +57 -0
  19. package/dist/fs/refresh-file-lock.d.ts +1 -1
  20. package/dist/fs/refresh-file-lock.js +20 -11
  21. package/dist/opencode2/errors.d.ts +4 -1
  22. package/dist/opencode2/index.d.ts +2 -2
  23. package/dist/opencode2/index.js +1 -1
  24. package/dist/opencode2/install.d.ts +7 -5
  25. package/dist/opencode2/install.js +139 -13
  26. package/dist/opencode2/types.d.ts +42 -10
  27. package/dist/quota/commit-interval.d.ts +9 -0
  28. package/dist/quota/commit-interval.js +18 -0
  29. package/dist/redaction/index.d.ts +8 -0
  30. package/dist/redaction/index.js +490 -0
  31. package/dist/rpc/rpc-server.js +29 -19
  32. package/dist/setup/command.js +52 -14
  33. package/dist/setup/register.d.ts +2 -0
  34. package/dist/setup/register.js +90 -11
  35. package/dist/store/mutate.d.ts +2 -0
  36. package/dist/store/mutate.js +4 -0
  37. package/dist/store/pool.d.ts +6 -1
  38. package/dist/store/pool.js +1 -1
  39. package/dist/store/quota-writer.d.ts +5 -1
  40. package/dist/store/quota-writer.js +27 -13
  41. package/dist/store/settings.d.ts +1 -1
  42. package/dist/store/settings.js +16 -6
  43. package/package.json +6 -2
@@ -10,6 +10,7 @@ import { assertHostsStopped, createProcessFence, ProcessFenceViolationError, Pro
10
10
  import { selectSetupHosts } from './prompts.js';
11
11
  import { planOpenCodeRegistration, registerOpenCode, registerPi, } from './register.js';
12
12
  export const AMBIGUOUS_OPENCODE_MESSAGE = 'Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.';
13
+ const UNAVAILABLE_HOST_MESSAGE = 'Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.';
13
14
  function flags(argv) {
14
15
  const result = {
15
16
  yes: false,
@@ -17,6 +18,8 @@ function flags(argv) {
17
18
  claustrum: false,
18
19
  noClaustrum: false,
19
20
  login: false,
21
+ enrollOnly: false,
22
+ hosts: [],
20
23
  opencode: undefined,
21
24
  };
22
25
  for (const arg of argv) {
@@ -30,6 +33,14 @@ function flags(argv) {
30
33
  result.noClaustrum = true;
31
34
  else if (arg === '--login')
32
35
  result.login = true;
36
+ else if (arg === '--enroll-only')
37
+ result.enrollOnly = true;
38
+ else if (arg.startsWith('--host=')) {
39
+ const host = arg.slice('--host='.length);
40
+ if (host !== 'opencode' && host !== 'pi')
41
+ throw new Error(UNAVAILABLE_HOST_MESSAGE);
42
+ result.hosts.push(host);
43
+ }
33
44
  else if (/^--opencode=(1|2|both)$/.test(arg))
34
45
  result.opencode = arg.slice('--opencode='.length);
35
46
  else
@@ -39,6 +50,10 @@ function flags(argv) {
39
50
  throw new Error('--claustrum and --no-claustrum cannot be used together.');
40
51
  if (result.login && result.claustrum)
41
52
  throw new Error('--login and --claustrum cannot be used together.');
53
+ if (result.enrollOnly && result.login)
54
+ throw new Error('--enroll-only and --login cannot be used together.');
55
+ if (result.enrollOnly && result.noClaustrum)
56
+ throw new Error('--enroll-only and --no-claustrum cannot be used together.');
42
57
  return result;
43
58
  }
44
59
  function validatePlugin(plugin) {
@@ -96,14 +111,18 @@ export async function runSetup(plugin, argv = [], io = {}) {
96
111
  if (piWithoutCli)
97
112
  printLine(terminal, 'Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.');
98
113
  const found = ['opencode', 'pi'].filter((host) => detection[host].installed && !(host === 'pi' && piWithoutCli));
114
+ if (options.hosts.some((host) => !found.includes(host)))
115
+ throw new Error(UNAVAILABLE_HOST_MESSAGE);
99
116
  // A dry run changes nothing, so without a terminal it plans the --yes path
100
117
  // instead of refusing; scripts and CI can preview setup with --dry-run alone.
101
118
  const assumeYes = options.yes || (options.dryRun && !isInteractive(terminal));
102
119
  if (!assumeYes && !isInteractive(terminal))
103
120
  throw new Error('Setup requires a TTY or --yes.');
104
- const hosts = assumeYes
105
- ? found
106
- : ((await selectSetupHosts(terminal, found)) ?? []);
121
+ const hosts = options.hosts.length
122
+ ? found.filter((host) => options.hosts.includes(host))
123
+ : assumeYes
124
+ ? found
125
+ : ((await selectSetupHosts(terminal, found)) ?? []);
107
126
  let generation = options.opencode ??
108
127
  (detection.opencode.generation === 'ambiguous'
109
128
  ? '1'
@@ -160,9 +179,10 @@ export async function runSetup(plugin, argv = [], io = {}) {
160
179
  }
161
180
  else
162
181
  await stopped();
163
- if (options.claustrum && !detection.claustrum.available)
164
- throw new Error('Claustrum is not available. Start ck or use --no-claustrum for local sign-in.');
165
- let useVault = Boolean(options.claustrum);
182
+ if ((options.claustrum || options.enrollOnly) &&
183
+ !detection.claustrum.available)
184
+ throw new Error('Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.');
185
+ let useVault = options.claustrum || options.enrollOnly;
166
186
  if (!useVault &&
167
187
  !options.login &&
168
188
  !options.noClaustrum &&
@@ -182,10 +202,20 @@ export async function runSetup(plugin, argv = [], io = {}) {
182
202
  useVault = choice === true;
183
203
  }
184
204
  const mode = useVault ? 'claustrum' : 'local';
185
- // Validate every config before login or enrollment can change credential state.
186
- const writes = hosts.includes('opencode')
205
+ // Validate configs before changing credentials; enrollment-only needs no registration plan.
206
+ const writes = !options.enrollOnly && hosts.includes('opencode')
187
207
  ? planOpenCodeRegistration(plugin, generation, io)
188
208
  : [];
209
+ for (const write of writes) {
210
+ for (const entry of write.existingLocalEntries ?? [])
211
+ printLine(terminal, `OpenCode: already registered from ${entry} in ${write.path}.`);
212
+ const entries = [
213
+ ...(write.existingLocalEntries ?? []),
214
+ ...(write.existingNpmEntries ?? []),
215
+ ];
216
+ if (entries.length > 1)
217
+ printLine(terminal, `Warning: ${plugin.displayName} may load twice in ${write.path}: ${entries.join(', ')}. Entries were left unchanged.`);
218
+ }
189
219
  if (options.dryRun) {
190
220
  printLine(terminal, 'Dry run: no registrations, enrollment, sign-in or migration will be performed.');
191
221
  for (const host of hosts) {
@@ -197,15 +227,16 @@ export async function runSetup(plugin, argv = [], io = {}) {
197
227
  }
198
228
  else
199
229
  printLine(terminal, `Would sign in locally for ${host}.`);
200
- if (plugin.beforeRegister)
230
+ if (!options.enrollOnly && plugin.beforeRegister)
201
231
  printLine(terminal, `Would run beforeRegister(${host}, ${mode}).`);
202
232
  }
203
233
  for (const write of writes)
204
234
  printLine(terminal, `${write.changed ? 'Would write' : 'Unchanged'} ${write.path}:\n${write.content}`);
205
- if (hosts.includes('pi'))
235
+ if (!options.enrollOnly && hosts.includes('pi'))
206
236
  printLine(terminal, `Would run ${detection.pi.executable} install npm:${plugin.packages.pi}@${plugin.version}`);
207
- for (const host of hosts)
208
- printLine(terminal, `Would migrate ${host} using the plugin callback (provider-specific writes).`);
237
+ if (!options.enrollOnly)
238
+ for (const host of hosts)
239
+ printLine(terminal, `Would migrate ${host} using the plugin callback (provider-specific writes).`);
209
240
  }
210
241
  else {
211
242
  const context = {
@@ -237,6 +268,8 @@ export async function runSetup(plugin, argv = [], io = {}) {
237
268
  else
238
269
  await plugin.signInLocal(host, context);
239
270
  await stopped();
271
+ if (options.enrollOnly)
272
+ continue;
240
273
  await plugin.beforeRegister?.(host, mode, context);
241
274
  await stopped();
242
275
  if (host === 'opencode')
@@ -265,7 +298,12 @@ export async function runSetup(plugin, argv = [], io = {}) {
265
298
  throw error;
266
299
  }
267
300
  }
268
- printLine(terminal, `${options.dryRun ? 'Planned' : 'Configured'} ${plugin.displayName} for ${hosts.join(', ')} (${mode}).`);
269
- printLine(terminal, `Next: ${hosts.includes('opencode') ? 'start OpenCode' : 'start Pi'} and run ${plugin.slashCommand}.`);
301
+ printLine(terminal, `${options.dryRun ? 'Planned' : options.enrollOnly ? 'Enrolled' : 'Configured'} ${plugin.displayName} for ${hosts.join(', ')} (${mode}).`);
302
+ if (options.enrollOnly) {
303
+ printLine(terminal, `Enroll-only: no host config or plugin registration ${options.dryRun ? 'will be' : 'was'} written.`);
304
+ printLine(terminal, 'Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.');
305
+ }
306
+ else
307
+ printLine(terminal, `Next: ${hosts.includes('opencode') ? 'start OpenCode' : 'start Pi'} and run ${plugin.slashCommand}.`);
270
308
  return { hosts, dryRun: options.dryRun, mode, detection };
271
309
  }
@@ -3,6 +3,8 @@ export interface PlannedWrite {
3
3
  path: string;
4
4
  content: string;
5
5
  changed: boolean;
6
+ existingLocalEntries?: string[];
7
+ existingNpmEntries?: string[];
6
8
  }
7
9
  /** Edit only array entries so unrelated JSONC text, including comments, survives. */
8
10
  export declare function updatePluginConfig(text: string, key: 'plugin' | 'plugins', pkg: string, version: string): string;
@@ -1,10 +1,11 @@
1
+ import { domainToUnicode } from 'node:url';
1
2
  import { applyEdits, createScanner, findNodeAtLocation, modify, parse, parseTree, } from 'jsonc-parser';
2
3
  import { SetupCommandError } from './command-error.js';
3
4
  import { defaultCommandRunner, runResolvedCommand } from './command-runner.js';
4
5
  import { writeHostConfigAtomic } from './config-write.js';
5
6
  import { defaultSetupFileSystem } from './detect.js';
6
7
  import { setupPaths } from './paths.js';
7
- function packageOf(value) {
8
+ function specifierOf(value) {
8
9
  const entry = typeof value === 'string'
9
10
  ? value
10
11
  : Array.isArray(value)
@@ -12,11 +13,72 @@ function packageOf(value) {
12
13
  : value && typeof value === 'object' && 'package' in value
13
14
  ? value.package
14
15
  : null;
15
- if (typeof entry !== 'string')
16
+ return typeof entry === 'string' ? entry : null;
17
+ }
18
+ function packageOf(value) {
19
+ const entry = specifierOf(value);
20
+ if (entry === null)
16
21
  return null;
17
22
  const at = entry.indexOf('@', entry.startsWith('@') ? 1 : 0);
18
23
  return at < 0 ? entry : entry.slice(0, at);
19
24
  }
25
+ function localFileURL(entry, windows) {
26
+ const url = new URL(entry);
27
+ if (/%2f/i.test(url.pathname) || (windows && /%5c/i.test(url.pathname)))
28
+ throw new Error('Encoded path separators are not valid in a file URL.');
29
+ const decoded = decodeURIComponent(url.pathname);
30
+ if (!windows) {
31
+ if (url.hostname)
32
+ throw new Error('A POSIX file URL must be local.');
33
+ return decoded;
34
+ }
35
+ const pathname = decoded.replaceAll('/', '\\');
36
+ if (url.hostname)
37
+ return `\\\\${domainToUnicode(url.hostname)}${pathname}`;
38
+ if (!/^\\[a-z]:/i.test(pathname))
39
+ throw new Error('A Windows file URL must have an absolute drive path.');
40
+ return pathname.slice(1);
41
+ }
42
+ function localPackageOf(entry, configFile, io) {
43
+ const { path, platform } = setupPaths(io);
44
+ try {
45
+ // Relative paths use the declaring config's directory, not setup's working directory:
46
+ // https://github.com/anomalyco/opencode/blob/b6478dce/packages/opencode/src/config/plugin.ts#L40-L60
47
+ // https://github.com/anomalyco/opencode/blob/v2.0.22/packages/core/src/config/plugin/source.ts#L139-L145
48
+ // Decode file URLs explicitly: Bun 1.3 ignores fileURLToPath's Windows override.
49
+ // The requested platform, not the OS running setup's tests, determines path rules.
50
+ const directory = /^file:\/\//i.test(entry)
51
+ ? localFileURL(entry, platform === 'win32')
52
+ : path.isAbsolute(entry) || entry.startsWith('.')
53
+ ? path.resolve(path.dirname(configFile), entry)
54
+ : null;
55
+ if (directory === null)
56
+ return null;
57
+ const manifest = JSON.parse((io.fs ?? defaultSetupFileSystem).readText(path.join(directory, 'package.json')));
58
+ return manifest &&
59
+ typeof manifest === 'object' &&
60
+ 'name' in manifest &&
61
+ typeof manifest.name === 'string'
62
+ ? manifest.name
63
+ : null;
64
+ }
65
+ catch {
66
+ // A missing, unreadable or invalid local package is not a registration of this plugin.
67
+ return null;
68
+ }
69
+ }
70
+ function pluginConfig(text, key) {
71
+ const errors = [];
72
+ const value = parse(text, errors, { allowTrailingComma: true });
73
+ if (errors.length ||
74
+ !value ||
75
+ typeof value !== 'object' ||
76
+ Array.isArray(value))
77
+ throw new Error('Invalid OpenCode config; refusing to overwrite it.');
78
+ if (value[key] !== undefined && !Array.isArray(value[key]))
79
+ throw new Error(`OpenCode ${key} must be an array.`);
80
+ return value;
81
+ }
20
82
  function removeArrayEntry(text, key, index) {
21
83
  const tree = parseTree(text);
22
84
  const array = tree && findNodeAtLocation(tree, [key]);
@@ -48,13 +110,7 @@ function removeArrayEntry(text, key, index) {
48
110
  }
49
111
  /** Edit only array entries so unrelated JSONC text, including comments, survives. */
50
112
  export function updatePluginConfig(text, key, pkg, version) {
51
- const errors = [];
52
- const value = parse(text, errors, { allowTrailingComma: true });
53
- if (errors.length ||
54
- !value ||
55
- typeof value !== 'object' ||
56
- Array.isArray(value))
57
- throw new Error('Invalid OpenCode config; refusing to overwrite it.');
113
+ const value = pluginConfig(text, key);
58
114
  const options = {
59
115
  formattingOptions: {
60
116
  insertSpaces: !/^\t+/m.test(text),
@@ -64,8 +120,6 @@ export function updatePluginConfig(text, key, pkg, version) {
64
120
  };
65
121
  let output = text;
66
122
  const array = value[key];
67
- if (array !== undefined && !Array.isArray(array))
68
- throw new Error(`OpenCode ${key} must be an array.`);
69
123
  const entries = Array.isArray(array) ? [...array] : [];
70
124
  const matches = entries.flatMap((entry, index) => packageOf(entry) === pkg ? [index] : []);
71
125
  const entry = `${pkg}@${version}`;
@@ -109,6 +163,31 @@ export function planOpenCodeRegistration(plugin, generation, io = {}) {
109
163
  const before = exists
110
164
  ? fs.readText(file)
111
165
  : `${JSON.stringify({ $schema: `https://opencode.ai/${name === 'tui' ? 'tui' : 'config'}.json` }, null, 2)}\n`;
166
+ const config = pluginConfig(before, key);
167
+ const existingLocalEntries = [];
168
+ const existingNpmEntries = [];
169
+ for (const field of ['plugin', 'plugins']) {
170
+ if (!Array.isArray(config[field]))
171
+ continue;
172
+ for (const entry of config[field]) {
173
+ const spec = specifierOf(entry);
174
+ if (spec === null)
175
+ continue;
176
+ if (localPackageOf(spec, file, io) === plugin.packages.opencode)
177
+ existingLocalEntries.push(JSON.stringify(entry));
178
+ else if (packageOf(entry) === plugin.packages.opencode)
179
+ existingNpmEntries.push(JSON.stringify(entry));
180
+ }
181
+ }
182
+ // A local build is deliberate: do not replace it, deduplicate it or migrate its key.
183
+ if (existingLocalEntries.length > 0)
184
+ return {
185
+ path: file,
186
+ content: before,
187
+ changed: false,
188
+ existingLocalEntries,
189
+ existingNpmEntries,
190
+ };
112
191
  const content = updatePluginConfig(before, key, plugin.packages.opencode, plugin.version);
113
192
  return { path: file, content, changed: !exists || content !== before };
114
193
  });
@@ -52,6 +52,8 @@ export type ReadResult = ({
52
52
  kind?: 'snapshot-contended';
53
53
  retryable?: true;
54
54
  };
55
+ /** Settings need only the config classification, not a joined roster snapshot. */
56
+ export declare function readPoolConfig(path: string): Promise<import("./schema.js").ConfigClassification>;
55
57
  /**
56
58
  * Validate config/state/config bytes without locks. Roster replacement writes
57
59
  * config before deleting old state credentials. Re-read a changed config so an
@@ -28,6 +28,10 @@ function parseFile(text) {
28
28
  return { exists: true, parseError };
29
29
  }
30
30
  }
31
+ /** Settings need only the config classification, not a joined roster snapshot. */
32
+ export async function readPoolConfig(path) {
33
+ return classifyConfig(parseFile(await readText(path)));
34
+ }
31
35
  /**
32
36
  * Validate config/state/config bytes without locks. Roster replacement writes
33
37
  * config before deleting old state credentials. Re-read a changed config so an
@@ -1,3 +1,4 @@
1
+ import type { QuotaCommitTimer } from '../quota/commit-interval.js';
1
2
  import { type Attribution } from './attribution.js';
2
3
  import type { PoolOperationError } from './errors.js';
3
4
  import type { PoolLogger } from './hooks.js';
@@ -24,11 +25,15 @@ export interface OpenPoolStoreOptions {
24
25
  * older reading replaces. Accepted readings appear in read/load
25
26
  * immediately, merged the same way; the returned promise still rejects
26
27
  * current-row refusals before queueing. Await dispose or close at shutdown
27
- * to drain.
28
+ * to attempt a bounded drain; readings still pending at its timeout are
29
+ * discarded. Normal quota commits are at least 30 seconds apart; a full
30
+ * queue commits early so response handling never waits for that interval.
28
31
  */
29
32
  coalesceQuota?: boolean;
30
33
  /** Bounded quota drain on close/dispose, in milliseconds; defaults to 1,000. */
31
34
  quotaDrainTimeoutMs?: number;
35
+ /** Monotonic clock and scheduling seam for detached quota commits. */
36
+ quotaCommitTimer?: QuotaCommitTimer;
32
37
  /**
33
38
  * The codec of the provider state kept beside each row's credential (see
34
39
  * `ProviderStateCodec`). Without it no row shows a provider state, and
@@ -82,7 +82,7 @@ export function openPoolStore(options) {
82
82
  firePull: (id, reason) => pulls.fire(id, reason),
83
83
  };
84
84
  const quotaWriter = options.coalesceQuota
85
- ? new PoolQuotaWriter(rt, options.quotaDrainTimeoutMs)
85
+ ? new PoolQuotaWriter(rt, options.quotaDrainTimeoutMs, options.quotaCommitTimer)
86
86
  : undefined;
87
87
  const record = (id, attribution, observation) => quotaWriter
88
88
  ? quotaWriter.record(id, attribution, observation)
@@ -1,3 +1,4 @@
1
+ import { type QuotaCommitTimer } from '../quota/commit-interval.js';
1
2
  import { type Attribution } from './attribution.js';
2
3
  import { type StoreRuntime } from './runtime.js';
3
4
  import { type PoolRow } from './schema.js';
@@ -14,17 +15,19 @@ export declare const POOL_QUOTA_QUEUE_LIMIT = 128;
14
15
  export declare class PoolQuotaWriter {
15
16
  private readonly rt;
16
17
  private readonly timeoutMs;
18
+ private readonly clock;
17
19
  private readonly pending;
18
20
  private readonly warned;
19
21
  private readonly wake;
20
22
  private readonly logger;
21
23
  private timer?;
24
+ private committedAt?;
22
25
  private running?;
23
26
  private closing?;
24
27
  private closed;
25
28
  private stopped;
26
29
  private failures;
27
- constructor(rt: StoreRuntime, timeoutMs?: number);
30
+ constructor(rt: StoreRuntime, timeoutMs?: number, clock?: QuotaCommitTimer);
28
31
  record(id: string, attribution: Attribution, observation: unknown): Promise<void>;
29
32
  private queued;
30
33
  private room;
@@ -32,6 +35,7 @@ export declare class PoolQuotaWriter {
32
35
  private overlayRow;
33
36
  overlay(rows: PoolRow[]): PoolRow[];
34
37
  private schedule;
38
+ private cancelTimer;
35
39
  private flushNow;
36
40
  private flush;
37
41
  private warn;
@@ -1,4 +1,5 @@
1
1
  import { createLogger } from '../logger/index.js';
2
+ import { QUOTA_COMMIT_INTERVAL_MS, quotaCommitTimer, } from '../quota/commit-interval.js';
2
3
  import { assertQuotaEpoch, assertQuotaRow, mergedQuota, } from './attribution.js';
3
4
  import { PoolOperationError } from './errors.js';
4
5
  import { toFailure, withTransaction } from './mutate.js';
@@ -24,19 +25,22 @@ export const POOL_QUOTA_QUEUE_LIMIT = 128;
24
25
  export class PoolQuotaWriter {
25
26
  rt;
26
27
  timeoutMs;
28
+ clock;
27
29
  pending = new Map();
28
30
  warned = new Set();
29
31
  wake = new Set();
30
32
  logger;
31
33
  timer;
34
+ committedAt;
32
35
  running;
33
36
  closing;
34
37
  closed = false;
35
38
  stopped = false;
36
39
  failures = 0;
37
- constructor(rt, timeoutMs = 1_000) {
40
+ constructor(rt, timeoutMs = 1_000, clock = quotaCommitTimer) {
38
41
  this.rt = rt;
39
42
  this.timeoutMs = timeoutMs;
43
+ this.clock = clock;
40
44
  this.logger = rt.ctx.logger ?? createLogger('store');
41
45
  }
42
46
  async record(id, attribution, observation) {
@@ -126,25 +130,33 @@ export class PoolQuotaWriter {
126
130
  schedule(delay) {
127
131
  if (this.running || this.timer || !this.pending.size || this.stopped)
128
132
  return;
129
- this.timer = setTimeout(() => {
133
+ const remaining = this.closed
134
+ ? 0
135
+ : (this.committedAt ?? -Infinity) +
136
+ QUOTA_COMMIT_INTERVAL_MS -
137
+ this.clock.now();
138
+ this.timer = this.clock.schedule(Math.max(delay, remaining), () => {
130
139
  this.timer = undefined;
131
- this.flush();
132
- }, delay);
140
+ return this.flush();
141
+ });
133
142
  if (!this.closed)
134
143
  this.timer.unref?.();
135
144
  }
136
- // Starts a flush now rather than at the coalescing timer or retry backoff;
137
- // a flush already running is left to finish.
145
+ cancelTimer() {
146
+ this.timer?.cancel();
147
+ this.timer = undefined;
148
+ }
149
+ // A full queue overrides the interval: response handling must not wait for
150
+ // a quota commit slot. A flush already running is left to finish.
138
151
  flushNow() {
139
152
  if (this.running)
140
153
  return;
141
- clearTimeout(this.timer);
142
- this.timer = undefined;
154
+ this.cancelTimer();
143
155
  this.flush();
144
156
  }
145
157
  flush() {
146
158
  if (this.running || this.stopped || !this.pending.size)
147
- return;
159
+ return this.running ?? Promise.resolve();
148
160
  // Every queued reading, each row's in arrival order.
149
161
  const batch = [...this.pending.values()].flat();
150
162
  // Short lock attempts allow retries to pick up freshly queued readings and
@@ -208,8 +220,10 @@ export class PoolQuotaWriter {
208
220
  tx.setEntry(id, { ...entry, quota, needsFirstReading: false });
209
221
  changed = true;
210
222
  }
211
- if (changed && !this.stopped)
223
+ if (changed && !this.stopped) {
212
224
  await tx.commitConfig();
225
+ this.committedAt = this.clock.now();
226
+ }
213
227
  }, { completeTorn: false });
214
228
  const flushed = new Set(batch);
215
229
  for (const [id, queue] of this.pending) {
@@ -240,6 +254,7 @@ export class PoolQuotaWriter {
240
254
  this.schedule(delay);
241
255
  }
242
256
  })();
257
+ return this.running;
243
258
  }
244
259
  warn(message, data) {
245
260
  try {
@@ -257,8 +272,7 @@ export class PoolQuotaWriter {
257
272
  return this.closing;
258
273
  }
259
274
  async drain() {
260
- clearTimeout(this.timer);
261
- this.timer = undefined;
275
+ this.cancelTimer();
262
276
  let deadline;
263
277
  let wake;
264
278
  const drained = new Promise((done) => {
@@ -281,7 +295,7 @@ export class PoolQuotaWriter {
281
295
  finally {
282
296
  this.stopped = true;
283
297
  clearTimeout(deadline);
284
- clearTimeout(this.timer);
298
+ this.cancelTimer();
285
299
  this.wake.delete(wake);
286
300
  if (this.pending.size)
287
301
  this.warn('pool quota drain timed out; pending readings left', {
@@ -50,7 +50,7 @@ export type UpdateSettingsResult = {
50
50
  /** `unchanged` when the mutator left the settings as they were; nothing was written. */
51
51
  outcome: 'updated' | 'unchanged';
52
52
  };
53
- /** Reads the settings without taking a lock or writing anything. */
53
+ /** Reads only the config's settings, without taking a lock or writing anything. */
54
54
  export declare function readPoolSettings(rt: StoreRuntime): Promise<SettingsRead>;
55
55
  /**
56
56
  * One locked read-modify-write of the plugin's settings in the config file
@@ -1,8 +1,10 @@
1
1
  import { isDeepStrictEqual } from 'node:util';
2
2
  import { writeJsonAtomic } from '../fs/atomic-write.js';
3
+ import { FileReadCache } from '../fs/file-read-cache.js';
4
+ import { windowsPrivateFiles } from '../fs/private-files.js';
3
5
  import { PoolOperationError } from './errors.js';
4
6
  import { assertNotInsideHook, runInsideHook } from './hooks.js';
5
- import { notReadyError, readPool, runOperation } from './mutate.js';
7
+ import { notReadyError, readPool, readPoolConfig, runOperation, } from './mutate.js';
6
8
  import { isRecord, POOL_KEY } from './schema.js';
7
9
  /**
8
10
  * Top-level config keys the pool owns: the legacy `version`, the legacy
@@ -58,12 +60,20 @@ function settingsRefusal(message) {
58
60
  message,
59
61
  });
60
62
  }
61
- /** Reads the settings without taking a lock or writing anything. */
63
+ const settingsCache = new FileReadCache();
64
+ /** Reads only the config's settings, without taking a lock or writing anything. */
62
65
  export async function readPoolSettings(rt) {
63
- const result = await readPool(rt.ctx);
64
- if (result.status === 'error')
65
- return result;
66
- return { status: result.status, settings: settingsOf(result.config) };
66
+ const read = async ([configPath = rt.ctx.configPath,] = []) => {
67
+ const result = await readPoolConfig(configPath);
68
+ if (result.status === 'error')
69
+ return { status: 'error', file: 'config', reason: result.reason };
70
+ return { status: result.status, settings: settingsOf(result.config) };
71
+ };
72
+ // Native Windows security checks cannot be replaced by a stat fingerprint.
73
+ const result = windowsPrivateFiles
74
+ ? await read()
75
+ : await settingsCache.read([rt.ctx.configPath], read);
76
+ return structuredClone(result);
67
77
  }
68
78
  /**
69
79
  * One locked read-modify-write of the plugin's settings in the config file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.26.0",
3
+ "version": "0.27.1",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -36,6 +36,10 @@
36
36
  "types": "./dist/logger/index.d.ts",
37
37
  "import": "./dist/logger/index.js"
38
38
  },
39
+ "./redaction": {
40
+ "types": "./dist/redaction/index.d.ts",
41
+ "import": "./dist/redaction/index.js"
42
+ },
39
43
  "./sidebar-file": {
40
44
  "types": "./dist/sidebar-file/index.d.ts",
41
45
  "import": "./dist/sidebar-file/index.js"
@@ -95,7 +99,7 @@
95
99
  "scripts": {
96
100
  "build": "bun scripts/check-local-deps.mjs && bun scripts/check-installed-ranges.mjs && tsc -p tsconfig.build.json && bun scripts/check-private-files-external.ts",
97
101
  "test": "bun test",
98
- "typecheck": "tsc --noEmit",
102
+ "typecheck": "tsc --noEmit && tsc -p test/redaction/tsconfig.json --noEmit",
99
103
  "types": "bun run typecheck",
100
104
  "format": "biome check --write --unsafe .",
101
105
  "format:check": "biome format .",