@cortexkit/opencode-openai-auth 1.7.0 → 1.8.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 (72) hide show
  1. package/dist/bin.js +9 -9
  2. package/dist/{codex-request-CN4rD2kf.d.ts → codex-request-DohnbsFR.d.ts} +69 -21
  3. package/dist/index-3v868rnp.js +63 -0
  4. package/dist/{index-7zy4vdd3.js → index-5d4y47h8.js} +2 -2
  5. package/dist/{index-yayz83vv.js → index-5dxpsa3t.js} +2 -2
  6. package/dist/{index-dr93b3g6.js → index-8pk9savd.js} +6 -6
  7. package/dist/{index-g08eptzm.js → index-cbcka7sa.js} +1 -1
  8. package/dist/{index-p9vnmnzr.js → index-cxstwq02.js} +1 -1
  9. package/dist/{index-r4avvxf0.js → index-dtwgf694.js} +1 -1
  10. package/dist/index-dzaqj248.js +2 -0
  11. package/dist/index-g3d50jz0.js +74 -0
  12. package/dist/{index-2e2kqmsy.js → index-n7fxqgfb.js} +2 -2
  13. package/dist/{index-b5459de4.js → index-th47aqez.js} +2 -2
  14. package/dist/index-tvban5vp.js +91 -0
  15. package/dist/{index-jaqm1xda.js → index-x7jzcvqy.js} +1 -1
  16. package/dist/index.d.ts +4 -2
  17. package/dist/index.js +1 -1
  18. package/dist/{port-file-8ElfwDcq.d.ts → port-file-DQ7-ItDK.d.ts} +1 -1
  19. package/dist/{protocol-BeeDdtpa.d.ts → protocol-CVQK-d3j.d.ts} +1 -1
  20. package/dist/rpc/port-file.d.ts +4 -2
  21. package/dist/rpc/port-file.js +1 -1
  22. package/dist/rpc/protocol.d.ts +1 -1
  23. package/dist/rpc/protocol.js +1 -1
  24. package/dist/rpc/rpc-client.d.ts +1 -1
  25. package/dist/rpc/rpc-client.js +1 -1
  26. package/dist/rpc/rpc-dir.js +1 -1
  27. package/dist/{rpc-client-DlR9a0_7.d.ts → rpc-client-BQfIKrXI.d.ts} +3 -3
  28. package/dist/{sidebar-state-DHsZ9axt.d.ts → sidebar-state-B1cq68UB.d.ts} +4 -4
  29. package/dist/sidebar-state.d.ts +1 -1
  30. package/dist/sidebar-state.js +1 -1
  31. package/dist/{token-511npvw8.js → token-gy442bba.js} +1 -1
  32. package/dist/token-util-rxy0p234.js +1 -0
  33. package/dist/tui-preferences.js +1 -1
  34. package/dist/tui.d.ts +3 -3
  35. package/dist/v2/server.d.ts +15 -7
  36. package/dist/v2/server.js +2 -2
  37. package/package.json +2 -2
  38. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +95 -11
  39. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +320 -35
  40. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +187 -12
  41. package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +988 -0
  42. package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +4 -0
  43. package/src/tui-compiled/raw/shared/81dddd203f1b92a3-quota-writer.js +34 -12
  44. package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +16 -6
  45. package/src/tui-compiled/raw/shared/88b7fc40900fb003-commit-interval.js +18 -0
  46. package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +57 -0
  47. package/src/tui-compiled/raw/shared/a670cb7f5987bc1b-shutdown.js +42 -0
  48. package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +37 -12
  49. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +1 -1
  50. package/src/tui-compiled/raw/shared/c911dbb64c9d85c7-quota-writer.js +27 -13
  51. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +20 -11
  52. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +37 -4
  53. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +95 -11
  54. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +320 -35
  55. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +187 -12
  56. package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +988 -0
  57. package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +4 -0
  58. package/src/tui-compiled/runtime/shared/81dddd203f1b92a3-quota-writer.js +34 -12
  59. package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +16 -6
  60. package/src/tui-compiled/runtime/shared/88b7fc40900fb003-commit-interval.js +18 -0
  61. package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +57 -0
  62. package/src/tui-compiled/runtime/shared/a670cb7f5987bc1b-shutdown.js +42 -0
  63. package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +37 -12
  64. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +1 -1
  65. package/src/tui-compiled/runtime/shared/c911dbb64c9d85c7-quota-writer.js +27 -13
  66. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +20 -11
  67. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +37 -4
  68. package/dist/index-0p3cbtwq.js +0 -2
  69. package/dist/index-apkavdvq.js +0 -90
  70. package/dist/index-qg2syg0r.js +0 -65
  71. package/dist/index-se9ykks8.js +0 -69
  72. package/dist/token-util-jsw1zdc6.js +0 -1
@@ -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,5 +1,6 @@
1
1
  import { resolve } from "node:path";
2
2
  import { createLogger } from "./cc9e0702a752cea7-index.js";
3
+ import { QUOTA_COMMIT_INTERVAL_MS, quotaCommitTimer, } from "./88b7fc40900fb003-commit-interval.js";
3
4
  import { isQuotaObservation } from "./d5a8f1061ee2f114-index.js";
4
5
  import { quotaFields } from "./e1c5e56df0ba4053-pending.js";
5
6
  import { applyVaultQuota, mutateVaultRoster, } from "./30f5bc480f31f51c-roster.js";
@@ -7,7 +8,7 @@ import { applyVaultQuota, mutateVaultRoster, } from "./30f5bc480f31f51c-roster.j
7
8
  const writers = new Map();
8
9
  const logger = createLogger('claustrum');
9
10
  const COALESCE_MS = 100;
10
- function writerFor(path) {
11
+ function writerFor(path, clock = quotaCommitTimer) {
11
12
  const key = resolve(path);
12
13
  let writer = writers.get(key);
13
14
  if (!writer) {
@@ -17,6 +18,7 @@ function writerFor(path) {
17
18
  listeners: new Set(),
18
19
  wake: new Set(),
19
20
  abort: new AbortController(),
21
+ clock,
20
22
  failures: 0,
21
23
  draining: false,
22
24
  order: 0,
@@ -26,8 +28,8 @@ function writerFor(path) {
26
28
  return writer;
27
29
  }
28
30
  /** Retain the shared writer; the last consumer's close drains it. */
29
- export function retainVaultQuotaWriter(path, listener) {
30
- const writer = writerFor(path);
31
+ export function retainVaultQuotaWriter(path, listener, clock) {
32
+ const writer = writerFor(path, clock);
31
33
  writer.listeners.add(listener);
32
34
  let released;
33
35
  return () => (released ??= (() => {
@@ -93,37 +95,57 @@ export function pendingVaultQuota(path, roster) {
93
95
  }
94
96
  return roster;
95
97
  }
98
+ /**
99
+ * Whether this process holds quota readings for `path` that no commit of the
100
+ * durable roster has written yet, so a reader of the file alone is not seeing
101
+ * everything this process would publish.
102
+ */
103
+ export function hasPendingVaultQuota(path) {
104
+ return !!writers.get(resolve(path))?.pending.size;
105
+ }
96
106
  function schedule(writer, delay) {
97
107
  if (writer.running ||
98
108
  writer.timer ||
99
109
  !writer.pending.size ||
100
110
  writer.abort.signal.aborted)
101
111
  return;
102
- writer.timer = setTimeout(() => {
112
+ const remaining = writer.draining
113
+ ? 0
114
+ : (writer.committedAt ?? -Infinity) +
115
+ QUOTA_COMMIT_INTERVAL_MS -
116
+ writer.clock.now();
117
+ writer.timer = writer.clock.schedule(Math.max(delay, remaining), () => {
103
118
  writer.timer = undefined;
104
- flush(writer);
105
- }, delay);
119
+ return flush(writer);
120
+ });
106
121
  if (!writer.draining)
107
122
  writer.timer.unref?.();
108
123
  }
124
+ function cancelTimer(writer) {
125
+ writer.timer?.cancel();
126
+ writer.timer = undefined;
127
+ }
109
128
  function flush(writer) {
110
129
  if (writer.running || writer.abort.signal.aborted)
111
- return;
130
+ return writer.running ?? Promise.resolve();
112
131
  const batch = new Map([...writer.pending].map(([account, pending]) => [
113
132
  account,
114
133
  new Map(pending),
115
134
  ]));
116
135
  writer.running = (async () => {
117
136
  try {
118
- await mutateVaultRoster(writer.path, (current) => {
137
+ const committed = await mutateVaultRoster(writer.path, (current) => {
119
138
  let next = current;
120
139
  for (const field of orderedFields(batch)) {
121
140
  if (field.priorReading)
122
141
  next = applyVaultQuota(next, field.priorReading).roster;
123
142
  next = applyVaultQuota(next, field.publication).roster;
124
143
  }
125
- return { ...(next !== current && { next }), result: undefined };
144
+ const changed = JSON.stringify(next) !== JSON.stringify(current);
145
+ return { ...(changed && { next }), result: changed };
126
146
  }, { signal: writer.abort.signal });
147
+ if (committed)
148
+ writer.committedAt = writer.clock.now();
127
149
  for (const [account, fields] of batch) {
128
150
  const pending = writer.pending.get(account);
129
151
  for (const [key, field] of fields) {
@@ -155,6 +177,7 @@ function flush(writer) {
155
177
  schedule(writer, backoff);
156
178
  }
157
179
  })();
180
+ return writer.running;
158
181
  }
159
182
  /** Wait at most timeoutMs for detached publication; shutdown loss is acceptable. */
160
183
  export async function drainVaultQuota(path, timeoutMs = 1_000) {
@@ -163,8 +186,7 @@ export async function drainVaultQuota(path, timeoutMs = 1_000) {
163
186
  if (!writer)
164
187
  return;
165
188
  writer.draining = true;
166
- clearTimeout(writer.timer);
167
- writer.timer = undefined;
189
+ cancelTimer(writer);
168
190
  let deadline;
169
191
  let wake;
170
192
  const drained = new Promise((done) => {
@@ -194,7 +216,7 @@ export async function drainVaultQuota(path, timeoutMs = 1_000) {
194
216
  // must not discard its observations or stop its retries.
195
217
  if (!writer.listeners.size) {
196
218
  writer.abort.abort();
197
- clearTimeout(writer.timer);
219
+ cancelTimer(writer);
198
220
  writer.pending.clear();
199
221
  if (writers.get(key) === writer)
200
222
  writers.delete(key);
@@ -1,8 +1,10 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
2
  import { writeJsonAtomic } from "./7211cfec06a298bc-atomic-write.js";
3
+ import { FileReadCache } from "./92e38944b51b2405-file-read-cache.js";
4
+ import { windowsPrivateFiles } from "./375d9cca2def037d-private-files.js";
3
5
  import { PoolOperationError } from "./04a6357627de5ed0-errors.js";
4
6
  import { assertNotInsideHook, runInsideHook } from "./9deae3c4da4fd63b-hooks.js";
5
- import { notReadyError, readPool, runOperation } from "./458b934e92490331-mutate.js";
7
+ import { notReadyError, readPool, readPoolConfig, runOperation, } from "./458b934e92490331-mutate.js";
6
8
  import { isRecord, POOL_KEY } from "./cd94316a888b0a8e-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
@@ -0,0 +1,18 @@
1
+ // Atomic quota commits create locks, markers and a renamed temp file. Keep
2
+ // those filesystem events at least 30 s apart under normal load; routing sees
3
+ // pending readings immediately, while other processes may lag by one interval.
4
+ // Shutdown drains and a full bounded pool queue can commit sooner.
5
+ // The vault shares one gate per resolved path; each pool handle has its own.
6
+ // N pool handles on one file can therefore make N normal commits per interval
7
+ // in one process. These gates do not coordinate with other processes.
8
+ export const QUOTA_COMMIT_INTERVAL_MS = 30_000;
9
+ export const quotaCommitTimer = {
10
+ now: () => performance.now(),
11
+ schedule(delayMs, run) {
12
+ const timer = setTimeout(() => void run(), delayMs);
13
+ return {
14
+ cancel: () => clearTimeout(timer),
15
+ unref: () => timer.unref?.(),
16
+ };
17
+ },
18
+ };
@@ -0,0 +1,57 @@
1
+ import { lstat } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ async function identity(path) {
4
+ try {
5
+ const metadata = await lstat(path);
6
+ // Do not follow a symlink: its target can change without changing the link.
7
+ return metadata.isFile() ? metadata : undefined;
8
+ }
9
+ catch (error) {
10
+ return error.code === 'ENOENT'
11
+ ? 'absent'
12
+ : undefined;
13
+ }
14
+ }
15
+ function sameIdentity(left, right) {
16
+ if (left === 'absent' || right === 'absent')
17
+ return left === right;
18
+ return (left.dev === right.dev &&
19
+ left.ino === right.ino &&
20
+ left.size === right.size &&
21
+ left.mtimeMs === right.mtimeMs &&
22
+ left.ctimeMs === right.ctimeMs);
23
+ }
24
+ /** Process-local reads, capped at 64 path sets with one value per resolved set. */
25
+ export class FileReadCache {
26
+ #entries = new Map();
27
+ async read(paths, read, validateHit) {
28
+ const resolvedPaths = paths.map((path) => resolve(path));
29
+ const key = JSON.stringify(resolvedPaths);
30
+ const probed = await Promise.all(resolvedPaths.map(identity));
31
+ const identities = probed.every((entry) => entry !== undefined)
32
+ ? probed
33
+ : undefined;
34
+ const cached = this.#entries.get(key);
35
+ if (identities &&
36
+ cached &&
37
+ identities.every((entry, index) => {
38
+ const previous = cached.identities[index];
39
+ return previous !== undefined && sameIdentity(entry, previous);
40
+ })) {
41
+ validateHit?.(identities);
42
+ return cached.value;
43
+ }
44
+ // A failed probe or read must not leave a previous successful value reusable.
45
+ this.#entries.delete(key);
46
+ const value = await read(resolvedPaths);
47
+ if (identities) {
48
+ if (this.#entries.size >= 64) {
49
+ const oldest = this.#entries.keys().next().value;
50
+ if (oldest !== undefined)
51
+ this.#entries.delete(oldest);
52
+ }
53
+ this.#entries.set(key, { identities, value });
54
+ }
55
+ return value;
56
+ }
57
+ }
@@ -0,0 +1,42 @@
1
+ /** Retired generations report separately until their owner closes and shares one warning. */
2
+ export function shutdownWarning(logger, shutdown) {
3
+ let warned = false;
4
+ return (pendingOperations) => {
5
+ if (warned)
6
+ return;
7
+ if (!shutdown || shutdown.aborted)
8
+ warned = true;
9
+ logger.warn('claustrum shutdown drain timed out', { pendingOperations });
10
+ };
11
+ }
12
+ /**
13
+ * Give cancelled background work two seconds to release its handles without letting
14
+ * an unresponsive connector or disk hold the host's shutdown indefinitely.
15
+ */
16
+ export async function drainShutdown(pending, onTimeout) {
17
+ if (!pending.size)
18
+ return;
19
+ let timer;
20
+ let expired = false;
21
+ const drained = (async () => {
22
+ while (!expired && pending.size)
23
+ await Promise.allSettled([...pending]);
24
+ })();
25
+ try {
26
+ await Promise.race([
27
+ drained,
28
+ new Promise((resolve) => {
29
+ timer = setTimeout(() => {
30
+ expired = true;
31
+ resolve();
32
+ }, 2_000);
33
+ }),
34
+ ]);
35
+ if (expired && pending.size)
36
+ onTimeout(pending.size);
37
+ }
38
+ finally {
39
+ expired = true;
40
+ clearTimeout(timer);
41
+ }
42
+ }
@@ -3,6 +3,7 @@ import { constants as fsConstants } from "node:fs";
3
3
  import { chmod, mkdir, open, readFile, realpath, rename, stat, unlink, } from "node:fs/promises";
4
4
  import { basename, dirname, extname, isAbsolute, join, resolve, } from "node:path";
5
5
  import { ClaustrumCredentialError, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile, } from "@cortexkit/claustrum-client";
6
+ import { FileReadCache } from "./92e38944b51b2405-file-read-cache.js";
6
7
  import { acquireRefreshFileLock } from "./ec971142548df90e-index.js";
7
8
  import { ensurePrivateDirectory as ensureWindowsDirectory, PrivateFileError, readPrivateText, verifySafeDirectory, windowsPrivateFiles, writePrivateAtomic, } from "./375d9cca2def037d-private-files.js";
8
9
  import { ClaustrumConsumerError } from "./ca0fccaba1d87af4-errors.js";
@@ -402,32 +403,56 @@ async function writeStateAtomic(path, state, ancestorOptions = {}) {
402
403
  await unlink(temporary).catch(() => { });
403
404
  }
404
405
  }
406
+ const enrollmentStatusCache = new FileReadCache();
405
407
  export async function readClaustrumEnrollmentStatus(paths, proposedName) {
408
+ // Windows ACL, owner and ancestry checks are not represented by stat identity.
409
+ // Keep the native private-file validation and full read on every call there.
410
+ const result = windowsPrivateFiles
411
+ ? await readEnrollmentStatus(paths, proposedName)
412
+ : await enrollmentStatusCache.read([paths.tokenPath, paths.statePath], async ([tokenPath = paths.tokenPath, statePath = paths.statePath]) => readEnrollmentStatus({ tokenPath, statePath }, proposedName), (identities) => {
413
+ // Recheck the current effective user as well as mode and regular-file kind.
414
+ // lstat probes also prevent a link to the old inode from becoming a hit.
415
+ for (const metadata of identities)
416
+ if (metadata !== 'absent')
417
+ validateReadableSecretFile(metadata);
418
+ });
419
+ const status = { ...result.status };
420
+ if (result.usesProposedName && status.state === 'approved')
421
+ status.proposedName = proposedName;
422
+ return status;
423
+ }
424
+ async function readEnrollmentStatus(paths, proposedName) {
406
425
  const tokenValue = await readBoundedJson(paths.tokenPath);
407
426
  const token = tokenValue === undefined ? undefined : decodeTokenFile(tokenValue);
408
427
  const stateValue = await readBoundedJson(paths.statePath);
409
428
  const state = stateValue === undefined ? undefined : decodeEnrollmentState(stateValue);
410
429
  if (token) {
411
430
  return {
412
- state: 'approved',
413
- proposedName: state?.proposedName ?? proposedName,
414
- ...(state?.phase === 'approved' &&
415
- state.approvedName !== undefined && {
416
- approvedName: state.approvedName,
417
- }),
418
- tokenGeneration: token.token_generation,
431
+ usesProposedName: state === undefined,
432
+ status: {
433
+ state: 'approved',
434
+ proposedName: state?.proposedName ?? proposedName,
435
+ ...(state?.phase === 'approved' &&
436
+ state.approvedName !== undefined && {
437
+ approvedName: state.approvedName,
438
+ }),
439
+ tokenGeneration: token.token_generation,
440
+ },
419
441
  };
420
442
  }
421
443
  if (!state)
422
- return { state: 'idle' };
444
+ return { status: { state: 'idle' }, usesProposedName: false };
423
445
  if (state.phase === 'approved') {
424
446
  return {
425
- state: 'blocked',
426
- proposedName: state.proposedName,
427
- code: 'missing_token',
447
+ usesProposedName: false,
448
+ status: {
449
+ state: 'blocked',
450
+ proposedName: state.proposedName,
451
+ code: 'missing_token',
452
+ },
428
453
  };
429
454
  }
430
- return statusFromState(state);
455
+ return { status: statusFromState(state), usesProposedName: false };
431
456
  }
432
457
  /**
433
458
  * Resolve the host's account mode from its enrollment files. It never changes
@@ -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,4 +1,5 @@
1
1
  import { createLogger } from "./cc9e0702a752cea7-index.js";
2
+ import { QUOTA_COMMIT_INTERVAL_MS, quotaCommitTimer, } from "./88b7fc40900fb003-commit-interval.js";
2
3
  import { assertQuotaEpoch, assertQuotaRow, mergedQuota, } from "./a62a27a204266acd-attribution.js";
3
4
  import { PoolOperationError } from "./04a6357627de5ed0-errors.js";
4
5
  import { toFailure, withTransaction } from "./458b934e92490331-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', {
@@ -178,19 +178,28 @@ export async function acquireRefreshFileLockWithClock(options) {
178
178
  }
179
179
  async function leaseContention(error) {
180
180
  const code = error.code;
181
- if (code === 'EEXIST') {
182
- if (windowsPrivateFiles)
183
- await readOwner();
184
- return true;
185
- }
186
- if (code === 'EISDIR') {
187
- if (windowsPrivateFiles) {
188
- await verifyPrivate(lockPath, 'directory', true);
189
- await readPrivateText(legacyOwnerPath, true);
181
+ if (code !== 'EEXIST' && code !== 'EISDIR')
182
+ return false;
183
+ if (windowsPrivateFiles) {
184
+ if (options.onStep)
185
+ await options.onStep('lease-contention-read-ready');
186
+ try {
187
+ if (code === 'EISDIR') {
188
+ await verifyPrivate(lockPath, 'directory', true);
189
+ await readPrivateText(legacyOwnerPath, true);
190
+ }
191
+ else
192
+ await readOwner();
193
+ }
194
+ catch (readError) {
195
+ // The holder can release after exclusive creation reports a collision.
196
+ // Only absence permits another acquisition attempt; security and sharing
197
+ // refusals must still escape rather than being treated as contention.
198
+ if (readError.code !== 'ENOENT')
199
+ throw readError;
190
200
  }
191
- return true;
192
201
  }
193
- return false;
202
+ return true;
194
203
  }
195
204
  async function tryAcquire() {
196
205
  if (windowsPrivateFiles)
@@ -4,25 +4,58 @@
4
4
  // declined-account interlock and the host-slot guard. Needs the optional
5
5
  // peer `@cortexkit/claustrum-client`.
6
6
  import { ClaustrumClient, } from "@cortexkit/claustrum-client";
7
+ import { ClaustrumUnreachableError } from "./94f53cfd572ba4bb-availability.js";
7
8
  import { insulaUsageTransport } from "./d0f0b6be200311af-insula.js";
8
9
  export { ClaustrumCredentialError, } from "@cortexkit/claustrum-client";
9
10
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, } from "./94f53cfd572ba4bb-availability.js";
10
- export { ClaustrumConsumer, } from "./169b2b4bf30909bc-consumer.js";
11
+ export { ClaustrumConsumer, DEFAULT_CONNECT_TIMEOUT_MS, } from "./169b2b4bf30909bc-consumer.js";
11
12
  export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, SERVING_MARGIN_MS, } from "./0f77ebc3c914c9c6-custody.js";
12
13
  export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from "./b9588ad4725c1d10-enrollment.js";
13
14
  export { ClaustrumConsumerError, } from "./ca0fccaba1d87af4-errors.js";
14
15
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from "./d9d2892a4c371301-host-slot.js";
16
+ export { ClaustrumDiscoveryHub, } from "./352d228be2832bd4-hub.js";
15
17
  export { acquireInsulaQuotaSource, } from "./d0f0b6be200311af-insula.js";
16
18
  export { acceptAccount, declineAccount, isDeclined, } from "./7c140680fc81be92-interlock.js";
17
19
  export { drainVaultQuota } from "./81dddd203f1b92a3-quota-writer.js";
18
- export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, resolveVaultPrimary, vaultRoutingRows, } from "./30f5bc480f31f51c-roster.js";
20
+ export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, resolveVaultPrimary, vaultRosterSeed, vaultRoutingRows, } from "./30f5bc480f31f51c-roster.js";
19
21
  export { ChangeNoticeReader, RESUBSCRIBE_BACKOFF_MS, SAFETY_POLL_MS, ScopedRosterWatch, WATCH_RETRY_MS, } from "./dc9290c2a7552ba6-watch.js";
22
+ /** How long `connectClaustrumScopedClient` waits by default. */
23
+ export const SCOPED_CONNECT_TIMEOUT_MS = 10_000;
20
24
  /**
21
25
  * Connect the client that lists and fetches this consumer's vault credentials
22
26
  * on the request path. `connectionFile` is required: this library
23
27
  * reads no environment, so the plugin resolves the vault's connection file.
28
+ *
29
+ * The wait is bounded by `connectTimeoutMs` (default 10 s) so a connect that
30
+ * never settles cannot leave a consumer with a pending connection forever; the
31
+ * caller then gets an unreachable error and may try again. A socket handshake
32
+ * has its own limit, but local reads before it (the connection file) do not,
33
+ * and a client that arrives after this deadline is closed, not returned.
24
34
  */
25
35
  export async function connectClaustrumScopedClient(options) {
26
- const client = await ClaustrumClient.connect(options);
27
- return Object.assign(client, { insula: insulaUsageTransport(options) });
36
+ const { connectTimeoutMs, ...client } = options;
37
+ const limit = connectTimeoutMs ?? SCOPED_CONNECT_TIMEOUT_MS;
38
+ const connecting = ClaustrumClient.connect(client);
39
+ let expired = false;
40
+ let timer;
41
+ const deadline = new Promise((_resolve, reject) => {
42
+ timer = setTimeout(() => {
43
+ expired = true;
44
+ reject(new ClaustrumUnreachableError());
45
+ }, limit);
46
+ timer.unref?.();
47
+ });
48
+ try {
49
+ const client = await Promise.race([connecting, deadline]);
50
+ return Object.assign(client, { insula: insulaUsageTransport(options) });
51
+ }
52
+ catch (error) {
53
+ // A connection that arrives after the deadline still owns a socket.
54
+ void connecting.then((client) => client.close(), () => { });
55
+ throw error;
56
+ }
57
+ finally {
58
+ if (!expired && timer)
59
+ clearTimeout(timer);
60
+ }
28
61
  }