@cortexkit/common-auth 0.39.2 → 0.41.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.
@@ -1,3 +1,4 @@
1
+ import { hasVaultHost, VAULT_HOST_STATUS } from '../claustrum/host.js';
1
2
  import { formatQuota, isQuotaMap, projectQuota, quotaTextParts, } from '../quota/index.js';
2
3
  import { PoolOperationError, } from '../store/index.js';
3
4
  import { doctorAction } from './doctor.js';
@@ -339,7 +340,7 @@ export function deleteAllAction(options) {
339
340
  * quotas, doctor and the extras; nothing that adds, signs in or removes.
340
341
  */
341
342
  export async function accountMenuActions(options) {
342
- return actionsFor(options, (await options.custody?.()) === true);
343
+ return actionsFor(options, hasVaultHost() || (await options.custody?.()) === true);
343
344
  }
344
345
  function actionsFor(options, custody) {
345
346
  const doctor = options.doctor?.length
@@ -369,7 +370,8 @@ function actionsFor(options, custody) {
369
370
  }
370
371
  /** Shows the account menu once and runs the chosen action. */
371
372
  export async function runAccountMenu(options) {
372
- const custody = (await options.custody?.()) === true;
373
+ const hosted = hasVaultHost();
374
+ const custody = hosted || (await options.custody?.()) === true;
373
375
  const actions = actionsFor(options, custody);
374
376
  const [read, status] = await Promise.all([
375
377
  readRows(options.store),
@@ -380,7 +382,11 @@ export async function runAccountMenu(options) {
380
382
  subtitle: custody
381
383
  ? 'Accounts come from the vault; select an action'
382
384
  : 'Select an account action',
383
- status: [...status, ...accountLines(read)],
385
+ status: [
386
+ ...status,
387
+ ...(hosted ? [VAULT_HOST_STATUS] : []),
388
+ ...accountLines(read),
389
+ ],
384
390
  actions,
385
391
  ...(options.terminal ? { terminal: options.terminal } : {}),
386
392
  });
@@ -0,0 +1,41 @@
1
+ import type { CacheWarmStopReason, SessionCacheHours, SessionKeepWarmMode } from '../routing-accessor/cache-policy.js';
2
+ export type CacheKeepDecisionInput = {
3
+ /** All times and the cache lifetime are in milliseconds. */
4
+ now: number;
5
+ ttlMs: number;
6
+ lastRealRequestAt: number;
7
+ lastWarmAt?: number;
8
+ /** The caller resets the count and costs on every real request. */
9
+ warmsSinceLastRealRequest: number;
10
+ /** Plugin-priced input-token equivalents; no prices are guessed here. */
11
+ warmCostSoFar?: number;
12
+ nextWarmCost?: number;
13
+ rewriteCost?: number;
14
+ } & ({
15
+ mode: 'hours';
16
+ hours: SessionCacheHours;
17
+ } | {
18
+ mode: Exclude<SessionKeepWarmMode, 'hours'>;
19
+ hours?: never;
20
+ });
21
+ export type CacheKeepDecision = {
22
+ action: 'warm';
23
+ at: number;
24
+ } | {
25
+ action: 'wait';
26
+ until: number;
27
+ } | {
28
+ action: 'stop';
29
+ reason: CacheWarmStopReason;
30
+ };
31
+ /**
32
+ * Decide the next idle or tool-wait warm using a validated mode/window. The
33
+ * caller owns timers, session liveness and resetting counts/costs on real
34
+ * requests. A warm is due before expiry, never in its final safety margin.
35
+ *
36
+ * Auto applies a cost cap only when all three plugin-priced costs are supplied;
37
+ * without them this is timing only, and the plugin must apply its idle bounds.
38
+ * No provider prices are inferred. Off returns unsupported; callers must not
39
+ * report a stop for a session that never warmed.
40
+ */
41
+ export declare function decideCacheKeep(input: CacheKeepDecisionInput): CacheKeepDecision;
@@ -0,0 +1,53 @@
1
+ function withinHours(hours, at) {
2
+ const parts = new Intl.DateTimeFormat('en-GB', {
3
+ timeZone: hours.tz,
4
+ hour: '2-digit',
5
+ minute: '2-digit',
6
+ hourCycle: 'h23',
7
+ }).formatToParts(at);
8
+ const hour = parts.find((part) => part.type === 'hour')?.value;
9
+ const minute = parts.find((part) => part.type === 'minute')?.value;
10
+ const time = `${hour}:${minute}`;
11
+ return hours.from < hours.to
12
+ ? time >= hours.from && time < hours.to
13
+ : time >= hours.from || time < hours.to;
14
+ }
15
+ /**
16
+ * Decide the next idle or tool-wait warm using a validated mode/window. The
17
+ * caller owns timers, session liveness and resetting counts/costs on real
18
+ * requests. A warm is due before expiry, never in its final safety margin.
19
+ *
20
+ * Auto applies a cost cap only when all three plugin-priced costs are supplied;
21
+ * without them this is timing only, and the plugin must apply its idle bounds.
22
+ * No provider prices are inferred. Off returns unsupported; callers must not
23
+ * report a stop for a session that never warmed.
24
+ */
25
+ export function decideCacheKeep(input) {
26
+ const { mode, now, ttlMs, lastRealRequestAt, lastWarmAt, warmsSinceLastRealRequest, warmCostSoFar, nextWarmCost, rewriteCost, } = input;
27
+ if (mode === 'off')
28
+ return { action: 'stop', reason: 'unsupported' };
29
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
30
+ return { action: 'stop', reason: 'unsupported' };
31
+ }
32
+ if ((mode === 'hours' || mode === 'always') &&
33
+ warmsSinceLastRealRequest >= 24)
34
+ return { action: 'stop', reason: 'count-cap' };
35
+ if (mode === 'auto' &&
36
+ warmCostSoFar !== undefined &&
37
+ nextWarmCost !== undefined &&
38
+ rewriteCost !== undefined &&
39
+ warmCostSoFar + nextWarmCost >= rewriteCost)
40
+ return { action: 'stop', reason: 'cost-cap' };
41
+ const last = Math.max(lastRealRequestAt, lastWarmAt ?? lastRealRequestAt);
42
+ const expiresAt = last + ttlMs;
43
+ const due = expiresAt - Math.min(30_000, ttlMs / 2);
44
+ const at = Math.max(now, due);
45
+ // Replaying inside the expiry margin risks paying for a cold cache rewrite.
46
+ if (at >= expiresAt - Math.min(5_000, ttlMs / 10)) {
47
+ return { action: 'stop', reason: 'cost-cap' };
48
+ }
49
+ if (mode === 'hours' &&
50
+ (!withinHours(input.hours, due) || !withinHours(input.hours, at)))
51
+ return { action: 'stop', reason: 'outside-hours' };
52
+ return now < due ? { action: 'wait', until: due } : { action: 'warm', at };
53
+ }
@@ -1,3 +1,5 @@
1
+ export type { CacheKeepDecision, CacheKeepDecisionInput } from './decision.js';
2
+ export { decideCacheKeep } from './decision.js';
1
3
  export type { CacheKeepAdapter, CacheKeepBackoff, CacheKeepLogger, CacheKeepManagerOptions, CacheKeepProfile, CacheKeepSendInput, CacheKeepStatus, CacheKeepTargetStatus, CacheKeepTargetView, CacheKeepTrackInput, CacheKeepTrackResult, } from './manager.js';
2
4
  export { CacheKeepManager } from './manager.js';
3
5
  export type { CacheKeepWindow } from './window.js';
@@ -1,2 +1,3 @@
1
+ export { decideCacheKeep } from './decision.js';
1
2
  export { CacheKeepManager } from './manager.js';
2
3
  export { isWithinCacheKeepWindow, normalizeCacheKeepWindow, } from './window.js';
@@ -18,7 +18,10 @@ export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
18
18
  /** This host's enrollment token, written by setup. */
19
19
  tokenPath: string;
20
20
  family: ClaustrumFamily;
21
- connect: () => Promise<ClaustrumScopedClient>;
21
+ /** Enrollment-name prefix, required by the default host connection. */
22
+ pluginId?: string;
23
+ /** Used outside host authority; hosted connections always use the relay. */
24
+ connect?: () => Promise<ClaustrumScopedClient>;
22
25
  /**
23
26
  * How long one `connect()` attempt may take before this consumer treats the
24
27
  * vault as unreachable (default 10 s). A connect that never settles would
@@ -31,6 +34,7 @@ export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
31
34
  * Whether the plugin currently takes its accounts from the vault (custody
32
35
  * mode) rather than from local logins. Checked before every discovery,
33
36
  * commit and dispatch; false closes the vault connection and refuses sends.
37
+ * Host authority always selects custody and does not call this callback.
34
38
  */
35
39
  isCustodyActive?: () => boolean | Promise<boolean>;
36
40
  /** Ids of the plugin's local pool rows; no vault route id may equal one. */
@@ -4,6 +4,7 @@ import { ClaustrumUnreachableError } from './availability.js';
4
4
  import { ClaustrumScopedCustody, decideScopedRetryAfter401, } from './custody.js';
5
5
  import { readClaustrumEnrollmentToken } from './enrollment.js';
6
6
  import { ClaustrumConsumerError } from './errors.js';
7
+ import { connectVaultHost, hasVaultHost } from './host.js';
7
8
  import { acquireInsulaQuotaSource, } from './insula.js';
8
9
  import { pendingVaultQuota, retainVaultQuotaWriter } from './quota-writer.js';
9
10
  import { acceptVaultRoute, applyVaultQuota, declineVaultRoute, forgetPendingVaultDiscovery, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, vaultRoutingRows, } from './roster.js';
@@ -98,6 +99,8 @@ export class ClaustrumConsumer {
98
99
  return pending;
99
100
  }
100
101
  async #active() {
102
+ if (hasVaultHost())
103
+ return true;
101
104
  return (await this.#options.isCustodyActive?.()) ?? true;
102
105
  }
103
106
  #wait(pending, signal) {
@@ -153,7 +156,9 @@ export class ClaustrumConsumer {
153
156
  #boundedConnect(attempt) {
154
157
  const setTimer = this.#options.setTimeoutImpl ?? setTimeout;
155
158
  const clearTimer = this.#options.clearTimeoutImpl ?? clearTimeout;
156
- const pending = this.#options.connect().then((client) => {
159
+ const pending = (!hasVaultHost() && this.#options.connect
160
+ ? this.#options.connect()
161
+ : Promise.resolve().then(() => connectVaultHost(this.#options.pluginId))).then((client) => {
157
162
  if (this.#shutdown.signal.aborted || attempt.timedOut) {
158
163
  client.close();
159
164
  if (!attempt.timedOut)
@@ -429,7 +434,8 @@ export class ClaustrumConsumer {
429
434
  !(await this.#active()))
430
435
  return;
431
436
  try {
432
- await readClaustrumEnrollmentToken(this.#options.tokenPath);
437
+ if (!hasVaultHost())
438
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
433
439
  await this.#getCustody();
434
440
  await this.#insula?.source.refresh((this.#options.now ?? Date.now)());
435
441
  }
@@ -449,7 +455,8 @@ export class ClaustrumConsumer {
449
455
  !(await this.#active()))
450
456
  return undefined;
451
457
  try {
452
- await readClaustrumEnrollmentToken(this.#options.tokenPath);
458
+ if (!hasVaultHost())
459
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
453
460
  return this.#normalizeInsulaQuota(receipt.assertedAccountIdentity);
454
461
  }
455
462
  catch {
@@ -467,7 +474,8 @@ export class ClaustrumConsumer {
467
474
  !(await this.#active()))
468
475
  return undefined;
469
476
  try {
470
- await readClaustrumEnrollmentToken(this.#options.tokenPath);
477
+ if (!hasVaultHost())
478
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
471
479
  const roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
472
480
  const row = roster?.rows.find((entry) => entry.routeId === routeId);
473
481
  return this.#normalizeInsulaQuota(row?.accountIdentity);
@@ -482,7 +490,8 @@ export class ClaustrumConsumer {
482
490
  if (!options || this.#shutdown.signal.aborted || !(await this.#active()))
483
491
  return { miss: 'unreachable' };
484
492
  try {
485
- await readClaustrumEnrollmentToken(this.#options.tokenPath);
493
+ if (!hasVaultHost())
494
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
486
495
  const roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
487
496
  const account = roster?.rows.find((row) => row.routeId === routeId)?.accountIdentity;
488
497
  if (!account || !this.#insula)
@@ -249,16 +249,19 @@ export declare const SERVING_MARGIN_MS = 300000;
249
249
  export declare const KEPT_RECEIPT_MARGIN_MS = 60000;
250
250
  /**
251
251
  * Reads this consumer's vault credentials (list, fetch, 401 report), with the
252
- * enrollment token as authorization. Used by every host of a plugin. Every
253
- * physical send asks the vault first while reachable. Only an unreachable vault permits
254
- * reuse of the last validated receipt, in memory and bounded by its expiry.
255
- * The enrollment token is re-read per operation so revocation and disconnect
256
- * still take effect without a process restart.
252
+ * enrollment token or the host's grant as authorization. Used by every host of a
253
+ * plugin. Every physical send asks the vault first while reachable. Only an
254
+ * unreachable vault permits reuse of the last validated receipt, in memory and
255
+ * bounded by its expiry. Outside host authority the enrollment token is re-read
256
+ * per operation so revocation and disconnect still take effect without a restart.
257
257
  */
258
258
  export declare class ClaustrumScopedCustody {
259
259
  #private;
260
260
  constructor(options: {
261
- client: ClaustrumScopedClient;
261
+ /** While hosted, only a client returned by connectVaultHost is accepted. */
262
+ client?: ClaustrumScopedClient;
263
+ /** Enrollment-name prefix, required when using the default host client. */
264
+ pluginId?: string;
262
265
  family: ClaustrumFamilyInput;
263
266
  tokenPath?: string;
264
267
  readToken?: () => Promise<EnrollmentTokenFile>;
@@ -309,8 +312,8 @@ export declare class ClaustrumScopedCustody {
309
312
  * Report that a send this consumer actually made was rejected. Only a 401
310
313
  * is reported (the vault refuses 429, 402 and 5xx reports), addressed by
311
314
  * credential id with the exact record version that send was served, and
312
- * signed with the enrollment token that authorized it. A receipt this
313
- * custody did not issue is refused rather than reported.
315
+ * sent through the client and enrollment token that authorized it. A receipt
316
+ * this custody did not issue is refused rather than reported.
314
317
  */
315
318
  reportFailure(attempt: ClaustrumScopedAttempt, status: number, reporterSource: ClaustrumReporterSource): Promise<void>;
316
319
  /**
@@ -4,6 +4,7 @@ import { createLogger } from '../logger/index.js';
4
4
  import { ClaustrumUnreachableError, classifyVaultFailure, } from './availability.js';
5
5
  import { readClaustrumEnrollmentToken } from './enrollment.js';
6
6
  import { ClaustrumConsumerError } from './errors.js';
7
+ import { connectVaultHost, hasVaultHost, isVaultHostClient } from './host.js';
7
8
  import { CUSTODY_PLACEHOLDER_PREFIX } from './host-slot.js';
8
9
  import { drainShutdown, shutdownWarning } from './shutdown.js';
9
10
  import { ScopedUsageReporter, } from './usage.js';
@@ -174,11 +175,11 @@ function grantReachOf(listed) {
174
175
  }
175
176
  /**
176
177
  * Reads this consumer's vault credentials (list, fetch, 401 report), with the
177
- * enrollment token as authorization. Used by every host of a plugin. Every
178
- * physical send asks the vault first while reachable. Only an unreachable vault permits
179
- * reuse of the last validated receipt, in memory and bounded by its expiry.
180
- * The enrollment token is re-read per operation so revocation and disconnect
181
- * still take effect without a process restart.
178
+ * enrollment token or the host's grant as authorization. Used by every host of a
179
+ * plugin. Every physical send asks the vault first while reachable. Only an
180
+ * unreachable vault permits reuse of the last validated receipt, in memory and
181
+ * bounded by its expiry. Outside host authority the enrollment token is re-read
182
+ * per operation so revocation and disconnect still take effect without a restart.
182
183
  */
183
184
  export class ClaustrumScopedCustody {
184
185
  #client;
@@ -211,6 +212,8 @@ export class ClaustrumScopedCustody {
211
212
  #onDrainTimeout;
212
213
  #disposing;
213
214
  constructor(options) {
215
+ if (hasVaultHost() && options.client && !isVaultHostClient(options.client))
216
+ throw new ClaustrumUnreachableError();
214
217
  const tokenPath = options.tokenPath;
215
218
  if (options.readToken) {
216
219
  this.#readToken = options.readToken;
@@ -218,10 +221,15 @@ export class ClaustrumScopedCustody {
218
221
  else if (tokenPath) {
219
222
  this.#readToken = () => readClaustrumEnrollmentToken(tokenPath);
220
223
  }
224
+ else if (hasVaultHost()) {
225
+ this.#readToken = async () => {
226
+ throw new ClaustrumConsumerError('not-enrolled', 'Claustrum enrollment token path is required');
227
+ };
228
+ }
221
229
  else {
222
230
  throw new ClaustrumConsumerError('not-enrolled', 'Claustrum enrollment token path is required');
223
231
  }
224
- this.#client = options.client;
232
+ this.#client = options.client ?? connectVaultHost(options.pluginId);
225
233
  this.#family = options.family;
226
234
  this.#parseIdentity = options.parseIdentity;
227
235
  this.#requireAssertion = options.requireAssertion ?? false;
@@ -233,7 +241,7 @@ export class ClaustrumScopedCustody {
233
241
  this.#usage = new ScopedUsageReporter({
234
242
  client: this.#client,
235
243
  owns: (id) => this.#usageServed.has(id),
236
- token: async () => checkedEnrollmentToken(await this.#readToken()),
244
+ token: async () => hasVaultHost() ? '' : checkedEnrollmentToken(await this.#readToken()),
237
245
  logger: this.#logger,
238
246
  setTimeout: this.#setTimeout,
239
247
  clearTimeout: this.#clearTimeout,
@@ -303,6 +311,9 @@ export class ClaustrumScopedCustody {
303
311
  }
304
312
  async #token(signal) {
305
313
  this.#check(signal);
314
+ // The host ignores this empty argument; it never reaches a vault as a token.
315
+ if (hasVaultHost())
316
+ return '';
306
317
  if (phaseDiagnostics.hasSubscribers)
307
318
  phaseDiagnostics.publish({
308
319
  logger: this.#logger,
@@ -592,7 +603,7 @@ export class ClaustrumScopedCustody {
592
603
  if (kept.since === null)
593
604
  kept.since = this.#now();
594
605
  const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, 'accessToken', { value: kept.attempt.accessToken, enumerable: false }));
595
- this.#provenance.set(attempt, token);
606
+ this.#provenance.set(attempt, this.#provenance.get(kept.attempt) ?? { token, client: this.#client });
596
607
  this.#keptAttempts.set(attempt, routeId);
597
608
  return attempt;
598
609
  }
@@ -673,22 +684,22 @@ export class ClaustrumScopedCustody {
673
684
  recordVersion: served.recordVersion,
674
685
  expiresAtMs,
675
686
  }, 'accessToken', { value: accessToken, enumerable: false }));
676
- this.#provenance.set(attempt, token);
687
+ this.#provenance.set(attempt, { token, client: this.#client });
677
688
  return attempt;
678
689
  }
679
690
  /**
680
691
  * Report that a send this consumer actually made was rejected. Only a 401
681
692
  * is reported (the vault refuses 429, 402 and 5xx reports), addressed by
682
693
  * credential id with the exact record version that send was served, and
683
- * signed with the enrollment token that authorized it. A receipt this
684
- * custody did not issue is refused rather than reported.
694
+ * sent through the client and enrollment token that authorized it. A receipt
695
+ * this custody did not issue is refused rather than reported.
685
696
  */
686
697
  async reportFailure(attempt, status, reporterSource) {
687
698
  if (status !== 401)
688
699
  return;
689
700
  this.#check();
690
- const token = this.#provenance.get(attempt);
691
- if (!token)
701
+ const provenance = this.#provenance.get(attempt);
702
+ if (!provenance)
692
703
  throw new ClaustrumConsumerError('no-receipt', 'Claustrum failure report requires an original dispatch receipt');
693
704
  const keptRoute = this.#keptAttempts.get(attempt);
694
705
  if (keptRoute !== undefined) {
@@ -708,9 +719,9 @@ export class ClaustrumScopedCustody {
708
719
  const pending = this.#reports.get(attempt);
709
720
  if (pending)
710
721
  return pending;
711
- const report = this.#call(() => this.#client.reportAuthFailureScoped({
722
+ const report = this.#call(() => provenance.client.reportAuthFailureScoped({
712
723
  credentialId: attempt.credentialId,
713
- enrollmentToken: token,
724
+ enrollmentToken: provenance.token,
714
725
  providerStatus: 401,
715
726
  recordVersion: attempt.recordVersion,
716
727
  reporterSource,
@@ -124,6 +124,8 @@ export declare function readClaustrumEnrollmentStatus(paths: ClaustrumEnrollment
124
124
  * owner-only, as every private-file read there does.
125
125
  */
126
126
  export declare function enrollmentAuthority(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<'vault' | 'local' | 'unreadable'>;
127
+ /** Host authority takes precedence without reading any plugin enrollment files. */
128
+ export declare function vaultAuthority(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<'host' | 'vault' | 'local' | 'unreadable'>;
127
129
  /**
128
130
  * Read fresh bearer material for one scoped operation; never publish it.
129
131
  * Re-reading per operation is what lets an operator reissue a token on disk.
@@ -7,6 +7,7 @@ import { FileReadCache } from '../fs/file-read-cache.js';
7
7
  import { acquireRefreshFileLock } from '../fs/index.js';
8
8
  import { ensurePrivateDirectory as ensureWindowsDirectory, PrivateFileError, readPrivateText, verifySafeDirectory, windowsPrivateFiles, writePrivateAtomic, } from '../fs/private-files.js';
9
9
  import { ClaustrumConsumerError } from './errors.js';
10
+ import { hasVaultHost } from './host.js';
10
11
  const ENROLLMENT_SCHEMA = 1;
11
12
  const ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
12
13
  const ENROLLMENT_LOCK_TTL_MS = 30_000;
@@ -500,6 +501,12 @@ export async function enrollmentAuthority(paths, proposedName) {
500
501
  }
501
502
  return 'local';
502
503
  }
504
+ /** Host authority takes precedence without reading any plugin enrollment files. */
505
+ export async function vaultAuthority(paths, proposedName) {
506
+ if (hasVaultHost())
507
+ return 'host';
508
+ return enrollmentAuthority(paths, proposedName);
509
+ }
503
510
  /**
504
511
  * Read fresh bearer material for one scoped operation; never publish it.
505
512
  * Re-reading per operation is what lets an operator reissue a token on disk.
@@ -0,0 +1,8 @@
1
+ import type { ClaustrumScopedClient } from './custody.js';
2
+ export declare const VAULT_HOST_STATUS = "Served by Thalamus";
3
+ export declare const VAULT_HOST_CONNECT_REFUSAL = "This host gets its vault accounts from Thalamus, so it can't connect to the vault itself.";
4
+ export declare function isVaultHostClient(client: ClaustrumScopedClient): boolean;
5
+ /** The spawn marker, not a global installed by another plugin, selects authority. */
6
+ export declare function hasVaultHost(): boolean;
7
+ /** Read at connect time so a bridge installed after the auth plugin can recover. */
8
+ export declare function connectVaultHost(pluginId?: string): ClaustrumScopedClient;
@@ -0,0 +1,113 @@
1
+ import { ClaustrumCredentialError } from '@cortexkit/claustrum-client';
2
+ import { ClaustrumUnreachableError, classifyVaultFailure, } from './availability.js';
3
+ export const VAULT_HOST_STATUS = 'Served by Thalamus';
4
+ export const VAULT_HOST_CONNECT_REFUSAL = "This host gets its vault accounts from Thalamus, so it can't connect to the vault itself.";
5
+ // Object identity prevents a native client from carrying the host's empty token argument.
6
+ const hostClients = new WeakSet();
7
+ export function isVaultHostClient(client) {
8
+ return hostClients.has(client);
9
+ }
10
+ /** The spawn marker, not a global installed by another plugin, selects authority. */
11
+ export function hasVaultHost() {
12
+ return process.env.CORTEXKIT_VAULT_HOST === 'thalamus';
13
+ }
14
+ function hostError(error) {
15
+ if (typeof error !== 'object' || error === null)
16
+ return error;
17
+ const value = error;
18
+ if (typeof value.code === 'string' &&
19
+ (value.class === 'transient' ||
20
+ value.class === 'permanent' ||
21
+ value.class === 'auth_required' ||
22
+ value.class === 'context_overflow') &&
23
+ (value.action === 'gone' ||
24
+ value.action === 'reauth' ||
25
+ value.action === 'retry' ||
26
+ value.action === 'reduce_and_retry'))
27
+ return new ClaustrumCredentialError(value.code, value.class, value.action);
28
+ if (value.name === 'ClaustrumUnreachableError' ||
29
+ (typeof value.code === 'string' &&
30
+ classifyVaultFailure(Object.assign(new Error(), { code: value.code })) ===
31
+ 'unreachable'))
32
+ return new ClaustrumUnreachableError();
33
+ return error;
34
+ }
35
+ function call(operation) {
36
+ try {
37
+ return operation();
38
+ }
39
+ catch (error) {
40
+ throw hostError(error);
41
+ }
42
+ }
43
+ async function request(operation) {
44
+ try {
45
+ return await operation();
46
+ }
47
+ catch (error) {
48
+ throw hostError(error);
49
+ }
50
+ }
51
+ /** Normalize only the host boundary; native clients keep their strict error identity. */
52
+ function wrapHostClient(client) {
53
+ const watchScoped = client.watchScoped?.bind(client);
54
+ const reportUsageScoped = client.reportUsageScoped?.bind(client);
55
+ return {
56
+ listScoped: (...args) => request(() => client.listScoped(...args)),
57
+ getScoped: (...args) => request(() => client.getScoped(...args)),
58
+ reportAuthFailureScoped: (...args) => request(() => client.reportAuthFailureScoped(...args)),
59
+ close: () => call(() => client.close()),
60
+ ...(watchScoped && {
61
+ watchScoped: (...args) => {
62
+ const watch = call(() => watchScoped(...args));
63
+ return {
64
+ stop: () => call(() => watch.stop()),
65
+ closed: request(async () => {
66
+ const end = await watch.closed;
67
+ return end.kind === 'refused' || end.kind === 'transport_lost'
68
+ ? { ...end, error: hostError(end.error) }
69
+ : end;
70
+ }),
71
+ };
72
+ },
73
+ }),
74
+ ...(reportUsageScoped && {
75
+ reportUsageScoped: (...args) => request(() => reportUsageScoped(...args)),
76
+ }),
77
+ ...(client.insula && {
78
+ insula: wrapInsula(client.insula),
79
+ }),
80
+ };
81
+ }
82
+ function wrapInsula(transport) {
83
+ const watchUsage = transport.watchUsage?.bind(transport);
84
+ return {
85
+ connectionFile: transport.connectionFile,
86
+ getUsage: () => request(() => transport.getUsage()),
87
+ ...(watchUsage && {
88
+ watchUsage: (...args) => {
89
+ const watch = call(() => watchUsage(...args));
90
+ return {
91
+ stop: () => call(() => watch.stop()),
92
+ closed: request(() => watch.closed),
93
+ };
94
+ },
95
+ }),
96
+ };
97
+ }
98
+ /** Read at connect time so a bridge installed after the auth plugin can recover. */
99
+ export function connectVaultHost(pluginId) {
100
+ if (!hasVaultHost() || !pluginId)
101
+ throw new ClaustrumUnreachableError();
102
+ try {
103
+ const accessor = globalThis[Symbol.for('cortexkit.vault')];
104
+ if (typeof accessor !== 'function')
105
+ throw new ClaustrumUnreachableError();
106
+ const client = wrapHostClient(accessor(pluginId));
107
+ hostClients.add(client);
108
+ return client;
109
+ }
110
+ catch {
111
+ throw new ClaustrumUnreachableError();
112
+ }
113
+ }
@@ -46,7 +46,10 @@ export interface ClaustrumDiscoveryHubOptions {
46
46
  * member for any row and is refused.
47
47
  */
48
48
  family: ClassifyingClaustrumFamily<string>;
49
- connect: () => Promise<ClaustrumScopedClient>;
49
+ /** Enrollment-name prefix, required by the default host connection. */
50
+ pluginId?: string;
51
+ /** Used outside host authority; hosted connections always use the relay. */
52
+ connect?: () => Promise<ClaustrumScopedClient>;
50
53
  /**
51
54
  * How long one `connect()` attempt may take before the hub treats the vault
52
55
  * as unreachable (default 10 s, as `ClaustrumConsumerOptions`). The hub's
@@ -60,6 +63,7 @@ export interface ClaustrumDiscoveryHubOptions {
60
63
  * state only, never from the vault: on every hub tick, and when a member
61
64
  * refreshes or authorizes. The first false read revokes every lease,
62
65
  * closes the connection and clears every member.
66
+ * Host authority always selects custody and does not call this callback.
63
67
  */
64
68
  isCustodyActive?: () => boolean | Promise<boolean>;
65
69
  parseIdentity?: IdentityParser;
@@ -21,6 +21,7 @@ import { createHubMember, DEFAULT_CONNECT_TIMEOUT_MS, } from './consumer.js';
21
21
  import { ClaustrumScopedCustody, } from './custody.js';
22
22
  import { ensureClaustrumPrivateDirectory } from './enrollment.js';
23
23
  import { ClaustrumConsumerError } from './errors.js';
24
+ import { connectVaultHost, hasVaultHost } from './host.js';
24
25
  import { DEFAULT_ROUTE_PREFIX, decodedVaultRoster, forgetPendingVaultDiscovery, isVaultRosterLockRefusal, readVaultRoster, refreshVaultRoster, vaultRosterSeed, } from './roster.js';
25
26
  import { drainShutdown, shutdownWarning } from './shutdown.js';
26
27
  import { SAFETY_POLL_MS } from './watch.js';
@@ -383,7 +384,9 @@ export class ClaustrumDiscoveryHub {
383
384
  // that never settles would otherwise hold them all for the hub's life.
384
385
  const connectTimeoutMs = this.#options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
385
386
  let timer;
386
- const connect = this.#options.connect().then((client) => {
387
+ const connect = (!hasVaultHost() && this.#options.connect
388
+ ? this.#options.connect()
389
+ : Promise.resolve().then(() => connectVaultHost(this.#options.pluginId))).then((client) => {
387
390
  // A connect resolves into its generation only while that generation
388
391
  // is current and still wanted; otherwise its client never serves.
389
392
  if (entry.timedOut) {
@@ -567,7 +570,7 @@ export class ClaustrumDiscoveryHub {
567
570
  * runs the inactive transition; nothing else does.
568
571
  */
569
572
  async #readAuthority() {
570
- const active = (await this.#options.isCustodyActive?.()) ?? true;
573
+ const active = hasVaultHost() || ((await this.#options.isCustodyActive?.()) ?? true);
571
574
  if (this.#shutdown.signal.aborted)
572
575
  return false;
573
576
  const was = this.#active;
@@ -4,8 +4,9 @@ export { ClaustrumCredentialError, type ClaustrumReporterSource, type Enrollment
4
4
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, type VaultFailureClass, } from './availability.js';
5
5
  export { ClaustrumConsumer, type ClaustrumConsumerOptions, type ClaustrumWatchState, DEFAULT_CONNECT_TIMEOUT_MS, type SendOptions, } from './consumer.js';
6
6
  export { type AccountIdentitySource, type ClassifyingClaustrumFamily, type ClaustrumFamily, type ClaustrumFamilyInput, type ClaustrumRosterWatch, type ClaustrumRosterWatchOptions, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, type KeptReceiptState, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, type VaultRowFacts, } from './custody.js';
7
- export { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentConnection, type ClaustrumEnrollmentDisconnectResult, ClaustrumEnrollmentManager, type ClaustrumEnrollmentPaths, type ClaustrumEnrollmentResetResult, type ClaustrumEnrollmentStatus, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, type EnrollmentDisposition, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
7
+ export { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentConnection, type ClaustrumEnrollmentDisconnectResult, ClaustrumEnrollmentManager, type ClaustrumEnrollmentPaths, type ClaustrumEnrollmentResetResult, type ClaustrumEnrollmentStatus, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, type EnrollmentDisposition, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, vaultAuthority, } from './enrollment.js';
8
8
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
9
+ export { connectVaultHost, hasVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from './host.js';
9
10
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, type HostSlotContent, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
10
11
  export { ClaustrumDiscoveryHub, type ClaustrumDiscoveryHubOptions, type ClaustrumHubMemberOptions, type ClaustrumHubRefusals, type ClaustrumLeasedCustody, type CustodyLease, } from './hub.js';
11
12
  export { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaLookup, type InsulaQuotaMiss, type InsulaQuotaOptions, type InsulaQuotaReading, type InsulaQuotaResult, type InsulaQuotaSource, type InsulaUsageEntry, type InsulaUsageTransport, type InsulaUsageWatch, type InsulaUsageWindow, type InsulaWatchOptions, } from './insula.js';
@@ -10,8 +10,9 @@ export { ClaustrumCredentialError, } from '@cortexkit/claustrum-client';
10
10
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, } from './availability.js';
11
11
  export { ClaustrumConsumer, DEFAULT_CONNECT_TIMEOUT_MS, } from './consumer.js';
12
12
  export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, SERVING_MARGIN_MS, } from './custody.js';
13
- export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
13
+ export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, vaultAuthority, } from './enrollment.js';
14
14
  export { ClaustrumConsumerError, } from './errors.js';
15
+ export { connectVaultHost, hasVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from './host.js';
15
16
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
16
17
  export { ClaustrumDiscoveryHub, } from './hub.js';
17
18
  export { acquireInsulaQuotaSource, } from './insula.js';
@@ -0,0 +1,51 @@
1
+ export type SessionCacheTtl = 'none' | 'short' | 'long';
2
+ export type SessionKeepWarmMode = 'off' | 'hours' | 'always' | 'auto';
3
+ export interface SessionCacheHours {
4
+ from: string;
5
+ to: string;
6
+ tz: string;
7
+ }
8
+ export interface SessionCachePolicy {
9
+ ttl?: SessionCacheTtl;
10
+ keep_warm?: SessionKeepWarmMode;
11
+ hours?: SessionCacheHours;
12
+ }
13
+ export interface SessionToolWait {
14
+ /** Epoch milliseconds when the oldest running plan tool started. */
15
+ since: number;
16
+ }
17
+ /**
18
+ * The stop reasons the llm-runner contract defines today; any other string is
19
+ * accepted too, for reasons that contract adds later.
20
+ */
21
+ export type CacheWarmStopReason = 'cost-cap' | 'count-cap' | 'outside-hours' | 'session-ended' | 'unsupported' | (string & Record<never, never>);
22
+ export interface CacheTouchInput {
23
+ /** Integer epoch milliseconds when the provider answered. */
24
+ at: number;
25
+ ttlMs: number | 'implicit';
26
+ source: 'response' | 'warm';
27
+ }
28
+ export interface CacheWarmStoppedInput {
29
+ /** Integer epoch milliseconds. */
30
+ at: number;
31
+ reason: CacheWarmStopReason;
32
+ }
33
+ /**
34
+ * Read the session's current plan on every decision; never retain it across
35
+ * requests. Null means the plugin keeps its own settings. No I/O or exceptions.
36
+ */
37
+ export declare function sessionCachePolicy(sessionId: string): SessionCachePolicy | null;
38
+ /** Read the oldest running plan tool afresh, without I/O or exceptions. */
39
+ export declare function sessionToolWait(sessionId: string): SessionToolWait | null;
40
+ /**
41
+ * Call only after the reply has been handed to the host, never on the awaited
42
+ * request path. Synchronous fire-and-forget, with no retries; the bridge owns
43
+ * redelivery of the newest touch. Accessor and report failures are absorbed.
44
+ */
45
+ export declare function reportCacheTouch(sessionId: string, input: CacheTouchInput): void;
46
+ /**
47
+ * Call off the request path, after handing the reply to the host. Report only
48
+ * a session that actually warmed, never one that was off from the start.
49
+ * Synchronous fire-and-forget; failures are absorbed and never retried here.
50
+ */
51
+ export declare function reportCacheWarmStopped(sessionId: string, input: CacheWarmStoppedInput): void;
@@ -0,0 +1,186 @@
1
+ import { routingHandle } from './handle.js';
2
+ const warned = new Set();
3
+ // Inspect descriptors rather than values so warning deduplication cannot invoke
4
+ // a broken bridge's getters a second time. Do not print policy contents.
5
+ function shape(value, seen = new Set()) {
6
+ if (typeof value !== 'object' || value === null) {
7
+ return `${typeof value}:${String(value)}`;
8
+ }
9
+ if (seen.has(value))
10
+ return 'cycle';
11
+ seen.add(value);
12
+ return `${Array.isArray(value) ? 'array' : 'object'}:{${Object.entries(Object.getOwnPropertyDescriptors(value))
13
+ .sort(([a], [b]) => a.localeCompare(b))
14
+ .map(([key, descriptor]) => `${key}:${'value' in descriptor ? shape(descriptor.value, seen) : 'accessor'}`)
15
+ .join(',')}}`;
16
+ }
17
+ function invalid(kind, value) {
18
+ let fingerprint = 'unreadable';
19
+ try {
20
+ fingerprint = shape(value);
21
+ }
22
+ catch {
23
+ // Uninspectable proxies share one diagnostic shape, without invoking getters.
24
+ }
25
+ try {
26
+ const key = `${kind}:${fingerprint}`;
27
+ if (!warned.has(key)) {
28
+ warned.add(key);
29
+ console.warn(`[common-auth] Ignoring invalid session ${kind} policy`);
30
+ }
31
+ }
32
+ catch {
33
+ // A broken warning sink must not break a request either.
34
+ }
35
+ return null;
36
+ }
37
+ function record(value) {
38
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
39
+ }
40
+ function rejectAsync(value) {
41
+ if (typeof value.then !== 'function')
42
+ return false;
43
+ // Absorb a rejected promise from a bridge that broke the synchronous contract.
44
+ void Promise.resolve(value).catch(() => { });
45
+ return true;
46
+ }
47
+ function onlyKeys(value, keys) {
48
+ return Reflect.ownKeys(value).every((key) => typeof key === 'string' && keys.includes(key));
49
+ }
50
+ /**
51
+ * Read the session's current plan on every decision; never retain it across
52
+ * requests. Null means the plugin keeps its own settings. No I/O or exceptions.
53
+ */
54
+ export function sessionCachePolicy(sessionId) {
55
+ let answer;
56
+ try {
57
+ const handle = routingHandle(sessionId);
58
+ if (!handle)
59
+ return null;
60
+ const read = handle.cache;
61
+ if (typeof read !== 'function')
62
+ return null;
63
+ answer = read.call(handle);
64
+ if (answer === null)
65
+ return null;
66
+ if (!record(answer) || rejectAsync(answer))
67
+ return invalid('cache', answer);
68
+ const { ttl, keep_warm, hours } = answer;
69
+ if (!onlyKeys(answer, ['ttl', 'keep_warm', 'hours']) ||
70
+ (ttl !== undefined &&
71
+ ttl !== 'none' &&
72
+ ttl !== 'short' &&
73
+ ttl !== 'long') ||
74
+ (keep_warm !== undefined &&
75
+ keep_warm !== 'off' &&
76
+ keep_warm !== 'hours' &&
77
+ keep_warm !== 'always' &&
78
+ keep_warm !== 'auto') ||
79
+ (ttl === 'none' && keep_warm !== undefined && keep_warm !== 'off') ||
80
+ (keep_warm !== 'hours' && 'hours' in answer)) {
81
+ return invalid('cache', answer);
82
+ }
83
+ const policy = {
84
+ ...(ttl !== undefined ? { ttl } : {}),
85
+ ...(keep_warm !== undefined ? { keep_warm } : {}),
86
+ };
87
+ if (keep_warm === 'hours') {
88
+ if (!record(hours) || !onlyKeys(hours, ['from', 'to', 'tz'])) {
89
+ return invalid('cache', answer);
90
+ }
91
+ const { from, to, tz } = hours;
92
+ const time = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
93
+ if (typeof from !== 'string' ||
94
+ !time.test(from) ||
95
+ typeof to !== 'string' ||
96
+ !time.test(to) ||
97
+ from === to ||
98
+ typeof tz !== 'string' ||
99
+ tz.length === 0) {
100
+ return invalid('cache', answer);
101
+ }
102
+ new Intl.DateTimeFormat('en', { timeZone: tz });
103
+ policy.hours = { from, to, tz };
104
+ }
105
+ return policy;
106
+ }
107
+ catch {
108
+ return invalid('cache', answer);
109
+ }
110
+ }
111
+ /** Read the oldest running plan tool afresh, without I/O or exceptions. */
112
+ export function sessionToolWait(sessionId) {
113
+ let answer;
114
+ try {
115
+ const handle = routingHandle(sessionId);
116
+ if (!handle)
117
+ return null;
118
+ const read = handle.tool_wait;
119
+ if (typeof read !== 'function')
120
+ return null;
121
+ answer = read.call(handle);
122
+ if (answer === null)
123
+ return null;
124
+ if (!record(answer) || rejectAsync(answer))
125
+ return invalid('tool_wait', answer);
126
+ const { since } = answer;
127
+ if (!onlyKeys(answer, ['since']) ||
128
+ typeof since !== 'number' ||
129
+ !Number.isSafeInteger(since) ||
130
+ since < 0) {
131
+ return invalid('tool_wait', answer);
132
+ }
133
+ return { since };
134
+ }
135
+ catch {
136
+ return invalid('tool_wait', answer);
137
+ }
138
+ }
139
+ function report(sessionId, payload) {
140
+ const handle = routingHandle(sessionId);
141
+ if (!handle)
142
+ return;
143
+ const send = handle.report;
144
+ if (typeof send !== 'function')
145
+ return;
146
+ const pending = send.call(handle, payload);
147
+ if (record(pending) && typeof pending.then === 'function') {
148
+ void Promise.resolve(pending).catch(() => { });
149
+ }
150
+ }
151
+ /**
152
+ * Call only after the reply has been handed to the host, never on the awaited
153
+ * request path. Synchronous fire-and-forget, with no retries; the bridge owns
154
+ * redelivery of the newest touch. Accessor and report failures are absorbed.
155
+ */
156
+ export function reportCacheTouch(sessionId, input) {
157
+ try {
158
+ const { at, ttlMs, source } = input;
159
+ if (!Number.isSafeInteger(at) ||
160
+ at < 0 ||
161
+ (ttlMs !== 'implicit' &&
162
+ (typeof ttlMs !== 'number' || !Number.isFinite(ttlMs) || ttlMs < 0)) ||
163
+ (source !== 'response' && source !== 'warm'))
164
+ return;
165
+ report(sessionId, { kind: 'cache_touch', at, ttl_ms: ttlMs, source });
166
+ }
167
+ catch {
168
+ // Optional reporting must never change the result of an auth request.
169
+ }
170
+ }
171
+ /**
172
+ * Call off the request path, after handing the reply to the host. Report only
173
+ * a session that actually warmed, never one that was off from the start.
174
+ * Synchronous fire-and-forget; failures are absorbed and never retried here.
175
+ */
176
+ export function reportCacheWarmStopped(sessionId, input) {
177
+ try {
178
+ const { at, reason } = input;
179
+ if (!Number.isSafeInteger(at) || at < 0 || typeof reason !== 'string')
180
+ return;
181
+ report(sessionId, { kind: 'cache_warm_stopped', at, reason });
182
+ }
183
+ catch {
184
+ // Optional reporting must never change the result of an auth request.
185
+ }
186
+ }
@@ -3,6 +3,8 @@
3
3
  * shaping. Account ids are vault account ids, not local pool rows. Nothing is
4
4
  * persisted here; plugins on routes the runner does not serve get no turn notes.
5
5
  */
6
+ export type { CacheTouchInput, CacheWarmStoppedInput, CacheWarmStopReason, SessionCacheHours, SessionCachePolicy, SessionCacheTtl, SessionKeepWarmMode, SessionToolWait, } from './cache-policy.js';
7
+ export { reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
6
8
  /** An eligible vault route, not a local pool row. */
7
9
  export interface RoutingCandidate {
8
10
  /** Vault account id, not the plugin's route id. */
@@ -94,4 +96,3 @@ export declare function askRouting<Candidate extends RoutingCandidate>(input: As
94
96
  * or redacted here.
95
97
  */
96
98
  export declare function reportRouting(input: ReportRoutingInput): void;
97
- export {};
@@ -4,6 +4,7 @@
4
4
  * persisted here; plugins on routes the runner does not serve get no turn notes.
5
5
  */
6
6
  import { routingHandle } from './handle.js';
7
+ export { reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
7
8
  function isObject(value) {
8
9
  return typeof value === 'object' && value !== null;
9
10
  }
@@ -1,6 +1,7 @@
1
1
  import { select } from '../auth-menu/select.js';
2
2
  import { isInteractive, printLine, processTerminal, } from '../auth-menu/terminal.js';
3
- import { enrollmentAuthority, hostEnrollmentPaths, } from '../claustrum/enrollment.js';
3
+ import { hostEnrollmentPaths, vaultAuthority } from '../claustrum/enrollment.js';
4
+ import { hasVaultHost, VAULT_HOST_CONNECT_REFUSAL } from '../claustrum/host.js';
4
5
  import { recordSetupEnrollment, setupEnrollmentLine } from './command-error.js';
5
6
  import { defaultCommandRunner } from './command-runner.js';
6
7
  import { detectHosts } from './detect.js';
@@ -27,7 +28,7 @@ function validatePlugin(plugin) {
27
28
  * Turn what setup recorded into one outcome per selected host, in setup order.
28
29
  * A host setup never reached was never asked to enroll. Only a host whose
29
30
  * enrollment was in flight when setup failed is checked on disk, by reading its
30
- * enrollment files once with `enrollmentAuthority`; if that read fails it stays
31
+ * authority once with `vaultAuthority`; if that read fails it stays
31
32
  * `unknown`.
32
33
  */
33
34
  async function enrollmentReport(plugin, hosts, recorded) {
@@ -36,8 +37,8 @@ async function enrollmentReport(plugin, hosts, recorded) {
36
37
  let outcome = recorded.get(host) ?? 'not-enrolled';
37
38
  if (outcome === 'unknown') {
38
39
  const { name, paths } = plugin.vault.hosts[host];
39
- const authority = await enrollmentAuthority(hostEnrollmentPaths(paths), name).catch(() => 'unreadable');
40
- if (authority === 'vault')
40
+ const authority = await vaultAuthority(hostEnrollmentPaths(paths), name).catch(() => 'unreadable');
41
+ if (authority === 'vault' || authority === 'host')
41
42
  outcome = 'enrolled';
42
43
  else if (authority === 'local')
43
44
  outcome = 'not-enrolled';
@@ -48,6 +49,9 @@ async function enrollmentReport(plugin, hosts, recorded) {
48
49
  }
49
50
  export async function runSetup(plugin, argv = [], io = {}) {
50
51
  const options = parseSetupFlags(argv);
52
+ // Hosted sign-in belongs to Thalamus, never to a plugin's local setup.
53
+ if (hasVaultHost())
54
+ throw new Error(VAULT_HOST_CONNECT_REFUSAL);
51
55
  validatePlugin(plugin);
52
56
  const terminal = io.terminal ?? processTerminal();
53
57
  const detection = await detectHosts(plugin, io);
@@ -2,6 +2,7 @@ import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { writeEnrollmentTokenFile } from '@cortexkit/claustrum-client';
3
3
  import { printLine } from '../auth-menu/terminal.js';
4
4
  import { ClaustrumEnrollmentManager, connectClaustrumEnrollmentClient, hostEnrollmentPaths, UNSUPPORTED_ENROLLMENT_CODE, } from '../claustrum/enrollment.js';
5
+ import { hasVaultHost, VAULT_HOST_CONNECT_REFUSAL } from '../claustrum/host.js';
5
6
  import { ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
6
7
  const ENROLLMENT_INCOMPLETE_MESSAGE = 'Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.';
7
8
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
@@ -51,6 +52,8 @@ function approveCommand(requestId, name) {
51
52
  }
52
53
  /** Enroll an independently revocable host; plugin callbacks choose its credential store and account permissions. */
53
54
  export async function connectSetupHost(plugin, host, io, terminal, fence) {
55
+ if (hasVaultHost())
56
+ throw new Error(VAULT_HOST_CONNECT_REFUSAL);
54
57
  const { name, paths: input } = plugin.vault.hosts[host];
55
58
  const paths = hostEnrollmentPaths(input);
56
59
  await fence();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.39.2",
3
+ "version": "0.41.0",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {