@cortexkit/opencode-antigravity-auth 3.0.38 → 3.0.40

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 (129) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +865 -357
  3. package/dist/cli.js.map +4 -4
  4. package/dist/cli.meta.json +136 -39
  5. package/dist/index.js +1509 -657
  6. package/dist/index.js.map +4 -4
  7. package/dist/index.meta.json +188 -49
  8. package/dist/server.js +1662 -803
  9. package/dist/server.js.map +4 -4
  10. package/dist/server.meta.json +1 -1
  11. package/dist/src/common-auth-embedded/claustrum/availability.d.ts +7 -1
  12. package/dist/src/common-auth-embedded/claustrum/availability.js +9 -1
  13. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +11 -2
  14. package/dist/src/common-auth-embedded/claustrum/custody.js +89 -31
  15. package/dist/src/common-auth-embedded/claustrum/enrollment.d.ts +29 -4
  16. package/dist/src/common-auth-embedded/claustrum/enrollment.js +110 -2
  17. package/dist/src/common-auth-embedded/claustrum/host.js +11 -7
  18. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  19. package/dist/src/common-auth-embedded/claustrum/index.js +1 -1
  20. package/dist/src/common-auth-embedded/fs/lock-record.js +55 -0
  21. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +148 -92
  22. package/dist/src/common-auth-embedded/fs/with-lock.js +19 -13
  23. package/dist/src/common-auth-embedded/quota-sidebar/index.d.ts +2 -36
  24. package/dist/src/common-auth-embedded/quota-sidebar/index.tsx +49 -607
  25. package/dist/src/common-auth-embedded/routing-accessor/cache-policy.d.ts +3 -0
  26. package/dist/src/common-auth-embedded/routing-accessor/cache-policy.js +11 -0
  27. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +48 -5
  28. package/dist/src/common-auth-embedded/routing-accessor/index.js +136 -5
  29. package/dist/src/common-auth-embedded/setup/command-error.d.ts +1 -1
  30. package/dist/src/common-auth-embedded/setup/command-error.js +3 -2
  31. package/dist/src/common-auth-embedded/setup/command.js +18 -5
  32. package/dist/src/common-auth-embedded/setup/enroll.d.ts +2 -2
  33. package/dist/src/common-auth-embedded/setup/enroll.js +14 -3
  34. package/dist/src/common-auth-embedded/setup/enrollment-access.js +77 -0
  35. package/dist/src/common-auth-embedded/setup/index.d.ts +1 -1
  36. package/dist/src/common-auth-embedded/setup/types.d.ts +13 -1
  37. package/dist/src/common-auth-embedded/source-output.json +95 -79
  38. package/dist/src/ga/tui/host-ga.d.ts +20 -3
  39. package/dist/src/ga/tui/host-ga.d.ts.map +1 -1
  40. package/dist/src/ga/tui/host-ga.js +102 -25
  41. package/dist/src/ga/tui/host-ga.js.map +1 -1
  42. package/dist/src/plugin/__fixtures__/release-model-ids.d.ts.map +1 -1
  43. package/dist/src/plugin/__fixtures__/release-model-ids.js +1 -0
  44. package/dist/src/plugin/__fixtures__/release-model-ids.js.map +1 -1
  45. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  46. package/dist/src/plugin/ga-location-services.d.ts +1 -0
  47. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  48. package/dist/src/plugin/ga-location-services.js +6 -0
  49. package/dist/src/plugin/ga-location-services.js.map +1 -1
  50. package/dist/src/plugin/logger.d.ts +3 -1
  51. package/dist/src/plugin/logger.d.ts.map +1 -1
  52. package/dist/src/plugin/logger.js +15 -7
  53. package/dist/src/plugin/logger.js.map +1 -1
  54. package/dist/src/plugin/request.d.ts.map +1 -1
  55. package/dist/src/plugin/request.js +3 -1
  56. package/dist/src/plugin/request.js.map +1 -1
  57. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  58. package/dist/src/plugin/shared/request-services.js +34 -9
  59. package/dist/src/plugin/shared/request-services.js.map +1 -1
  60. package/dist/src/plugin/shared/vault-billing.d.ts +30 -0
  61. package/dist/src/plugin/shared/vault-billing.d.ts.map +1 -0
  62. package/dist/src/plugin/shared/vault-billing.js +196 -0
  63. package/dist/src/plugin/shared/vault-billing.js.map +1 -0
  64. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  65. package/dist/src/plugin/vault-custody.js +3 -0
  66. package/dist/src/plugin/vault-custody.js.map +1 -1
  67. package/dist/src/setup.d.ts.map +1 -1
  68. package/dist/src/setup.js +14 -0
  69. package/dist/src/setup.js.map +1 -1
  70. package/dist/tui-build-map.json +19 -5
  71. package/dist/tui-ga-build-map.json +23 -9
  72. package/dist/types/src/common-auth-embedded/claustrum/availability.d.ts +7 -1
  73. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +11 -2
  74. package/dist/types/src/common-auth-embedded/claustrum/enrollment.d.ts +29 -4
  75. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  76. package/dist/types/src/common-auth-embedded/routing-accessor/cache-policy.d.ts +3 -0
  77. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +48 -5
  78. package/dist/types/src/common-auth-embedded/setup/command-error.d.ts +1 -1
  79. package/dist/types/src/common-auth-embedded/setup/enroll.d.ts +2 -2
  80. package/dist/types/src/common-auth-embedded/setup/index.d.ts +1 -1
  81. package/dist/types/src/common-auth-embedded/setup/types.d.ts +13 -1
  82. package/dist/types/src/plugin/ga-location-services.d.ts +1 -0
  83. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  84. package/dist/types/src/plugin/logger.d.ts +3 -1
  85. package/dist/types/src/plugin/logger.d.ts.map +1 -1
  86. package/dist/types/src/plugin/request.d.ts.map +1 -1
  87. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  88. package/dist/types/src/plugin/shared/vault-billing.d.ts +30 -0
  89. package/dist/types/src/plugin/shared/vault-billing.d.ts.map +1 -0
  90. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  91. package/dist/types/src/setup.d.ts.map +1 -1
  92. package/package.json +4 -3
  93. package/src/common-auth-embedded/claustrum/availability.d.ts +7 -1
  94. package/src/common-auth-embedded/claustrum/availability.js +9 -1
  95. package/src/common-auth-embedded/claustrum/custody.d.ts +11 -2
  96. package/src/common-auth-embedded/claustrum/custody.js +89 -31
  97. package/src/common-auth-embedded/claustrum/enrollment.d.ts +29 -4
  98. package/src/common-auth-embedded/claustrum/enrollment.js +110 -2
  99. package/src/common-auth-embedded/claustrum/host.js +11 -7
  100. package/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  101. package/src/common-auth-embedded/claustrum/index.js +1 -1
  102. package/src/common-auth-embedded/fs/lock-record.js +55 -0
  103. package/src/common-auth-embedded/fs/refresh-file-lock.js +148 -92
  104. package/src/common-auth-embedded/fs/with-lock.js +19 -13
  105. package/src/common-auth-embedded/quota-sidebar/index.d.ts +2 -36
  106. package/src/common-auth-embedded/quota-sidebar/index.tsx +49 -607
  107. package/src/common-auth-embedded/routing-accessor/cache-policy.d.ts +3 -0
  108. package/src/common-auth-embedded/routing-accessor/cache-policy.js +11 -0
  109. package/src/common-auth-embedded/routing-accessor/index.d.ts +48 -5
  110. package/src/common-auth-embedded/routing-accessor/index.js +136 -5
  111. package/src/common-auth-embedded/setup/command-error.d.ts +1 -1
  112. package/src/common-auth-embedded/setup/command-error.js +3 -2
  113. package/src/common-auth-embedded/setup/command.js +18 -5
  114. package/src/common-auth-embedded/setup/enroll.d.ts +2 -2
  115. package/src/common-auth-embedded/setup/enroll.js +14 -3
  116. package/src/common-auth-embedded/setup/enrollment-access.js +77 -0
  117. package/src/common-auth-embedded/setup/index.d.ts +1 -1
  118. package/src/common-auth-embedded/setup/types.d.ts +13 -1
  119. package/src/common-auth-embedded/source-output.json +95 -79
  120. package/src/tui-compiled/common-auth-embedded/quota-sidebar/index.js +36 -674
  121. package/src/tui-compiled/shared/a75d0d866c227b3f-index.js +678 -0
  122. package/src/tui-ga-compiled/host-ga.js +86 -26
  123. package/src/tui-ga-compiled/shared/a75d0d866c227b3f-index.js +678 -0
  124. package/src/tui-ga-compiled/shared/e4ec36f367492969-index.js +36 -674
  125. package/src/tui-ga-raw/host-ga.tsx +122 -25
  126. package/src/tui-ga-raw/shared/a75d0d866c227b3f-index.tsx +681 -0
  127. package/src/tui-ga-raw/shared/e4ec36f367492969-index.tsx +49 -607
  128. package/src/tui-raw/common-auth-embedded/quota-sidebar/index.tsx +49 -607
  129. package/src/tui-raw/shared/a75d0d866c227b3f-index.tsx +681 -0
@@ -3,8 +3,9 @@
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
+ import { type CacheWarmStopReason } from './cache-policy.js';
6
7
  export type { CacheTouchInput, CacheWarmStoppedInput, CacheWarmStopReason, SessionCacheHours, SessionCachePolicy, SessionCacheTtl, SessionKeepWarmMode, SessionToolWait, } from './cache-policy.js';
7
- export { reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
8
+ export { CACHE_WARM_STOP_REASONS, isCacheWarmStopReason, reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
8
9
  /** An eligible vault route, not a local pool row. */
9
10
  export interface RoutingCandidate {
10
11
  /** Vault account id, not the plugin's route id. */
@@ -42,6 +43,19 @@ interface RoutingReportIdentity {
42
43
  accountId: string;
43
44
  credentialId?: string;
44
45
  }
46
+ export type BillingRequestKind = 'primary' | 'title' | 'compaction' | 'generate' | 'keep_warm' | 'prime';
47
+ export type BillingOutcome = 'completed' | 'cut' | 'failed';
48
+ /** Omit unread counts; zero represents a measured count, not a default. */
49
+ export interface BillingUsage {
50
+ input?: number;
51
+ output?: number;
52
+ cacheRead?: number;
53
+ cacheWrite?: number;
54
+ cacheWrite5m?: number;
55
+ cacheWrite1h?: number;
56
+ reasoning?: number;
57
+ reasoningIncludedInOutput?: boolean;
58
+ }
45
59
  export type ReportRoutingInput = (RoutingReportIdentity & ({
46
60
  outcome: 'served';
47
61
  /**
@@ -73,6 +87,35 @@ export type ReportRoutingInput = (RoutingReportIdentity & ({
73
87
  kind: 'turn_note_skipped';
74
88
  after_tool_use_id: string;
75
89
  reason: 'anchor_missing' | 'before_user_message' | 'unsupported_model' | 'not_oauth';
90
+ } | {
91
+ sessionId: string;
92
+ kind: 'billing';
93
+ attemptId: string;
94
+ requestKind: BillingRequestKind;
95
+ credentialId: string;
96
+ accountId?: string;
97
+ provider: string;
98
+ model: string;
99
+ outcome: BillingOutcome;
100
+ providerRequestId?: string;
101
+ providerResponseId?: string;
102
+ userMessageId?: string;
103
+ status?: number;
104
+ attempt?: number;
105
+ chargeBasis?: 'subscription_included' | 'metered_api';
106
+ usage?: BillingUsage;
107
+ usageByModel?: readonly {
108
+ modelUsed: string;
109
+ usage: BillingUsage;
110
+ }[];
111
+ cache?: {
112
+ ttlMs?: number;
113
+ implicit?: true;
114
+ warming?: {
115
+ on: boolean;
116
+ stopReason?: CacheWarmStopReason;
117
+ };
118
+ };
76
119
  };
77
120
  /**
78
121
  * Read advisory input for request shaping, in landing order, without persisting
@@ -90,9 +133,9 @@ export declare function turnNotes(sessionId: string): readonly {
90
133
  */
91
134
  export declare function askRouting<Candidate extends RoutingCandidate>(input: AskRoutingInput<Candidate>): Promise<RoutingSelection<Candidate> | undefined>;
92
135
  /**
93
- * Report a vault request or turn-note event without waiting for routing. Only
94
- * contract fields are sent, and all accessor failures are ignored. Headers must
95
- * already be limited to rate-limit headers by the caller; values are not filtered
96
- * or redacted here.
136
+ * Report a vault request, billing result or turn-note event without waiting for
137
+ * routing. Only contract fields are sent, and all accessor failures are ignored.
138
+ * Headers must already be limited to rate-limit headers by the caller; values
139
+ * are not filtered or redacted here.
97
140
  */
98
141
  export declare function reportRouting(input: ReportRoutingInput): void;
@@ -3,11 +3,68 @@
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
+ import { isCacheWarmStopReason, } from './cache-policy.js';
6
7
  import { routingHandle } from './handle.js';
7
- export { reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
8
+ export { CACHE_WARM_STOP_REASONS, isCacheWarmStopReason, reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
8
9
  function isObject(value) {
9
10
  return typeof value === 'object' && value !== null;
10
11
  }
12
+ function isNonEmptyString(value) {
13
+ return typeof value === 'string' && value.length > 0;
14
+ }
15
+ function billingCache(value) {
16
+ if (!isObject(value) || Array.isArray(value))
17
+ return;
18
+ const { ttlMs, implicit, warming } = value;
19
+ const cache = {};
20
+ // Conflicting lifetime claims cannot prove what the request cached.
21
+ if (!(ttlMs !== undefined && implicit !== undefined)) {
22
+ if (typeof ttlMs === 'number' && Number.isSafeInteger(ttlMs) && ttlMs > 0) {
23
+ cache.ttl_ms = ttlMs;
24
+ }
25
+ else if (implicit === true) {
26
+ cache.implicit = true;
27
+ }
28
+ }
29
+ if (isObject(warming) && !Array.isArray(warming)) {
30
+ const { on, stopReason } = warming;
31
+ if (typeof on === 'boolean') {
32
+ cache.warming = {
33
+ on,
34
+ ...(!on && isCacheWarmStopReason(stopReason)
35
+ ? { stop_reason: stopReason }
36
+ : {}),
37
+ };
38
+ }
39
+ }
40
+ return Object.keys(cache).length > 0 ? cache : undefined;
41
+ }
42
+ function billingUsage(value) {
43
+ if (!isObject(value) || Array.isArray(value))
44
+ return;
45
+ const usage = {};
46
+ for (const [inputKey, payloadKey] of [
47
+ ['input', 'input'],
48
+ ['output', 'output'],
49
+ ['cacheRead', 'cache_read'],
50
+ ['cacheWrite', 'cache_write'],
51
+ ['cacheWrite5m', 'cache_write_5m'],
52
+ ['cacheWrite1h', 'cache_write_1h'],
53
+ ['reasoning', 'reasoning'],
54
+ ]) {
55
+ const count = value[inputKey];
56
+ if (typeof count === 'number' &&
57
+ Number.isSafeInteger(count) &&
58
+ count >= 0) {
59
+ usage[payloadKey] = count;
60
+ }
61
+ }
62
+ const reasoningIncludedInOutput = value.reasoningIncludedInOutput;
63
+ if (typeof reasoningIncludedInOutput === 'boolean') {
64
+ usage.reasoning_included_in_output = reasoningIncludedInOutput;
65
+ }
66
+ return Object.keys(usage).length > 0 ? usage : undefined;
67
+ }
11
68
  /**
12
69
  * Read advisory input for request shaping, in landing order, without persisting
13
70
  * it. If no routing handle is available or the runner does not serve the route,
@@ -124,10 +181,10 @@ export async function askRouting(input) {
124
181
  }
125
182
  }
126
183
  /**
127
- * Report a vault request or turn-note event without waiting for routing. Only
128
- * contract fields are sent, and all accessor failures are ignored. Headers must
129
- * already be limited to rate-limit headers by the caller; values are not filtered
130
- * or redacted here.
184
+ * Report a vault request, billing result or turn-note event without waiting for
185
+ * routing. Only contract fields are sent, and all accessor failures are ignored.
186
+ * Headers must already be limited to rate-limit headers by the caller; values
187
+ * are not filtered or redacted here.
131
188
  */
132
189
  export function reportRouting(input) {
133
190
  try {
@@ -140,6 +197,80 @@ export function reportRouting(input) {
140
197
  let payload;
141
198
  if ('kind' in input) {
142
199
  switch (input.kind) {
200
+ case 'billing': {
201
+ const { attemptId, requestKind, credentialId, provider, model, outcome, accountId, providerRequestId, providerResponseId, userMessageId, status, attempt, chargeBasis, usage: inputUsage, usageByModel: inputUsageByModel, cache: inputCache, } = input;
202
+ if (!isNonEmptyString(attemptId) ||
203
+ !isNonEmptyString(credentialId) ||
204
+ !isNonEmptyString(provider) ||
205
+ !isNonEmptyString(model) ||
206
+ (requestKind !== 'primary' &&
207
+ requestKind !== 'title' &&
208
+ requestKind !== 'compaction' &&
209
+ requestKind !== 'generate' &&
210
+ requestKind !== 'keep_warm' &&
211
+ requestKind !== 'prime') ||
212
+ (outcome !== 'completed' &&
213
+ outcome !== 'cut' &&
214
+ outcome !== 'failed'))
215
+ return;
216
+ const usage = billingUsage(inputUsage);
217
+ const cache = billingCache(inputCache);
218
+ const usageByModel = [];
219
+ if (Array.isArray(inputUsageByModel)) {
220
+ for (const entry of inputUsageByModel) {
221
+ if (!isObject(entry) || Array.isArray(entry))
222
+ continue;
223
+ const modelUsed = entry.modelUsed;
224
+ if (!isNonEmptyString(modelUsed))
225
+ continue;
226
+ const modelUsage = billingUsage(entry.usage);
227
+ // Thalamus rejects the whole report when an entry has no usage
228
+ // object, so an entry without a valid reading is dropped.
229
+ if (!modelUsage)
230
+ continue;
231
+ usageByModel.push({ model_used: modelUsed, usage: modelUsage });
232
+ }
233
+ }
234
+ payload = {
235
+ kind: 'billing',
236
+ attempt_id: attemptId,
237
+ request_kind: requestKind,
238
+ credential_id: credentialId,
239
+ provider,
240
+ model,
241
+ outcome,
242
+ ...(isNonEmptyString(accountId) ? { account_id: accountId } : {}),
243
+ ...(isNonEmptyString(providerRequestId)
244
+ ? { provider_request_id: providerRequestId }
245
+ : {}),
246
+ ...(isNonEmptyString(providerResponseId)
247
+ ? { provider_response_id: providerResponseId }
248
+ : {}),
249
+ ...(isNonEmptyString(userMessageId)
250
+ ? { user_message_id: userMessageId }
251
+ : {}),
252
+ ...(typeof status === 'number' &&
253
+ Number.isInteger(status) &&
254
+ status >= 0
255
+ ? { status }
256
+ : {}),
257
+ ...(typeof attempt === 'number' &&
258
+ Number.isInteger(attempt) &&
259
+ attempt >= 1
260
+ ? { attempt }
261
+ : {}),
262
+ ...(chargeBasis === 'subscription_included' ||
263
+ chargeBasis === 'metered_api'
264
+ ? { charge_basis: chargeBasis }
265
+ : {}),
266
+ ...(usage ? { usage } : {}),
267
+ ...(usageByModel.length > 0
268
+ ? { usage_by_model: usageByModel }
269
+ : {}),
270
+ ...(cache ? { cache } : {}),
271
+ };
272
+ break;
273
+ }
143
274
  case 'turn_notes_supported': {
144
275
  const { model, supported } = input;
145
276
  if (typeof model !== 'string' ||
@@ -17,7 +17,7 @@ export declare class SetupCommandError extends Error {
17
17
  });
18
18
  }
19
19
  /** The line setup prints for one host's outcome, e.g. `Pi: not connected`. */
20
- export declare function setupEnrollmentLine({ host, outcome, }: SetupHostEnrollment): string;
20
+ export declare function setupEnrollmentLine({ host, outcome, access, }: SetupHostEnrollment): string;
21
21
  /**
22
22
  * Remember which hosts a failed setup left connected to the vault, against the
23
23
  * thrown value. Only objects can carry a record; a thrown primitive is left as
@@ -1,5 +1,6 @@
1
1
  import { redact } from '../logger/redact.js';
2
2
  import { STDERR_TAIL_MAX_BYTES } from './command-runner.js';
3
+ import { enrollmentAccessLines } from './enrollment-access.js';
3
4
  const PI_INSTALL_ERROR_MESSAGE = 'Pi install failed; run pi install after checking your npm connection.';
4
5
  function utf8Tail(value) {
5
6
  const bytes = Buffer.from(value, 'utf8');
@@ -47,8 +48,8 @@ const OUTCOME_TEXT = {
47
48
  unknown: 'unknown, check with ck auth status',
48
49
  };
49
50
  /** The line setup prints for one host's outcome, e.g. `Pi: not connected`. */
50
- export function setupEnrollmentLine({ host, outcome, }) {
51
- return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}`;
51
+ export function setupEnrollmentLine({ host, outcome, access, }) {
52
+ return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}${access ? ` — ${enrollmentAccessLines(access).join('\n')}` : ''}`;
52
53
  }
53
54
  // Outcomes recorded against the value a failed `runSetup` threw. A WeakMap
54
55
  // keeps the thrown value itself untouched: setup never reads, rewrites or
@@ -1,11 +1,12 @@
1
1
  import { select } from '../auth-menu/select.js';
2
2
  import { isInteractive, printLine, processTerminal, } from '../auth-menu/terminal.js';
3
- import { hostEnrollmentPaths, vaultAuthority } from '../claustrum/enrollment.js';
3
+ import { hostEnrollmentPaths, readClaustrumEnrollmentStatus, validEnrollmentRequestedGrants, vaultAuthority, } from '../claustrum/enrollment.js';
4
4
  import { hasVaultHost, VAULT_HOST_CONNECT_REFUSAL } from '../claustrum/host.js';
5
5
  import { recordSetupEnrollment, setupEnrollmentLine } from './command-error.js';
6
6
  import { defaultCommandRunner } from './command-runner.js';
7
7
  import { detectHosts } from './detect.js';
8
8
  import { connectSetupHost, HostNotEnrolledError } from './enroll.js';
9
+ import { confirmEnrollmentAccess } from './enrollment-access.js';
9
10
  import { parseSetupFlags, UNAVAILABLE_HOST_MESSAGE } from './flags.js';
10
11
  import { setupPaths } from './paths.js';
11
12
  import { assertHostsStopped, createProcessFence, ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
@@ -22,6 +23,9 @@ function validatePlugin(plugin) {
22
23
  for (const host of Object.values(plugin.vault.hosts)) {
23
24
  if (!/^[a-z0-9][a-z0-9-]*$/.test(host.name))
24
25
  throw new Error('Setup requires lowercase vault names containing only letters, digits and dashes.');
26
+ if (host.requestedGrants !== undefined &&
27
+ !validEnrollmentRequestedGrants(host.requestedGrants))
28
+ throw new Error('invalid Claustrum enrollment requested grants');
25
29
  }
26
30
  }
27
31
  /**
@@ -31,10 +35,11 @@ function validatePlugin(plugin) {
31
35
  * authority once with `vaultAuthority`; if that read fails it stays
32
36
  * `unknown`.
33
37
  */
34
- async function enrollmentReport(plugin, hosts, recorded) {
38
+ async function enrollmentReport(plugin, hosts, recorded, recordedAccess) {
35
39
  const report = [];
36
40
  for (const host of hosts) {
37
41
  let outcome = recorded.get(host) ?? 'not-enrolled';
42
+ let access = recordedAccess.get(host);
38
43
  if (outcome === 'unknown') {
39
44
  const { name, paths } = plugin.vault.hosts[host];
40
45
  const authority = await vaultAuthority(hostEnrollmentPaths(paths), name).catch(() => 'unreadable');
@@ -42,8 +47,13 @@ async function enrollmentReport(plugin, hosts, recorded) {
42
47
  outcome = 'enrolled';
43
48
  else if (authority === 'local')
44
49
  outcome = 'not-enrolled';
50
+ if (outcome === 'enrolled') {
51
+ const status = await readClaustrumEnrollmentStatus(hostEnrollmentPaths(paths), name).catch(() => undefined);
52
+ if (status?.state === 'approved')
53
+ access = await confirmEnrollmentAccess({}, status, hostEnrollmentPaths(paths).tokenPath, plugin.vault.hosts[host].requestedGrants);
54
+ }
45
55
  }
46
- report.push({ host, outcome });
56
+ report.push({ host, outcome, ...(access && { access }) });
47
57
  }
48
58
  return report;
49
59
  }
@@ -207,6 +217,7 @@ export async function runSetup(plugin, argv = [], io = {}) {
207
217
  // Each host's vault enrollment as it happens. A host the operator approved
208
218
  // stays enrolled if a later step fails, so a failure reports this record.
209
219
  const enrollment = new Map();
220
+ const enrollmentAccess = new Map();
210
221
  try {
211
222
  for (const host of hosts) {
212
223
  await stopped();
@@ -215,7 +226,9 @@ export async function runSetup(plugin, argv = [], io = {}) {
215
226
  if (useVault) {
216
227
  enrollment.set(host, 'unknown');
217
228
  try {
218
- await connectSetupHost(plugin, host, io, terminal, stopped);
229
+ const access = await connectSetupHost(plugin, host, io, terminal, stopped);
230
+ if (access)
231
+ enrollmentAccess.set(host, access);
219
232
  }
220
233
  catch (error) {
221
234
  if (error instanceof HostNotEnrolledError)
@@ -248,7 +261,7 @@ export async function runSetup(plugin, argv = [], io = {}) {
248
261
  // then rethrow the original value untouched. Reporting must never
249
262
  // replace the failure, so its own errors are ignored.
250
263
  try {
251
- const report = await enrollmentReport(plugin, hosts, enrollment);
264
+ const report = await enrollmentReport(plugin, hosts, enrollment, enrollmentAccess);
252
265
  recordSetupEnrollment(error, report);
253
266
  for (const entry of report)
254
267
  printLine(terminal, setupEnrollmentLine(entry));
@@ -1,5 +1,5 @@
1
1
  import { type MenuTerminal } from '../auth-menu/terminal.js';
2
- import type { SetupHost, SetupIO, SetupPlugin } from './types.js';
2
+ import type { SetupEnrollmentAccess, SetupHost, SetupIO, SetupPlugin } from './types.js';
3
3
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
4
4
  export declare const UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read \"Upgrading from v0.1.3\" in its release notes first), or run setup without --claustrum to use local accounts.";
5
5
  /**
@@ -31,4 +31,4 @@ export declare class HostNotEnrolledError extends Error {
31
31
  });
32
32
  }
33
33
  /** Enroll an independently revocable host; plugin callbacks choose its credential store and account permissions. */
34
- export declare function connectSetupHost(plugin: SetupPlugin, host: SetupHost, io: SetupIO, terminal: MenuTerminal, fence: () => Promise<void>): Promise<void>;
34
+ export declare function connectSetupHost(plugin: SetupPlugin, host: SetupHost, io: SetupIO, terminal: MenuTerminal, fence: () => Promise<void>): Promise<SetupEnrollmentAccess | undefined>;
@@ -3,6 +3,7 @@ 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
5
  import { hasVaultHost, VAULT_HOST_CONNECT_REFUSAL } from '../claustrum/host.js';
6
+ import { confirmEnrollmentAccess, enrollmentAccessLines, } from './enrollment-access.js';
6
7
  import { ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
7
8
  const ENROLLMENT_INCOMPLETE_MESSAGE = 'Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.';
8
9
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
@@ -54,7 +55,7 @@ function approveCommand(requestId, name) {
54
55
  export async function connectSetupHost(plugin, host, io, terminal, fence) {
55
56
  if (hasVaultHost())
56
57
  throw new Error(VAULT_HOST_CONNECT_REFUSAL);
57
- const { name, paths: input } = plugin.vault.hosts[host];
58
+ const { name, displayName, requestedGrants, paths: input, } = plugin.vault.hosts[host];
58
59
  const paths = hostEnrollmentPaths(input);
59
60
  await fence();
60
61
  const client = await (io.connect ?? connectClaustrumEnrollmentClient)({
@@ -68,6 +69,8 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
68
69
  try {
69
70
  const manager = new ClaustrumEnrollmentManager({
70
71
  proposedName: name,
72
+ displayName,
73
+ requestedGrants,
71
74
  paths,
72
75
  // Each tick of the wait below checks the fence once, just before
73
76
  // reconcile proposes or polls. Checking again inside every vault call
@@ -84,7 +87,11 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
84
87
  const initial = await manager.status();
85
88
  if (initial.state === 'approved') {
86
89
  printLine(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
87
- return;
90
+ const access = await confirmEnrollmentAccess(client, initial, paths.tokenPath, requestedGrants);
91
+ if (access)
92
+ for (const line of enrollmentAccessLines(access))
93
+ printLine(terminal, line);
94
+ return access;
88
95
  }
89
96
  printLine(terminal, `Asking the vault to connect ${name}…`);
90
97
  const deadline = now() + ENROLLMENT_WAIT_MS;
@@ -96,7 +103,11 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
96
103
  const status = await manager.reconcile();
97
104
  if (status.state === 'approved') {
98
105
  printLine(terminal, `Connected ${host} to Claustrum.`);
99
- return;
106
+ const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
107
+ if (access)
108
+ for (const line of enrollmentAccessLines(access))
109
+ printLine(terminal, line);
110
+ return access;
100
111
  }
101
112
  if (status.state === 'unavailable' &&
102
113
  status.code === UNSUPPORTED_ENROLLMENT_CODE)
@@ -0,0 +1,77 @@
1
+ import { readClaustrumEnrollmentToken } from '../claustrum/enrollment.js';
2
+ function shellArgument(value) {
3
+ if (/^[a-zA-Z0-9_:@./-]+$/.test(value))
4
+ return value;
5
+ return process.platform === 'win32'
6
+ ? `'${value.replaceAll("'", "''")}'`
7
+ : `'${value.replaceAll("'", "'\\''")}'`;
8
+ }
9
+ /** Check access on the enrollment connection, after the token has reached disk. */
10
+ export async function confirmEnrollmentAccess(client, status, tokenPath, configuredGrants) {
11
+ const requestedGrants = status.requestedGrants ?? configuredGrants;
12
+ if (!requestedGrants)
13
+ return undefined;
14
+ const grants = requestedGrants.map((grant) => ({
15
+ grant,
16
+ ...(status.approvedName !== undefined && {
17
+ grantCommand: `ck auth grant --principal ${shellArgument(`enrolled:${status.approvedName}`)} --selector-kind ${grant.selector.exact === undefined ? 'category' : 'exact'} --selector ${shellArgument(grant.selector.exact ?? grant.selector.category)} --operation ${grant.operation}`,
18
+ }),
19
+ }));
20
+ if (status.requestedGrantsStatus === 'dropped')
21
+ return { state: 'older-vault', grants };
22
+ try {
23
+ if (!client.listScoped)
24
+ return { state: 'unconfirmed', grants };
25
+ const { token } = await readClaustrumEnrollmentToken(tokenPath);
26
+ const inventory = await client.listScoped(token);
27
+ const confirmed = grants.map((entry) => ({
28
+ ...entry,
29
+ reachableLogins: inventory.rows.filter((row) => row.operations.includes(entry.grant.operation) &&
30
+ (entry.grant.selector.exact !== undefined
31
+ ? row.id === entry.grant.selector.exact
32
+ : row.categories.includes(entry.grant.selector.category))).length,
33
+ }));
34
+ return {
35
+ state: confirmed.every((entry) => entry.reachableLogins > 0)
36
+ ? 'reachable'
37
+ : confirmed.some((entry) => entry.reachableLogins > 0)
38
+ ? 'partial'
39
+ : 'no-logins',
40
+ grants: confirmed.map((entry) => {
41
+ if (entry.reachableLogins === 0)
42
+ return entry;
43
+ const { grantCommand: _, ...reachable } = entry;
44
+ return reachable;
45
+ }),
46
+ };
47
+ }
48
+ catch {
49
+ // A listing failure cannot undo approval, and its error may contain secrets.
50
+ return { state: 'unconfirmed', grants };
51
+ }
52
+ }
53
+ export function enrollmentAccessLines(access) {
54
+ const lines = [];
55
+ const remedy = access.grants.some((entry) => entry.grantCommand)
56
+ ? 'run:'
57
+ : 'check ck auth status for the approved name before granting access.';
58
+ if (access.state === 'older-vault')
59
+ lines.push(`Approved. This vault is too old to grant access with the approval; ${remedy}`);
60
+ else if (access.state === 'no-logins')
61
+ lines.push(`Approved, but no logins are reachable yet; ${remedy}`);
62
+ else if (access.state === 'partial')
63
+ lines.push(`Approved, but some requested access has no reachable logins yet; ${remedy}`);
64
+ else if (access.state === 'unconfirmed')
65
+ lines.push(`Approved, but access could not be confirmed; ${access.grants.some((entry) => entry.grantCommand) ? 'check ck auth status or run:' : remedy}`);
66
+ for (const { grant, reachableLogins, grantCommand } of access.grants) {
67
+ if (reachableLogins !== undefined && reachableLogins > 0) {
68
+ const target = grant.selector.exact === undefined
69
+ ? `the vault's ${JSON.stringify(grant.selector.category)} accounts`
70
+ : `credential ${JSON.stringify(grant.selector.exact)}`;
71
+ lines.push(`Confirmed ${grant.operation} access to ${target} (${reachableLogins} reachable ${reachableLogins === 1 ? 'login' : 'logins'}).`);
72
+ }
73
+ if (grantCommand)
74
+ lines.push(` ${grantCommand}`);
75
+ }
76
+ return lines;
77
+ }
@@ -5,4 +5,4 @@ export { ENROLLMENT_WAIT_MS, HostNotEnrolledError, type HostNotEnrolledReason, U
5
5
  export { setupUsage } from './flags.js';
6
6
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, type ProcessInspectionStep, } from './process-fence.js';
7
7
  export { type PlannedWrite, planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
8
- export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnrollmentOutcome, SetupEnvironment, SetupFileSystem, SetupHost, SetupHostEnrollment, SetupIO, SetupPlugin, SetupResult, } from './types.js';
8
+ export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnrollmentAccess, SetupEnrollmentOutcome, SetupEnvironment, SetupFileSystem, SetupHost, SetupHostEnrollment, SetupIO, SetupPlugin, SetupResult, } from './types.js';
@@ -1,5 +1,5 @@
1
1
  import type { MenuTerminal } from '../auth-menu/terminal.js';
2
- import type { ClaustrumEnrollmentConnection, hostEnrollmentPaths } from '../claustrum/index.js';
2
+ import type { ClaustrumEnrollmentConnection, ClaustrumRequestedGrant, hostEnrollmentPaths } from '../claustrum/index.js';
3
3
  export type SetupHost = 'opencode' | 'pi';
4
4
  export type OpenCodeGeneration = '1' | '2' | 'both';
5
5
  export type SetupEnvironment = Record<string, string | undefined>;
@@ -11,9 +11,19 @@ export type SetupEnvironment = Record<string, string | undefined>;
11
11
  * flight and the host's token file could not settle it.
12
12
  */
13
13
  export type SetupEnrollmentOutcome = 'enrolled' | 'not-enrolled' | 'unknown';
14
+ export interface SetupEnrollmentAccess {
15
+ state: 'reachable' | 'no-logins' | 'partial' | 'older-vault' | 'unconfirmed';
16
+ /** One result per requested grant, in proposal order. No count means unknown. */
17
+ grants: readonly {
18
+ grant: ClaustrumRequestedGrant;
19
+ reachableLogins?: number;
20
+ grantCommand?: string;
21
+ }[];
22
+ }
14
23
  export interface SetupHostEnrollment {
15
24
  host: SetupHost;
16
25
  outcome: SetupEnrollmentOutcome;
26
+ access?: SetupEnrollmentAccess;
17
27
  }
18
28
  /**
19
29
  * What setup decided before calling a plugin callback. The OpenCode generation
@@ -50,6 +60,8 @@ export interface SetupPlugin {
50
60
  connectionFile: string;
51
61
  hosts: Record<SetupHost, {
52
62
  name: string;
63
+ displayName?: string;
64
+ requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
53
65
  paths: Parameters<typeof hostEnrollmentPaths>[0];
54
66
  }>;
55
67
  };