@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
@@ -4,6 +4,7 @@ import { ClaustrumUnreachableError, classifyVaultFailure, } from "./94f53cfd572b
4
4
  import { readClaustrumEnrollmentToken } from "./b9588ad4725c1d10-enrollment.js";
5
5
  import { ClaustrumConsumerError } from "./ca0fccaba1d87af4-errors.js";
6
6
  import { CUSTODY_PLACEHOLDER_PREFIX } from "./d9d2892a4c371301-host-slot.js";
7
+ import { drainShutdown, shutdownWarning } from "./a670cb7f5987bc1b-shutdown.js";
7
8
  import { ScopedRosterWatch, } from "./dc9290c2a7552ba6-watch.js";
8
9
  /** Only a new version of the same account may replace an in-flight 401. */
9
10
  export function isScopedCredentialRotation(served, current) {
@@ -79,15 +80,56 @@ function accessTokenFromMaterial(material) {
79
80
  return access;
80
81
  }
81
82
  function credentialTypeOf(row, family) {
83
+ const notMine = { kind: 'not-mine' };
82
84
  if (!row.operations.includes('read'))
83
- return undefined;
85
+ return notMine;
84
86
  if (!row.categories.includes(family.category))
85
- return undefined;
87
+ return notMine;
88
+ if (row.credentialType !== 'oauth' && row.credentialType !== 'api_key')
89
+ return notMine;
90
+ if ('classify' in family) {
91
+ // Older clients omit these facts entirely; do not call a policy that needs them.
92
+ const facts = {
93
+ credentialId: row.id,
94
+ credentialType: row.credentialType,
95
+ categories: row.categories,
96
+ refreshAdapter: row.refreshAdapter,
97
+ ...rowFactsOf(row),
98
+ };
99
+ if (facts.providerIds === undefined)
100
+ return { kind: 'refused', code: 'unmapped' };
101
+ try {
102
+ const result = family.classify(facts);
103
+ if (result.kind === 'not-mine')
104
+ return notMine;
105
+ if (result.kind === 'mine' && typeof result.member === 'string')
106
+ return { kind: 'mine', type: row.credentialType, member: result.member };
107
+ if (result.kind === 'refused' &&
108
+ typeof result.code === 'string' &&
109
+ /^[a-z][a-z0-9-]{0,31}$/.test(result.code) &&
110
+ !result.code.includes('\n') &&
111
+ family.refusalCodes.includes(result.code))
112
+ return { kind: 'refused', code: result.code };
113
+ }
114
+ catch {
115
+ // A classifier error may contain vault data; expose only a fixed code.
116
+ }
117
+ return { kind: 'refused', code: 'unclassified' };
118
+ }
86
119
  if (row.credentialType === 'oauth')
87
- return row.refreshAdapter === family.refreshAdapter ? 'oauth' : undefined;
120
+ return row.refreshAdapter === family.refreshAdapter
121
+ ? { kind: 'mine', type: 'oauth' }
122
+ : notMine;
88
123
  if (row.credentialType === 'api_key' && family.apiKeys)
89
- return row.refreshAdapter === undefined ? 'api_key' : undefined;
90
- return undefined;
124
+ return row.refreshAdapter === undefined
125
+ ? { kind: 'mine', type: 'api_key' }
126
+ : notMine;
127
+ return notMine;
128
+ }
129
+ /** Structural access keeps the public facts independent of client declarations. */
130
+ function rowFactsOf(row) {
131
+ const metadata = row;
132
+ return { providerIds: metadata.providerIds, authMethod: metadata.authMethod };
91
133
  }
92
134
  /**
93
135
  * The grants named in the vault's list reply, or undefined when it names none.
@@ -136,6 +178,9 @@ export class ClaustrumScopedCustody {
136
178
  /** The view of the last successful `discover()`, for `watchRoster`. */
137
179
  #discoveredView;
138
180
  #watches = new Set();
181
+ #tokenReads = new Set();
182
+ #warnShutdown;
183
+ #disposing;
139
184
  constructor(options) {
140
185
  const tokenPath = options.tokenPath;
141
186
  if (options.readToken) {
@@ -153,6 +198,7 @@ export class ClaustrumScopedCustody {
153
198
  this.#requireAssertion = options.requireAssertion ?? false;
154
199
  this.#now = options.now ?? Date.now;
155
200
  this.#logger = options.logger ?? defaultLogger;
201
+ this.#warnShutdown = shutdownWarning(this.#logger);
156
202
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
157
203
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
158
204
  }
@@ -220,7 +266,15 @@ export class ClaustrumScopedCustody {
220
266
  }
221
267
  async #token(signal) {
222
268
  this.#check(signal);
223
- const value = await this.#readToken();
269
+ const pending = this.#readToken();
270
+ this.#tokenReads.add(pending);
271
+ let value;
272
+ try {
273
+ value = await pending;
274
+ }
275
+ finally {
276
+ this.#tokenReads.delete(pending);
277
+ }
224
278
  this.#check(signal);
225
279
  if (!/^[0-9a-f]{64}$/.test(value.token) ||
226
280
  !Number.isSafeInteger(value.token_generation) ||
@@ -299,17 +353,32 @@ export class ClaustrumScopedCustody {
299
353
  throw error;
300
354
  }
301
355
  const skipped = [];
356
+ const refused = [];
357
+ let notMine = 0;
302
358
  const candidates = [];
303
359
  const counts = new Map();
304
360
  for (const row of inventory.rows) {
305
- const type = credentialTypeOf(row, this.#family);
306
- if (!type)
361
+ const classified = credentialTypeOf(row, this.#family);
362
+ if (classified.kind === 'not-mine') {
363
+ notMine++;
364
+ continue;
365
+ }
366
+ if (classified.kind === 'refused') {
367
+ refused.push({
368
+ ...(row.id.trim() && { credentialId: row.id }),
369
+ code: classified.code,
370
+ });
307
371
  continue;
308
- candidates.push({ row, type });
372
+ }
373
+ candidates.push({
374
+ row,
375
+ type: classified.type,
376
+ ...(classified.member !== undefined && { member: classified.member }),
377
+ });
309
378
  counts.set(row.id, (counts.get(row.id) ?? 0) + 1);
310
379
  }
311
380
  const credentials = [];
312
- for (const { row, type } of candidates) {
381
+ for (const { row, type, member } of candidates) {
313
382
  let reason;
314
383
  if (!row.id.trim())
315
384
  reason = 'empty credential id';
@@ -320,12 +389,17 @@ export class ClaustrumScopedCustody {
320
389
  else if (!row.state.trim())
321
390
  reason = 'empty state';
322
391
  if (reason) {
323
- skipped.push({ ...(row.id.trim() && { credentialId: row.id }), reason });
392
+ skipped.push({
393
+ ...(row.id.trim() && { credentialId: row.id }),
394
+ ...(member !== undefined && { member }),
395
+ reason,
396
+ });
324
397
  continue;
325
398
  }
326
399
  credentials.push(Object.freeze({
327
400
  credentialId: row.id,
328
401
  credentialType: type,
402
+ ...(member !== undefined && { member }),
329
403
  ...(row.accountId !== undefined && {
330
404
  accountIdentity: row.accountId,
331
405
  }),
@@ -341,6 +415,10 @@ export class ClaustrumScopedCustody {
341
415
  view: inventory.view,
342
416
  credentials: Object.freeze(credentials),
343
417
  skipped: Object.freeze(skipped),
418
+ ...('classify' in this.#family && {
419
+ refused: Object.freeze(refused),
420
+ notMine,
421
+ }),
344
422
  ...(grantReach && { grantReach }),
345
423
  };
346
424
  }
@@ -646,4 +724,10 @@ export class ClaustrumScopedCustody {
646
724
  this.#kept.clear();
647
725
  this.#client.close();
648
726
  }
727
+ /** Stop immediately; allow token reads 2 s and share an owner's timeout warning. */
728
+ async dispose(onTimeout = this.#warnShutdown) {
729
+ this.close();
730
+ this.#disposing ??= drainShutdown(this.#tokenReads, onTimeout);
731
+ await this.#disposing;
732
+ }
649
733
  }
@@ -1,12 +1,39 @@
1
1
  import { createLogger } from "./cc9e0702a752cea7-index.js";
2
2
  import { combineAbortSignals } from "./6371b24a0573d79e-any-signal.js";
3
+ import { ClaustrumUnreachableError } from "./94f53cfd572ba4bb-availability.js";
3
4
  import { ClaustrumScopedCustody, decideScopedRetryAfter401, } from "./0f77ebc3c914c9c6-custody.js";
4
5
  import { readClaustrumEnrollmentToken } from "./b9588ad4725c1d10-enrollment.js";
5
6
  import { ClaustrumConsumerError } from "./ca0fccaba1d87af4-errors.js";
6
7
  import { acquireInsulaQuotaSource, } from "./d0f0b6be200311af-insula.js";
7
8
  import { pendingVaultQuota, retainVaultQuotaWriter } from "./81dddd203f1b92a3-quota-writer.js";
8
9
  import { acceptVaultRoute, applyVaultQuota, declineVaultRoute, forgetPendingVaultDiscovery, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, vaultRoutingRows, } from "./30f5bc480f31f51c-roster.js";
10
+ import { drainShutdown, shutdownWarning } from "./a670cb7f5987bc1b-shutdown.js";
9
11
  import { SAFETY_POLL_MS } from "./dc9290c2a7552ba6-watch.js";
12
+ /**
13
+ * How long one connect attempt may take by default. It bounds a connect that
14
+ * never settles; the client's own handshake limit is not guaranteed to cover
15
+ * every stall, and callers waiting on discovery need an answer either way.
16
+ */
17
+ export const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;
18
+ /** An unreachable vault, raised when a connect passed its time limit. */
19
+ function unreachableConnect() {
20
+ return new ClaustrumUnreachableError();
21
+ }
22
+ let buildHubMember;
23
+ /**
24
+ * Build the consumer for one hub member. `options` holds only what the member
25
+ * uses: the hub's roster path for this member and the member's own fields.
26
+ * Hub-mode paths never read `tokenPath`, `family` or `connect`, which the hub
27
+ * owns. Package-internal: only `ClaustrumDiscoveryHub.member` calls it.
28
+ */
29
+ export function createHubMember(port, options) {
30
+ if (!buildHubMember)
31
+ throw new Error('ClaustrumConsumer is not initialized');
32
+ return buildHubMember(port, options);
33
+ }
34
+ function notActive() {
35
+ return new ClaustrumConsumerError('not-active', 'Claustrum scoped custody is not active');
36
+ }
10
37
  /**
11
38
  * One plugin host's view of its vault accounts. It turns vault credentials
12
39
  * into rows for `/routing`, authorizes each physical send with the vault, and
@@ -19,6 +46,7 @@ export class ClaustrumConsumer {
19
46
  #options;
20
47
  #shutdown = new AbortController();
21
48
  #logger;
49
+ #warnShutdown;
22
50
  #custody;
23
51
  #connecting;
24
52
  #refreshing;
@@ -30,6 +58,8 @@ export class ClaustrumConsumer {
30
58
  #grantReach;
31
59
  #timer;
32
60
  #started = false;
61
+ #pending = new Set();
62
+ #disposing;
33
63
  #insula;
34
64
  #vaultWatch;
35
65
  #releaseInsulaWatch;
@@ -37,9 +67,23 @@ export class ClaustrumConsumer {
37
67
  /** When this instance last completed a discovery, by `now`. */
38
68
  #discoveredAt;
39
69
  #releaseQuotaWriter;
70
+ /** Set only on a member built by `ClaustrumDiscoveryHub.member`. */
71
+ #hub;
72
+ /** A hub member's one custody lease at a time. */
73
+ #lease;
74
+ /** The lease that issued each receipt, so a 401 goes back through it. */
75
+ #issuedBy = new WeakMap();
76
+ static {
77
+ buildHubMember = (port, options) => {
78
+ const consumer = new ClaustrumConsumer(options);
79
+ consumer.#hub = port;
80
+ return { consumer, hooks: consumer.#hubHooks() };
81
+ };
82
+ }
40
83
  constructor(options) {
41
84
  this.#options = options;
42
85
  this.#logger = options.logger ?? createLogger('claustrum');
86
+ this.#warnShutdown = shutdownWarning(this.#logger, this.#shutdown.signal);
43
87
  this.#releaseQuotaWriter = retainVaultQuotaWriter(options.rosterPath, (publication) => {
44
88
  this.#roster = applyVaultQuota(this.#roster, publication).roster;
45
89
  });
@@ -48,6 +92,11 @@ export class ClaustrumConsumer {
48
92
  this.#shutdown.signal.throwIfAborted();
49
93
  signal?.throwIfAborted();
50
94
  }
95
+ #track(pending) {
96
+ this.#pending.add(pending);
97
+ void pending.then(() => this.#pending.delete(pending), () => this.#pending.delete(pending));
98
+ return pending;
99
+ }
51
100
  async #active() {
52
101
  return (await this.#options.isCustodyActive?.()) ?? true;
53
102
  }
@@ -87,35 +136,69 @@ export class ClaustrumConsumer {
87
136
  if (this.#custody)
88
137
  return this.#custody;
89
138
  if (!this.#connecting) {
90
- this.#connecting = this.#options
91
- .connect()
92
- .then((client) => {
93
- if (this.#shutdown.signal.aborted) {
94
- client.close();
95
- this.#assertOpen();
96
- }
97
- this.#custody = new ClaustrumScopedCustody({
98
- client,
99
- family: this.#options.family,
100
- tokenPath: this.#options.tokenPath,
101
- parseIdentity: this.#options.parseIdentity,
102
- requireAssertion: this.#options.requireAssertion,
103
- now: this.#options.now,
104
- logger: this.#logger,
105
- setTimeoutImpl: this.#options.setTimeoutImpl,
106
- clearTimeoutImpl: this.#options.clearTimeoutImpl,
107
- });
108
- if (this.#options.insula && client.insula) {
109
- this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
110
- }
111
- return this.#custody;
112
- })
113
- .finally(() => {
114
- this.#connecting = undefined;
115
- });
139
+ // A connect that never settles must not hold #connecting open: every
140
+ // later refresh would wait on the same promise. The race below bounds
141
+ // each attempt, and only a client that arrives in time is installed.
142
+ const attempt = { timedOut: false };
143
+ this.#connecting = this.#boundedConnect(attempt);
144
+ this.#track(this.#connecting);
116
145
  }
117
146
  return this.#wait(this.#connecting);
118
147
  }
148
+ /**
149
+ * One `connect()` attempt under `connectTimeoutMs`. The late promise is still
150
+ * observed after the deadline, so a client that arrives then is closed
151
+ * rather than leaked.
152
+ */
153
+ #boundedConnect(attempt) {
154
+ const setTimer = this.#options.setTimeoutImpl ?? setTimeout;
155
+ const clearTimer = this.#options.clearTimeoutImpl ?? clearTimeout;
156
+ const pending = this.#options.connect().then((client) => {
157
+ if (this.#shutdown.signal.aborted || attempt.timedOut) {
158
+ client.close();
159
+ if (!attempt.timedOut)
160
+ this.#assertOpen();
161
+ throw unreachableConnect();
162
+ }
163
+ this.#custody = new ClaustrumScopedCustody({
164
+ client,
165
+ family: this.#options.family,
166
+ tokenPath: this.#options.tokenPath,
167
+ parseIdentity: this.#options.parseIdentity,
168
+ requireAssertion: this.#options.requireAssertion,
169
+ now: this.#options.now,
170
+ logger: this.#logger,
171
+ setTimeoutImpl: this.#options.setTimeoutImpl,
172
+ clearTimeoutImpl: this.#options.clearTimeoutImpl,
173
+ });
174
+ if (this.#options.insula && client.insula) {
175
+ this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
176
+ }
177
+ return this.#custody;
178
+ });
179
+ let timer;
180
+ const deadline = new Promise((_resolve, reject) => {
181
+ timer = setTimer(() => {
182
+ attempt.timedOut = true;
183
+ if (this.#shutdown.signal.aborted)
184
+ return;
185
+ this.#logger.warn('vault connect timed out', {
186
+ reason: 'unreachable',
187
+ connectTimeoutMs: this.#connectTimeoutMs(),
188
+ });
189
+ reject(unreachableConnect());
190
+ }, this.#connectTimeoutMs());
191
+ timer.unref?.();
192
+ });
193
+ return Promise.race([pending, deadline]).finally(() => {
194
+ if (timer)
195
+ clearTimer(timer);
196
+ this.#connecting = undefined;
197
+ });
198
+ }
199
+ #connectTimeoutMs() {
200
+ return this.#options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
201
+ }
119
202
  /** The last committed roster this instance saw, without any I/O. */
120
203
  snapshot() {
121
204
  return this.#roster;
@@ -130,6 +213,8 @@ export class ClaustrumConsumer {
130
213
  * held the discovery lease and its newer roster was served instead).
131
214
  */
132
215
  grantReach() {
216
+ if (this.#hub)
217
+ return this.#hub.grantReach(this.#roster?.view);
133
218
  const latest = this.#grantReach;
134
219
  return latest && this.#roster?.view === latest.view
135
220
  ? latest.reach
@@ -137,6 +222,8 @@ export class ClaustrumConsumer {
137
222
  }
138
223
  /** How this consumer currently learns about changes, without I/O. */
139
224
  watchState() {
225
+ if (this.#hub)
226
+ return Object.freeze({ vault: this.#hub.watchMode() });
140
227
  return Object.freeze({
141
228
  vault: this.#vaultWatch?.mode ?? 'polling',
142
229
  ...(this.#options.insula && {
@@ -153,6 +240,13 @@ export class ClaustrumConsumer {
153
240
  }
154
241
  /** Whether any account is using an in-memory outage receipt, without I/O. */
155
242
  keptReceiptState() {
243
+ if (this.#hub) {
244
+ // Kept receipts live in the one shared custody, whichever lease reads it.
245
+ const lease = this.#lease;
246
+ return lease && this.#hub.leaseLive(lease)
247
+ ? lease.custody.keptReceiptState()
248
+ : this.#hub.keptReceiptState();
249
+ }
156
250
  return (this.#custody?.keptReceiptState() ??
157
251
  Object.freeze({ active: false, since: null }));
158
252
  }
@@ -162,6 +256,8 @@ export class ClaustrumConsumer {
162
256
  }
163
257
  refresh() {
164
258
  this.#assertOpen();
259
+ if (this.#hub)
260
+ return this.#track(this.#hubRefresh(this.#hub));
165
261
  if (this.#refreshing)
166
262
  return this.#refreshing;
167
263
  this.#refreshing = (async () => {
@@ -169,7 +265,10 @@ export class ClaustrumConsumer {
169
265
  this.#roster = undefined;
170
266
  this.#grantReach = undefined;
171
267
  this.#stopWatch();
172
- this.#custody?.close();
268
+ if (this.#custody) {
269
+ this.#custody.close();
270
+ this.#track(this.#custody.dispose(this.#warnShutdown));
271
+ }
173
272
  this.#custody = undefined;
174
273
  this.#insula?.release();
175
274
  this.#insula = undefined;
@@ -214,6 +313,7 @@ export class ClaustrumConsumer {
214
313
  })().finally(() => {
215
314
  this.#refreshing = undefined;
216
315
  });
316
+ this.#track(this.#refreshing);
217
317
  return this.#refreshing;
218
318
  }
219
319
  /**
@@ -231,6 +331,11 @@ export class ClaustrumConsumer {
231
331
  return;
232
332
  this.#assertOpen();
233
333
  this.#started = true;
334
+ // A hub member has no tick or watch of its own: the hub drives it.
335
+ if (this.#hub) {
336
+ this.#hub.start();
337
+ return;
338
+ }
234
339
  const tick = async () => {
235
340
  try {
236
341
  if (await this.#listDue())
@@ -249,11 +354,11 @@ export class ClaustrumConsumer {
249
354
  return;
250
355
  this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
251
356
  this.#timer = undefined;
252
- void tick();
357
+ void this.#track(tick());
253
358
  }, delay);
254
359
  this.#timer.unref?.();
255
360
  };
256
- void tick();
361
+ void this.#track(tick());
257
362
  }
258
363
  /** Whether a background tick must list the vault now. */
259
364
  async #listDue() {
@@ -282,11 +387,13 @@ export class ClaustrumConsumer {
282
387
  // re-applies it to kept receipts exactly as a poll does. A refresh
283
388
  // already in flight may have listed before the change was announced,
284
389
  // so wait for it and list again.
285
- onView: async () => {
390
+ onView: () => this.#track((async () => {
286
391
  while (this.#refreshing)
287
392
  await this.#refreshing.catch(() => { });
393
+ if (this.#shutdown.signal.aborted)
394
+ return;
288
395
  await this.refresh();
289
- },
396
+ })()),
290
397
  // Custody has dropped kept receipts, as a poll meeting the same
291
398
  // refusal from list_scoped would.
292
399
  onRefused: (error) => this.#options.onError?.(error),
@@ -412,6 +519,8 @@ export class ClaustrumConsumer {
412
519
  * poll, and a route whose credential or account changed is refused.
413
520
  */
414
521
  async authorize(routeId, signal) {
522
+ if (this.#hub)
523
+ return this.#hubAuthorize(this.#hub, routeId, signal);
415
524
  this.#assertOpen(signal);
416
525
  const roster = this.#roster ?? (await this.#wait(this.refresh(), signal));
417
526
  if (!roster || !(await this.#active())) {
@@ -459,8 +568,168 @@ export class ClaustrumConsumer {
459
568
  combined.dispose();
460
569
  }
461
570
  }
571
+ /** The hub's handle on this member's memory. */
572
+ #hubHooks() {
573
+ return {
574
+ install: (roster) => {
575
+ if (this.#shutdown.signal.aborted)
576
+ return;
577
+ const changed = roster.view !== this.#roster?.view;
578
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, roster);
579
+ // One subscriber's failure must not stop the hub's fan-out.
580
+ if (changed)
581
+ try {
582
+ this.#options.onRoster?.(roster);
583
+ }
584
+ catch (error) {
585
+ this.#options.onError?.(error);
586
+ }
587
+ },
588
+ reset: () => {
589
+ this.#roster = undefined;
590
+ },
591
+ roster: () => this.#roster,
592
+ projection: () => ({
593
+ reservedRouteIds: new Set(this.#options.reservedRouteIds?.() ?? []),
594
+ routePrefix: this.#options.routePrefix,
595
+ mapAccount: this.#options.mapAccount,
596
+ now: (this.#options.now ?? Date.now)(),
597
+ }),
598
+ onError: (error) => {
599
+ if (!this.#shutdown.signal.aborted)
600
+ this.#options.onError?.(error);
601
+ },
602
+ };
603
+ }
604
+ /**
605
+ * A hub member's refresh is the hub's: the hub has already pushed this
606
+ * member's committed roster into memory when it resolves.
607
+ */
608
+ async #hubRefresh(hub) {
609
+ const outcome = await hub.refresh();
610
+ this.#assertOpen();
611
+ if (!outcome)
612
+ return undefined;
613
+ if (outcome.errors.has(hub.provider))
614
+ throw outcome.errors.get(hub.provider);
615
+ return this.#roster;
616
+ }
617
+ /** Release this member's lease, or only `lease` when one is named. */
618
+ #dropLease(lease) {
619
+ if (lease && this.#lease !== lease)
620
+ return;
621
+ this.#lease?.release();
622
+ this.#lease = undefined;
623
+ }
624
+ /** This member's lease, re-acquired once its connection has ended. */
625
+ async #currentLease(hub, signal) {
626
+ const held = this.#lease;
627
+ if (held && hub.leaseLive(held))
628
+ return held;
629
+ this.#dropLease();
630
+ const lease = await hub.acquire(signal);
631
+ if (this.#shutdown.signal.aborted) {
632
+ lease.release();
633
+ this.#assertOpen();
634
+ }
635
+ // A concurrent authorize may have acquired first; keep one lease.
636
+ const raced = this.#lease;
637
+ if (raced && hub.leaseLive(raced)) {
638
+ lease.release();
639
+ return raced;
640
+ }
641
+ this.#lease = lease;
642
+ return lease;
643
+ }
644
+ /**
645
+ * `authorize` for a hub member. Only the hub's own authority read decides
646
+ * that vault mode is off. If the hub's refresh still leaves this member
647
+ * without a roster, it fails with `route-unavailable` before acquiring a
648
+ * lease or asking for a credential, and no other member is affected.
649
+ */
650
+ async #hubAuthorize(hub, routeId, signal) {
651
+ this.#assertOpen(signal);
652
+ // A failed list rejects here; this member's own failed commit leaves it
653
+ // without a roster, handled below.
654
+ if (!this.#roster)
655
+ await this.#wait(hub.refresh(), signal);
656
+ const roster = this.#roster;
657
+ if (!(await hub.readAuthority())) {
658
+ this.#dropLease();
659
+ throw notActive();
660
+ }
661
+ this.#assertOpen(signal);
662
+ if (!roster)
663
+ throw new ClaustrumConsumerError('route-unavailable', 'Claustrum has no roster for this provider yet');
664
+ const current = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
665
+ this.#assertOpen(signal);
666
+ const observed = roster.rows.find((row) => row.routeId === routeId);
667
+ const configured = current?.rows.find((row) => row.routeId === routeId);
668
+ if (configured && !configured.enabled) {
669
+ if (observed)
670
+ hub.forget(observed.credentialId);
671
+ throw new ClaustrumConsumerError('route-declined', 'Claustrum route is disabled');
672
+ }
673
+ if (!observed ||
674
+ !configured ||
675
+ configured.state !== 'active' ||
676
+ configured.credentialId !== observed.credentialId ||
677
+ configured.accountIdentity !== observed.accountIdentity ||
678
+ configured.credentialType !== observed.credentialType) {
679
+ if (observed)
680
+ hub.forget(observed.credentialId);
681
+ throw new ClaustrumConsumerError('route-unavailable', 'Claustrum route is disabled, removed or changed');
682
+ }
683
+ const identity = {
684
+ credentialId: configured.credentialId,
685
+ credentialType: configured.credentialType,
686
+ ...(configured.accountIdentity !== undefined && {
687
+ accountIdentity: configured.accountIdentity,
688
+ }),
689
+ };
690
+ const combined = combineAbortSignals([
691
+ this.#shutdown.signal,
692
+ ...(signal ? [signal] : []),
693
+ ]);
694
+ try {
695
+ for (let attempt = 0;; attempt++) {
696
+ const lease = await this.#currentLease(hub, combined.signal);
697
+ try {
698
+ const served = await lease.custody.authorize(identity, combined.signal, routeId);
699
+ this.#issuedBy.set(served, lease);
700
+ return served;
701
+ }
702
+ catch (error) {
703
+ // Only a lease whose connection ended meanwhile earns one more
704
+ // try, in the current connection; anything else, or a second
705
+ // closed, is the answer.
706
+ if (attempt > 0 ||
707
+ combined.signal.aborted ||
708
+ hub.leaseLive(lease) ||
709
+ !(error instanceof ClaustrumConsumerError) ||
710
+ error.kind !== 'closed')
711
+ throw error;
712
+ this.#dropLease(lease);
713
+ if (!(await hub.readAuthority()))
714
+ throw notActive();
715
+ }
716
+ }
717
+ }
718
+ finally {
719
+ combined.dispose();
720
+ }
721
+ }
462
722
  async reportFailure(attempt, status, source) {
463
723
  this.#assertOpen();
724
+ if (this.#hub) {
725
+ // Only the lease that issued the receipt may report it; once that
726
+ // lease was released or its connection ended, its view throws closed.
727
+ const lease = this.#issuedBy.get(attempt);
728
+ if (!lease)
729
+ throw new ClaustrumConsumerError('no-receipt', 'Claustrum dispatch receipt has no active owner');
730
+ await lease.custody.reportFailure(attempt, status, source);
731
+ return;
732
+ }
464
733
  if (!this.#custody)
465
734
  throw new ClaustrumConsumerError('no-receipt', 'Claustrum dispatch receipt has no active owner');
466
735
  await this.#custody.reportFailure(attempt, status, source);
@@ -519,7 +788,12 @@ export class ClaustrumConsumer {
519
788
  this.#assertOpen();
520
789
  await declineVaultRoute(this.#options.rosterPath, routeId);
521
790
  this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
522
- this.#custody?.retain(this.#roster?.rows ?? []);
791
+ // A hub member shares kept receipts with every other member, so they are
792
+ // retained against all members' rosters, never against this one alone.
793
+ if (this.#hub)
794
+ this.#hub.retainUnion();
795
+ else
796
+ this.#custody?.retain(this.#roster?.rows ?? []);
523
797
  }
524
798
  async accept(routeId) {
525
799
  this.#assertOpen();
@@ -581,7 +855,14 @@ export class ClaustrumConsumer {
581
855
  (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
582
856
  this.#timer = undefined;
583
857
  this.#stopWatch();
584
- this.#custody?.close();
858
+ if (this.#custody) {
859
+ this.#custody.close();
860
+ this.#track(this.#custody.dispose(this.#warnShutdown));
861
+ }
862
+ // A hub member gives back its lease; the shared custody stays open.
863
+ this.#lease?.release();
864
+ this.#lease = undefined;
865
+ this.#hub?.detach();
585
866
  this.#insula?.release();
586
867
  this.#insula = undefined;
587
868
  this.#roster = undefined;
@@ -589,9 +870,13 @@ export class ClaustrumConsumer {
589
870
  void this.#releaseQuotaWriter();
590
871
  forgetPendingVaultDiscovery(this.#options.rosterPath);
591
872
  }
592
- /** Close immediately; the last consumer also waits for the writer's bounded drain. */
873
+ /** Close immediately; background work gets 2 s and the quota writer its own 1 s. */
593
874
  async dispose() {
594
875
  this.close();
595
- await this.#releaseQuotaWriter();
876
+ this.#disposing ??= Promise.all([
877
+ drainShutdown(this.#pending, this.#warnShutdown),
878
+ this.#releaseQuotaWriter(),
879
+ ]).then(() => { });
880
+ await this.#disposing;
596
881
  }
597
882
  }