@cortexkit/opencode-antigravity-auth 3.0.39 → 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 (69) hide show
  1. package/dist/cli.js +266 -40
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +48 -19
  4. package/dist/index.js +708 -279
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +85 -22
  7. package/dist/server.js +840 -411
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/claustrum/enrollment.d.ts +25 -4
  11. package/dist/src/common-auth-embedded/claustrum/enrollment.js +81 -4
  12. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  13. package/dist/src/common-auth-embedded/claustrum/index.js +1 -1
  14. package/dist/src/common-auth-embedded/setup/command-error.d.ts +1 -1
  15. package/dist/src/common-auth-embedded/setup/command-error.js +3 -2
  16. package/dist/src/common-auth-embedded/setup/command.js +18 -5
  17. package/dist/src/common-auth-embedded/setup/enroll.d.ts +2 -2
  18. package/dist/src/common-auth-embedded/setup/enroll.js +13 -3
  19. package/dist/src/common-auth-embedded/setup/enrollment-access.js +77 -0
  20. package/dist/src/common-auth-embedded/setup/index.d.ts +1 -1
  21. package/dist/src/common-auth-embedded/setup/types.d.ts +12 -1
  22. package/dist/src/common-auth-embedded/source-output.json +48 -40
  23. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  24. package/dist/src/plugin/logger.d.ts +3 -1
  25. package/dist/src/plugin/logger.d.ts.map +1 -1
  26. package/dist/src/plugin/logger.js +15 -7
  27. package/dist/src/plugin/logger.js.map +1 -1
  28. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  29. package/dist/src/plugin/shared/request-services.js +34 -9
  30. package/dist/src/plugin/shared/request-services.js.map +1 -1
  31. package/dist/src/plugin/shared/vault-billing.d.ts +30 -0
  32. package/dist/src/plugin/shared/vault-billing.d.ts.map +1 -0
  33. package/dist/src/plugin/shared/vault-billing.js +196 -0
  34. package/dist/src/plugin/shared/vault-billing.js.map +1 -0
  35. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  36. package/dist/src/plugin/vault-custody.js +3 -0
  37. package/dist/src/plugin/vault-custody.js.map +1 -1
  38. package/dist/src/setup.d.ts.map +1 -1
  39. package/dist/src/setup.js +12 -0
  40. package/dist/src/setup.js.map +1 -1
  41. package/dist/tui-build-map.json +1 -1
  42. package/dist/tui-ga-build-map.json +1 -1
  43. package/dist/types/src/common-auth-embedded/claustrum/enrollment.d.ts +25 -4
  44. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  45. package/dist/types/src/common-auth-embedded/setup/command-error.d.ts +1 -1
  46. package/dist/types/src/common-auth-embedded/setup/enroll.d.ts +2 -2
  47. package/dist/types/src/common-auth-embedded/setup/index.d.ts +1 -1
  48. package/dist/types/src/common-auth-embedded/setup/types.d.ts +12 -1
  49. package/dist/types/src/plugin/logger.d.ts +3 -1
  50. package/dist/types/src/plugin/logger.d.ts.map +1 -1
  51. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  52. package/dist/types/src/plugin/shared/vault-billing.d.ts +30 -0
  53. package/dist/types/src/plugin/shared/vault-billing.d.ts.map +1 -0
  54. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  55. package/dist/types/src/setup.d.ts.map +1 -1
  56. package/package.json +3 -3
  57. package/src/common-auth-embedded/claustrum/enrollment.d.ts +25 -4
  58. package/src/common-auth-embedded/claustrum/enrollment.js +81 -4
  59. package/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  60. package/src/common-auth-embedded/claustrum/index.js +1 -1
  61. package/src/common-auth-embedded/setup/command-error.d.ts +1 -1
  62. package/src/common-auth-embedded/setup/command-error.js +3 -2
  63. package/src/common-auth-embedded/setup/command.js +18 -5
  64. package/src/common-auth-embedded/setup/enroll.d.ts +2 -2
  65. package/src/common-auth-embedded/setup/enroll.js +13 -3
  66. package/src/common-auth-embedded/setup/enrollment-access.js +77 -0
  67. package/src/common-auth-embedded/setup/index.d.ts +1 -1
  68. package/src/common-auth-embedded/setup/types.d.ts +12 -1
  69. package/src/common-auth-embedded/source-output.json +48 -40
package/dist/index.js CHANGED
@@ -989,10 +989,10 @@ async function readPointerRecord(legacyPath) {
989
989
  return decodeAccountStorePointerRecord(jsonBytes(await secureRead(path5)), legacyPath);
990
990
  }
991
991
  async function readPointer(legacyPath) {
992
- const record3 = await readPointerRecord(legacyPath);
993
- if (record3?.schemaVersion === 2)
994
- throw new AccountMigrationError(`the account store moved to ${record3.relocatedTo.legacyPath}; this operation does not follow a moved store`);
995
- return record3;
992
+ const record4 = await readPointerRecord(legacyPath);
993
+ if (record4?.schemaVersion === 2)
994
+ throw new AccountMigrationError(`the account store moved to ${record4.relocatedTo.legacyPath}; this operation does not follow a moved store`);
995
+ return record4;
996
996
  }
997
997
  async function forwardTarget(legacyPath, forward) {
998
998
  const target = forward.relocatedTo.legacyPath;
@@ -1258,11 +1258,11 @@ function generationJson(journal) {
1258
1258
  };
1259
1259
  }
1260
1260
  function exact(value, keys, path5) {
1261
- const record3 = object(value, path5);
1262
- if (Object.keys(record3).some((key) => !keys.includes(key))) {
1261
+ const record4 = object(value, path5);
1262
+ if (Object.keys(record4).some((key) => !keys.includes(key))) {
1263
1263
  throw new AccountMigrationError(`${path5} has unknown fields`);
1264
1264
  }
1265
- return record3;
1265
+ return record4;
1266
1266
  }
1267
1267
  function text(value, pattern, path5) {
1268
1268
  if (typeof value !== "string" || !pattern.test(value))
@@ -2148,14 +2148,14 @@ async function trustedCurrentGeneration(store, paths, journal) {
2148
2148
  }
2149
2149
  async function readAccountStoreBinding(legacyPath, modules, now, expectedGeneration) {
2150
2150
  try {
2151
- const record3 = await readPointerRecord(legacyPath);
2152
- const restored = await restoredRelocationAnchor(legacyPath, record3);
2151
+ const record4 = await readPointerRecord(legacyPath);
2152
+ const restored = await restoredRelocationAnchor(legacyPath, record4);
2153
2153
  if (restored !== void 0)
2154
2154
  return await bindPublishedGeneration(restored, modules, now, expectedGeneration);
2155
- if (record3?.schemaVersion === 2) {
2155
+ if (record4?.schemaVersion === 2) {
2156
2156
  if (await exists(legacyPath))
2157
- throw new AccountMigrationError(`a pool file reappeared at ${legacyPath} after the account store moved to ${record3.relocatedTo.legacyPath}`);
2158
- return await bindPublishedGeneration(await forwardTarget(legacyPath, record3), modules, now, expectedGeneration, legacyPath);
2157
+ throw new AccountMigrationError(`a pool file reappeared at ${legacyPath} after the account store moved to ${record4.relocatedTo.legacyPath}`);
2158
+ return await bindPublishedGeneration(await forwardTarget(legacyPath, record4), modules, now, expectedGeneration, legacyPath);
2159
2159
  }
2160
2160
  return await bindPublishedGeneration(legacyPath, modules, now, expectedGeneration);
2161
2161
  } catch (error) {
@@ -2174,12 +2174,12 @@ async function assertSourceForwarded(journal, forwardedFrom) {
2174
2174
  throw new AccountMigrationError(`the forwarding pointer ${accountStorePointerPath(forwardedFrom)} leads to a store moved from ${source.legacyPath}`);
2175
2175
  if (await exists(source.legacyPath))
2176
2176
  throw new AccountMigrationError(`a pool file reappeared at ${source.legacyPath} after the account store moved to ${journal.legacyPath}`);
2177
- const record3 = await readPointerRecord(source.legacyPath);
2178
- if (record3 === void 0)
2177
+ const record4 = await readPointerRecord(source.legacyPath);
2178
+ if (record4 === void 0)
2179
2179
  throw new AccountMigrationError(`the forwarding pointer ${pointer} to the moved account store at ${journal.storeDir} is missing; restore it`);
2180
- if (record3.schemaVersion === 1)
2181
- throw new AccountMigrationError(`the account store in ${dirname2(source.legacyPath)} was reactivated: ${pointer} publishes generation ${record3.id} while the moved store at ${journal.storeDir} is active; restore the forwarding pointer`);
2182
- if (record3.id !== source.journalId || record3.relocatedTo.legacyPath !== journal.legacyPath || record3.relocatedTo.id !== journal.id)
2180
+ if (record4.schemaVersion === 1)
2181
+ throw new AccountMigrationError(`the account store in ${dirname2(source.legacyPath)} was reactivated: ${pointer} publishes generation ${record4.id} while the moved store at ${journal.storeDir} is active; restore the forwarding pointer`);
2182
+ if (record4.id !== source.journalId || record4.relocatedTo.legacyPath !== journal.legacyPath || record4.relocatedTo.id !== journal.id)
2183
2183
  throw new AccountMigrationError(`the forwarding pointer ${pointer} names another store than the moved account store at ${journal.storeDir}`);
2184
2184
  }
2185
2185
  async function bindPublishedGeneration(legacyPath, modules, now, expectedGeneration, forwardedFrom) {
@@ -2214,12 +2214,12 @@ async function bindPublishedGeneration(legacyPath, modules, now, expectedGenerat
2214
2214
  const settings = await trustedCurrentGeneration(openAdmissionStore(modules, paths, now), paths, journal);
2215
2215
  const pending = settings[MANAGEMENT_SETTINGS_KEY];
2216
2216
  if (pending !== void 0) {
2217
- const record3 = object(pending, "repository management");
2218
- if (record3.kind === "migration" && record3.id !== journal.id)
2219
- throw new AccountMigrationError(`the account store at ${paths.storeDir} was moved to generation ${String(record3.id)}, but ${accountStorePointerPath(legacyPath)} publishes the old store again; restore the forwarding pointer`);
2220
- if (record3.kind === "migration")
2217
+ const record4 = object(pending, "repository management");
2218
+ if (record4.kind === "migration" && record4.id !== journal.id)
2219
+ throw new AccountMigrationError(`the account store at ${paths.storeDir} was moved to generation ${String(record4.id)}, but ${accountStorePointerPath(legacyPath)} publishes the old store again; restore the forwarding pointer`);
2220
+ if (record4.kind === "migration")
2221
2221
  return { status: "pending", phase: "activate", operation: "migrate" };
2222
- if (record3.kind !== "clear" && record3.kind !== "replace-pool")
2222
+ if (record4.kind !== "clear" && record4.kind !== "replace-pool")
2223
2223
  throw new AccountMigrationError("unknown management owner prevents binding");
2224
2224
  }
2225
2225
  return { status: "bound", receipt: receipt(journal), paths };
@@ -3114,7 +3114,7 @@ async function reverseRelocation(modules, options, sourceParent, targetParent) {
3114
3114
  const store = openMigrationStore(modules, paths, options.now);
3115
3115
  const progressPath = join2(paths.transfersDir, `${journal.id}.reverse.json`);
3116
3116
  const progress = async (phase, snapshotSha256) => {
3117
- const record3 = {
3117
+ const record4 = {
3118
3118
  schemaVersion: 1,
3119
3119
  id: journal.id,
3120
3120
  sourcePath: paths.legacyPath,
@@ -3129,7 +3129,7 @@ async function reverseRelocation(modules, options, sourceParent, targetParent) {
3129
3129
  await lease.assertOwned();
3130
3130
  await unlink2(stage);
3131
3131
  }
3132
- await modules.fs.writeJsonAtomic(progressPath, record3, {
3132
+ await modules.fs.writeJsonAtomic(progressPath, record4, {
3133
3133
  stageName: () => journal.id,
3134
3134
  beforeRename: async () => {
3135
3135
  await lease.assertOwned();
@@ -3138,7 +3138,7 @@ async function reverseRelocation(modules, options, sourceParent, targetParent) {
3138
3138
  });
3139
3139
  await syncFile(progressPath, options.onBoundary, "reverse-progress");
3140
3140
  await syncDirectory(paths.transfersDir);
3141
- if (!isDeepStrictEqual(jsonBytes(await secureRead(progressPath)), record3))
3141
+ if (!isDeepStrictEqual(jsonBytes(await secureRead(progressPath)), record4))
3142
3142
  throw new AccountMigrationError("reverse progress readback differs");
3143
3143
  };
3144
3144
  await verifyCopies(paths, journal, true);
@@ -3322,9 +3322,9 @@ function createAccountRollbackFactory(modules) {
3322
3322
  throw new AccountMigrationError("stopped processes and timers must be explicitly confirmed");
3323
3323
  try {
3324
3324
  return await withParentTopology(modules, options.legacyPath, async () => {
3325
- const record3 = await readPointerRecord(options.legacyPath);
3326
- if (record3?.schemaVersion === 2)
3327
- throw new AccountMigrationError(`the account store moved to ${record3.relocatedTo.legacyPath}; move it back with \`antigravity-auth store relocate --back --offline\` before rolling it back`);
3325
+ const record4 = await readPointerRecord(options.legacyPath);
3326
+ if (record4?.schemaVersion === 2)
3327
+ throw new AccountMigrationError(`the account store moved to ${record4.relocatedTo.legacyPath}; move it back with \`antigravity-auth store relocate --back --offline\` before rolling it back`);
3328
3328
  const paths = await resolvePublishedAccountStorePaths(options.legacyPath);
3329
3329
  if (!paths)
3330
3330
  throw new AccountMigrationError("rollback requires a published generation");
@@ -4269,14 +4269,14 @@ function canonicalJson(value) {
4269
4269
  function replacementInputDigest(inputs) {
4270
4270
  return createHash2("sha256").update(canonicalJson(inputs.map(encodeLoginInput))).digest("hex");
4271
4271
  }
4272
- function publicManagementRecord(record3) {
4272
+ function publicManagementRecord(record4) {
4273
4273
  return {
4274
- id: record3.id,
4275
- kind: record3.kind,
4276
- targets: [...record3.targets],
4274
+ id: record4.id,
4275
+ kind: record4.kind,
4276
+ targets: [...record4.targets],
4277
4277
  progress: {
4278
- step: record3.progress.step,
4279
- completedTargets: [...record3.progress.completedTargets]
4278
+ step: record4.progress.step,
4279
+ completedTargets: [...record4.progress.completedTargets]
4280
4280
  }
4281
4281
  };
4282
4282
  }
@@ -4298,31 +4298,31 @@ function decodeManagementRecord(raw) {
4298
4298
  if (!isRecord(raw)) {
4299
4299
  throw new AccountCodecError("$", "must be an object");
4300
4300
  }
4301
- const record3 = raw;
4302
- const progress = record3.progress;
4303
- if (typeof record3.id !== "string" || !MANAGEMENT_ID.test(record3.id)) {
4301
+ const record4 = raw;
4302
+ const progress = record4.progress;
4303
+ if (typeof record4.id !== "string" || !MANAGEMENT_ID.test(record4.id)) {
4304
4304
  throw new AccountCodecError("$.id", "must be a lowercase UUID");
4305
4305
  }
4306
- if (!isManagementKind(record3.kind)) {
4306
+ if (!isManagementKind(record4.kind)) {
4307
4307
  throw new AccountCodecError("$.kind", "must be a management kind");
4308
4308
  }
4309
- const targets = uniqueIds(record3.targets, "$.targets");
4309
+ const targets = uniqueIds(record4.targets, "$.targets");
4310
4310
  if (!isRecord(progress)) {
4311
4311
  throw new AccountCodecError("$.progress", "must be an object");
4312
4312
  }
4313
4313
  const { step } = progress;
4314
- const steps = MANAGEMENT_STEPS[record3.kind];
4314
+ const steps = MANAGEMENT_STEPS[record4.kind];
4315
4315
  if (typeof step !== "string" || !steps.includes(step)) {
4316
- throw new AccountCodecError("$.progress.step", `must be a step of a ${record3.kind} record`);
4316
+ throw new AccountCodecError("$.progress.step", `must be a step of a ${record4.kind} record`);
4317
4317
  }
4318
4318
  const completedTargets = uniqueIds(progress.completedTargets, "$.progress.completedTargets");
4319
4319
  if (step === "remove" && completedTargets.some((id) => !targets.includes(id))) {
4320
4320
  throw new AccountCodecError("$.progress.completedTargets", "must name only targets while rows are being removed");
4321
4321
  }
4322
- const inputDigest = record3.inputDigest;
4323
- if (record3.publication !== void 0 && record3.kind !== "replace-pool")
4322
+ const inputDigest = record4.inputDigest;
4323
+ if (record4.publication !== void 0 && record4.kind !== "replace-pool")
4324
4324
  throw new AccountCodecError("$.publication", "belongs only to a replace-pool record");
4325
- if (record3.kind === "replace-pool") {
4325
+ if (record4.kind === "replace-pool") {
4326
4326
  if (typeof inputDigest !== "string" || !SHA256_HEX.test(inputDigest)) {
4327
4327
  throw new AccountCodecError("$.inputDigest", "must be the SHA-256 of the replacement inputs");
4328
4328
  }
@@ -4330,12 +4330,12 @@ function decodeManagementRecord(raw) {
4330
4330
  throw new AccountCodecError("$.inputDigest", "belongs only to a replace-pool record");
4331
4331
  }
4332
4332
  return {
4333
- id: record3.id,
4334
- kind: record3.kind,
4333
+ id: record4.id,
4334
+ kind: record4.kind,
4335
4335
  targets,
4336
4336
  progress: { step, completedTargets },
4337
4337
  ...typeof inputDigest === "string" ? { inputDigest } : {},
4338
- ...record3.publication !== void 0 ? { publication: decodePublicationPlan(record3.publication, record3.id) } : {}
4338
+ ...record4.publication !== void 0 ? { publication: decodePublicationPlan(record4.publication, record4.id) } : {}
4339
4339
  };
4340
4340
  }
4341
4341
  function decodePublicationPlan(raw, operationId) {
@@ -4390,17 +4390,17 @@ function encodePublicationPlan(plan) {
4390
4390
  order: [...plan.order]
4391
4391
  };
4392
4392
  }
4393
- function encodeManagementRecord(record3) {
4393
+ function encodeManagementRecord(record4) {
4394
4394
  return {
4395
- id: record3.id,
4396
- kind: record3.kind,
4397
- targets: [...record3.targets],
4395
+ id: record4.id,
4396
+ kind: record4.kind,
4397
+ targets: [...record4.targets],
4398
4398
  progress: {
4399
- step: record3.progress.step,
4400
- completedTargets: [...record3.progress.completedTargets]
4399
+ step: record4.progress.step,
4400
+ completedTargets: [...record4.progress.completedTargets]
4401
4401
  },
4402
- ...record3.inputDigest !== void 0 ? { inputDigest: record3.inputDigest } : {},
4403
- ...record3.publication !== void 0 ? { publication: encodePublicationPlan(record3.publication) } : {}
4402
+ ...record4.inputDigest !== void 0 ? { inputDigest: record4.inputDigest } : {},
4403
+ ...record4.publication !== void 0 ? { publication: encodePublicationPlan(record4.publication) } : {}
4404
4404
  };
4405
4405
  }
4406
4406
  function decodeTransferFile(raw, managementId) {
@@ -5319,22 +5319,22 @@ var init_account_repository = __esm({
5319
5319
  clear() {
5320
5320
  return this.run("clear", void 0, () => this.withTopology("clear", async (lease) => {
5321
5321
  await this.boundSettings("clear");
5322
- let record3 = await this.readManagement("clear");
5323
- if (record3 !== void 0 && record3.kind !== "clear") {
5324
- throw refusal("clear", "management-pending", `a ${record3.kind} of the account pool is pending`, {
5322
+ let record4 = await this.readManagement("clear");
5323
+ if (record4 !== void 0 && record4.kind !== "clear") {
5324
+ throw refusal("clear", "management-pending", `a ${record4.kind} of the account pool is pending`, {
5325
5325
  retryable: true
5326
5326
  });
5327
5327
  }
5328
- if (record3 === void 0) {
5328
+ if (record4 === void 0) {
5329
5329
  const rows = await this.readRows("clear");
5330
- record3 = await this.startManagement("clear", {
5330
+ record4 = await this.startManagement("clear", {
5331
5331
  id: randomUUID3(),
5332
5332
  kind: "clear",
5333
5333
  targets: rows.map((row) => row.id),
5334
5334
  progress: { step: "remove", completedTargets: [] }
5335
5335
  }, lease);
5336
5336
  }
5337
- return this.continueManagement("clear", record3, async (current) => this.removeTargets("clear", current, lease), lease);
5337
+ return this.continueManagement("clear", record4, async (current) => this.removeTargets("clear", current, lease), lease);
5338
5338
  }));
5339
5339
  }
5340
5340
  replacePool(inputs) {
@@ -5347,14 +5347,14 @@ var init_account_repository = __esm({
5347
5347
  const inputDigest = replacementInputDigest(inputs);
5348
5348
  const inputIds = inputs.map((input2) => input2.id);
5349
5349
  await this.boundSettings("replacePool");
5350
- let record3 = await this.readManagement("replacePool");
5351
- if (record3 !== void 0) {
5352
- if (record3.kind !== "replace-pool") {
5353
- throw refusal("replacePool", "management-pending", `a ${record3.kind} of the account pool is pending`, {
5350
+ let record4 = await this.readManagement("replacePool");
5351
+ if (record4 !== void 0) {
5352
+ if (record4.kind !== "replace-pool") {
5353
+ throw refusal("replacePool", "management-pending", `a ${record4.kind} of the account pool is pending`, {
5354
5354
  retryable: true
5355
5355
  });
5356
5356
  }
5357
- if (record3.inputDigest !== inputDigest) {
5357
+ if (record4.inputDigest !== inputDigest) {
5358
5358
  throw refusal("replacePool", "management-pending", "another pool replacement is pending", {
5359
5359
  retryable: true
5360
5360
  });
@@ -5372,7 +5372,7 @@ var init_account_repository = __esm({
5372
5372
  const id = randomUUID3();
5373
5373
  await lease.assertOwned();
5374
5374
  await this.writeTransfer(id, inputs);
5375
- record3 = await this.startManagement("replacePool", {
5375
+ record4 = await this.startManagement("replacePool", {
5376
5376
  id,
5377
5377
  kind: "replace-pool",
5378
5378
  targets: rows.map((row) => row.id),
@@ -5380,7 +5380,7 @@ var init_account_repository = __esm({
5380
5380
  inputDigest
5381
5381
  }, lease);
5382
5382
  }
5383
- return this.continueManagement("replacePool", record3, async (current) => {
5383
+ return this.continueManagement("replacePool", record4, async (current) => {
5384
5384
  let next = current;
5385
5385
  if (next.progress.step !== "verified") {
5386
5386
  if (next.progress.step === "remove") {
@@ -5429,9 +5429,9 @@ var init_account_repository = __esm({
5429
5429
  throw refusal("replacePool", "replacement-unavailable", "Atomic roster publication is unavailable");
5430
5430
  await this.boundSettings("replacePool");
5431
5431
  const inputDigest = replacementInputDigest(inputs);
5432
- let record3 = await this.readManagement("replacePool");
5433
- if (record3) {
5434
- if (record3.kind !== "replace-pool" || record3.inputDigest !== inputDigest || !record3.publication)
5432
+ let record4 = await this.readManagement("replacePool");
5433
+ if (record4) {
5434
+ if (record4.kind !== "replace-pool" || record4.inputDigest !== inputDigest || !record4.publication)
5435
5435
  throw refusal("replacePool", "management-pending", "another management operation needs recovery");
5436
5436
  } else {
5437
5437
  const rows = (await this.readRows("replacePool")).filter((row) => row.invalid !== "roster");
@@ -5453,7 +5453,7 @@ var init_account_repository = __esm({
5453
5453
  const id = randomUUID3();
5454
5454
  await lease.assertOwned();
5455
5455
  await this.writeTransfer(id, inputs);
5456
- record3 = await this.startManagement("replacePool", {
5456
+ record4 = await this.startManagement("replacePool", {
5457
5457
  id,
5458
5458
  kind: "replace-pool",
5459
5459
  targets: remove2.map((row) => row.id),
@@ -5467,7 +5467,7 @@ var init_account_repository = __esm({
5467
5467
  }
5468
5468
  }, lease);
5469
5469
  }
5470
- return this.continueManagement("replacePool", record3, async (current) => {
5470
+ return this.continueManagement("replacePool", record4, async (current) => {
5471
5471
  let next = current;
5472
5472
  let plan = next.publication;
5473
5473
  if (!plan || !isDeepStrictEqual2(plan.order, inputs.map((input2) => input2.id)))
@@ -5598,7 +5598,7 @@ var init_account_repository = __esm({
5598
5598
  secrets.add(input2.refreshToken);
5599
5599
  }
5600
5600
  }
5601
- async startManagement(operation, record3, lease) {
5601
+ async startManagement(operation, record4, lease) {
5602
5602
  await lease.assertOwned();
5603
5603
  await this.store.updateSettings((settings) => {
5604
5604
  if (settings[MANAGEMENT_SETTINGS_KEY] !== void 0) {
@@ -5608,31 +5608,31 @@ var init_account_repository = __esm({
5608
5608
  }
5609
5609
  return {
5610
5610
  ...settings,
5611
- [MANAGEMENT_SETTINGS_KEY]: encodeManagementRecord(record3)
5611
+ [MANAGEMENT_SETTINGS_KEY]: encodeManagementRecord(record4)
5612
5612
  };
5613
5613
  }, { extraLocks: [managementLock(this.paths)] });
5614
- return record3;
5614
+ return record4;
5615
5615
  }
5616
- ownsManagement(settings, record3) {
5616
+ ownsManagement(settings, record4) {
5617
5617
  const raw = settings[MANAGEMENT_SETTINGS_KEY];
5618
5618
  if (raw === void 0)
5619
5619
  return false;
5620
5620
  try {
5621
5621
  const current = decodeManagementRecord(raw);
5622
- return current.id === record3.id && current.kind === record3.kind && current.inputDigest === record3.inputDigest;
5622
+ return current.id === record4.id && current.kind === record4.kind && current.inputDigest === record4.inputDigest;
5623
5623
  } catch {
5624
5624
  return false;
5625
5625
  }
5626
5626
  }
5627
- async saveProgress(operation, record3, step, completedTargets, lease, publication2) {
5627
+ async saveProgress(operation, record4, step, completedTargets, lease, publication2) {
5628
5628
  const next = {
5629
- ...record3,
5629
+ ...record4,
5630
5630
  ...publication2 !== void 0 ? { publication: publication2 } : {},
5631
5631
  progress: { step, completedTargets }
5632
5632
  };
5633
5633
  await lease.assertOwned();
5634
5634
  await this.store.updateSettings((settings) => {
5635
- if (!this.ownsManagement(settings, record3)) {
5635
+ if (!this.ownsManagement(settings, record4)) {
5636
5636
  throw new CallbackRefusal(refusal(operation, "management-pending", "the management record changed under this operation"));
5637
5637
  }
5638
5638
  return {
@@ -5642,16 +5642,16 @@ var init_account_repository = __esm({
5642
5642
  }, { extraLocks: [managementLock(this.paths)] });
5643
5643
  return next;
5644
5644
  }
5645
- async removeTargets(operation, record3, lease) {
5646
- let next = record3;
5647
- for (const target of record3.targets) {
5645
+ async removeTargets(operation, record4, lease) {
5646
+ let next = record4;
5647
+ for (const target of record4.targets) {
5648
5648
  if (next.progress.completedTargets.includes(target))
5649
5649
  continue;
5650
5650
  await lease.assertOwned();
5651
5651
  try {
5652
5652
  await this.store.remove(target, {
5653
5653
  extraLocks: [managementLock(this.paths)],
5654
- protect: (_id, view) => this.ownsManagement(view.config, record3) ? void 0 : "the management record changed under this removal"
5654
+ protect: (_id, view) => this.ownsManagement(view.config, record4) ? void 0 : "the management record changed under this removal"
5655
5655
  });
5656
5656
  } catch (error) {
5657
5657
  const failure2 = this.failureOf(operation, target, error);
@@ -5667,13 +5667,13 @@ var init_account_repository = __esm({
5667
5667
  * A retryable failure (lock contention, a lost lease) leaves the record
5668
5668
  * pending and reports it instead of looping; the next call resumes.
5669
5669
  */
5670
- async continueManagement(operation, record3, steps, lease) {
5670
+ async continueManagement(operation, record4, steps, lease) {
5671
5671
  let finished;
5672
5672
  try {
5673
- finished = await steps(record3);
5673
+ finished = await steps(record4);
5674
5674
  await lease.assertOwned();
5675
5675
  await this.store.updateSettings((settings) => {
5676
- if (!this.ownsManagement(settings, record3)) {
5676
+ if (!this.ownsManagement(settings, record4)) {
5677
5677
  throw new CallbackRefusal(refusal(operation, "management-pending", "the management journal no longer holds this operation; it was not cleared"));
5678
5678
  }
5679
5679
  const { [MANAGEMENT_SETTINGS_KEY]: _done, ...rest } = settings;
@@ -5682,7 +5682,7 @@ var init_account_repository = __esm({
5682
5682
  } catch (error) {
5683
5683
  const failure2 = this.failureOf(operation, void 0, error);
5684
5684
  if (failure2.failure.retryable) {
5685
- const now = await this.readManagement(operation) ?? record3;
5685
+ const now = await this.readManagement(operation) ?? record4;
5686
5686
  return { management: publicManagementRecord(now), outcome: "pending" };
5687
5687
  }
5688
5688
  throw failure2;
@@ -7692,9 +7692,9 @@ var init_account_selector = __esm({
7692
7692
  const today = new Date(this.now()).toISOString().slice(0, 10);
7693
7693
  const result = [];
7694
7694
  for (const account of this.accounts) {
7695
- const count3 = account.dailyRequestCounts?.date === today ? account.dailyRequestCounts[family] : 0;
7696
- if (count3 > 0) {
7697
- result.push({ index: account.index, email: account.email, count: count3 });
7695
+ const count4 = account.dailyRequestCounts?.date === today ? account.dailyRequestCounts[family] : 0;
7696
+ if (count4 > 0) {
7697
+ result.push({ index: account.index, email: account.email, count: count4 });
7698
7698
  }
7699
7699
  }
7700
7700
  return result.sort((a, b) => b.count - a.count);
@@ -8571,11 +8571,11 @@ async function readAndNormalizeV4(path5) {
8571
8571
  }
8572
8572
  };
8573
8573
  }
8574
- function validateV4AccountRecord(record3, index) {
8575
- if (record3 === null || typeof record3 !== "object" || Array.isArray(record3)) {
8574
+ function validateV4AccountRecord(record4, index) {
8575
+ if (record4 === null || typeof record4 !== "object" || Array.isArray(record4)) {
8576
8576
  return `accounts[${index}] is not an object`;
8577
8577
  }
8578
- const acc = record3;
8578
+ const acc = record4;
8579
8579
  if (typeof acc.refreshToken !== "string" || acc.refreshToken.length === 0) {
8580
8580
  return `accounts[${index}].refreshToken is missing or not a non-empty string`;
8581
8581
  }
@@ -9280,15 +9280,15 @@ var init_account_manager = __esm({
9280
9280
  }
9281
9281
  /** The stored selection's index for `family` among `accounts`. */
9282
9282
  routedIndex(accounts, routing, family) {
9283
- const count3 = accounts.length;
9283
+ const count4 = accounts.length;
9284
9284
  const indexOf = (ref) => {
9285
9285
  if (ref == null)
9286
9286
  return void 0;
9287
9287
  const found = accounts.findIndex((account) => account.ref !== void 0 && sameRowRef(account.ref, ref));
9288
9288
  return found < 0 ? void 0 : found;
9289
9289
  };
9290
- const defaultIndex = indexOf(routing?.activeRow) ?? clampNonNegativeInt(routing?.activeIndex, 0) % count3;
9291
- return indexOf(routing?.activeRowByFamily?.[family]) ?? clampNonNegativeInt(routing?.activeIndexByFamily?.[family], defaultIndex) % count3;
9290
+ const defaultIndex = indexOf(routing?.activeRow) ?? clampNonNegativeInt(routing?.activeIndex, 0) % count4;
9291
+ return indexOf(routing?.activeRowByFamily?.[family]) ?? clampNonNegativeInt(routing?.activeIndexByFamily?.[family], defaultIndex) % count4;
9292
9292
  }
9293
9293
  loadRepositoryRows(read) {
9294
9294
  const baseNow = this.now();
@@ -11334,8 +11334,8 @@ function isFiniteNumber(value) {
11334
11334
  function isName(value) {
11335
11335
  return typeof value === "string" && value.length > 0;
11336
11336
  }
11337
- function optional2(record3, key, check) {
11338
- return record3[key] === void 0 || check(record3[key]);
11337
+ function optional2(record4, key, check) {
11338
+ return record4[key] === void 0 || check(record4[key]);
11339
11339
  }
11340
11340
  function isPositiveFinite(value) {
11341
11341
  return isFiniteNumber(value) && value > 0;
@@ -11437,11 +11437,11 @@ function isScope(value) {
11437
11437
  function isLabel(value) {
11438
11438
  return typeof value === "string" && value !== "";
11439
11439
  }
11440
- function optionalFinite(record3, key) {
11441
- return record3[key] === void 0 || isFiniteNumber2(record3[key]);
11440
+ function optionalFinite(record4, key) {
11441
+ return record4[key] === void 0 || isFiniteNumber2(record4[key]);
11442
11442
  }
11443
- function optionalString(record3, key) {
11444
- return record3[key] === void 0 || typeof record3[key] === "string";
11443
+ function optionalString(record4, key) {
11444
+ return record4[key] === void 0 || typeof record4[key] === "string";
11445
11445
  }
11446
11446
  function isObservedReading(value) {
11447
11447
  return isRecord3(value) && isScope(value.scope) && isLabel(value.label) && isFiniteNumber2(value.usedPercent) && optionalString(value, "resetsAt") && (value.windowMinutes === void 0 || isFiniteNumber2(value.windowMinutes) && value.windowMinutes > 0);
@@ -16567,8 +16567,8 @@ var init_pull = __esm({
16567
16567
  // ../core/dist/common-auth-embedded/logger/capture-sink.js
16568
16568
  function createCaptureSink() {
16569
16569
  const records = [];
16570
- const sink = (record3) => {
16571
- records.push(record3);
16570
+ const sink = (record4) => {
16571
+ records.push(record4);
16572
16572
  };
16573
16573
  return {
16574
16574
  records,
@@ -17710,8 +17710,8 @@ function openPoolStore(options) {
17710
17710
  firePull: (id, reason) => pulls.fire(id, reason)
17711
17711
  };
17712
17712
  const quotaWriter = options.coalesceQuota ? new PoolQuotaWriter(rt, options.quotaDrainTimeoutMs, options.quotaCommitTimer) : void 0;
17713
- const record3 = (id, attribution, observation) => quotaWriter ? quotaWriter.record(id, attribution, observation) : recordQuota(rt, id, attribution, observation);
17714
- rt.publishQuota = record3;
17713
+ const record4 = (id, attribution, observation) => quotaWriter ? quotaWriter.record(id, attribution, observation) : recordQuota(rt, id, attribution, observation);
17714
+ rt.publishQuota = record4;
17715
17715
  const overlay = (result) => {
17716
17716
  if (result.status === "ready" && quotaWriter)
17717
17717
  return { ...result, rows: quotaWriter.overlay(result.rows) };
@@ -17748,7 +17748,7 @@ function openPoolStore(options) {
17748
17748
  updateLimitsNamespace: (mutator, options2) => updatePoolLimitsNamespace(rt, mutator, options2),
17749
17749
  recordIdentity: (id, identity3, attribution, callOptions) => recordRowIdentity(rt, id, identity3, attribution, callOptions),
17750
17750
  refresh: (id, provider2, callOptions) => refreshRow(rt, id, provider2, callOptions),
17751
- recordQuota: record3,
17751
+ recordQuota: record4,
17752
17752
  close: () => quotaWriter?.close() ?? Promise.resolve(),
17753
17753
  dispose: () => quotaWriter?.close() ?? Promise.resolve(),
17754
17754
  requestReading: (id) => pulls.fire(id, "admission"),
@@ -21398,6 +21398,25 @@ function validEnrollmentDisplayName(displayName) {
21398
21398
  const length = Array.from(displayName).length;
21399
21399
  return length >= 1 && length <= 40 && !/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\u200b-\u200d\u2060\ufeff]/u.test(displayName);
21400
21400
  }
21401
+ function validEnrollmentRequestedGrants(grants) {
21402
+ return Array.isArray(grants) && grants.length >= 1 && grants.length <= 4 && Array.from(grants).every((grant) => {
21403
+ if (!isRecord6(grant) || Object.keys(grant).length !== 2 || grant.operation !== "read" && grant.operation !== "list" || !isRecord6(grant.selector))
21404
+ return false;
21405
+ const keys = Object.keys(grant.selector);
21406
+ const key = keys[0];
21407
+ return keys.length === 1 && (key === "category" || key === "exact") && typeof grant.selector[key] === "string" && grant.selector[key].trim().length > 0;
21408
+ });
21409
+ }
21410
+ function grantProposal(state) {
21411
+ return {
21412
+ ...state.requestedGrants !== void 0 && {
21413
+ requestedGrants: state.requestedGrants
21414
+ },
21415
+ ...state.requestedGrantsStatus !== void 0 && {
21416
+ requestedGrantsStatus: state.requestedGrantsStatus
21417
+ }
21418
+ };
21419
+ }
21401
21420
  function connectClaustrumEnrollmentClient(options) {
21402
21421
  return ClaustrumWireClient.connect(options);
21403
21422
  }
@@ -21433,6 +21452,7 @@ function decodeEnrollmentState(value) {
21433
21452
  throw invalidState();
21434
21453
  }
21435
21454
  if (value.phase === "pending") {
21455
+ const grants = decodeGrantProposal(value);
21436
21456
  if (!TOKEN_RE.test(String(value.requestSecret ?? "")) || value.requestId !== void 0 && (typeof value.requestId !== "string" || value.requestId.length === 0) || !validTimestamp(value.createdAt) || !validTimestamp(value.updatedAt)) {
21437
21457
  throw invalidState();
21438
21458
  }
@@ -21445,10 +21465,12 @@ function decodeEnrollmentState(value) {
21445
21465
  requestId: value.requestId
21446
21466
  },
21447
21467
  createdAt: value.createdAt,
21448
- updatedAt: value.updatedAt
21468
+ updatedAt: value.updatedAt,
21469
+ ...grants
21449
21470
  };
21450
21471
  }
21451
21472
  if (value.phase === "approved") {
21473
+ const grants = decodeGrantProposal(value);
21452
21474
  if (value.approvedName !== void 0 && (typeof value.approvedName !== "string" || value.approvedName.length === 0) || !validGeneration(value.tokenGeneration) || !validTimestamp(value.updatedAt)) {
21453
21475
  throw invalidState();
21454
21476
  }
@@ -21460,7 +21482,8 @@ function decodeEnrollmentState(value) {
21460
21482
  approvedName: value.approvedName
21461
21483
  },
21462
21484
  tokenGeneration: value.tokenGeneration,
21463
- updatedAt: value.updatedAt
21485
+ updatedAt: value.updatedAt,
21486
+ ...grants
21464
21487
  };
21465
21488
  }
21466
21489
  if (value.phase === "denied" || value.phase === "blocked") {
@@ -21479,6 +21502,11 @@ function decodeEnrollmentState(value) {
21479
21502
  }
21480
21503
  throw invalidState();
21481
21504
  }
21505
+ function decodeGrantProposal(value) {
21506
+ if (value.requestedGrants !== void 0 && !validEnrollmentRequestedGrants(value.requestedGrants) || value.requestedGrantsStatus !== void 0 && (value.requestedGrants === void 0 || value.requestedGrantsStatus !== "sent" && value.requestedGrantsStatus !== "dropped"))
21507
+ return {};
21508
+ return grantProposal(value);
21509
+ }
21482
21510
  function decodeTokenFile(value) {
21483
21511
  if (!isRecord6(value) || !TOKEN_RE.test(String(value.token ?? "")) || !validGeneration(value.token_generation)) {
21484
21512
  throw new ClaustrumConsumerError("invalid-token", "invalid Claustrum enrollment token file");
@@ -21692,7 +21720,8 @@ async function readEnrollmentStatus(paths, proposedName) {
21692
21720
  ...state?.phase === "approved" && state.approvedName !== void 0 && {
21693
21721
  approvedName: state.approvedName
21694
21722
  },
21695
- tokenGeneration: token.token_generation
21723
+ tokenGeneration: token.token_generation,
21724
+ ...state && (state.phase === "approved" || state.phase === "pending") && grantProposal(state)
21696
21725
  }
21697
21726
  };
21698
21727
  }
@@ -21751,7 +21780,8 @@ function statusFromState(state) {
21751
21780
  return {
21752
21781
  state: "pending",
21753
21782
  proposedName: state.proposedName,
21754
- ...state.requestId !== void 0 && { requestId: state.requestId }
21783
+ ...state.requestId !== void 0 && { requestId: state.requestId },
21784
+ ...grantProposal(state)
21755
21785
  };
21756
21786
  }
21757
21787
  if (state.phase === "approved") {
@@ -21761,7 +21791,8 @@ function statusFromState(state) {
21761
21791
  ...state.approvedName !== void 0 && {
21762
21792
  approvedName: state.approvedName
21763
21793
  },
21764
- tokenGeneration: state.tokenGeneration
21794
+ tokenGeneration: state.tokenGeneration,
21795
+ ...grantProposal(state)
21765
21796
  };
21766
21797
  }
21767
21798
  if (state.phase === "denied")
@@ -21881,6 +21912,7 @@ var init_enrollment = __esm({
21881
21912
  #paths;
21882
21913
  #proposedName;
21883
21914
  #displayName;
21915
+ #requestedGrants;
21884
21916
  #now;
21885
21917
  #mintSecret;
21886
21918
  #writeTokenFile;
@@ -21888,6 +21920,12 @@ var init_enrollment = __esm({
21888
21920
  constructor(options) {
21889
21921
  if (options.displayName !== void 0 && !validEnrollmentDisplayName(options.displayName))
21890
21922
  throw new ClaustrumConsumerError("invalid-state", "invalid Claustrum enrollment display name");
21923
+ if (options.requestedGrants !== void 0 && !validEnrollmentRequestedGrants(options.requestedGrants))
21924
+ throw new ClaustrumConsumerError("invalid-state", "invalid Claustrum enrollment requested grants");
21925
+ this.#requestedGrants = options.requestedGrants?.map((grant) => ({
21926
+ selector: { ...grant.selector },
21927
+ operation: grant.operation
21928
+ }));
21891
21929
  this.#ancestorOptions = options.ancestorOptions ?? {};
21892
21930
  this.#client = options.client;
21893
21931
  this.#paths = options.paths;
@@ -21938,6 +21976,7 @@ var init_enrollment = __esm({
21938
21976
  phase: "approved",
21939
21977
  proposedName: state?.proposedName ?? this.#proposedName,
21940
21978
  tokenGeneration: token.token_generation,
21979
+ ...state && grantProposal(state),
21941
21980
  updatedAt: this.#now()
21942
21981
  };
21943
21982
  await writeStateAtomic(this.#paths.statePath, approved, this.#ancestorOptions);
@@ -21949,7 +21988,8 @@ var init_enrollment = __esm({
21949
21988
  ...state.phase === "approved" && state.approvedName !== void 0 && {
21950
21989
  approvedName: state.approvedName
21951
21990
  },
21952
- tokenGeneration: token.token_generation
21991
+ tokenGeneration: token.token_generation,
21992
+ ...state.phase === "approved" && grantProposal(state)
21953
21993
  };
21954
21994
  }
21955
21995
  if (state?.phase === "approved") {
@@ -21973,7 +22013,10 @@ var init_enrollment = __esm({
21973
22013
  proposedName: this.#proposedName,
21974
22014
  requestSecret: this.#mintSecret(),
21975
22015
  createdAt: now,
21976
- updatedAt: now
22016
+ updatedAt: now,
22017
+ ...this.#requestedGrants !== void 0 && {
22018
+ requestedGrants: this.#requestedGrants
22019
+ }
21977
22020
  };
21978
22021
  if (!TOKEN_RE.test(state.requestSecret))
21979
22022
  throw new ClaustrumConsumerError("invalid-state", "invalid minted Claustrum enrollment secret");
@@ -21987,22 +22030,33 @@ var init_enrollment = __esm({
21987
22030
  requestSecretHash
21988
22031
  };
21989
22032
  let proposed;
22033
+ let requestedGrantsStatus = state.requestedGrantsStatus;
21990
22034
  try {
21991
22035
  proposed = await this.#client.enrollPropose({
21992
22036
  ...proposal,
21993
22037
  ...this.#displayName !== void 0 && {
21994
22038
  displayName: this.#displayName
22039
+ },
22040
+ ...state.requestedGrants !== void 0 && {
22041
+ requestedGrants: state.requestedGrants
21995
22042
  }
21996
22043
  });
22044
+ if (state.requestedGrants !== void 0)
22045
+ requestedGrantsStatus = "sent";
21997
22046
  } catch (error) {
21998
- if (this.#displayName === void 0 || !(error instanceof ClaustrumCredentialError3) || error.code !== "invalid_params")
22047
+ if (this.#displayName === void 0 && state.requestedGrants === void 0 || !(error instanceof ClaustrumCredentialError3) || error.code !== "invalid_params")
21999
22048
  throw error;
22000
22049
  proposed = await this.#client.enrollPropose(proposal);
22050
+ if (state.requestedGrants !== void 0)
22051
+ requestedGrantsStatus = "dropped";
22001
22052
  }
22002
22053
  state = {
22003
22054
  ...state,
22004
22055
  requestId: proposed.requestId,
22005
- updatedAt: this.#now()
22056
+ updatedAt: this.#now(),
22057
+ ...requestedGrantsStatus !== void 0 && {
22058
+ requestedGrantsStatus
22059
+ }
22006
22060
  };
22007
22061
  await writeStateAtomic(this.#paths.statePath, state, this.#ancestorOptions);
22008
22062
  } catch (error) {
@@ -22013,7 +22067,8 @@ var init_enrollment = __esm({
22013
22067
  return {
22014
22068
  state: "pending",
22015
22069
  proposedName: state.proposedName,
22016
- retryCode: refusal3.code
22070
+ retryCode: refusal3.code,
22071
+ ...grantProposal(state)
22017
22072
  };
22018
22073
  }
22019
22074
  if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE) {
@@ -22063,6 +22118,7 @@ var init_enrollment = __esm({
22063
22118
  proposedName: state.proposedName,
22064
22119
  approvedName: outcome.name,
22065
22120
  tokenGeneration: outcome.tokenGeneration,
22121
+ ...grantProposal(state),
22066
22122
  updatedAt: this.#now()
22067
22123
  };
22068
22124
  await writeStateAtomic(this.#paths.statePath, approved, this.#ancestorOptions);
@@ -22076,7 +22132,8 @@ var init_enrollment = __esm({
22076
22132
  state: "pending",
22077
22133
  proposedName: state.proposedName,
22078
22134
  requestId,
22079
- retryCode: refusal3.code
22135
+ retryCode: refusal3.code,
22136
+ ...grantProposal(state)
22080
22137
  };
22081
22138
  }
22082
22139
  return this.#block(state, refusal3.code);
@@ -22369,8 +22426,8 @@ function accessTokenFromMaterial(material) {
22369
22426
  }
22370
22427
  if (!parsed || typeof parsed !== "object")
22371
22428
  throw invalidMaterial();
22372
- const record3 = parsed;
22373
- const value = record3.access_token ?? record3.access;
22429
+ const record4 = parsed;
22430
+ const value = record4.access_token ?? record4.access;
22374
22431
  access = typeof value === "string" ? value : "";
22375
22432
  }
22376
22433
  if (!/^[\x21-\x7e]+$/.test(access) || access.startsWith(CUSTODY_PLACEHOLDER_PREFIX)) {
@@ -22752,8 +22809,8 @@ var init_custody = __esm({
22752
22809
  ...row.orgName !== void 0 && { orgName: row.orgName }
22753
22810
  }));
22754
22811
  }
22755
- for (const record3 of skipped)
22756
- this.#logger.warn("skipped malformed vault record", record3);
22812
+ for (const record4 of skipped)
22813
+ this.#logger.warn("skipped malformed vault record", record4);
22757
22814
  const grantReach = grantReachOf(inventory);
22758
22815
  return {
22759
22816
  view: inventory.view,
@@ -23095,7 +23152,7 @@ var init_custody = __esm({
23095
23152
  void usage.then(() => this.#tokenReads.delete(usage));
23096
23153
  } else
23097
23154
  this.#client.close();
23098
- this.#disposing = drainShutdown(this.#tokenReads, (count3) => (this.#onDrainTimeout ?? this.#warnShutdown)(count3)).finally(() => {
23155
+ this.#disposing = drainShutdown(this.#tokenReads, (count4) => (this.#onDrainTimeout ?? this.#warnShutdown)(count4)).finally(() => {
23099
23156
  this.#usage.drop();
23100
23157
  this.#usageServed.clear();
23101
23158
  if (usage)
@@ -23237,8 +23294,8 @@ function projectVaultRoster(previous, inventory, options = {}) {
23237
23294
  const declined = [...previous?.declined ?? seed?.declined ?? []];
23238
23295
  const complete = inventory.skipped.length === 0;
23239
23296
  const listed = new Set(inventory.credentials.map((credential) => credential.credentialId));
23240
- const rejectedIds = new Set(inventory.skipped.flatMap((record3) => record3.credentialId === void 0 ? [] : [record3.credentialId]));
23241
- const unrecoverable = inventory.skipped.some((record3) => record3.credentialId === void 0);
23297
+ const rejectedIds = new Set(inventory.skipped.flatMap((record4) => record4.credentialId === void 0 ? [] : [record4.credentialId]));
23298
+ const unrecoverable = inventory.skipped.some((record4) => record4.credentialId === void 0);
23242
23299
  const unaccounted = (id) => !listed.has(id) && (rejectedIds.has(id) || unrecoverable);
23243
23300
  const lastKnown = /* @__PURE__ */ new Map();
23244
23301
  for (const row of previousRows) {
@@ -23349,11 +23406,11 @@ function projectVaultRoster(previous, inventory, options = {}) {
23349
23406
  ...previous?.limits !== void 0 && { limits: previous.limits },
23350
23407
  complete,
23351
23408
  ...!complete && {
23352
- rejected: inventory.skipped.map((record3) => ({
23353
- ...record3.credentialId !== void 0 && {
23354
- credentialId: record3.credentialId
23409
+ rejected: inventory.skipped.map((record4) => ({
23410
+ ...record4.credentialId !== void 0 && {
23411
+ credentialId: record4.credentialId
23355
23412
  },
23356
- reason: record3.reason
23413
+ reason: record4.reason
23357
23414
  }))
23358
23415
  },
23359
23416
  rows: projected2.map((entry) => entry.row),
@@ -23732,19 +23789,19 @@ function resolveVaultPrimary(input2) {
23732
23789
  reason,
23733
23790
  ...previous && { lastVerified: previous }
23734
23791
  });
23735
- const record3 = inventory.credentials.find((credential) => credential.credentialId === input2.primaryCredentialId);
23736
- if (!record3) {
23792
+ const record4 = inventory.credentials.find((credential) => credential.credentialId === input2.primaryCredentialId);
23793
+ if (!record4) {
23737
23794
  if (inventory.skipped.some((skipped) => skipped.credentialId === input2.primaryCredentialId))
23738
23795
  return unavailable("malformed");
23739
23796
  const incomplete = input2.complete === false || inventory.skipped.some((skipped) => skipped.credentialId === void 0);
23740
23797
  return incomplete ? unavailable("incomplete") : { status: "absent" };
23741
23798
  }
23742
- const identity3 = record3.accountIdentity;
23799
+ const identity3 = record4.accountIdentity;
23743
23800
  if (identity3 === void 0)
23744
23801
  return unavailable("unclaimed");
23745
23802
  if (input2.expectedAccountIdentity !== void 0 && input2.expectedAccountIdentity !== identity3)
23746
23803
  return unavailable("identity-changed");
23747
- const representative = record3.state === "active" ? record3 : inventory.credentials.filter((credential) => credential.accountIdentity === identity3 && credential.state === "active").toSorted((left, right) => left.credentialId.localeCompare(right.credentialId))[0] ?? record3;
23804
+ const representative = record4.state === "active" ? record4 : inventory.credentials.filter((credential) => credential.accountIdentity === identity3 && credential.state === "active").toSorted((left, right) => left.credentialId.localeCompare(right.credentialId))[0] ?? record4;
23748
23805
  const binding = {
23749
23806
  routeId: input2.routeId,
23750
23807
  credentialId: representative.credentialId,
@@ -25509,7 +25566,7 @@ var init_hub = __esm({
25509
25566
  const share = {
25510
25567
  ...inventory,
25511
25568
  credentials: inventory.credentials.filter((credential) => credential.member === entry.provider),
25512
- skipped: inventory.skipped.filter((record3) => record3.member === entry.provider)
25569
+ skipped: inventory.skipped.filter((record4) => record4.member === entry.provider)
25513
25570
  };
25514
25571
  try {
25515
25572
  if (!base)
@@ -25901,6 +25958,7 @@ __export(claustrum_exports, {
25901
25958
  resetClaustrumEnrollmentState: () => resetClaustrumEnrollmentState,
25902
25959
  resolveVaultPrimary: () => resolveVaultPrimary,
25903
25960
  validEnrollmentDisplayName: () => validEnrollmentDisplayName,
25961
+ validEnrollmentRequestedGrants: () => validEnrollmentRequestedGrants,
25904
25962
  vaultAuthority: () => vaultAuthority,
25905
25963
  vaultRosterSeed: () => vaultRosterSeed,
25906
25964
  vaultRoutingRows: () => vaultRoutingRows
@@ -31296,6 +31354,9 @@ function createOpenCodeVaultCustody(options) {
31296
31354
  client,
31297
31355
  paths: await enrollmentPaths(),
31298
31356
  proposedName: OPENCODE_VAULT_ENROLLMENT_NAME,
31357
+ requestedGrants: [
31358
+ { selector: { category: "antigravity-native" }, operation: "read" }
31359
+ ],
31299
31360
  ...options.now ? { now: options.now } : {}
31300
31361
  });
31301
31362
  const current = await manager.status();
@@ -32085,9 +32146,9 @@ function bootTime(options) {
32085
32146
  return Number.NaN;
32086
32147
  }
32087
32148
  }
32088
- async function staleRecord(path5, record3, boot, heartbeat) {
32089
- if (record3.text === void 0 || !Number.isFinite(boot)) return false;
32090
- let start = heartbeat ? record3.startedAt : void 0;
32149
+ async function staleRecord(path5, record4, boot, heartbeat) {
32150
+ if (record4.text === void 0 || !Number.isFinite(boot)) return false;
32151
+ let start = heartbeat ? record4.startedAt : void 0;
32091
32152
  if (start === void 0) {
32092
32153
  try {
32093
32154
  start = (await stat10(path5)).mtimeMs;
@@ -32099,7 +32160,7 @@ async function staleRecord(path5, record3, boot, heartbeat) {
32099
32160
  return false;
32100
32161
  if (heartbeat) {
32101
32162
  try {
32102
- if (await readFile11(path5, "utf8") === record3.text) {
32163
+ if (await readFile11(path5, "utf8") === record4.text) {
32103
32164
  await unlink9(path5);
32104
32165
  log5.debug("Removed stale pre-boot heartbeat", { path: path5 });
32105
32166
  }
@@ -34209,9 +34270,9 @@ function redactSensitiveFields(value) {
34209
34270
  if (value == null) return value;
34210
34271
  if (Array.isArray(value)) return value.map(redactSensitiveFields);
34211
34272
  if (typeof value === "object") {
34212
- const record3 = value;
34273
+ const record4 = value;
34213
34274
  const redacted = {};
34214
- for (const [key, entry] of Object.entries(record3)) {
34275
+ for (const [key, entry] of Object.entries(record4)) {
34215
34276
  if (SENSITIVE_FIELD_PATTERN.test(key) && typeof entry === "string") {
34216
34277
  redacted[key] = redactSensitive(entry);
34217
34278
  } else {
@@ -34774,10 +34835,10 @@ var init_debug = __esm({
34774
34835
  // src/plugin/logger.ts
34775
34836
  function createLocationLogger(options) {
34776
34837
  let configuredLevel = options.level ? LOG_LEVEL_FROM_OPERATOR[options.level] ?? "debug" : "debug";
34777
- const emit = (record3) => {
34778
- if (options.sink && options.sinkEnabled()) {
34838
+ const emit = (record4, alwaysHost = false) => {
34839
+ if (options.sink && (alwaysHost || options.sinkEnabled())) {
34779
34840
  try {
34780
- const pending = options.sink(record3);
34841
+ const pending = options.sink(record4);
34781
34842
  if (isThenable(pending)) {
34782
34843
  pending.then(void 0, () => {
34783
34844
  });
@@ -34786,34 +34847,41 @@ function createLocationLogger(options) {
34786
34847
  }
34787
34848
  }
34788
34849
  if (isConsoleLogEnabled2()) {
34789
- const prefix = `[${record3.service}]`;
34790
- const args = record3.extra ? [prefix, record3.message, record3.extra] : [prefix, record3.message];
34850
+ const prefix = `[${record4.service}]`;
34851
+ const args = record4.extra ? [prefix, record4.message, record4.extra] : [prefix, record4.message];
34791
34852
  try {
34792
- writeConsoleLog2(record3.level, ...args);
34853
+ writeConsoleLog2(record4.level, ...args);
34793
34854
  } catch {
34794
34855
  }
34795
34856
  }
34796
34857
  };
34797
- const engine = createLoggerInstance2({
34858
+ const createEngine3 = (alwaysHost) => createLoggerInstance2({
34798
34859
  level: () => configuredLevel,
34799
34860
  extraSecretKeys: isProviderSecretKey,
34800
34861
  extraValuePatterns: OAUTH_REDIRECT_VALUE_PATTERNS,
34801
34862
  captureSink: ({ channel: channel3, level, message, data }) => {
34802
34863
  const extra = data !== null && typeof data === "object" && !Array.isArray(data) ? Object.fromEntries(Object.entries(data)) : void 0;
34803
- emit({
34804
- service: channel3,
34805
- level: level === "trace" ? "debug" : level,
34806
- message,
34807
- extra
34808
- });
34864
+ emit(
34865
+ {
34866
+ service: channel3,
34867
+ level: level === "trace" ? "debug" : level,
34868
+ message,
34869
+ extra
34870
+ },
34871
+ alwaysHost
34872
+ );
34809
34873
  }
34810
34874
  });
34875
+ const engine = createEngine3(false);
34876
+ const hostEngine = createEngine3(true);
34811
34877
  return {
34812
34878
  createLogger(module) {
34813
34879
  const channel3 = engine.createLogger(`antigravity.${module}`);
34880
+ const hostChannel = hostEngine.createLogger(`antigravity.${module}`);
34814
34881
  return {
34815
34882
  debug: (message, extra) => channel3.debug(message, extra),
34816
34883
  info: (message, extra) => channel3.info(message, extra),
34884
+ hostInfo: (message, extra) => hostChannel.info(message, extra),
34817
34885
  warn: (message, extra) => channel3.warn(message, extra),
34818
34886
  error: (message, extra) => channel3.error(message, extra)
34819
34887
  };
@@ -34827,10 +34895,10 @@ function createLocationLogger(options) {
34827
34895
  };
34828
34896
  }
34829
34897
  function createAppLogSink(client) {
34830
- return (record3) => {
34898
+ return (record4) => {
34831
34899
  const app = client.app;
34832
34900
  if (app && typeof app.log === "function") {
34833
- return app.log({ body: record3 });
34901
+ return app.log({ body: record4 });
34834
34902
  }
34835
34903
  return void 0;
34836
34904
  };
@@ -34843,7 +34911,7 @@ function isConsoleLogEnabled2() {
34843
34911
  }
34844
34912
  function getLegacyLogger() {
34845
34913
  legacyLogger ??= createLocationLogger({
34846
- sink: (record3) => legacyClient ? createAppLogSink(legacyClient)(record3) : void 0,
34914
+ sink: (record4) => legacyClient ? createAppLogSink(legacyClient)(record4) : void 0,
34847
34915
  sinkEnabled: isDebugTuiEnabled
34848
34916
  });
34849
34917
  return legacyLogger;
@@ -34864,6 +34932,10 @@ function createLogger4(module) {
34864
34932
  return {
34865
34933
  debug: (message, extra) => log17("debug", message, extra),
34866
34934
  info: (message, extra) => log17("info", message, extra),
34935
+ hostInfo: (message, extra) => {
34936
+ channel3 ??= getLegacyLogger().createLogger(module);
34937
+ channel3.hostInfo?.(message, extra);
34938
+ },
34867
34939
  warn: (message, extra) => log17("warn", message, extra),
34868
34940
  error: (message, extra) => log17("error", message, extra)
34869
34941
  };
@@ -34891,7 +34963,7 @@ var init_logger4 = __esm({
34891
34963
 
34892
34964
  // src/plugin/index.ts
34893
34965
  init_dist();
34894
- import { createHash as createHash24, randomUUID as randomUUID21 } from "node:crypto";
34966
+ import { createHash as createHash24, randomUUID as randomUUID22 } from "node:crypto";
34895
34967
  import { join as join39, resolve as resolve28 } from "node:path";
34896
34968
 
34897
34969
  // src/cli.ts
@@ -35231,17 +35303,17 @@ function normalizeSidebarState(input2) {
35231
35303
  if (!isObject(input2)) {
35232
35304
  return { ...DEFAULT_SIDEBAR_STATE, lastError: "shape" };
35233
35305
  }
35234
- const record3 = input2;
35235
- const version = record3.version;
35306
+ const record4 = input2;
35307
+ const version = record4.version;
35236
35308
  if (version !== 1 && version !== SIDEBAR_STATE_VERSION) {
35237
35309
  return {
35238
35310
  ...DEFAULT_SIDEBAR_STATE,
35239
35311
  lastError: `unsupported-version:${stringifySafe(version)}`
35240
35312
  };
35241
35313
  }
35242
- const accountsRaw = record3.accounts;
35314
+ const accountsRaw = record4.accounts;
35243
35315
  const accounts = Array.isArray(accountsRaw) ? accountsRaw.map((entry) => normalizeAccount(entry)).filter((entry) => entry !== null) : [];
35244
- const routingRaw = record3.activeRouting;
35316
+ const routingRaw = record4.activeRouting;
35245
35317
  const activeRouting = {};
35246
35318
  if (isObject(routingRaw)) {
35247
35319
  for (const [sessionId, entry] of Object.entries(
@@ -35251,10 +35323,10 @@ function normalizeSidebarState(input2) {
35251
35323
  if (normalized) activeRouting[sessionId] = normalized;
35252
35324
  }
35253
35325
  }
35254
- const checkedAt = toFiniteNumber(record3.checkedAt);
35255
- const routingAuthoritative = record3.routingAuthoritative === true;
35256
- const quotaBackoffUntil = toFiniteNumber(record3.quotaBackoffUntil);
35257
- const lastError = typeof record3.lastError === "string" ? record3.lastError : void 0;
35326
+ const checkedAt = toFiniteNumber(record4.checkedAt);
35327
+ const routingAuthoritative = record4.routingAuthoritative === true;
35328
+ const quotaBackoffUntil = toFiniteNumber(record4.quotaBackoffUntil);
35329
+ const lastError = typeof record4.lastError === "string" ? record4.lastError : void 0;
35258
35330
  return {
35259
35331
  version: SIDEBAR_STATE_VERSION,
35260
35332
  checkedAt: checkedAt ?? 0,
@@ -35267,15 +35339,15 @@ function normalizeSidebarState(input2) {
35267
35339
  }
35268
35340
  function normalizeAccount(input2) {
35269
35341
  if (!isObject(input2)) return null;
35270
- const record3 = input2;
35271
- const id = typeof record3.id === "string" ? record3.id : null;
35272
- const label = typeof record3.label === "string" ? record3.label : null;
35342
+ const record4 = input2;
35343
+ const id = typeof record4.id === "string" ? record4.id : null;
35344
+ const label = typeof record4.label === "string" ? record4.label : null;
35273
35345
  if (!id || !label) return null;
35274
- const enabled = record3.enabled !== false;
35275
- const health = clampNumber(toFiniteNumber(record3.health), 0, 100);
35276
- const current = record3.current === true;
35277
- const cooldownUntil = toFiniteNumber(record3.cooldownUntil) ?? void 0;
35278
- const quotaRaw = record3.quota;
35346
+ const enabled = record4.enabled !== false;
35347
+ const health = clampNumber(toFiniteNumber(record4.health), 0, 100);
35348
+ const current = record4.current === true;
35349
+ const cooldownUntil = toFiniteNumber(record4.cooldownUntil) ?? void 0;
35350
+ const quotaRaw = record4.quota;
35279
35351
  const quota = {};
35280
35352
  if (isObject(quotaRaw)) {
35281
35353
  for (const key of ["gemini", "non-gemini", "gemini-argon"]) {
@@ -35284,11 +35356,11 @@ function normalizeAccount(input2) {
35284
35356
  if (normalized) quota[key] = normalized;
35285
35357
  }
35286
35358
  }
35287
- const tier = normalizeTier(record3.tier);
35359
+ const tier = normalizeTier(record4.tier);
35288
35360
  return {
35289
35361
  id,
35290
35362
  label,
35291
- ...typeof record3.email === "string" ? { email: record3.email } : {},
35363
+ ...typeof record4.email === "string" ? { email: record4.email } : {},
35292
35364
  enabled,
35293
35365
  health,
35294
35366
  current,
@@ -35299,22 +35371,22 @@ function normalizeAccount(input2) {
35299
35371
  }
35300
35372
  function normalizeTier(input2) {
35301
35373
  if (!isObject(input2)) return void 0;
35302
- const record3 = input2;
35303
- const id = typeof record3.id === "string" && record3.id.length > 0 ? record3.id : null;
35304
- const capturedAt = toFiniteNumber(record3.capturedAt);
35374
+ const record4 = input2;
35375
+ const id = typeof record4.id === "string" && record4.id.length > 0 ? record4.id : null;
35376
+ const capturedAt = toFiniteNumber(record4.capturedAt);
35305
35377
  if (!id || capturedAt === null) return void 0;
35306
- const paidId = typeof record3.paidId === "string" && record3.paidId.length > 0 ? record3.paidId : void 0;
35378
+ const paidId = typeof record4.paidId === "string" && record4.paidId.length > 0 ? record4.paidId : void 0;
35307
35379
  return { id, ...paidId ? { paidId } : {}, capturedAt };
35308
35380
  }
35309
35381
  function normalizeQuota(input2) {
35310
35382
  if (!isObject(input2)) return null;
35311
- const record3 = input2;
35312
- const remaining = toFiniteNumber(record3.remainingPercent);
35313
- const fraction = toFiniteNumber(record3.remainingFraction);
35383
+ const record4 = input2;
35384
+ const remaining = toFiniteNumber(record4.remainingPercent);
35385
+ const fraction = toFiniteNumber(record4.remainingFraction);
35314
35386
  if (remaining === null) return null;
35315
- const resetAt = toFiniteNumber(record3.resetAt) ?? void 0;
35316
- const checkedAt = toFiniteNumber(record3.checkedAt) ?? void 0;
35317
- const windowsRaw = record3.windows;
35387
+ const resetAt = toFiniteNumber(record4.resetAt) ?? void 0;
35388
+ const checkedAt = toFiniteNumber(record4.checkedAt) ?? void 0;
35389
+ const windowsRaw = record4.windows;
35318
35390
  let windows2;
35319
35391
  if (Array.isArray(windowsRaw)) {
35320
35392
  const parsed = windowsRaw.filter(isObject).map((w) => {
@@ -35346,12 +35418,12 @@ function normalizeQuota(input2) {
35346
35418
  }
35347
35419
  function normalizeRouting(input2) {
35348
35420
  if (!isObject(input2)) return null;
35349
- const record3 = input2;
35350
- const accountId = typeof record3.accountId === "string" ? record3.accountId : null;
35351
- const modelFamily = record3.modelFamily;
35352
- const headerStyle = record3.headerStyle;
35353
- const strategy = record3.strategy;
35354
- const updatedAt = toFiniteNumber(record3.updatedAt) ?? 0;
35421
+ const record4 = input2;
35422
+ const accountId = typeof record4.accountId === "string" ? record4.accountId : null;
35423
+ const modelFamily = record4.modelFamily;
35424
+ const headerStyle = record4.headerStyle;
35425
+ const strategy = record4.strategy;
35426
+ const updatedAt = toFiniteNumber(record4.updatedAt) ?? 0;
35355
35427
  if (!accountId || modelFamily !== "claude" && modelFamily !== "gemini" || headerStyle !== "antigravity" && headerStyle !== "gemini-cli") {
35356
35428
  return null;
35357
35429
  }
@@ -36858,7 +36930,7 @@ function createStoreQuotaService(options) {
36858
36930
  fetchTimeoutMs: options.fetchTimeoutMs,
36859
36931
  sidebar: options.sidebar
36860
36932
  });
36861
- const record3 = async (target, result) => {
36933
+ const record4 = async (target, result) => {
36862
36934
  if (result.status !== "ok" || result.quota === void 0) {
36863
36935
  return { status: "failed", result };
36864
36936
  }
@@ -36892,7 +36964,7 @@ function createStoreQuotaService(options) {
36892
36964
  index,
36893
36965
  force: refreshOptions.force === true
36894
36966
  });
36895
- return record3(target, result);
36967
+ return record4(target, result);
36896
36968
  };
36897
36969
  return {
36898
36970
  quotaManager,
@@ -36946,7 +37018,7 @@ function createStoreQuotaService(options) {
36946
37018
  return Promise.all(
36947
37019
  results.map((result, position) => {
36948
37020
  const target = targets[position];
36949
- return target === void 0 ? { status: "failed", result } : record3(target, result);
37021
+ return target === void 0 ? { status: "failed", result } : record4(target, result);
36950
37022
  })
36951
37023
  );
36952
37024
  },
@@ -38617,6 +38689,25 @@ function validEnrollmentDisplayName2(displayName) {
38617
38689
  const length = Array.from(displayName).length;
38618
38690
  return length >= 1 && length <= 40 && !/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\u200b-\u200d\u2060\ufeff]/u.test(displayName);
38619
38691
  }
38692
+ function validEnrollmentRequestedGrants2(grants) {
38693
+ return Array.isArray(grants) && grants.length >= 1 && grants.length <= 4 && Array.from(grants).every((grant) => {
38694
+ if (!isRecord11(grant) || Object.keys(grant).length !== 2 || grant.operation !== "read" && grant.operation !== "list" || !isRecord11(grant.selector))
38695
+ return false;
38696
+ const keys = Object.keys(grant.selector);
38697
+ const key = keys[0];
38698
+ return keys.length === 1 && (key === "category" || key === "exact") && typeof grant.selector[key] === "string" && grant.selector[key].trim().length > 0;
38699
+ });
38700
+ }
38701
+ function grantProposal2(state) {
38702
+ return {
38703
+ ...state.requestedGrants !== void 0 && {
38704
+ requestedGrants: state.requestedGrants
38705
+ },
38706
+ ...state.requestedGrantsStatus !== void 0 && {
38707
+ requestedGrantsStatus: state.requestedGrantsStatus
38708
+ }
38709
+ };
38710
+ }
38620
38711
  function connectClaustrumEnrollmentClient2(options) {
38621
38712
  return ClaustrumWireClient2.connect(options);
38622
38713
  }
@@ -38652,6 +38743,7 @@ function decodeEnrollmentState2(value) {
38652
38743
  throw invalidState2();
38653
38744
  }
38654
38745
  if (value.phase === "pending") {
38746
+ const grants = decodeGrantProposal2(value);
38655
38747
  if (!TOKEN_RE2.test(String(value.requestSecret ?? "")) || value.requestId !== void 0 && (typeof value.requestId !== "string" || value.requestId.length === 0) || !validTimestamp2(value.createdAt) || !validTimestamp2(value.updatedAt)) {
38656
38748
  throw invalidState2();
38657
38749
  }
@@ -38664,10 +38756,12 @@ function decodeEnrollmentState2(value) {
38664
38756
  requestId: value.requestId
38665
38757
  },
38666
38758
  createdAt: value.createdAt,
38667
- updatedAt: value.updatedAt
38759
+ updatedAt: value.updatedAt,
38760
+ ...grants
38668
38761
  };
38669
38762
  }
38670
38763
  if (value.phase === "approved") {
38764
+ const grants = decodeGrantProposal2(value);
38671
38765
  if (value.approvedName !== void 0 && (typeof value.approvedName !== "string" || value.approvedName.length === 0) || !validGeneration2(value.tokenGeneration) || !validTimestamp2(value.updatedAt)) {
38672
38766
  throw invalidState2();
38673
38767
  }
@@ -38679,7 +38773,8 @@ function decodeEnrollmentState2(value) {
38679
38773
  approvedName: value.approvedName
38680
38774
  },
38681
38775
  tokenGeneration: value.tokenGeneration,
38682
- updatedAt: value.updatedAt
38776
+ updatedAt: value.updatedAt,
38777
+ ...grants
38683
38778
  };
38684
38779
  }
38685
38780
  if (value.phase === "denied" || value.phase === "blocked") {
@@ -38698,6 +38793,11 @@ function decodeEnrollmentState2(value) {
38698
38793
  }
38699
38794
  throw invalidState2();
38700
38795
  }
38796
+ function decodeGrantProposal2(value) {
38797
+ if (value.requestedGrants !== void 0 && !validEnrollmentRequestedGrants2(value.requestedGrants) || value.requestedGrantsStatus !== void 0 && (value.requestedGrants === void 0 || value.requestedGrantsStatus !== "sent" && value.requestedGrantsStatus !== "dropped"))
38798
+ return {};
38799
+ return grantProposal2(value);
38800
+ }
38701
38801
  function decodeTokenFile2(value) {
38702
38802
  if (!isRecord11(value) || !TOKEN_RE2.test(String(value.token ?? "")) || !validGeneration2(value.token_generation)) {
38703
38803
  throw new ClaustrumConsumerError2("invalid-token", "invalid Claustrum enrollment token file");
@@ -38912,7 +39012,8 @@ async function readEnrollmentStatus2(paths, proposedName) {
38912
39012
  ...state?.phase === "approved" && state.approvedName !== void 0 && {
38913
39013
  approvedName: state.approvedName
38914
39014
  },
38915
- tokenGeneration: token.token_generation
39015
+ tokenGeneration: token.token_generation,
39016
+ ...state && (state.phase === "approved" || state.phase === "pending") && grantProposal2(state)
38916
39017
  }
38917
39018
  };
38918
39019
  }
@@ -38960,12 +39061,19 @@ async function vaultAuthority3(paths, proposedName) {
38960
39061
  return "host";
38961
39062
  return enrollmentAuthority2(paths, proposedName);
38962
39063
  }
39064
+ async function readClaustrumEnrollmentToken2(tokenPath) {
39065
+ const value = await readBoundedJson2(tokenPath);
39066
+ if (value === void 0)
39067
+ throw new ClaustrumConsumerError2("not-enrolled", "Claustrum enrollment is not configured");
39068
+ return decodeTokenFile2(value);
39069
+ }
38963
39070
  function statusFromState2(state) {
38964
39071
  if (state.phase === "pending") {
38965
39072
  return {
38966
39073
  state: "pending",
38967
39074
  proposedName: state.proposedName,
38968
- ...state.requestId !== void 0 && { requestId: state.requestId }
39075
+ ...state.requestId !== void 0 && { requestId: state.requestId },
39076
+ ...grantProposal2(state)
38969
39077
  };
38970
39078
  }
38971
39079
  if (state.phase === "approved") {
@@ -38975,7 +39083,8 @@ function statusFromState2(state) {
38975
39083
  ...state.approvedName !== void 0 && {
38976
39084
  approvedName: state.approvedName
38977
39085
  },
38978
- tokenGeneration: state.tokenGeneration
39086
+ tokenGeneration: state.tokenGeneration,
39087
+ ...grantProposal2(state)
38979
39088
  };
38980
39089
  }
38981
39090
  if (state.phase === "denied")
@@ -38994,6 +39103,7 @@ var ClaustrumEnrollmentManager2 = class {
38994
39103
  #paths;
38995
39104
  #proposedName;
38996
39105
  #displayName;
39106
+ #requestedGrants;
38997
39107
  #now;
38998
39108
  #mintSecret;
38999
39109
  #writeTokenFile;
@@ -39001,6 +39111,12 @@ var ClaustrumEnrollmentManager2 = class {
39001
39111
  constructor(options) {
39002
39112
  if (options.displayName !== void 0 && !validEnrollmentDisplayName2(options.displayName))
39003
39113
  throw new ClaustrumConsumerError2("invalid-state", "invalid Claustrum enrollment display name");
39114
+ if (options.requestedGrants !== void 0 && !validEnrollmentRequestedGrants2(options.requestedGrants))
39115
+ throw new ClaustrumConsumerError2("invalid-state", "invalid Claustrum enrollment requested grants");
39116
+ this.#requestedGrants = options.requestedGrants?.map((grant) => ({
39117
+ selector: { ...grant.selector },
39118
+ operation: grant.operation
39119
+ }));
39004
39120
  this.#ancestorOptions = options.ancestorOptions ?? {};
39005
39121
  this.#client = options.client;
39006
39122
  this.#paths = options.paths;
@@ -39051,6 +39167,7 @@ var ClaustrumEnrollmentManager2 = class {
39051
39167
  phase: "approved",
39052
39168
  proposedName: state?.proposedName ?? this.#proposedName,
39053
39169
  tokenGeneration: token.token_generation,
39170
+ ...state && grantProposal2(state),
39054
39171
  updatedAt: this.#now()
39055
39172
  };
39056
39173
  await writeStateAtomic2(this.#paths.statePath, approved, this.#ancestorOptions);
@@ -39062,7 +39179,8 @@ var ClaustrumEnrollmentManager2 = class {
39062
39179
  ...state.phase === "approved" && state.approvedName !== void 0 && {
39063
39180
  approvedName: state.approvedName
39064
39181
  },
39065
- tokenGeneration: token.token_generation
39182
+ tokenGeneration: token.token_generation,
39183
+ ...state.phase === "approved" && grantProposal2(state)
39066
39184
  };
39067
39185
  }
39068
39186
  if (state?.phase === "approved") {
@@ -39086,7 +39204,10 @@ var ClaustrumEnrollmentManager2 = class {
39086
39204
  proposedName: this.#proposedName,
39087
39205
  requestSecret: this.#mintSecret(),
39088
39206
  createdAt: now,
39089
- updatedAt: now
39207
+ updatedAt: now,
39208
+ ...this.#requestedGrants !== void 0 && {
39209
+ requestedGrants: this.#requestedGrants
39210
+ }
39090
39211
  };
39091
39212
  if (!TOKEN_RE2.test(state.requestSecret))
39092
39213
  throw new ClaustrumConsumerError2("invalid-state", "invalid minted Claustrum enrollment secret");
@@ -39100,22 +39221,33 @@ var ClaustrumEnrollmentManager2 = class {
39100
39221
  requestSecretHash
39101
39222
  };
39102
39223
  let proposed;
39224
+ let requestedGrantsStatus = state.requestedGrantsStatus;
39103
39225
  try {
39104
39226
  proposed = await this.#client.enrollPropose({
39105
39227
  ...proposal,
39106
39228
  ...this.#displayName !== void 0 && {
39107
39229
  displayName: this.#displayName
39230
+ },
39231
+ ...state.requestedGrants !== void 0 && {
39232
+ requestedGrants: state.requestedGrants
39108
39233
  }
39109
39234
  });
39235
+ if (state.requestedGrants !== void 0)
39236
+ requestedGrantsStatus = "sent";
39110
39237
  } catch (error) {
39111
- if (this.#displayName === void 0 || !(error instanceof ClaustrumCredentialError9) || error.code !== "invalid_params")
39238
+ if (this.#displayName === void 0 && state.requestedGrants === void 0 || !(error instanceof ClaustrumCredentialError9) || error.code !== "invalid_params")
39112
39239
  throw error;
39113
39240
  proposed = await this.#client.enrollPropose(proposal);
39241
+ if (state.requestedGrants !== void 0)
39242
+ requestedGrantsStatus = "dropped";
39114
39243
  }
39115
39244
  state = {
39116
39245
  ...state,
39117
39246
  requestId: proposed.requestId,
39118
- updatedAt: this.#now()
39247
+ updatedAt: this.#now(),
39248
+ ...requestedGrantsStatus !== void 0 && {
39249
+ requestedGrantsStatus
39250
+ }
39119
39251
  };
39120
39252
  await writeStateAtomic2(this.#paths.statePath, state, this.#ancestorOptions);
39121
39253
  } catch (error) {
@@ -39126,7 +39258,8 @@ var ClaustrumEnrollmentManager2 = class {
39126
39258
  return {
39127
39259
  state: "pending",
39128
39260
  proposedName: state.proposedName,
39129
- retryCode: refusal3.code
39261
+ retryCode: refusal3.code,
39262
+ ...grantProposal2(state)
39130
39263
  };
39131
39264
  }
39132
39265
  if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE2) {
@@ -39176,6 +39309,7 @@ var ClaustrumEnrollmentManager2 = class {
39176
39309
  proposedName: state.proposedName,
39177
39310
  approvedName: outcome.name,
39178
39311
  tokenGeneration: outcome.tokenGeneration,
39312
+ ...grantProposal2(state),
39179
39313
  updatedAt: this.#now()
39180
39314
  };
39181
39315
  await writeStateAtomic2(this.#paths.statePath, approved, this.#ancestorOptions);
@@ -39189,7 +39323,8 @@ var ClaustrumEnrollmentManager2 = class {
39189
39323
  state: "pending",
39190
39324
  proposedName: state.proposedName,
39191
39325
  requestId,
39192
- retryCode: refusal3.code
39326
+ retryCode: refusal3.code,
39327
+ ...grantProposal2(state)
39193
39328
  };
39194
39329
  }
39195
39330
  return this.#block(state, refusal3.code);
@@ -39368,6 +39503,68 @@ function runResolvedCommand(runner, platform, file, args, env3, timeoutMs = 15e3
39368
39503
  return runner.run(file, args, { env: env3, timeoutMs });
39369
39504
  }
39370
39505
 
39506
+ // src/common-auth-embedded/setup/enrollment-access.js
39507
+ function shellArgument(value) {
39508
+ if (/^[a-zA-Z0-9_:@./-]+$/.test(value))
39509
+ return value;
39510
+ return process.platform === "win32" ? `'${value.replaceAll("'", "''")}'` : `'${value.replaceAll("'", "'\\''")}'`;
39511
+ }
39512
+ async function confirmEnrollmentAccess(client, status, tokenPath, configuredGrants) {
39513
+ const requestedGrants = status.requestedGrants ?? configuredGrants;
39514
+ if (!requestedGrants)
39515
+ return void 0;
39516
+ const grants = requestedGrants.map((grant) => ({
39517
+ grant,
39518
+ ...status.approvedName !== void 0 && {
39519
+ grantCommand: `ck auth grant --principal ${shellArgument(`enrolled:${status.approvedName}`)} --selector-kind ${grant.selector.exact === void 0 ? "category" : "exact"} --selector ${shellArgument(grant.selector.exact ?? grant.selector.category)} --operation ${grant.operation}`
39520
+ }
39521
+ }));
39522
+ if (status.requestedGrantsStatus === "dropped")
39523
+ return { state: "older-vault", grants };
39524
+ try {
39525
+ if (!client.listScoped)
39526
+ return { state: "unconfirmed", grants };
39527
+ const { token } = await readClaustrumEnrollmentToken2(tokenPath);
39528
+ const inventory = await client.listScoped(token);
39529
+ const confirmed = grants.map((entry) => ({
39530
+ ...entry,
39531
+ reachableLogins: inventory.rows.filter((row) => row.operations.includes(entry.grant.operation) && (entry.grant.selector.exact !== void 0 ? row.id === entry.grant.selector.exact : row.categories.includes(entry.grant.selector.category))).length
39532
+ }));
39533
+ return {
39534
+ state: confirmed.every((entry) => entry.reachableLogins > 0) ? "reachable" : confirmed.some((entry) => entry.reachableLogins > 0) ? "partial" : "no-logins",
39535
+ grants: confirmed.map((entry) => {
39536
+ if (entry.reachableLogins === 0)
39537
+ return entry;
39538
+ const { grantCommand: _, ...reachable } = entry;
39539
+ return reachable;
39540
+ })
39541
+ };
39542
+ } catch {
39543
+ return { state: "unconfirmed", grants };
39544
+ }
39545
+ }
39546
+ function enrollmentAccessLines(access) {
39547
+ const lines = [];
39548
+ const remedy = access.grants.some((entry) => entry.grantCommand) ? "run:" : "check ck auth status for the approved name before granting access.";
39549
+ if (access.state === "older-vault")
39550
+ lines.push(`Approved. This vault is too old to grant access with the approval; ${remedy}`);
39551
+ else if (access.state === "no-logins")
39552
+ lines.push(`Approved, but no logins are reachable yet; ${remedy}`);
39553
+ else if (access.state === "partial")
39554
+ lines.push(`Approved, but some requested access has no reachable logins yet; ${remedy}`);
39555
+ else if (access.state === "unconfirmed")
39556
+ lines.push(`Approved, but access could not be confirmed; ${access.grants.some((entry) => entry.grantCommand) ? "check ck auth status or run:" : remedy}`);
39557
+ for (const { grant, reachableLogins, grantCommand } of access.grants) {
39558
+ if (reachableLogins !== void 0 && reachableLogins > 0) {
39559
+ const target = grant.selector.exact === void 0 ? `the vault's ${JSON.stringify(grant.selector.category)} accounts` : `credential ${JSON.stringify(grant.selector.exact)}`;
39560
+ lines.push(`Confirmed ${grant.operation} access to ${target} (${reachableLogins} reachable ${reachableLogins === 1 ? "login" : "logins"}).`);
39561
+ }
39562
+ if (grantCommand)
39563
+ lines.push(` ${grantCommand}`);
39564
+ }
39565
+ return lines;
39566
+ }
39567
+
39371
39568
  // src/common-auth-embedded/setup/command-error.js
39372
39569
  var PI_INSTALL_ERROR_MESSAGE = "Pi install failed; run pi install after checking your npm connection.";
39373
39570
  function utf8Tail(value) {
@@ -39408,8 +39605,8 @@ var OUTCOME_TEXT = {
39408
39605
  "not-enrolled": "not connected",
39409
39606
  unknown: "unknown, check with ck auth status"
39410
39607
  };
39411
- function setupEnrollmentLine({ host, outcome }) {
39412
- return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}`;
39608
+ function setupEnrollmentLine({ host, outcome, access }) {
39609
+ return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}${access ? ` \u2014 ${enrollmentAccessLines(access).join("\n")}` : ""}`;
39413
39610
  }
39414
39611
  var recordedEnrollment = /* @__PURE__ */ new WeakMap();
39415
39612
  function recordSetupEnrollment(failure2, enrollment) {
@@ -39947,7 +40144,7 @@ function approveCommand(requestId, name) {
39947
40144
  async function connectSetupHost(plugin, host, io, terminal, fence) {
39948
40145
  if (hasVaultHost2())
39949
40146
  throw new Error(VAULT_HOST_CONNECT_REFUSAL2);
39950
- const { name, displayName, paths: input2 } = plugin.vault.hosts[host];
40147
+ const { name, displayName, requestedGrants, paths: input2 } = plugin.vault.hosts[host];
39951
40148
  const paths = hostEnrollmentPaths2(input2);
39952
40149
  await fence();
39953
40150
  const client = await (io.connect ?? connectClaustrumEnrollmentClient2)({
@@ -39962,6 +40159,7 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
39962
40159
  const manager = new ClaustrumEnrollmentManager2({
39963
40160
  proposedName: name,
39964
40161
  displayName,
40162
+ requestedGrants,
39965
40163
  paths,
39966
40164
  // Each tick of the wait below checks the fence once, just before
39967
40165
  // reconcile proposes or polls. Checking again inside every vault call
@@ -39977,7 +40175,11 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
39977
40175
  const initial = await manager.status();
39978
40176
  if (initial.state === "approved") {
39979
40177
  printLine2(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
39980
- return;
40178
+ const access = await confirmEnrollmentAccess(client, initial, paths.tokenPath, requestedGrants);
40179
+ if (access)
40180
+ for (const line of enrollmentAccessLines(access))
40181
+ printLine2(terminal, line);
40182
+ return access;
39981
40183
  }
39982
40184
  printLine2(terminal, `Asking the vault to connect ${name}\u2026`);
39983
40185
  const deadline = now() + ENROLLMENT_WAIT_MS;
@@ -39989,7 +40191,11 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
39989
40191
  const status = await manager.reconcile();
39990
40192
  if (status.state === "approved") {
39991
40193
  printLine2(terminal, `Connected ${host} to Claustrum.`);
39992
- return;
40194
+ const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
40195
+ if (access)
40196
+ for (const line of enrollmentAccessLines(access))
40197
+ printLine2(terminal, line);
40198
+ return access;
39993
40199
  }
39994
40200
  if (status.state === "unavailable" && status.code === UNSUPPORTED_ENROLLMENT_CODE2)
39995
40201
  throw new HostNotEnrolledError(UNSUPPORTED_VAULT_MESSAGE, {
@@ -40423,12 +40629,15 @@ function validatePlugin(plugin) {
40423
40629
  for (const host of Object.values(plugin.vault.hosts)) {
40424
40630
  if (!/^[a-z0-9][a-z0-9-]*$/.test(host.name))
40425
40631
  throw new Error("Setup requires lowercase vault names containing only letters, digits and dashes.");
40632
+ if (host.requestedGrants !== void 0 && !validEnrollmentRequestedGrants2(host.requestedGrants))
40633
+ throw new Error("invalid Claustrum enrollment requested grants");
40426
40634
  }
40427
40635
  }
40428
- async function enrollmentReport(plugin, hosts, recorded) {
40636
+ async function enrollmentReport(plugin, hosts, recorded, recordedAccess) {
40429
40637
  const report = [];
40430
40638
  for (const host of hosts) {
40431
40639
  let outcome = recorded.get(host) ?? "not-enrolled";
40640
+ let access = recordedAccess.get(host);
40432
40641
  if (outcome === "unknown") {
40433
40642
  const { name, paths } = plugin.vault.hosts[host];
40434
40643
  const authority = await vaultAuthority3(hostEnrollmentPaths2(paths), name).catch(() => "unreadable");
@@ -40436,8 +40645,13 @@ async function enrollmentReport(plugin, hosts, recorded) {
40436
40645
  outcome = "enrolled";
40437
40646
  else if (authority === "local")
40438
40647
  outcome = "not-enrolled";
40648
+ if (outcome === "enrolled") {
40649
+ const status = await readClaustrumEnrollmentStatus2(hostEnrollmentPaths2(paths), name).catch(() => void 0);
40650
+ if (status?.state === "approved")
40651
+ access = await confirmEnrollmentAccess({}, status, hostEnrollmentPaths2(paths).tokenPath, plugin.vault.hosts[host].requestedGrants);
40652
+ }
40439
40653
  }
40440
- report.push({ host, outcome });
40654
+ report.push({ host, outcome, ...access && { access } });
40441
40655
  }
40442
40656
  return report;
40443
40657
  }
@@ -40566,6 +40780,7 @@ ${write.content}`);
40566
40780
  piAgentDir: detection.pi.directory
40567
40781
  };
40568
40782
  const enrollment = /* @__PURE__ */ new Map();
40783
+ const enrollmentAccess = /* @__PURE__ */ new Map();
40569
40784
  try {
40570
40785
  for (const host of hosts) {
40571
40786
  await stopped();
@@ -40574,7 +40789,9 @@ ${write.content}`);
40574
40789
  if (useVault) {
40575
40790
  enrollment.set(host, "unknown");
40576
40791
  try {
40577
- await connectSetupHost(plugin, host, io, terminal, stopped);
40792
+ const access = await connectSetupHost(plugin, host, io, terminal, stopped);
40793
+ if (access)
40794
+ enrollmentAccess.set(host, access);
40578
40795
  } catch (error) {
40579
40796
  if (error instanceof HostNotEnrolledError)
40580
40797
  enrollment.set(host, "not-enrolled");
@@ -40599,7 +40816,7 @@ ${write.content}`);
40599
40816
  if (enrollment.size === 0)
40600
40817
  throw error;
40601
40818
  try {
40602
- const report = await enrollmentReport(plugin, hosts, enrollment);
40819
+ const report = await enrollmentReport(plugin, hosts, enrollment, enrollmentAccess);
40603
40820
  recordSetupEnrollment(error, report);
40604
40821
  for (const entry of report)
40605
40822
  printLine2(terminal, setupEnrollmentLine(entry));
@@ -40790,6 +41007,12 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
40790
41007
  opencode: {
40791
41008
  name: OPENCODE_VAULT_ENROLLMENT_NAME,
40792
41009
  displayName: "Antigravity sign-in for OpenCode",
41010
+ requestedGrants: [
41011
+ {
41012
+ selector: { category: "antigravity-native" },
41013
+ operation: "read"
41014
+ }
41015
+ ],
40793
41016
  // Read at each use: a real run settles the vault folder in
40794
41017
  // `beforeSignIn`, which may move it after this plugin is built.
40795
41018
  paths: {
@@ -40802,6 +41025,12 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
40802
41025
  pi: {
40803
41026
  name: "antigravity-auth-pi",
40804
41027
  displayName: "Antigravity sign-in for Pi",
41028
+ requestedGrants: [
41029
+ {
41030
+ selector: { category: "antigravity-native" },
41031
+ operation: "read"
41032
+ }
41033
+ ],
40805
41034
  paths: { stateDir: piDir, host: "pi" }
40806
41035
  }
40807
41036
  };
@@ -48299,11 +48528,11 @@ function redactForDump(value) {
48299
48528
  function headersToRecord2(headers) {
48300
48529
  if (!headers) return {};
48301
48530
  if (headers instanceof Headers) {
48302
- const record3 = {};
48531
+ const record4 = {};
48303
48532
  headers.forEach((value, key) => {
48304
- record3[key] = value;
48533
+ record4[key] = value;
48305
48534
  });
48306
- return record3;
48535
+ return record4;
48307
48536
  }
48308
48537
  if (Array.isArray(headers)) return Object.fromEntries(headers);
48309
48538
  return { ...headers };
@@ -48324,8 +48553,8 @@ function collectToolNames(value) {
48324
48553
  return;
48325
48554
  }
48326
48555
  if (!entry || typeof entry !== "object") return;
48327
- const record3 = entry;
48328
- const declarations = record3.functionDeclarations;
48556
+ const record4 = entry;
48557
+ const declarations = record4.functionDeclarations;
48329
48558
  if (Array.isArray(declarations)) {
48330
48559
  for (const declaration of declarations) {
48331
48560
  if (declaration && typeof declaration === "object") {
@@ -48334,7 +48563,7 @@ function collectToolNames(value) {
48334
48563
  }
48335
48564
  }
48336
48565
  }
48337
- for (const item of Object.values(record3)) walk(item);
48566
+ for (const item of Object.values(record4)) walk(item);
48338
48567
  };
48339
48568
  walk(value);
48340
48569
  return names;
@@ -49641,9 +49870,9 @@ function normalizeThinkingConfig(config) {
49641
49870
  if (!config || typeof config !== "object") {
49642
49871
  return void 0;
49643
49872
  }
49644
- const record3 = config;
49645
- const budgetRaw = record3.thinkingBudget ?? record3.thinking_budget;
49646
- const includeRaw = record3.includeThoughts ?? record3.include_thoughts;
49873
+ const record4 = config;
49874
+ const budgetRaw = record4.thinkingBudget ?? record4.thinking_budget;
49875
+ const includeRaw = record4.includeThoughts ?? record4.include_thoughts;
49647
49876
  const thinkingBudget = typeof budgetRaw === "number" && Number.isFinite(budgetRaw) ? budgetRaw : void 0;
49648
49877
  const includeThoughts = typeof includeRaw === "boolean" ? includeRaw : void 0;
49649
49878
  const enableThinking = thinkingBudget !== void 0 && thinkingBudget > 0;
@@ -50525,8 +50754,8 @@ function collectForwardedHeaders(sourceHeaders) {
50525
50754
  if (typeof sourceHeaders.get === "function") {
50526
50755
  return sourceHeaders.get(name);
50527
50756
  }
50528
- const record3 = sourceHeaders;
50529
- for (const [key, value] of Object.entries(record3)) {
50757
+ const record4 = sourceHeaders;
50758
+ for (const [key, value] of Object.entries(record4)) {
50530
50759
  if (key.toLowerCase() === name) return value;
50531
50760
  }
50532
50761
  return void 0;
@@ -50563,14 +50792,14 @@ function hasStructuredQuotaReason(details) {
50563
50792
  if (!Array.isArray(details)) return false;
50564
50793
  return details.some((detail) => {
50565
50794
  if (!detail || typeof detail !== "object") return false;
50566
- const record3 = detail;
50567
- const type = record3["@type"];
50795
+ const record4 = detail;
50796
+ const type = record4["@type"];
50568
50797
  if (typeof type === "string" && type.includes("google.rpc.QuotaFailure"))
50569
50798
  return true;
50570
- const reason = record3.reason;
50799
+ const reason = record4.reason;
50571
50800
  if (typeof reason === "string" && QUOTA_REASON_CODES.has(reason))
50572
50801
  return true;
50573
- const nested = record3.details;
50802
+ const nested = record4.details;
50574
50803
  return Array.isArray(nested) ? hasStructuredQuotaReason(nested) : false;
50575
50804
  });
50576
50805
  }
@@ -50756,8 +50985,8 @@ function resolveRetryMetadata(options) {
50756
50985
  if (typeof headers.get === "function") {
50757
50986
  return headers.get(name);
50758
50987
  }
50759
- const record3 = headers;
50760
- for (const [key, value] of Object.entries(record3)) {
50988
+ const record4 = headers;
50989
+ for (const [key, value] of Object.entries(record4)) {
50761
50990
  if (key.toLowerCase() === name) return value;
50762
50991
  }
50763
50992
  return void 0;
@@ -50884,14 +51113,14 @@ function stripAllThinkingBlocks2(contents) {
50884
51113
  });
50885
51114
  }
50886
51115
  function countTrailingToolResults(contents) {
50887
- let count3 = 0;
51116
+ let count4 = 0;
50888
51117
  for (let i = contents.length - 1; i >= 0; i--) {
50889
51118
  const msg = contents[i];
50890
51119
  if (msg?.role === "user") {
50891
51120
  const parts = msg.parts || [];
50892
51121
  const functionResponses = parts.filter(isFunctionResponsePart);
50893
51122
  if (functionResponses.length > 0) {
50894
- count3 += functionResponses.length;
51123
+ count4 += functionResponses.length;
50895
51124
  } else {
50896
51125
  break;
50897
51126
  }
@@ -50899,7 +51128,7 @@ function countTrailingToolResults(contents) {
50899
51128
  break;
50900
51129
  }
50901
51130
  }
50902
- return count3;
51131
+ return count4;
50903
51132
  }
50904
51133
  function closeToolLoopForThinking(contents) {
50905
51134
  const strippedContents = stripAllThinkingBlocks2(contents);
@@ -51225,12 +51454,12 @@ function stripInjectedDebugFromParts(parts) {
51225
51454
  if (!part || typeof part !== "object") {
51226
51455
  return part;
51227
51456
  }
51228
- const record3 = part;
51229
- const text2 = typeof record3.text === "string" ? record3.text : typeof record3.thinking === "string" ? record3.thinking : void 0;
51457
+ const record4 = part;
51458
+ const text2 = typeof record4.text === "string" ? record4.text : typeof record4.thinking === "string" ? record4.thinking : void 0;
51230
51459
  if (text2 && (text2.startsWith(DEBUG_MESSAGE_PREFIX) || text2.startsWith(SYNTHETIC_THINKING_PLACEHOLDER.trim()))) {
51231
51460
  const sentinel = { text: "." };
51232
- if (record3.cache_control !== void 0)
51233
- sentinel.cache_control = record3.cache_control;
51461
+ if (record4.cache_control !== void 0)
51462
+ sentinel.cache_control = record4.cache_control;
51234
51463
  return sentinel;
51235
51464
  }
51236
51465
  return part;
@@ -51274,8 +51503,8 @@ function isValidRequestPart(part) {
51274
51503
  if (!part || typeof part !== "object") {
51275
51504
  return false;
51276
51505
  }
51277
- const record3 = part;
51278
- return Object.hasOwn(record3, "text") || Object.hasOwn(record3, "functionCall") || Object.hasOwn(record3, "functionResponse") || Object.hasOwn(record3, "inlineData") || Object.hasOwn(record3, "fileData") || Object.hasOwn(record3, "executableCode") || Object.hasOwn(record3, "codeExecutionResult") || Object.hasOwn(record3, "thought");
51506
+ const record4 = part;
51507
+ return Object.hasOwn(record4, "text") || Object.hasOwn(record4, "functionCall") || Object.hasOwn(record4, "functionResponse") || Object.hasOwn(record4, "inlineData") || Object.hasOwn(record4, "fileData") || Object.hasOwn(record4, "executableCode") || Object.hasOwn(record4, "codeExecutionResult") || Object.hasOwn(record4, "thought");
51279
51508
  }
51280
51509
  function stripCacheControlFromParts(parts) {
51281
51510
  if (!Array.isArray(parts)) {
@@ -51285,9 +51514,9 @@ function stripCacheControlFromParts(parts) {
51285
51514
  if (!part || typeof part !== "object" || Array.isArray(part)) {
51286
51515
  continue;
51287
51516
  }
51288
- const record3 = part;
51289
- delete record3.cache_control;
51290
- delete record3.cacheControl;
51517
+ const record4 = part;
51518
+ delete record4.cache_control;
51519
+ delete record4.cacheControl;
51291
51520
  }
51292
51521
  }
51293
51522
  function stripUnsupportedAntigravityFields(payload) {
@@ -51315,9 +51544,9 @@ function stripUnsupportedAntigravityFields(payload) {
51315
51544
  if (!item || typeof item !== "object" || Array.isArray(item)) {
51316
51545
  continue;
51317
51546
  }
51318
- const record3 = item;
51319
- stripCacheControlFromParts(record3.parts);
51320
- stripCacheControlFromParts(record3.content);
51547
+ const record4 = item;
51548
+ stripCacheControlFromParts(record4.parts);
51549
+ stripCacheControlFromParts(record4.content);
51321
51550
  }
51322
51551
  };
51323
51552
  stripContentParts(payload.contents);
@@ -51365,14 +51594,14 @@ function normalizeNativeFunctionResponseRoles(payload) {
51365
51594
  }
51366
51595
  for (const content of contents) {
51367
51596
  if (!content || typeof content !== "object") continue;
51368
- const record3 = content;
51369
- if (record3.role !== "user" || !Array.isArray(record3.parts)) continue;
51370
- if (record3.parts.length === 0) continue;
51371
- const sameTarget = record3.parts.every((part) => {
51597
+ const record4 = content;
51598
+ if (record4.role !== "user" || !Array.isArray(record4.parts)) continue;
51599
+ if (record4.parts.length === 0) continue;
51600
+ const sameTarget = record4.parts.every((part) => {
51372
51601
  const response = part?.functionResponse;
51373
51602
  return response !== void 0 && signedCalls.has(String(response.id ?? response.name));
51374
51603
  });
51375
- if (sameTarget) record3.role = "model";
51604
+ if (sameTarget) record4.role = "model";
51376
51605
  }
51377
51606
  }
51378
51607
  function sanitizeRequestPayloadForAntigravity(payload) {
@@ -51466,10 +51695,10 @@ function sanitizeRequestPayloadForAntigravity(payload) {
51466
51695
  if (Array.isArray(sys.parts)) {
51467
51696
  const sanitizedSystemParts = sys.parts.map((part) => {
51468
51697
  if (isValidRequestPart(part)) return part;
51469
- const record3 = part;
51698
+ const record4 = part;
51470
51699
  const sentinel = { text: "." };
51471
- if (record3?.cache_control !== void 0)
51472
- sentinel.cache_control = record3.cache_control;
51700
+ if (record4?.cache_control !== void 0)
51701
+ sentinel.cache_control = record4.cache_control;
51473
51702
  return sentinel;
51474
51703
  });
51475
51704
  const hasRealContent = sanitizedSystemParts.some(
@@ -55060,9 +55289,9 @@ function billingUsage(value) {
55060
55289
  ["cacheWrite1h", "cache_write_1h"],
55061
55290
  ["reasoning", "reasoning"]
55062
55291
  ]) {
55063
- const count3 = value[inputKey];
55064
- if (typeof count3 === "number" && Number.isSafeInteger(count3) && count3 >= 0) {
55065
- usage[payloadKey] = count3;
55292
+ const count4 = value[inputKey];
55293
+ if (typeof count4 === "number" && Number.isSafeInteger(count4) && count4 >= 0) {
55294
+ usage[payloadKey] = count4;
55066
55295
  }
55067
55296
  }
55068
55297
  const reasoningIncludedInOutput = value.reasoningIncludedInOutput;
@@ -55770,6 +55999,175 @@ var AgySessionRegistry = class {
55770
55999
  }
55771
56000
  };
55772
56001
 
56002
+ // src/plugin/shared/vault-billing.ts
56003
+ import { randomUUID as randomUUID21 } from "node:crypto";
56004
+ function record3(value) {
56005
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
56006
+ }
56007
+ function count3(value) {
56008
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
56009
+ }
56010
+ function geminiBillingUsage(value) {
56011
+ const meta = record3(value);
56012
+ if (!meta) return void 0;
56013
+ const usage = {};
56014
+ const prompt = meta.promptTokenCount;
56015
+ const cached = meta.cachedContentTokenCount;
56016
+ if (count3(prompt) && (cached === void 0 || count3(cached) && cached <= prompt))
56017
+ usage.input = prompt - (count3(cached) ? cached : 0);
56018
+ if (count3(cached)) usage.cacheRead = cached;
56019
+ if (count3(meta.candidatesTokenCount)) usage.output = meta.candidatesTokenCount;
56020
+ if (count3(meta.thoughtsTokenCount)) usage.reasoning = meta.thoughtsTokenCount;
56021
+ if (Object.keys(usage).length === 0) return void 0;
56022
+ usage.reasoningIncludedInOutput = false;
56023
+ return usage;
56024
+ }
56025
+ var VaultBillingAttempt = class {
56026
+ constructor(sessionId, receipt2, requestKind, model, attempt, signal) {
56027
+ this.sessionId = sessionId;
56028
+ this.receipt = receipt2;
56029
+ this.requestKind = requestKind;
56030
+ this.model = model;
56031
+ this.attempt = attempt;
56032
+ this.signal = signal;
56033
+ signal?.addEventListener("abort", this.aborted, { once: true });
56034
+ }
56035
+ sessionId;
56036
+ receipt;
56037
+ requestKind;
56038
+ model;
56039
+ attempt;
56040
+ signal;
56041
+ attemptId = randomUUID21();
56042
+ reported = false;
56043
+ started = false;
56044
+ terminal = false;
56045
+ failed = false;
56046
+ status;
56047
+ metadata;
56048
+ aborted = () => this.end(false);
56049
+ event(value) {
56050
+ const outer = record3(value);
56051
+ if (!outer) return;
56052
+ const response = record3(outer.response) ?? outer;
56053
+ if (outer.error || response.error || outer.type === "error")
56054
+ this.failed = true;
56055
+ const meta = record3(response.usageMetadata);
56056
+ if (meta) this.metadata = { ...this.metadata, ...meta };
56057
+ if (Array.isArray(response.candidates))
56058
+ this.terminal ||= response.candidates.some(
56059
+ (candidate) => typeof record3(candidate)?.finishReason === "string"
56060
+ );
56061
+ }
56062
+ /** Tap raw bytes before the wire transformer can inject synthetic zero usage. */
56063
+ observe(response) {
56064
+ this.status = response.status;
56065
+ if (!response.ok) {
56066
+ this.failed = true;
56067
+ this.end(false);
56068
+ return response;
56069
+ }
56070
+ if (!response.body) {
56071
+ this.end(true);
56072
+ return response;
56073
+ }
56074
+ const sse = response.headers.get("content-type")?.includes("text/event-stream");
56075
+ const reader = response.body.getReader();
56076
+ const decoder = new TextDecoder();
56077
+ let pending = "";
56078
+ let oversized = false;
56079
+ const inspect = (line) => {
56080
+ if (line.length > 1024 * 1024 || this.reported) return;
56081
+ if (sse && line.startsWith("event:") && line.slice(6).trim() === "error")
56082
+ this.failed = true;
56083
+ if (sse && !line.startsWith("data:")) return;
56084
+ try {
56085
+ this.event(JSON.parse(sse ? line.slice(5).trim() : line));
56086
+ } catch {
56087
+ }
56088
+ };
56089
+ const body = new ReadableStream(
56090
+ {
56091
+ pull: async (controller) => {
56092
+ try {
56093
+ const chunk = await reader.read();
56094
+ if (chunk.done) {
56095
+ if (!oversized) inspect(pending + decoder.decode());
56096
+ this.end(true);
56097
+ controller.close();
56098
+ reader.releaseLock();
56099
+ return;
56100
+ }
56101
+ this.started = true;
56102
+ if (!oversized) {
56103
+ pending += decoder.decode(chunk.value, { stream: true });
56104
+ if (sse) {
56105
+ let newline = pending.indexOf("\n");
56106
+ while (newline >= 0) {
56107
+ inspect(pending.slice(0, newline));
56108
+ pending = pending.slice(newline + 1);
56109
+ newline = pending.indexOf("\n");
56110
+ }
56111
+ }
56112
+ if (pending.length > 1024 * 1024) {
56113
+ oversized = true;
56114
+ pending = "";
56115
+ }
56116
+ }
56117
+ controller.enqueue(chunk.value);
56118
+ } catch (error) {
56119
+ this.failed = true;
56120
+ this.end(false);
56121
+ controller.error(error);
56122
+ reader.releaseLock();
56123
+ }
56124
+ },
56125
+ cancel: async (reason) => {
56126
+ this.end(this.terminal);
56127
+ try {
56128
+ await reader.cancel(reason);
56129
+ } finally {
56130
+ reader.releaseLock();
56131
+ }
56132
+ }
56133
+ },
56134
+ { highWaterMark: 0 }
56135
+ );
56136
+ const observed = new Response(body, {
56137
+ status: response.status,
56138
+ statusText: response.statusText,
56139
+ headers: response.headers
56140
+ });
56141
+ Object.defineProperties(observed, {
56142
+ url: { value: response.url },
56143
+ redirected: { value: response.redirected }
56144
+ });
56145
+ return observed;
56146
+ }
56147
+ end(ended) {
56148
+ if (this.reported) return;
56149
+ this.reported = true;
56150
+ this.signal?.removeEventListener("abort", this.aborted);
56151
+ const usage = geminiBillingUsage(this.metadata);
56152
+ reportRouting({
56153
+ sessionId: this.sessionId,
56154
+ kind: "billing",
56155
+ attemptId: this.attemptId,
56156
+ requestKind: this.requestKind,
56157
+ credentialId: this.receipt.credentialId,
56158
+ accountId: this.receipt.accountIdentity,
56159
+ provider: "antigravity",
56160
+ model: this.model,
56161
+ attempt: this.attempt,
56162
+ chargeBasis: "subscription_included",
56163
+ cache: { implicit: true },
56164
+ outcome: this.failed ? "failed" : ended ? "completed" : this.started ? "cut" : "failed",
56165
+ ...this.status !== void 0 ? { status: this.status } : {},
56166
+ ...usage ? { usage } : {}
56167
+ });
56168
+ }
56169
+ };
56170
+
55773
56171
  // src/plugin/shared/vault-routing.ts
55774
56172
  function hasVaultRoutingAccessor() {
55775
56173
  try {
@@ -56297,6 +56695,7 @@ function createRequestExecutor(deps) {
56297
56695
  parentId: requestSessionIdentity.parentSessionId
56298
56696
  } : void 0;
56299
56697
  const isChildRequest = requestSessionIdentity.parentSessionId !== null;
56698
+ let physicalSendCount = 0;
56300
56699
  if (accountManager.getAccountCount() === 0) {
56301
56700
  const urlString2 = typeof input2 === "string" ? input2 : toUrlString(input2);
56302
56701
  const modelFromUrl = extractModelFromUrl(urlString2) ?? "unknown";
@@ -56883,6 +57282,32 @@ function createRequestExecutor(deps) {
56883
57282
  }
56884
57283
  }
56885
57284
  const selected = account;
57285
+ const sendPhysical = async (url, sendInit, admission, sendModel, requestKind) => {
57286
+ const source = credentials.domain === "local" ? "local" : hasVaultHost2() ? "hosted" : "vault";
57287
+ const message = `request-send source=${source} model=${sendModel} account=Account ${account.index + 1}`;
57288
+ if (source === "local") log17.info(message);
57289
+ else (log17.hostInfo ?? log17.info)(message);
57290
+ const attempt = ++physicalSendCount;
57291
+ const sessionId = requestSessionIdentity.sessionId;
57292
+ const billing = admission && sessionId && hasVaultRoutingAccessor() ? new VaultBillingAttempt(
57293
+ sessionId,
57294
+ admission,
57295
+ requestKind,
57296
+ sendModel,
57297
+ attempt,
57298
+ abortSignal
57299
+ ) : void 0;
57300
+ try {
57301
+ const response = await transport(url, sendInit, {
57302
+ signal: abortSignal,
57303
+ onDebug: pushDebug
57304
+ });
57305
+ return billing?.observe(response) ?? response;
57306
+ } catch (error) {
57307
+ billing?.end(false);
57308
+ throw error;
57309
+ }
57310
+ };
56886
57311
  const credentialForAuxiliarySend = async (sendInit, preparedProjectId) => {
56887
57312
  await assertAdmission();
56888
57313
  if (credentials.domain === "vault") {
@@ -56944,10 +57369,13 @@ function createRequestExecutor(deps) {
56944
57369
  warmupInit,
56945
57370
  projectId
56946
57371
  );
56947
- const warmupResponse = await transport(warmupUrl, warmupSend.init, {
56948
- signal: abortSignal,
56949
- onDebug: pushDebug
56950
- });
57372
+ const warmupResponse = await sendPhysical(
57373
+ warmupUrl,
57374
+ warmupSend.init,
57375
+ warmupSend.admission,
57376
+ prepared.effectiveModel ?? model ?? "unknown",
57377
+ "prime"
57378
+ );
56951
57379
  reportVault401(warmupSend.admission, warmupResponse.status);
56952
57380
  const transformed = await deadline.wait(
56953
57381
  () => wire.transformResponse(
@@ -56985,13 +57413,12 @@ function createRequestExecutor(deps) {
56985
57413
  { ...prepared.init, method: "POST", body: bodyStr },
56986
57414
  prepared.projectId ?? ""
56987
57415
  );
56988
- const probeResponse = await transport(
57416
+ const probeResponse = await sendPhysical(
56989
57417
  toUrlString(prepared.request),
56990
57418
  probeSend.init,
56991
- {
56992
- signal: abortSignal,
56993
- onDebug: pushDebug
56994
- }
57419
+ probeSend.admission,
57420
+ prepared.effectiveModel ?? model ?? "unknown",
57421
+ "keep_warm"
56995
57422
  );
56996
57423
  reportVault401(probeSend.admission, probeResponse.status);
56997
57424
  if (probeResponse.body) {
@@ -57162,10 +57589,12 @@ function createRequestExecutor(deps) {
57162
57589
  `dispatching request via ${prepared.headerStyle} transport`
57163
57590
  );
57164
57591
  physicalAttemptStarted = true;
57165
- const response = await transport(
57592
+ const response = await sendPhysical(
57166
57593
  toUrlString(prepared.request),
57167
57594
  prepared.init,
57168
- { signal: abortSignal, onDebug: pushDebug }
57595
+ sendAdmission,
57596
+ prepared.effectiveModel ?? model ?? "unknown",
57597
+ kind ?? "primary"
57169
57598
  );
57170
57599
  if (response.ok) deadline.acceptHeaders();
57171
57600
  apiRequestCount++;
@@ -58575,7 +59004,7 @@ function createPluginLifecycle(options) {
58575
59004
  const queueDrained = (async () => {
58576
59005
  await queue2?.dispose();
58577
59006
  })();
58578
- const record3 = {
59007
+ const record4 = {
58579
59008
  requests,
58580
59009
  done: (async () => {
58581
59010
  const failures = [];
@@ -58587,14 +59016,14 @@ function createPluginLifecycle(options) {
58587
59016
  reportCleanupFailures(failures);
58588
59017
  })()
58589
59018
  };
58590
- retiring.add(record3);
58591
- record3.done.then(
58592
- () => retiring.delete(record3),
59019
+ retiring.add(record4);
59020
+ record4.done.then(
59021
+ () => retiring.delete(record4),
58593
59022
  () => {
58594
- if (!requests) retiring.delete(record3);
59023
+ if (!requests) retiring.delete(record4);
58595
59024
  }
58596
59025
  );
58597
- return { queueDrained, done: record3.done };
59026
+ return { queueDrained, done: record4.done };
58598
59027
  };
58599
59028
  const disposeAccountRuntime = async () => {
58600
59029
  const oldQueue = refreshQueue;
@@ -58609,7 +59038,7 @@ function createPluginLifecycle(options) {
58609
59038
  const aborted = Promise.all([
58610
59039
  collectCleanupFailure(() => oldRequests?.dispose(), failures),
58611
59040
  ...retired.map(
58612
- (record3) => collectCleanupFailure(() => record3.requests?.dispose(), failures)
59041
+ (record4) => collectCleanupFailure(() => record4.requests?.dispose(), failures)
58613
59042
  )
58614
59043
  ]);
58615
59044
  const liveQueueDrained = collectCleanupFailure(
@@ -58620,7 +59049,7 @@ function createPluginLifecycle(options) {
58620
59049
  aborted,
58621
59050
  liveQueueDrained,
58622
59051
  ...retired.map(
58623
- (record3) => collectCleanupFailure(() => record3.done, failures)
59052
+ (record4) => collectCleanupFailure(() => record4.done, failures)
58624
59053
  )
58625
59054
  ]);
58626
59055
  await collectCleanupFailure(() => oldManager?.dispose(), failures);
@@ -59217,7 +59646,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
59217
59646
  const key = vaultAccountRowKey(row);
59218
59647
  const existing = vaultSelectors.get(key);
59219
59648
  if (existing) return existing;
59220
- const selector = randomUUID21();
59649
+ const selector = randomUUID22();
59221
59650
  vaultSelectors.set(key, selector);
59222
59651
  return selector;
59223
59652
  },