@cortexkit/opencode-openai-auth 1.9.3 → 1.9.5

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 (77) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/{codex-request-By530v1D.d.ts → codex-request-CZ16goZ6.d.ts} +20 -4
  3. package/dist/index-1nrre3d8.js +91 -0
  4. package/dist/index-41yn5c02.js +8 -0
  5. package/dist/{index-2dwy4yab.js → index-4gnwkw3a.js} +1 -1
  6. package/dist/{index-7bjgmbx4.js → index-7qxa018z.js} +1 -1
  7. package/dist/{index-vaqxca8c.js → index-8rj2xddq.js} +12 -12
  8. package/dist/{index-v1ztg103.js → index-cf0mrvqj.js} +1 -1
  9. package/dist/{index-ezwfbnx5.js → index-f1cqptqa.js} +1 -1
  10. package/dist/index-h3vtzckv.js +76 -0
  11. package/dist/index-mcy24ej8.js +2 -0
  12. package/dist/index-npj40h62.js +12 -0
  13. package/dist/{index-cmybrjbd.js → index-s2vrkdj4.js} +1 -1
  14. package/dist/{index-2bf808fw.js → index-s52j2h64.js} +1 -1
  15. package/dist/{index-g3gbp1m4.js → index-y4j7y8b8.js} +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/{port-file-DXCxv8tU.d.ts → port-file-CEjki7bM.d.ts} +6 -1
  19. package/dist/rpc/port-file.d.ts +1 -1
  20. package/dist/rpc/port-file.js +1 -1
  21. package/dist/rpc/protocol.js +1 -1
  22. package/dist/rpc/rpc-client.d.ts +1 -1
  23. package/dist/rpc/rpc-client.js +1 -1
  24. package/dist/rpc/rpc-dir.js +1 -1
  25. package/dist/{rpc-client-CmaZW1by.d.ts → rpc-client-rWuV04C-.d.ts} +1 -1
  26. package/dist/sidebar-state.js +1 -1
  27. package/dist/{token-dcr3tgsk.js → token-djwdynff.js} +1 -1
  28. package/dist/token-util-0xt1ws82.js +1 -0
  29. package/dist/tui-preferences.js +1 -1
  30. package/dist/tui.d.ts +1 -1
  31. package/dist/v2/server.d.ts +1 -1
  32. package/dist/v2/server.js +3 -3
  33. package/package.json +3 -3
  34. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +74 -9
  35. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +36 -0
  36. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +2 -0
  37. package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +8 -0
  38. package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +7 -0
  39. package/src/tui-compiled/raw/shared/45bf5343bbbf9add-admission.js +17 -7
  40. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +2 -5
  41. package/src/tui-compiled/raw/shared/4ede5af6a878a14e-usage.js +145 -0
  42. package/src/tui-compiled/raw/shared/5f8cc863449a6c85-limits-namespace.js +34 -0
  43. package/src/tui-compiled/raw/shared/754d6017f8e419cf-builtins.js +38 -0
  44. package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +11 -4
  45. package/src/tui-compiled/raw/shared/97484d9bb98c705b-provider-state.js +5 -5
  46. package/src/tui-compiled/raw/shared/9d3fc9e37456504e-refresh.js +1 -1
  47. package/src/tui-compiled/raw/shared/9deae3c4da4fd63b-hooks.js +20 -5
  48. package/src/tui-compiled/raw/shared/a62a27a204266acd-attribution.js +3 -2
  49. package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +46 -4
  50. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +2 -0
  51. package/src/tui-compiled/raw/shared/cd94316a888b0a8e-schema.js +9 -4
  52. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +142 -47
  53. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +74 -9
  54. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +36 -0
  55. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +2 -0
  56. package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +8 -0
  57. package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +7 -0
  58. package/src/tui-compiled/runtime/shared/45bf5343bbbf9add-admission.js +17 -7
  59. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +2 -5
  60. package/src/tui-compiled/runtime/shared/4ede5af6a878a14e-usage.js +145 -0
  61. package/src/tui-compiled/runtime/shared/5f8cc863449a6c85-limits-namespace.js +34 -0
  62. package/src/tui-compiled/runtime/shared/754d6017f8e419cf-builtins.js +38 -0
  63. package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +11 -4
  64. package/src/tui-compiled/runtime/shared/97484d9bb98c705b-provider-state.js +5 -5
  65. package/src/tui-compiled/runtime/shared/9d3fc9e37456504e-refresh.js +1 -1
  66. package/src/tui-compiled/runtime/shared/9deae3c4da4fd63b-hooks.js +20 -5
  67. package/src/tui-compiled/runtime/shared/a62a27a204266acd-attribution.js +3 -2
  68. package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +46 -4
  69. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +2 -0
  70. package/src/tui-compiled/runtime/shared/cd94316a888b0a8e-schema.js +9 -4
  71. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +142 -47
  72. package/dist/index-2esezxst.js +0 -12
  73. package/dist/index-3sda8acd.js +0 -76
  74. package/dist/index-6xz3n4qh.js +0 -91
  75. package/dist/index-81yvwra9.js +0 -8
  76. package/dist/index-hz6f9gpq.js +0 -2
  77. package/dist/token-util-gbd7jw6d.js +0 -1
@@ -738,6 +738,42 @@ export class ClaustrumConsumer {
738
738
  combined.dispose();
739
739
  }
740
740
  }
741
+ /**
742
+ * Queue reply quota metadata without waiting or throwing. Pass rate-limit
743
+ * headers only, never tokens: the library does not filter header names.
744
+ * The credential must have been served by this host and still belong to the route.
745
+ */
746
+ reportUsage(input) {
747
+ if (this.#shutdown.signal.aborted)
748
+ return;
749
+ try {
750
+ const row = this.#roster?.rows.find((row) => row.routeId === input.routeId);
751
+ if (!row?.enabled ||
752
+ row.state !== 'active' ||
753
+ (row.credentialId !== input.credentialId &&
754
+ !row.aliases?.includes(input.credentialId)))
755
+ return;
756
+ if (this.#hub) {
757
+ if (this.#lease && this.#hub.leaseLive(this.#lease))
758
+ this.#lease.custody.reportUsage(input);
759
+ }
760
+ else
761
+ this.#custody?.reportUsage(input);
762
+ }
763
+ catch {
764
+ // Quota bookkeeping must never reject a provider request.
765
+ }
766
+ }
767
+ usageReportState() {
768
+ try {
769
+ return ((this.#hub
770
+ ? this.#lease?.custody
771
+ : this.#custody)?.usageReportState() ?? { pending: 0, inFlight: false, dropped: 0 });
772
+ }
773
+ catch {
774
+ return { pending: 0, inFlight: false, dropped: 0 };
775
+ }
776
+ }
741
777
  async reportFailure(attempt, status, source) {
742
778
  this.#assertOpen();
743
779
  if (this.#hub) {
@@ -209,6 +209,7 @@ export function projectVaultRoster(previous, inventory, options = {}) {
209
209
  return {
210
210
  version: 1,
211
211
  view: inventory.view,
212
+ ...(previous?.limits !== undefined && { limits: previous.limits }),
212
213
  complete,
213
214
  ...(!complete && {
214
215
  rejected: inventory.skipped.map((record) => ({
@@ -319,6 +320,7 @@ function decodeRoster(value) {
319
320
  // that was used whole, so it reads as complete.
320
321
  complete: value.complete !== false,
321
322
  ...(rejected && { rejected }),
323
+ ...(value.limits !== undefined && { limits: value.limits }),
322
324
  rows,
323
325
  declined,
324
326
  };
@@ -523,6 +523,14 @@ export class ClaustrumDiscoveryHub {
523
523
  check();
524
524
  return custody.reportFailure(attempt, status, source);
525
525
  },
526
+ reportUsage: (input) => {
527
+ if (!state.released && !generation.ended)
528
+ custody.reportUsage(input);
529
+ },
530
+ usageReportState: () => {
531
+ check();
532
+ return custody.usageReportState();
533
+ },
526
534
  forget: (credentialId) => {
527
535
  check();
528
536
  custody.forget(credentialId);
@@ -93,6 +93,13 @@ export class PrivateFileError extends Error {
93
93
  this.reason = detail?.reason;
94
94
  }
95
95
  }
96
+ /** Native sharing and delete-pending errors reveal neither ownership nor expiry. */
97
+ export function isWindowsSharingViolation(error) {
98
+ return (windowsPrivateFiles &&
99
+ error instanceof PrivateFileError &&
100
+ error.reason === 'io-error' &&
101
+ (error.win32Code === 32 || error.win32Code === 303));
102
+ }
96
103
  export async function privateOperation(path, stage, operation) {
97
104
  try {
98
105
  return await operation();
@@ -14,7 +14,7 @@
14
14
  // 3. a required label with no entry is unknown: refused, pull requested;
15
15
  // 4. a reading at or beyond 100% whose reset is missing, unparsable or not
16
16
  // after `now` cannot confirm the exhaustion, so the window is unknown:
17
- // refused, pull requested;
17
+ // refused unless lifted for this wake dispatch; either way, pull requested;
18
18
  // 5. a reading at or beyond 100% with a future reset is exhausted: refused.
19
19
  // Gates 4 and 5 look at every projected limit, not only the required labels.
20
20
  // Stage 2 judges the credit budget across the stage-1 survivors: a row whose
@@ -36,7 +36,7 @@ export function exclusionFor(id, inputs, now) {
36
36
  }
37
37
  return undefined;
38
38
  }
39
- function judgeStageOne(id, projection, requiredLabels, now) {
39
+ function judgeStageOne(id, projection, requiredLabels, now, liftedWindows) {
40
40
  if (projection.limits.length === 0) {
41
41
  return {
42
42
  id,
@@ -60,7 +60,8 @@ function judgeStageOne(id, projection, requiredLabels, now) {
60
60
  }
61
61
  const exhausted = projection.limits.filter(readsExhausted);
62
62
  for (const limit of exhausted) {
63
- if (futureResetAt(limit, now) === undefined) {
63
+ if (futureResetAt(limit, now) === undefined &&
64
+ !liftedWindows.some((window) => window.scope === limit.scope && window.label === limit.label)) {
64
65
  return {
65
66
  id,
66
67
  stage: 1,
@@ -94,6 +95,7 @@ export function admit(input) {
94
95
  const excluded = [];
95
96
  const refused = [];
96
97
  const survivors = [];
98
+ const needsPull = new Set();
97
99
  for (const row of input.rows) {
98
100
  const exclusion = exclusionFor(row.id, input, input.now);
99
101
  if (exclusion) {
@@ -105,7 +107,12 @@ export function admit(input) {
105
107
  continue;
106
108
  }
107
109
  const projection = projectQuota(row.quota, scope);
108
- const refusal = judgeStageOne(row.id, projection, requiredLabels, input.now);
110
+ const lifted = input.liftedWindows?.get(row.id) ?? [];
111
+ if (projection.limits.some((limit) => readsExhausted(limit) &&
112
+ futureResetAt(limit, input.now) === undefined &&
113
+ lifted.some((window) => window.scope === limit.scope && window.label === limit.label)))
114
+ needsPull.add(row.id);
115
+ const refusal = judgeStageOne(row.id, projection, requiredLabels, input.now, lifted);
109
116
  if (refusal) {
110
117
  refused.push(refusal);
111
118
  continue;
@@ -133,9 +140,12 @@ export function admit(input) {
133
140
  const order = new Map(input.rows.map((row, index) => [row.id, index]));
134
141
  const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
135
142
  refused.sort(byInput);
136
- const pulls = refused
137
- .filter((refusal) => 'pullRequested' in refusal)
138
- .map((refusal) => refusal.id);
143
+ for (const refusal of refused)
144
+ if ('pullRequested' in refusal)
145
+ needsPull.add(refusal.id);
146
+ const pulls = input.rows
147
+ .filter((row) => needsPull.has(row.id))
148
+ .map((row) => row.id);
139
149
  for (const id of pulls)
140
150
  input.requestPull?.(id);
141
151
  return { admitted, refused, excluded, pulls };
@@ -1,5 +1,5 @@
1
1
  import { join, resolve } from "node:path";
2
- import { PrivateFileError, windowsPrivateFiles } from "./375d9cca2def037d-private-files.js";
2
+ import { isWindowsSharingViolation, } from "./375d9cca2def037d-private-files.js";
3
3
  import { acquireRefreshFileLock } from "./e8cd4929507508d8-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,145 @@
1
+ import { ClaustrumCredentialError } from "@cortexkit/claustrum-client";
2
+ function plain(value) {
3
+ return (value !== null &&
4
+ typeof value === 'object' &&
5
+ (Object.getPrototypeOf(value) === Object.prototype ||
6
+ Object.getPrototypeOf(value) === null));
7
+ }
8
+ /** One queue per custody connection, shared by every hub member on it. */
9
+ export class ScopedUsageReporter {
10
+ options;
11
+ #queue = new Map();
12
+ #latest = new Map();
13
+ #errors = new Set();
14
+ #timer;
15
+ #running;
16
+ #closing = false;
17
+ #stopped = false;
18
+ #dropped = 0;
19
+ constructor(options) {
20
+ this.options = options;
21
+ }
22
+ state() {
23
+ return {
24
+ pending: this.#queue.size,
25
+ inFlight: this.#running !== undefined,
26
+ dropped: this.#dropped,
27
+ };
28
+ }
29
+ report(credentialId, reading) {
30
+ if (this.#closing || !this.options.client.reportUsageScoped)
31
+ return;
32
+ try {
33
+ if (!this.options.owns(credentialId)) {
34
+ this.#dropped++;
35
+ return;
36
+ }
37
+ if (!plain(reading) || 'credentialId' in reading || 'vouched' in reading)
38
+ throw new Error('invalid reading');
39
+ const json = JSON.stringify(reading);
40
+ if (Buffer.byteLength(json, 'utf8') > 15_360)
41
+ throw new Error('oversized reading');
42
+ // Snapshot now: a caller mutating its reply metadata later cannot change
43
+ // an already validated queued reading, including its ordering timestamp.
44
+ const copy = JSON.parse(json);
45
+ if (!plain(copy) ||
46
+ 'credentialId' in copy ||
47
+ 'vouched' in copy ||
48
+ typeof copy.observedAtMs !== 'number' ||
49
+ !Number.isFinite(copy.observedAtMs))
50
+ throw new Error('invalid reading');
51
+ if (copy.observedAtMs <= (this.#latest.get(credentialId) ?? -Infinity)) {
52
+ this.#dropped++;
53
+ return;
54
+ }
55
+ if (this.#queue.has(credentialId))
56
+ this.#dropped++;
57
+ this.#latest.set(credentialId, copy.observedAtMs);
58
+ this.#queue.set(credentialId, copy);
59
+ if (!this.#timer && !this.#running) {
60
+ this.#timer = this.options.setTimeout(() => {
61
+ this.#timer = undefined;
62
+ this.#flush();
63
+ }, 1_000);
64
+ this.#timer.unref?.();
65
+ }
66
+ }
67
+ catch {
68
+ this.#dropped++;
69
+ }
70
+ }
71
+ forget(credentialId) {
72
+ if (this.#queue.delete(credentialId))
73
+ this.#dropped++;
74
+ this.#latest.delete(credentialId);
75
+ }
76
+ #flush() {
77
+ if (this.#running || !this.#queue.size || this.#stopped)
78
+ return this.#running;
79
+ // Start on a microtask even during close, so all failures stay off the
80
+ // provider request path and only one send can be in flight on this client.
81
+ const running = Promise.resolve().then(async () => {
82
+ while (!this.#stopped && this.#queue.size) {
83
+ const entry = this.#queue.entries().next().value;
84
+ if (!entry)
85
+ break;
86
+ const [credentialId, reading] = entry;
87
+ this.#queue.delete(credentialId);
88
+ try {
89
+ const enrollmentToken = await this.options.token();
90
+ if (this.#stopped || !this.options.owns(credentialId)) {
91
+ if (!this.#stopped)
92
+ this.#dropped++;
93
+ continue;
94
+ }
95
+ await this.options.client.reportUsageScoped?.({
96
+ credentialId,
97
+ reading,
98
+ enrollmentToken,
99
+ });
100
+ }
101
+ catch (error) {
102
+ if (!this.#stopped)
103
+ this.#dropped++;
104
+ this.#log(error);
105
+ }
106
+ }
107
+ });
108
+ this.#running = running;
109
+ void running.finally(() => {
110
+ this.#running = undefined;
111
+ });
112
+ return running;
113
+ }
114
+ #log(error) {
115
+ // Only codes from credential refusals are exposed. Transport messages,
116
+ // arbitrary thrown objects and reply contents can contain secrets.
117
+ let code = 'transport_error';
118
+ try {
119
+ if (error instanceof ClaustrumCredentialError)
120
+ code = /^[a-z][a-z0-9_]{0,63}$/.test(error.code) ? error.code : code;
121
+ if (this.#errors.has(code))
122
+ return;
123
+ this.#errors.add(code);
124
+ this.options.logger.debug('claustrum usage report dropped', { code });
125
+ }
126
+ catch {
127
+ // A caller's logger must not turn best-effort reporting into a rejection.
128
+ }
129
+ }
130
+ /** Start the final flush; the custody's existing shutdown drain bounds it. */
131
+ close() {
132
+ this.#closing = true;
133
+ if (this.#timer)
134
+ this.options.clearTimeout(this.#timer);
135
+ this.#timer = undefined;
136
+ return this.#flush();
137
+ }
138
+ drop() {
139
+ this.#stopped = true;
140
+ this.#dropped += this.#queue.size + (this.#running ? 1 : 0);
141
+ this.#running = undefined;
142
+ this.#queue.clear();
143
+ this.#latest.clear();
144
+ }
145
+ }
@@ -0,0 +1,34 @@
1
+ import { writeJsonAtomic } from "./7211cfec06a298bc-atomic-write.js";
2
+ import { assertLimitsWriteAllowed, runInsideHook } from "./9deae3c4da4fd63b-hooks.js";
3
+ import { notReadyError, readPool, runOperation } from "./458b934e92490331-mutate.js";
4
+ /** A namespace merge and its check of current row bindings share one locked config snapshot. */
5
+ export async function updatePoolLimitsNamespace(rt, mutator) {
6
+ assertLimitsWriteAllowed();
7
+ const { ctx } = rt;
8
+ await runOperation(ctx, 'updateLimitsNamespace', undefined, undefined, async (locks, progress) => {
9
+ for (const spec of ctx.storeLocks)
10
+ await locks.acquire(spec);
11
+ const result = await readPool(ctx);
12
+ if (result.status !== 'ready')
13
+ throw notReadyError(result, 'updateLimitsNamespace', undefined);
14
+ const rows = result.rows.map(({ id, credentialEpoch, identity }) => ({
15
+ id,
16
+ credentialEpoch,
17
+ identity,
18
+ }));
19
+ const envelope = await runInsideHook('updateLimitsNamespace', () => mutator(structuredClone(result.config.commonAuthLimits), rows));
20
+ const config = { ...result.config, commonAuthLimits: envelope };
21
+ const info = {
22
+ operation: 'updateLimitsNamespace',
23
+ rowId: undefined,
24
+ };
25
+ await writeJsonAtomic(ctx.configPath, config, {
26
+ beforeRename: async () => {
27
+ await ctx.onStep?.('before-config-write', info);
28
+ await locks.assertAll();
29
+ },
30
+ });
31
+ progress.writes++;
32
+ await ctx.onStep?.('after-config-write', info);
33
+ });
34
+ }
@@ -468,6 +468,44 @@ function routingSection(options, snap) {
468
468
  : `Order set to ${result.ids.map(nameOf).join(', ')}.`;
469
469
  },
470
470
  });
471
+ if (options.routing?.sameAccountWait) {
472
+ const waitLabel = 'Longest wait on the same account';
473
+ const waitChoices = [
474
+ { value: '0', label: "Don't wait" },
475
+ { value: '15', label: '15 minutes' },
476
+ { value: 'max', label: 'Until the cache expires' },
477
+ ];
478
+ const rawWait = record(snap.settings.routing).maxSameAccountWait;
479
+ const wait = String(rawWait === 0 || rawWait === 'max' ? rawWait : 15);
480
+ const waitName = (value) => waitChoices.find((choice) => choice.value === value)?.label ?? value;
481
+ lines.push(`${waitLabel}: ${waitName(wait)}`);
482
+ actions.push({
483
+ id: 'maxSameAccountWait',
484
+ label: waitLabel,
485
+ group: ACTIONS_GROUP,
486
+ knobs: [
487
+ {
488
+ kind: 'choice',
489
+ id: 'maxSameAccountWait',
490
+ label: waitLabel,
491
+ choices: waitChoices,
492
+ value: wait,
493
+ },
494
+ ],
495
+ run: async ({ values }) => {
496
+ const value = String(values.maxSameAccountWait);
497
+ const maxSameAccountWait = value === 'max' ? 'max' : Number(value);
498
+ await store.updateSettings((settings) => {
499
+ settings.routing = {
500
+ ...record(settings.routing),
501
+ maxSameAccountWait,
502
+ };
503
+ return undefined;
504
+ }, locks);
505
+ return `${waitLabel} set to ${waitName(value)}.`;
506
+ },
507
+ });
508
+ }
471
509
  return {
472
510
  id: 'routing',
473
511
  slot: 'routing',
@@ -36,12 +36,13 @@ function defineKey(target, key, value) {
36
36
  /**
37
37
  * The next config: the pool-owned keys exactly as read, every settings key
38
38
  * from `next` in its existing position, settings keys `next` dropped left
39
- * out, and new settings keys appended.
39
+ * out, and new settings keys appended. The limits envelope is always carried
40
+ * through from disk; ordinary settings mutators do not own that namespace.
40
41
  */
41
42
  function composeConfig(config, next) {
42
43
  const out = {};
43
44
  for (const [key, value] of Object.entries(config)) {
44
- if (POOL_OWNED_KEYS.includes(key))
45
+ if (POOL_OWNED_KEYS.includes(key) || key === 'commonAuthLimits')
45
46
  defineKey(out, key, value);
46
47
  else if (Object.hasOwn(next, key))
47
48
  defineKey(out, key, next[key]);
@@ -82,6 +83,8 @@ export async function readPoolSettings(rt) {
82
83
  * pool-owned key refuses (`invalid-input`) with nothing written; a result
83
84
  * equal to the current settings writes nothing. The state file is never
84
85
  * touched, and the pool-owned keys are written back exactly as read.
86
+ * commonAuthLimits is also carried through unchanged, even when omitted by
87
+ * the mutator; an explicit change to it refuses before writing anything.
85
88
  */
86
89
  export async function updatePoolSettings(rt, mutator, options = {}) {
87
90
  assertNotInsideHook('updateSettings');
@@ -109,9 +112,13 @@ export async function updatePoolSettings(rt, mutator, options = {}) {
109
112
  const owned = POOL_OWNED_KEYS.filter((key) => Object.hasOwn(next, key));
110
113
  if (owned.length > 0)
111
114
  throw settingsRefusal(`settings cannot set the pool-owned key(s) ${owned.join(', ')}`);
112
- if (isDeepStrictEqual(next, current))
113
- return { settings: current, outcome: 'unchanged' };
115
+ if (Object.hasOwn(next, 'commonAuthLimits') &&
116
+ (!Object.hasOwn(current, 'commonAuthLimits') ||
117
+ !isDeepStrictEqual(next.commonAuthLimits, current.commonAuthLimits)))
118
+ throw settingsRefusal('settings cannot alter commonAuthLimits; use updateLimitsNamespace');
114
119
  const config = composeConfig(result.config, next);
120
+ if (isDeepStrictEqual(settingsOf(config), current))
121
+ return { settings: current, outcome: 'unchanged' };
115
122
  const info = { operation: 'updateSettings', rowId: undefined };
116
123
  await writeJsonAtomic(ctx.configPath, config, {
117
124
  beforeRename: async () => {
@@ -1,4 +1,4 @@
1
- import { assertNotInsideHook, runInsideHook } from "./9deae3c4da4fd63b-hooks.js";
1
+ import { assertNotInsideHook, runInsideCodec, runInsideHook } from "./9deae3c4da4fd63b-hooks.js";
2
2
  import { runOperation, withTransaction } from "./458b934e92490331-mutate.js";
3
3
  import { readRow, refusal, requireBound, rowLockSpec, unknownRow, } from "./83bc3ba9d0fe2761-runtime.js";
4
4
  import { boundProviderStateDigest, CREDENTIAL_STAMP_KEY, credentialDigest, isCredentialEpoch, isRecord, PROVIDER_STATE_KEY, parseStamp, providerStateDigest, rowLockKey, } from "./cd94316a888b0a8e-schema.js";
@@ -21,7 +21,7 @@ export function acceptProviderState(codec, operation, id, value, what = 'the pro
21
21
  }
22
22
  if (normalized === undefined)
23
23
  throw refusal(operation, id, 'invalid-provider-state', `${what} cannot be stored as JSON`);
24
- if (!codec.validate(normalized))
24
+ if (!runInsideCodec(() => codec.validate(normalized)))
25
25
  throw refusal(operation, id, 'invalid-provider-state', `the provider-state codec rejected ${what}`);
26
26
  return normalized;
27
27
  }
@@ -35,7 +35,7 @@ export function mergedProviderState(codec, operation, id, onDisk, incoming) {
35
35
  return { kind: 'set', value: incoming };
36
36
  return {
37
37
  kind: 'set',
38
- value: acceptProviderState(codec, operation, id, codec.merge(structuredClone(onDisk), structuredClone(incoming)), 'the merged provider state'),
38
+ value: acceptProviderState(codec, operation, id, runInsideCodec(() => codec.merge?.(structuredClone(onDisk), structuredClone(incoming))), 'the merged provider state'),
39
39
  };
40
40
  }
41
41
  /**
@@ -48,7 +48,7 @@ export function mergedProviderState(codec, operation, id, onDisk, incoming) {
48
48
  export function replacementProviderState(codec, row, credentialEpoch, identity, incoming) {
49
49
  const hook = codec?.onReplace;
50
50
  const next = hook
51
- ? hook(row.providerState === undefined
51
+ ? runInsideCodec(() => hook(row.providerState === undefined
52
52
  ? undefined
53
53
  : structuredClone(row.providerState), {
54
54
  id: row.id,
@@ -60,7 +60,7 @@ export function replacementProviderState(codec, row, credentialEpoch, identity,
60
60
  ...(incoming !== undefined
61
61
  ? { incoming: structuredClone(incoming) }
62
62
  : {}),
63
- })
63
+ }))
64
64
  : incoming;
65
65
  if (next === undefined)
66
66
  return { kind: 'clear' };
@@ -200,7 +200,7 @@ export async function refreshRow(rt, id, provider, options = {}) {
200
200
  if (options.onPersisted) {
201
201
  try {
202
202
  const persisted = options.onPersisted;
203
- await runInsideHook('refresh', () => persisted(id, commit.stored));
203
+ await runInsideHook('refresh', () => persisted(id, commit.stored), true);
204
204
  }
205
205
  catch (cause) {
206
206
  throw new PoolOperationError({
@@ -1,18 +1,33 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { PoolReentryError } from "./04a6357627de5ed0-errors.js";
3
3
  /**
4
- * Set while a hook of a lock-holding operation runs. Async context is
5
- * inherited by every timer, promise and continuation created inside the hook,
4
+ * Set while a store hook runs, recording whether its store locks are released.
5
+ * Async context is inherited by every timer, promise and continuation inside the hook,
6
6
  * so work a hook schedules is inside the guarded region too.
7
7
  */
8
8
  const insideHook = new AsyncLocalStorage();
9
+ const insideCodec = new AsyncLocalStorage();
9
10
  /** Refuses a row operation or refresh called from inside a hook. */
10
11
  export function assertNotInsideHook(operation) {
11
12
  if (insideHook.getStore() !== undefined)
12
13
  throw new PoolReentryError(operation);
13
14
  }
14
- export function runInsideHook(operation, fn) {
15
- return insideHook.run(operation, async () => await fn());
15
+ /** Namespace writes need only the store locks, not the row lock a hook may retain. */
16
+ export function assertLimitsWriteAllowed() {
17
+ if (insideHook.getStore()?.storeLocksReleased === false ||
18
+ insideCodec.getStore())
19
+ throw new PoolReentryError('updateLimitsNamespace');
20
+ }
21
+ /** Codecs may run under store locks even when no asynchronous hook is active. */
22
+ export function runInsideCodec(fn) {
23
+ return insideCodec.run(true, fn);
24
+ }
25
+ export function runInsideHook(operation, fn, storeLocksReleased = false) {
26
+ return insideHook.run({
27
+ operation,
28
+ storeLocksReleased: storeLocksReleased &&
29
+ insideHook.getStore()?.storeLocksReleased !== false,
30
+ }, async () => await fn());
16
31
  }
17
32
  /**
18
33
  * Runs a failure hook. A hook that throws never replaces the failure it was
@@ -22,7 +37,7 @@ export async function callFailureHook(operation, hook, rowId, error, logger) {
22
37
  if (!hook)
23
38
  return;
24
39
  try {
25
- await runInsideHook(operation, () => hook(rowId, error));
40
+ await runInsideHook(operation, () => hook(rowId, error), true);
26
41
  }
27
42
  catch (hookError) {
28
43
  logger?.warn('store failure hook threw; the original failure stands', {
@@ -1,4 +1,5 @@
1
1
  import { PoolOperationError } from "./04a6357627de5ed0-errors.js";
2
+ import { runInsideCodec } from "./9deae3c4da4fd63b-hooks.js";
2
3
  import { toFailure, withTransaction, } from "./458b934e92490331-mutate.js";
3
4
  import { LockStack } from "./43fc9e6b994519c7-refresh-lock.js";
4
5
  import { refusal, requireBound, unknownRow, } from "./83bc3ba9d0fe2761-runtime.js";
@@ -31,8 +32,8 @@ export function assertQuotaRow(id, attribution, row) {
31
32
  });
32
33
  }
33
34
  export function mergedQuota(ctx, id, stored, observation) {
34
- const merged = ctx.codec.merge(stored, observation);
35
- if (!ctx.codec.validate(merged))
35
+ const merged = runInsideCodec(() => ctx.codec.merge(stored, observation));
36
+ if (!runInsideCodec(() => ctx.codec.validate(merged)))
36
37
  throw refusal('pull', id, 'invalid-quota', 'the quota codec rejected the merged map');
37
38
  return merged;
38
39
  }
@@ -1,7 +1,36 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { chmod, mkdir, open, readdir, rename, rmdir, stat, unlink, } from "node:fs/promises";
3
+ import { uptime } from "node:os";
3
4
  import { join, resolve } from "node:path";
4
5
  import { ensurePrivateDirectory, PrivateFileError, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from "./375d9cca2def037d-private-files.js";
6
+ function staleBefore(clock) {
7
+ // A five-minute margin favors keeping a live record when clocks are uncertain.
8
+ return (clock.now ?? Date.now)() - (clock.uptime ?? uptime)() * 1000 - 300_000;
9
+ }
10
+ function isStalePortFile(entry, info, cutoff) {
11
+ const time = entry.startedAt === undefined ? info?.mtimeMs : entry.startedAt;
12
+ return typeof time === 'number' && Number.isFinite(time) && time < cutoff;
13
+ }
14
+ async function removeStalePortFile(path, raw, info, beforeRemove) {
15
+ if (!info)
16
+ return;
17
+ await beforeRemove?.(path);
18
+ try {
19
+ // A live PID may have replaced its old record while the sweep was reading it.
20
+ const current = await readPrivateText(path);
21
+ const identity = await stat(path);
22
+ if (current === raw &&
23
+ identity.dev === info.dev &&
24
+ identity.ino === info.ino &&
25
+ identity.mtimeMs === info.mtimeMs &&
26
+ identity.size === info.size)
27
+ await unlink(path).catch(() => { });
28
+ }
29
+ catch (error) {
30
+ if (error instanceof PrivateFileError && error.code !== 'ENOENT')
31
+ throw error;
32
+ }
33
+ }
5
34
  /**
6
35
  * A PID a liveness probe may address. `process.kill(0 | negative, 0)` signals
7
36
  * a process group rather than a process, and an unsafe integer cannot name a
@@ -117,7 +146,8 @@ export async function writePortFile(dir, entry, options = {}) {
117
146
  throw error;
118
147
  }
119
148
  }
120
- export async function sweepRpcState(root, activeDir, isManagedDir, log) {
149
+ export async function sweepRpcState(root, activeDir, isManagedDir, log, options = {}) {
150
+ const cutoff = staleBefore(options);
121
151
  let projectDirs;
122
152
  try {
123
153
  projectDirs = await readdir(root, { withFileTypes: true });
@@ -146,6 +176,7 @@ export async function sweepRpcState(root, activeDir, isManagedDir, log) {
146
176
  if (!name.startsWith('port-') || !name.endsWith('.json'))
147
177
  continue;
148
178
  const portFile = join(dir, name);
179
+ const info = await stat(portFile).catch(() => undefined);
149
180
  let raw;
150
181
  try {
151
182
  raw = await readPrivateText(portFile);
@@ -172,13 +203,16 @@ export async function sweepRpcState(root, activeDir, isManagedDir, log) {
172
203
  const entry = parsed;
173
204
  if (!pidAlive(entry.pid))
174
205
  await unlink(portFile).catch(() => { });
206
+ else if (isStalePortFile(entry, info, cutoff))
207
+ await removeStalePortFile(portFile, raw, info, options.beforeRemove);
175
208
  }
176
209
  if (resolve(dir) !== active)
177
210
  await rmdir(dir).catch(() => { });
178
211
  }
179
212
  }
180
213
  /** Internal cache validation: probe only the selected file and its PID. */
181
- export async function portFileIdentity(dir, entry) {
214
+ export async function portFileIdentity(dir, entry, options = {}) {
215
+ const cutoff = staleBefore(options);
182
216
  if (!pidAlive(entry.pid))
183
217
  return null;
184
218
  const path = join(resolve(dir), `port-${entry.pid}.json`);
@@ -186,6 +220,8 @@ export async function portFileIdentity(dir, entry) {
186
220
  if (windowsPrivateFiles)
187
221
  await verifyPrivate(path, 'file');
188
222
  const info = await stat(path);
223
+ if (isStalePortFile(entry, info, cutoff))
224
+ return null;
189
225
  return `${path}:${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`;
190
226
  }
191
227
  catch (error) {
@@ -195,6 +231,7 @@ export async function portFileIdentity(dir, entry) {
195
231
  }
196
232
  }
197
233
  export async function discoverPortFile(dir, expectedPid, options = {}) {
234
+ const cutoff = staleBefore(options);
198
235
  let names;
199
236
  try {
200
237
  if (windowsPrivateFiles)
@@ -213,8 +250,13 @@ export async function discoverPortFile(dir, expectedPid, options = {}) {
213
250
  try {
214
251
  const parsed = JSON.parse(await readPrivateText(join(dir, name)));
215
252
  if (isUsablePortFileEntry(parsed, name)) {
216
- if (pidAlive(parsed.pid))
217
- live.push(parsed);
253
+ if (pidAlive(parsed.pid)) {
254
+ const info = parsed.startedAt === undefined
255
+ ? await stat(join(dir, name)).catch(() => undefined)
256
+ : undefined;
257
+ if (!isStalePortFile(parsed, info, cutoff))
258
+ live.push(parsed);
259
+ }
218
260
  else
219
261
  await unlink(join(dir, name)).catch(() => { });
220
262
  }