@cortexkit/opencode-antigravity-auth 3.0.6 → 3.0.7

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 (164) hide show
  1. package/dist/cli.js +620 -120
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +128 -44
  4. package/dist/index.js +1469 -675
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +154 -73
  7. package/dist/server.js +1075 -280
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +11 -1
  11. package/dist/src/common-auth-embedded/claustrum/consumer.js +38 -1
  12. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +29 -0
  13. package/dist/src/common-auth-embedded/claustrum/custody.js +17 -0
  14. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  15. package/dist/src/common-auth-embedded/fs/refresh-file-lock.d.ts +8 -2
  16. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +6 -1
  17. package/dist/src/common-auth-embedded/pi-slot/lock.js +7 -3
  18. package/dist/src/common-auth-embedded/quota/format.d.ts +14 -3
  19. package/dist/src/common-auth-embedded/quota/format.js +135 -18
  20. package/dist/src/common-auth-embedded/quota/index.d.ts +1 -1
  21. package/dist/src/common-auth-embedded/quota/index.js +1 -1
  22. package/dist/src/common-auth-embedded/setup/command-error.d.ts +32 -0
  23. package/dist/src/common-auth-embedded/setup/command-error.js +79 -0
  24. package/dist/src/common-auth-embedded/setup/command-runner.js +118 -24
  25. package/dist/src/common-auth-embedded/setup/command.js +75 -19
  26. package/dist/src/common-auth-embedded/setup/enroll.js +17 -5
  27. package/dist/src/common-auth-embedded/setup/index.d.ts +2 -1
  28. package/dist/src/common-auth-embedded/setup/index.js +1 -0
  29. package/dist/src/common-auth-embedded/setup/register.js +8 -2
  30. package/dist/src/common-auth-embedded/setup/types.d.ts +14 -0
  31. package/dist/src/common-auth-embedded/source-output.json +92 -76
  32. package/dist/src/common-auth-embedded/store/pool.d.ts +1 -1
  33. package/dist/src/common-auth-embedded/store/pool.js +0 -1
  34. package/dist/src/common-auth-embedded/store/refresh-lock.d.ts +0 -1
  35. package/dist/src/common-auth-embedded/store/refresh-lock.js +0 -1
  36. package/dist/src/ga/server/index.d.ts.map +1 -1
  37. package/dist/src/ga/server/index.js +4 -2
  38. package/dist/src/ga/server/index.js.map +1 -1
  39. package/dist/src/ga/tui/host-ga.d.ts.map +1 -1
  40. package/dist/src/ga/tui/host-ga.js +37 -3
  41. package/dist/src/ga/tui/host-ga.js.map +1 -1
  42. package/dist/src/plugin/config/schema.d.ts.map +1 -1
  43. package/dist/src/plugin/config/schema.js +2 -1
  44. package/dist/src/plugin/config/schema.js.map +1 -1
  45. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  46. package/dist/src/plugin/ga-location-services.js +4 -3
  47. package/dist/src/plugin/ga-location-services.js.map +1 -1
  48. package/dist/src/plugin/gemini-dump.d.ts.map +1 -1
  49. package/dist/src/plugin/gemini-dump.js +2 -5
  50. package/dist/src/plugin/gemini-dump.js.map +1 -1
  51. package/dist/src/plugin/index.d.ts.map +1 -1
  52. package/dist/src/plugin/index.js +3 -3
  53. package/dist/src/plugin/index.js.map +1 -1
  54. package/dist/src/plugin/logging-utils.d.ts.map +1 -1
  55. package/dist/src/plugin/logging-utils.js +2 -5
  56. package/dist/src/plugin/logging-utils.js.map +1 -1
  57. package/dist/src/plugin/request.d.ts +1 -2
  58. package/dist/src/plugin/request.d.ts.map +1 -1
  59. package/dist/src/plugin/request.js +8 -12
  60. package/dist/src/plugin/request.js.map +1 -1
  61. package/dist/src/plugin/shared/request-services.d.ts +8 -1
  62. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  63. package/dist/src/plugin/shared/request-services.js +140 -58
  64. package/dist/src/plugin/shared/request-services.js.map +1 -1
  65. package/dist/src/plugin/shared/vault-request-credentials.d.ts +12 -3
  66. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  67. package/dist/src/plugin/shared/vault-request-credentials.js +3 -0
  68. package/dist/src/plugin/shared/vault-request-credentials.js.map +1 -1
  69. package/dist/src/plugin/vault-custody.d.ts +14 -1
  70. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  71. package/dist/src/plugin/vault-custody.js +57 -10
  72. package/dist/src/plugin/vault-custody.js.map +1 -1
  73. package/dist/src/sidebar-projection.d.ts +4 -0
  74. package/dist/src/sidebar-projection.d.ts.map +1 -1
  75. package/dist/src/sidebar-projection.js +6 -2
  76. package/dist/src/sidebar-projection.js.map +1 -1
  77. package/dist/src/tui/quota-layout.d.ts +94 -0
  78. package/dist/src/tui/quota-layout.d.ts.map +1 -0
  79. package/dist/src/tui/quota-layout.js +139 -0
  80. package/dist/src/tui/quota-layout.js.map +1 -0
  81. package/dist/src/tui/route-layout.d.ts +8 -0
  82. package/dist/src/tui/route-layout.d.ts.map +1 -0
  83. package/dist/src/tui/route-layout.js +36 -0
  84. package/dist/src/tui/route-layout.js.map +1 -0
  85. package/dist/src/tui.d.ts.map +1 -1
  86. package/dist/src/tui.js +26 -128
  87. package/dist/src/tui.js.map +1 -1
  88. package/dist/tui-build-map.json +42 -13
  89. package/dist/tui-ga-build-map.json +46 -17
  90. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +11 -1
  91. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +29 -0
  92. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  93. package/dist/types/src/common-auth-embedded/fs/refresh-file-lock.d.ts +8 -2
  94. package/dist/types/src/common-auth-embedded/quota/format.d.ts +14 -3
  95. package/dist/types/src/common-auth-embedded/quota/index.d.ts +1 -1
  96. package/dist/types/src/common-auth-embedded/setup/command-error.d.ts +32 -0
  97. package/dist/types/src/common-auth-embedded/setup/index.d.ts +2 -1
  98. package/dist/types/src/common-auth-embedded/setup/types.d.ts +14 -0
  99. package/dist/types/src/common-auth-embedded/store/pool.d.ts +1 -1
  100. package/dist/types/src/common-auth-embedded/store/refresh-lock.d.ts +0 -1
  101. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  102. package/dist/types/src/plugin/config/schema.d.ts.map +1 -1
  103. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  104. package/dist/types/src/plugin/gemini-dump.d.ts.map +1 -1
  105. package/dist/types/src/plugin/index.d.ts.map +1 -1
  106. package/dist/types/src/plugin/logging-utils.d.ts.map +1 -1
  107. package/dist/types/src/plugin/request.d.ts +1 -2
  108. package/dist/types/src/plugin/request.d.ts.map +1 -1
  109. package/dist/types/src/plugin/shared/request-services.d.ts +8 -1
  110. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  111. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +12 -3
  112. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  113. package/dist/types/src/plugin/vault-custody.d.ts +14 -1
  114. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  115. package/package.json +3 -3
  116. package/src/common-auth-embedded/claustrum/consumer.d.ts +11 -1
  117. package/src/common-auth-embedded/claustrum/consumer.js +38 -1
  118. package/src/common-auth-embedded/claustrum/custody.d.ts +29 -0
  119. package/src/common-auth-embedded/claustrum/custody.js +17 -0
  120. package/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  121. package/src/common-auth-embedded/fs/refresh-file-lock.d.ts +8 -2
  122. package/src/common-auth-embedded/fs/refresh-file-lock.js +6 -1
  123. package/src/common-auth-embedded/pi-slot/lock.js +7 -3
  124. package/src/common-auth-embedded/quota/format.d.ts +14 -3
  125. package/src/common-auth-embedded/quota/format.js +135 -18
  126. package/src/common-auth-embedded/quota/index.d.ts +1 -1
  127. package/src/common-auth-embedded/quota/index.js +1 -1
  128. package/src/common-auth-embedded/setup/command-error.d.ts +32 -0
  129. package/src/common-auth-embedded/setup/command-error.js +79 -0
  130. package/src/common-auth-embedded/setup/command-runner.js +118 -24
  131. package/src/common-auth-embedded/setup/command.js +75 -19
  132. package/src/common-auth-embedded/setup/enroll.js +17 -5
  133. package/src/common-auth-embedded/setup/index.d.ts +2 -1
  134. package/src/common-auth-embedded/setup/index.js +1 -0
  135. package/src/common-auth-embedded/setup/register.js +8 -2
  136. package/src/common-auth-embedded/setup/types.d.ts +14 -0
  137. package/src/common-auth-embedded/source-output.json +92 -76
  138. package/src/common-auth-embedded/store/pool.d.ts +1 -1
  139. package/src/common-auth-embedded/store/pool.js +0 -1
  140. package/src/common-auth-embedded/store/refresh-lock.d.ts +0 -1
  141. package/src/common-auth-embedded/store/refresh-lock.js +0 -1
  142. package/src/tui-compiled/common-auth-embedded/quota/format.js +135 -18
  143. package/src/tui-compiled/common-auth-embedded/quota/index.js +1 -1
  144. package/src/tui-compiled/tui/quota-layout.js +378 -0
  145. package/src/tui-compiled/tui/route-layout.js +30 -0
  146. package/src/tui-compiled/tui.js +145 -427
  147. package/src/tui-ga-compiled/host-ga.js +82 -52
  148. package/src/tui-ga-compiled/shared/6ca47cd4ec33fe72-route-layout.js +30 -0
  149. package/src/tui-ga-compiled/shared/8ae1927e5910ea81-sidebar-projection.js +2 -2
  150. package/src/tui-ga-compiled/shared/aef2402f8fc342f0-format.js +135 -18
  151. package/src/tui-ga-compiled/shared/bf17cbee28e58197-index.js +1 -1
  152. package/src/tui-ga-compiled/shared/dd4c9e1a907f8ef0-quota-layout.js +378 -0
  153. package/src/tui-ga-raw/host-ga.tsx +71 -30
  154. package/src/tui-ga-raw/shared/6ca47cd4ec33fe72-route-layout.js +30 -0
  155. package/src/tui-ga-raw/shared/8ae1927e5910ea81-sidebar-projection.js +2 -2
  156. package/src/tui-ga-raw/shared/aef2402f8fc342f0-format.js +135 -18
  157. package/src/tui-ga-raw/shared/bf17cbee28e58197-index.js +1 -1
  158. package/src/tui-ga-raw/shared/dd4c9e1a907f8ef0-quota-layout.tsx +391 -0
  159. package/src/tui-raw/common-auth-embedded/quota/format.js +135 -18
  160. package/src/tui-raw/common-auth-embedded/quota/index.js +1 -1
  161. package/src/tui-raw/tui/quota-layout.tsx +391 -0
  162. package/src/tui-raw/tui/route-layout.js +30 -0
  163. package/src/tui-raw/tui.tsx +50 -309
  164. package/src/tui.tsx +50 -309
package/dist/server.js CHANGED
@@ -293,8 +293,11 @@ function quotaWindowName(limit) {
293
293
  function clampPercent(remaining) {
294
294
  return Math.min(100, Math.max(0, remaining));
295
295
  }
296
+ function wholePercent(remaining) {
297
+ return Math.round(clampPercent(remaining));
298
+ }
296
299
  function percentLeft(remaining) {
297
- return `${Math.round(clampPercent(remaining))}% left`;
300
+ return `${wholePercent(remaining)}% left`;
298
301
  }
299
302
  function resetDetails(resetsAt, checkedAt, now) {
300
303
  const at = resetsAt === void 0 ? Number.NaN : Date.parse(resetsAt);
@@ -320,6 +323,11 @@ function displayOrder(left, right) {
320
323
  return left.label < right.label ? -1 : left.label > right.label ? 1 : 0;
321
324
  }
322
325
  function quotaWindowParts(quota, options) {
326
+ const { windows, age } = scopedWindowParts(quota, options);
327
+ const parts = windows.map(({ part }) => part);
328
+ return age === void 0 ? { windows: parts } : { windows: parts, age };
329
+ }
330
+ function scopedWindowParts(quota, options) {
323
331
  if (!quota)
324
332
  return { windows: [] };
325
333
  const { now } = options;
@@ -327,12 +335,15 @@ function quotaWindowParts(quota, options) {
327
335
  const windows = readings.map((limit) => {
328
336
  const remainingPercent = clampPercent(limit.remainingPercent ?? 0);
329
337
  return {
330
- kind: "window",
331
- name: quotaWindowName(limit),
332
- figure: percentLeft(limit.remainingPercent ?? 0),
333
- remainingPercent,
334
- checkedAt: limit.checkedAt,
335
- ...resetDetails(limit.resetsAt, limit.checkedAt, now)
338
+ scope: limit.scope,
339
+ part: {
340
+ kind: "window",
341
+ name: quotaWindowName(limit),
342
+ figure: percentLeft(limit.remainingPercent ?? 0),
343
+ remainingPercent,
344
+ checkedAt: limit.checkedAt,
345
+ ...resetDetails(limit.resetsAt, limit.checkedAt, now)
346
+ }
336
347
  };
337
348
  });
338
349
  const budget = quota.budget;
@@ -340,23 +351,85 @@ function quotaWindowParts(quota, options) {
340
351
  const remainingPercent = budget.remainingPercent;
341
352
  const figure = budget.reached ? "credits spent" : remainingPercent !== void 0 ? `credits ${percentLeft(remainingPercent)}` : "credits available";
342
353
  windows.push({
343
- kind: "budget",
344
- name: "credits",
345
- figure,
346
- ...remainingPercent === void 0 ? {} : { remainingPercent: clampPercent(remainingPercent) },
347
- checkedAt: budget.checkedAt,
348
- ...resetDetails(budget.resetsAt, budget.checkedAt, now)
354
+ scope: ALL_SCOPE,
355
+ spent: budget.reached,
356
+ part: {
357
+ kind: "budget",
358
+ name: "credits",
359
+ figure,
360
+ ...remainingPercent === void 0 ? {} : { remainingPercent: clampPercent(remainingPercent) },
361
+ checkedAt: budget.checkedAt,
362
+ ...resetDetails(budget.resetsAt, budget.checkedAt, now)
363
+ }
349
364
  });
350
365
  }
351
366
  if (windows.length > 0) {
352
- const age = now - Math.min(...windows.map((part) => part.checkedAt));
367
+ const age = now - Math.min(...windows.map(({ part }) => part.checkedAt));
353
368
  if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
354
369
  return { windows, age: `checked ${shortSpan(age)} ago` };
355
370
  }
356
371
  }
357
372
  return { windows };
358
373
  }
374
+ function isQuotaStale(quota, options) {
375
+ return scopedWindowParts(quota, options).age !== void 0;
376
+ }
377
+ function scopeDisplayName(scope) {
378
+ const model = scope.slice(scope.indexOf(":") + 1);
379
+ return model.charAt(0).toUpperCase() + model.slice(1);
380
+ }
381
+ function scopeAbbreviations(scopes) {
382
+ const names = [...new Set(scopes.map(scopeDisplayName))];
383
+ const lengths = new Map(names.map((name) => [name, 2]));
384
+ const short = (name) => name.slice(0, lengths.get(name));
385
+ for (; ; ) {
386
+ const byShort = /* @__PURE__ */ new Map();
387
+ for (const name of names) {
388
+ byShort.set(short(name), [...byShort.get(short(name)) ?? [], name]);
389
+ }
390
+ let extended = false;
391
+ for (const group of byShort.values()) {
392
+ if (group.length < 2)
393
+ continue;
394
+ for (const name of group) {
395
+ const length = lengths.get(name) ?? 2;
396
+ if (length < name.length) {
397
+ lengths.set(name, length + 1);
398
+ extended = true;
399
+ }
400
+ }
401
+ }
402
+ if (!extended)
403
+ break;
404
+ }
405
+ return new Map(scopes.map((scope) => [scope, short(scopeDisplayName(scope))]));
406
+ }
407
+ function narrowTextParts(quota, options) {
408
+ const { windows } = scopedWindowParts(quota, options);
409
+ const general = windows.filter(({ part, scope }) => part.kind === "window" && scope === ALL_SCOPE);
410
+ const scoped = windows.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE);
411
+ const abbreviations = scopeAbbreviations(scoped.map(({ scope }) => scope));
412
+ const budget = windows.find(({ part }) => part.kind === "budget");
413
+ const budgetLeft = budget?.spent ? 0 : budget?.part.remainingPercent;
414
+ const extras = [
415
+ ...scoped.map(({ scope, part }) => ({
416
+ label: abbreviations.get(scope) ?? scope,
417
+ remaining: part.remainingPercent ?? 0
418
+ })),
419
+ ...budgetLeft === void 0 ? [] : [{ label: "cr", remaining: budgetLeft }]
420
+ ];
421
+ const tightest = extras.reduce((best, item) => best === void 0 || item.remaining < best.remaining ? item : best, void 0);
422
+ const pieces = general.map(({ part }) => `${part.name} ${wholePercent(part.remainingPercent ?? 0)}%`);
423
+ if (tightest) {
424
+ pieces.push(`${tightest.label} ${wholePercent(tightest.remaining)}%`);
425
+ }
426
+ if (pieces.length === 0)
427
+ return windows.map(({ part }) => part.figure);
428
+ return pieces.map((piece, index) => index === pieces.length - 1 ? `${piece} left` : piece);
429
+ }
359
430
  function quotaTextParts(quota, options) {
431
+ if (options.form === "narrow")
432
+ return narrowTextParts(quota, options);
360
433
  const parts = quotaWindowParts(quota, options);
361
434
  const full = (options.form ?? "full") === "full";
362
435
  const text2 = parts.windows.map((part) => {
@@ -501,6 +574,7 @@ __export(quota_exports, {
501
574
  futureResetAt: () => futureResetAt,
502
575
  isQuotaMap: () => isQuotaMap,
503
576
  isQuotaObservation: () => isQuotaObservation,
577
+ isQuotaStale: () => isQuotaStale,
504
578
  mergeQuotaObservation: () => mergeQuotaObservation,
505
579
  projectQuota: () => projectQuota,
506
580
  quotaCodec: () => quotaCodec2,
@@ -985,7 +1059,10 @@ function isLostMarkerRaceError(error) {
985
1059
  const code2 = error?.code;
986
1060
  return code2 === "ENOENT" || !windowsPrivateFiles && (code2 === "EINVAL" || code2 === "ENOTDIR");
987
1061
  }
988
- async function acquireRefreshFileLock(options) {
1062
+ function acquireRefreshFileLock(options) {
1063
+ return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
1064
+ }
1065
+ async function acquireRefreshFileLockWithClock(options) {
989
1066
  const lockPath = lockPathFor(options.path, options.name);
990
1067
  const legacyOwnerPath = join4(lockPath, "owner.json");
991
1068
  const ownerId = randomUUID9();
@@ -1707,7 +1784,6 @@ async function acquirePoolLock(spec, defaults, env3) {
1707
1784
  name: spec.name,
1708
1785
  path: spec.path,
1709
1786
  ttlMs: options.ttlMs,
1710
- now: env3.now,
1711
1787
  renew: options.renew,
1712
1788
  onContended: () => emit("contended"),
1713
1789
  ...env3.onRenewalTimer ? {
@@ -4823,7 +4899,6 @@ function openPoolStore(options) {
4823
4899
  ],
4824
4900
  lockDefaults,
4825
4901
  lockEnv: {
4826
- now: options.now ?? Date.now,
4827
4902
  ...options.onLockEvent ? { onLockEvent: options.onLockEvent } : {},
4828
4903
  ...options.onLockStep ? { onLockStep: options.onLockStep } : {},
4829
4904
  ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
@@ -7111,11 +7186,11 @@ var init_doctor = __esm({
7111
7186
 
7112
7187
  // ../core/dist/common-auth-embedded/auth-menu/login.js
7113
7188
  import { execFileSync as defaultExecFileSync, spawn as defaultSpawn } from "node:child_process";
7114
- function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn = defaultSpawn) {
7189
+ function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn2 = defaultSpawn) {
7115
7190
  try {
7116
7191
  if (platform === "win32") {
7117
7192
  const command = `Start-Process '${url.replaceAll("'", "''")}'`;
7118
- const child = spawn("powershell.exe", [
7193
+ const child = spawn2("powershell.exe", [
7119
7194
  "-NoProfile",
7120
7195
  "-NonInteractive",
7121
7196
  "-WindowStyle",
@@ -8895,6 +8970,15 @@ function credentialTypeOf(row, family) {
8895
8970
  return row.refreshAdapter === void 0 ? "api_key" : void 0;
8896
8971
  return void 0;
8897
8972
  }
8973
+ function grantReachOf(listed) {
8974
+ const { grants, grantTuples } = listed;
8975
+ if (grants === void 0 || grantTuples === void 0)
8976
+ return void 0;
8977
+ return Object.freeze({
8978
+ grants,
8979
+ tuples: Object.freeze(grantTuples.map(({ selectorKind, selector, operation }) => Object.freeze({ selectorKind, selector, operation })))
8980
+ });
8981
+ }
8898
8982
  var defaultLogger, SERVING_MARGIN_MS, ClaustrumScopedCustody;
8899
8983
  var init_custody = __esm({
8900
8984
  "../core/dist/common-auth-embedded/claustrum/custody.js"() {
@@ -9020,10 +9104,12 @@ var init_custody = __esm({
9020
9104
  }
9021
9105
  for (const record3 of skipped)
9022
9106
  this.#logger.warn("skipped malformed vault record", record3);
9107
+ const grantReach = grantReachOf(inventory);
9023
9108
  return {
9024
9109
  view: inventory.view,
9025
9110
  credentials: Object.freeze(credentials),
9026
- skipped: Object.freeze(skipped)
9111
+ skipped: Object.freeze(skipped),
9112
+ ...grantReach && { grantReach }
9027
9113
  };
9028
9114
  }
9029
9115
  /**
@@ -9589,6 +9675,11 @@ var init_consumer = __esm({
9589
9675
  #connecting;
9590
9676
  #refreshing;
9591
9677
  #roster;
9678
+ /**
9679
+ * The grants named by this instance's latest discovery, with the view that
9680
+ * discovery committed. Memory only: the roster file never carries it.
9681
+ */
9682
+ #grantReach;
9592
9683
  #timer;
9593
9684
  #started = false;
9594
9685
  #insula;
@@ -9665,6 +9756,19 @@ var init_consumer = __esm({
9665
9756
  snapshot() {
9666
9757
  return this.#roster;
9667
9758
  }
9759
+ /**
9760
+ * What this consumer is granted, from its latest discovery, without any I/O.
9761
+ * It explains an empty roster: `grants === 0` means no grant at all, while
9762
+ * `grants > 0` means a grant that reaches no credential (`tuples` names its
9763
+ * selector). Undefined means unknown, never zero: the vault or client is too
9764
+ * old to send it, nothing was discovered yet, or the roster now in memory is
9765
+ * a different view than the one this instance discovered (a peer process
9766
+ * held the discovery lease and its newer roster was served instead).
9767
+ */
9768
+ grantReach() {
9769
+ const latest2 = this.#grantReach;
9770
+ return latest2 && this.#roster?.view === latest2.view ? latest2.reach : void 0;
9771
+ }
9668
9772
  /** Rows for `/routing`, from the last committed roster. */
9669
9773
  routingRows() {
9670
9774
  return vaultRoutingRows(this.#roster);
@@ -9676,6 +9780,7 @@ var init_consumer = __esm({
9676
9780
  this.#refreshing = (async () => {
9677
9781
  if (!await this.#active()) {
9678
9782
  this.#roster = void 0;
9783
+ this.#grantReach = void 0;
9679
9784
  this.#custody?.close();
9680
9785
  this.#custody = void 0;
9681
9786
  this.#insula?.release();
@@ -9683,9 +9788,15 @@ var init_consumer = __esm({
9683
9788
  return void 0;
9684
9789
  }
9685
9790
  const custody = await this.#getCustody();
9791
+ let discovered;
9686
9792
  const roster = await refreshVaultRoster({
9687
9793
  path: this.#options.rosterPath,
9688
- custody,
9794
+ custody: {
9795
+ discover: async (signal) => {
9796
+ discovered = await custody.discover(signal);
9797
+ return discovered;
9798
+ }
9799
+ },
9689
9800
  isActive: () => this.#active(),
9690
9801
  signal: this.#shutdown.signal,
9691
9802
  projection: () => ({
@@ -9698,6 +9809,8 @@ var init_consumer = __esm({
9698
9809
  this.#assertOpen();
9699
9810
  const changed = roster?.view !== this.#roster?.view;
9700
9811
  this.#roster = roster;
9812
+ if (discovered && roster?.view !== void 0)
9813
+ this.#grantReach = discovered.grantReach ? { view: roster.view, reach: discovered.grantReach } : void 0;
9701
9814
  if (roster && changed)
9702
9815
  this.#options.onRoster?.(roster);
9703
9816
  return roster;
@@ -9925,6 +10038,7 @@ var init_consumer = __esm({
9925
10038
  this.#insula?.release();
9926
10039
  this.#insula = void 0;
9927
10040
  this.#roster = void 0;
10041
+ this.#grantReach = void 0;
9928
10042
  }
9929
10043
  };
9930
10044
  }
@@ -9998,7 +10112,7 @@ var init_claustrum = __esm({
9998
10112
  });
9999
10113
 
10000
10114
  // ../core/dist/common-auth-embedded/pi-slot/lock.js
10001
- import { rmdirSync, statSync as statSync2 } from "node:fs";
10115
+ import { rmdirSync, statSync as statSync2, utimesSync } from "node:fs";
10002
10116
  import { mkdir as mkdir9, rmdir, stat as stat5, utimes } from "node:fs/promises";
10003
10117
  function sameDirectory(observed, identity) {
10004
10118
  return observed.dev === identity.dev && observed.ino === identity.ino;
@@ -10094,7 +10208,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
10094
10208
  return;
10095
10209
  let observed;
10096
10210
  try {
10097
- observed = await stat5(path5);
10211
+ observed = statSync2(path5);
10098
10212
  } catch (error) {
10099
10213
  retry(error);
10100
10214
  return;
@@ -10108,11 +10222,12 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
10108
10222
  }
10109
10223
  const next = new Date(precision === "s" ? Math.ceil(Date.now() / 1e3) * 1e3 : Date.now());
10110
10224
  try {
10111
- await utimes(path5, next, next);
10225
+ utimesSync(path5, next, next);
10112
10226
  } catch (error) {
10113
10227
  retry(error);
10114
10228
  return;
10115
10229
  }
10230
+ assertFresh();
10116
10231
  if (released)
10117
10232
  return;
10118
10233
  mtime = next.getTime();
@@ -11262,7 +11377,7 @@ function legacyOptional(row, key, predicate, path5) {
11262
11377
  throw new AccountMigrationError(`${path5}.${key} has an invalid type`);
11263
11378
  }
11264
11379
  }
11265
- function parseAccount(value, ordinal, version, clock) {
11380
+ function parseAccount(value, ordinal, version, clock2) {
11266
11381
  const path5 = `accounts[${ordinal}]`;
11267
11382
  const source = object(value, path5);
11268
11383
  if (typeof source.refreshToken !== "string" || !source.refreshToken.trim().length) {
@@ -11289,7 +11404,7 @@ function parseAccount(value, ordinal, version, clock) {
11289
11404
  const quota = hasQuota ? decodeQuotaState(quotaRaw) : void 0;
11290
11405
  const normalized = encodeProviderMetadata(originalMetadata);
11291
11406
  if (version === 1) {
11292
- if (source.isRateLimited && finite(source.rateLimitResetTime) && source.rateLimitResetTime > clock) {
11407
+ if (source.isRateLimited && finite(source.rateLimitResetTime) && source.rateLimitResetTime > clock2) {
11293
11408
  if (originalMetadata.rateLimitResetTimes === null)
11294
11409
  throw new AccountMigrationError(`${path5} has conflicting rate-limit encodings`);
11295
11410
  const resets = { ...originalMetadata.rateLimitResetTimes };
@@ -11306,9 +11421,9 @@ function parseAccount(value, ordinal, version, clock) {
11306
11421
  const gemini = resets.gemini;
11307
11422
  delete resets.claude;
11308
11423
  delete resets.gemini;
11309
- if (claude === null || finite(claude) && claude > clock)
11424
+ if (claude === null || finite(claude) && claude > clock2)
11310
11425
  resets.claude = claude;
11311
- if (gemini === null || finite(gemini) && gemini > clock) {
11426
+ if (gemini === null || finite(gemini) && gemini > clock2) {
11312
11427
  if (Object.hasOwn(resets, "gemini-antigravity") && resets["gemini-antigravity"] !== gemini)
11313
11428
  throw new AccountMigrationError(`${path5} has conflicting rate-limit encodings`);
11314
11429
  resets["gemini-antigravity"] = gemini;
@@ -11842,7 +11957,7 @@ async function syncDirectory(path5, boundary) {
11842
11957
  }
11843
11958
  await boundary?.("after-directory-sync");
11844
11959
  }
11845
- async function exclusiveBytes(path5, bytes, expectedHash, boundary) {
11960
+ async function exclusiveBytes(path5, bytes, expectedHash, boundary, pointerStage = false) {
11846
11961
  let handle;
11847
11962
  try {
11848
11963
  handle = await open(path5, "wx", 384);
@@ -11861,7 +11976,8 @@ async function exclusiveBytes(path5, bytes, expectedHash, boundary) {
11861
11976
  const reopened = await secureRead(path5);
11862
11977
  if (digest(reopened) !== expectedHash || !reopened.equals(bytes))
11863
11978
  throw new AccountMigrationError("exclusive backup or recovery copy differs");
11864
- await syncFile(path5);
11979
+ if (handle === void 0 || !pointerStage)
11980
+ await syncFile(path5);
11865
11981
  await syncDirectory(dirname(path5), boundary);
11866
11982
  }
11867
11983
  async function readJournal(paths) {
@@ -12563,7 +12679,7 @@ function createAccountMigrationFactory(modules) {
12563
12679
  throw new AccountMigrationError("source changed before pointer publication");
12564
12680
  if (!journal)
12565
12681
  throw new AccountMigrationError("capture journal missing");
12566
- await publishGenerationPointer(modules, physical, journal, parentLease, prior, options.onBoundary);
12682
+ await publishGenerationPointer(modules, physical, journal, parentLease, lease, prior, options.onBoundary);
12567
12683
  });
12568
12684
  await options.onBoundary?.("after-capture");
12569
12685
  }
@@ -12908,47 +13024,9 @@ async function initializeFreshAccountStore(modules, options) {
12908
13024
  timeoutMs: 2e3,
12909
13025
  renew: true
12910
13026
  }, async (lease) => {
12911
- let journal = await readJournal(physical);
12912
- if (pointer === void 0) {
12913
- await options.onBoundary?.("before-capture");
12914
- await assertSourceAbsent(physical);
12915
- await modules.fs.withLock(physical.legacyPath, {
12916
- name: "accounts",
12917
- ttlMs: 1e4,
12918
- timeoutMs: 2e3,
12919
- renew: true
12920
- }, async (accountsLease) => {
12921
- await assertSourceAbsent(physical);
12922
- await accountsLease.assertOwned();
12923
- await lease.assertOwned();
12924
- if (journal !== void 0 || await exists(physical.configPath) || await exists(physical.statePath))
12925
- throw new AccountMigrationError("fresh stage has unrelated artifacts");
12926
- journal = {
12927
- schemaVersion: 1,
12928
- id: pathGenerationId(physical),
12929
- legacyPath: physical.legacyPath,
12930
- storeDir: physical.storeDir,
12931
- sourceKind: "absent",
12932
- status: "pending",
12933
- operation: "migrate",
12934
- phase: "capture",
12935
- manifest: {
12936
- sourceVersion: null,
12937
- normalizationClock: options.now(),
12938
- accounts: [],
12939
- routing: { schemaVersion: 1 },
12940
- effectiveActiveIndex: 0
12941
- },
12942
- mapping: [],
12943
- completedRows: []
12944
- };
12945
- await saveJournal(modules, physical, lease, journal, true, options.onBoundary);
12946
- await options.onBoundary?.("pointer:before-publication");
12947
- await assertSourceAbsent(physical);
12948
- await publishGenerationPointer(modules, physical, journal, parentLease, void 0, options.onBoundary);
12949
- await options.onBoundary?.("pointer:after-publication");
12950
- });
12951
- }
13027
+ const journal = await readJournal(physical);
13028
+ if (pointer === void 0)
13029
+ return initializePrivateEmptyGeneration(modules, physical, parentLease, lease, options);
12952
13030
  if (journal?.sourceKind !== "absent" || journal.operation !== "migrate" || journal.status === "inactive")
12953
13031
  throw new AccountMigrationError("fresh resume has no compatible pointed generation");
12954
13032
  await assertPublishedAccountStoreGeneration(physical);
@@ -13024,6 +13102,187 @@ async function initializeFreshAccountStore(modules, options) {
13024
13102
  throw error;
13025
13103
  }
13026
13104
  }
13105
+ async function exclusiveUnpublishedBytes(path5, bytes) {
13106
+ const handle = await open(path5, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
13107
+ try {
13108
+ await handle.writeFile(bytes);
13109
+ } finally {
13110
+ await handle.close();
13111
+ }
13112
+ if (!(await secureRead(path5)).equals(bytes))
13113
+ throw new AccountMigrationError("private stage readback differs");
13114
+ }
13115
+ async function initializePrivateEmptyGeneration(modules, paths, parentLease, managementLease, options) {
13116
+ return modules.fs.withLock(paths.legacyPath, { name: "accounts", ttlMs: 1e4, timeoutMs: 2e3, renew: true }, async (accountsLease) => {
13117
+ const directory = await lstat(paths.storeDir);
13118
+ const assertOwned = async () => {
13119
+ await parentLease.assertOwned();
13120
+ await managementLease.assertOwned();
13121
+ await accountsLease.assertOwned();
13122
+ const current = await lstat(paths.storeDir);
13123
+ if (!current.isDirectory() || current.isSymbolicLink() || current.dev !== directory.dev || current.ino !== directory.ino || !sameFilesystemPath(await realpath(paths.storeDir), paths.storeDir))
13124
+ throw new AccountMigrationError("private generation directory changed");
13125
+ privateMode(current.mode, 448);
13126
+ };
13127
+ const boundary = options.onBoundary;
13128
+ await assertOwned();
13129
+ await assertSourceAbsent(paths);
13130
+ if (await readPointer(paths.legacyPath))
13131
+ throw new AccountMigrationError("private initialization found a competing pointer");
13132
+ if (await readJournal(paths) || await exists(paths.configPath) || await exists(paths.statePath))
13133
+ throw new AccountMigrationError("fresh stage has unrelated artifacts");
13134
+ const journal = {
13135
+ schemaVersion: 1,
13136
+ id: pathGenerationId(paths),
13137
+ legacyPath: paths.legacyPath,
13138
+ storeDir: paths.storeDir,
13139
+ sourceKind: "absent",
13140
+ status: "pending",
13141
+ operation: "migrate",
13142
+ phase: "build",
13143
+ manifest: {
13144
+ sourceVersion: null,
13145
+ normalizationClock: options.now(),
13146
+ accounts: [],
13147
+ routing: { schemaVersion: 1 },
13148
+ effectiveActiveIndex: 0
13149
+ },
13150
+ mapping: [],
13151
+ completedRows: []
13152
+ };
13153
+ await assertOwned();
13154
+ await exclusiveUnpublishedBytes(paths.configPath, Buffer.from('{"version":1,"accounts":[]}\n'));
13155
+ await boundary?.("empty-stage:after-seed");
13156
+ const store = openMigrationStore(modules, paths, options.now, async (step, info) => {
13157
+ await assertOwned();
13158
+ if (!step.includes("config") || await exists(paths.statePath))
13159
+ throw new AccountMigrationError("private empty stage attempted a credential write");
13160
+ await secureRead(paths.configPath);
13161
+ await boundary?.(`public:${info.operation}:${step}`);
13162
+ await assertOwned();
13163
+ });
13164
+ await assertOwned();
13165
+ await store.initialize();
13166
+ await boundary?.("empty-stage:after-initialize");
13167
+ await assertOwned();
13168
+ await store.updateSettings((settings) => {
13169
+ settings[ROUTING_SETTINGS_KEY] = encodeRoutingSettings(journal.manifest.routing);
13170
+ settings[ACCOUNT_STORE_GENERATION_SETTINGS_KEY] = generationJson(journal);
13171
+ settings[MANAGEMENT_SETTINGS_KEY] = {
13172
+ id: journal.id,
13173
+ kind: "migration",
13174
+ targets: [],
13175
+ progress: { step: "build", completedTargets: [] }
13176
+ };
13177
+ return settings;
13178
+ });
13179
+ await boundary?.("empty-stage:after-build-settings");
13180
+ await expectedFreshArtifacts(paths, journal);
13181
+ await assertStateOwnership(paths, journal, true);
13182
+ await verifyImported(store, journal);
13183
+ const snapshot2 = await secureRead(paths.configPath);
13184
+ await verifyImported(store, journal);
13185
+ journal.verification = {
13186
+ manifestSha256: digest(canonical2(manifestJson(journal.manifest))),
13187
+ configSha256: digest(snapshot2),
13188
+ statePresent: false,
13189
+ durability: accountMigrationDurability()
13190
+ };
13191
+ await assertOwned();
13192
+ await assertSourceAbsent(paths);
13193
+ journal.sourceAbsenceVerified = true;
13194
+ await management(store, journal, true);
13195
+ await boundary?.("empty-stage:after-clear-settings");
13196
+ await expectedFreshArtifacts(paths, journal);
13197
+ await currentSuccessor(store, paths, journal);
13198
+ if ((await settingsOf(store))[MANAGEMENT_SETTINGS_KEY] !== void 0)
13199
+ throw new AccountMigrationError("private stage still has management work");
13200
+ journal.phase = "activate";
13201
+ journal.status = "active";
13202
+ decodeAccountMigrationJournal(journalJson(journal));
13203
+ await assertOwned();
13204
+ await exclusiveUnpublishedBytes(paths.migrationPath, Buffer.from(`${JSON.stringify(journalJson(journal), null, 2)}
13205
+ `));
13206
+ await boundary?.("empty-stage:after-journal");
13207
+ await syncFile(paths.configPath);
13208
+ await boundary?.("empty-stage:after-config-sync");
13209
+ await syncFile(paths.migrationPath);
13210
+ await boundary?.("empty-stage:after-journal-sync");
13211
+ for (const [name, path6] of [
13212
+ ["backups", paths.backupsDir],
13213
+ ["retired", paths.retiredDir],
13214
+ ["transfers", paths.transfersDir]
13215
+ ]) {
13216
+ await syncDirectory(path6);
13217
+ await boundary?.(`empty-stage:after-${name}-sync`);
13218
+ }
13219
+ await syncDirectory(paths.storeDir);
13220
+ await boundary?.("empty-stage:after-generation-sync");
13221
+ await boundary?.("pointer:before-publication");
13222
+ const reopened = await readJournal(paths);
13223
+ if (!isDeepStrictEqual(reopened, journal))
13224
+ throw new AccountMigrationError("publication requires its complete synced canonical journal");
13225
+ const pointer = {
13226
+ schemaVersion: 1,
13227
+ id: journal.id,
13228
+ directoryBasename: basename(paths.storeDir)
13229
+ };
13230
+ const path5 = accountStorePointerPath(paths.legacyPath);
13231
+ const stage = `${path5}.${journal.id}.tmp`;
13232
+ const bytes = Buffer.from(`${JSON.stringify(pointer, null, 2)}
13233
+ `);
13234
+ await assertOwned();
13235
+ let stageHandle;
13236
+ try {
13237
+ stageHandle = await open(stage, "wx", 384);
13238
+ } catch (error) {
13239
+ if (errno(error) !== "EEXIST")
13240
+ throw error;
13241
+ }
13242
+ if (stageHandle) {
13243
+ try {
13244
+ await stageHandle.writeFile(bytes);
13245
+ await stageHandle.sync();
13246
+ } finally {
13247
+ await stageHandle.close();
13248
+ }
13249
+ }
13250
+ if (!(await secureRead(stage)).equals(bytes))
13251
+ throw new AccountMigrationError("exclusive pointer stage differs");
13252
+ if (!stageHandle)
13253
+ await syncFile(stage);
13254
+ await boundary?.("empty-stage:after-pointer-stage");
13255
+ await syncDirectory(dirname(path5));
13256
+ await boundary?.("empty-stage:after-parent-prelink-sync");
13257
+ await boundary?.("pointer:before-link");
13258
+ await assertOwned();
13259
+ await assertSourceAbsent(paths);
13260
+ if (await exists(path5))
13261
+ throw new AccountMigrationError("foreign or competing pointer publication refuses overwrite");
13262
+ if (await exists(resolveAccountStorePaths(paths.legacyPath).storeDir))
13263
+ throw new AccountMigrationError("foreign logical store directory appeared before publication");
13264
+ try {
13265
+ await link(stage, path5);
13266
+ } catch (error) {
13267
+ if (errno(error) === "EEXIST")
13268
+ throw new AccountMigrationError("foreign or competing pointer publication refuses overwrite");
13269
+ throw new AccountMigrationError("exclusive pointer hard-link publication failed");
13270
+ }
13271
+ await boundary?.("pointer:after-link-before-parent-sync");
13272
+ await syncDirectory(dirname(path5));
13273
+ if (!isDeepStrictEqual(await readPointer(paths.legacyPath), pointer) || !isDeepStrictEqual(await readJournal(paths), journal))
13274
+ throw new AccountMigrationError("pointer publication readback differs");
13275
+ await expectedFreshArtifacts(paths, journal);
13276
+ await currentSuccessor(store, paths, journal);
13277
+ const admission = await readAccountStoreAdmission(paths.legacyPath, modules, options.now, journal.id);
13278
+ if (admission.status !== "active" || !isDeepStrictEqual(admission.receipt, receipt(journal)))
13279
+ throw new AccountMigrationError("published empty generation is not admitted");
13280
+ await boundary?.("pointer:after-sync-before-stage-cleanup");
13281
+ await cleanupPointerStage(paths.legacyPath, pointer, parentLease);
13282
+ await assertOwned();
13283
+ return { status: "completed", receipt: receipt(journal) };
13284
+ });
13285
+ }
13027
13286
  async function allocateGeneration(legacyPath) {
13028
13287
  if (await exists(resolveAccountStorePaths(legacyPath).storeDir))
13029
13288
  throw new AccountMigrationError("foreign logical directory refuses generation allocation");
@@ -13032,13 +13291,16 @@ async function allocateGeneration(legacyPath) {
13032
13291
  await prepareDirectories(paths);
13033
13292
  return paths;
13034
13293
  }
13035
- async function publishGenerationPointer(modules, paths, journal, parentLease, prior, boundary) {
13294
+ async function publishGenerationPointer(modules, paths, journal, parentLease, managementLease, prior, boundary, journalSavedBy) {
13036
13295
  await parentLease.assertOwned();
13296
+ await managementLease.assertOwned();
13037
13297
  const currentJournal = await readJournal(paths);
13038
13298
  if (!currentJournal || currentJournal.id !== journal.id || !isDeepStrictEqual(journalJson(currentJournal), journalJson(journal)))
13039
13299
  throw new AccountMigrationError("publication requires its complete synced canonical journal");
13040
- await syncFile(paths.migrationPath);
13041
- await syncDirectory(paths.storeDir);
13300
+ if (journalSavedBy !== managementLease) {
13301
+ await syncFile(paths.migrationPath);
13302
+ await syncDirectory(paths.storeDir);
13303
+ }
13042
13304
  const pointer = {
13043
13305
  schemaVersion: 1,
13044
13306
  id: journal.id,
@@ -13049,8 +13311,9 @@ async function publishGenerationPointer(modules, paths, journal, parentLease, pr
13049
13311
  const stage = `${path5}.${journal.id}.tmp`;
13050
13312
  const bytes = Buffer.from(`${JSON.stringify(pointer, null, 2)}
13051
13313
  `);
13052
- await exclusiveBytes(stage, bytes, digest(bytes));
13314
+ await exclusiveBytes(stage, bytes, digest(bytes), void 0, true);
13053
13315
  await parentLease.assertOwned();
13316
+ await managementLease.assertOwned();
13054
13317
  await boundary?.("pointer:before-link");
13055
13318
  if (await exists(resolveAccountStorePaths(paths.legacyPath).storeDir))
13056
13319
  throw new AccountMigrationError("foreign logical store directory appeared before publication");
@@ -13082,6 +13345,7 @@ async function publishGenerationPointer(modules, paths, journal, parentLease, pr
13082
13345
  stageName: () => stageName,
13083
13346
  beforeRename: async () => {
13084
13347
  await parentLease.assertOwned();
13348
+ await managementLease.assertOwned();
13085
13349
  if (!isDeepStrictEqual(await readPointer(paths.legacyPath), prior) || (await readJournal(oldPaths))?.status !== "inactive")
13086
13350
  throw new AccountMigrationError("inactive pointer changed before transition");
13087
13351
  await syncFile(`${path5}.${stageName}.tmp`);
@@ -13091,6 +13355,7 @@ async function publishGenerationPointer(modules, paths, journal, parentLease, pr
13091
13355
  await syncDirectory(dirname(path5));
13092
13356
  }
13093
13357
  await parentLease.assertOwned();
13358
+ await managementLease.assertOwned();
13094
13359
  }
13095
13360
  function withParentTopology(modules, legacyPath, body) {
13096
13361
  return modules.fs.withLock(legacyPath, {
@@ -13117,9 +13382,14 @@ async function finishPointerPublication(legacyPath, pointer, lease) {
13117
13382
  const path5 = accountStorePointerPath(legacyPath);
13118
13383
  await syncFile(path5);
13119
13384
  await syncDirectory(dirname(path5));
13385
+ if (await cleanupPointerStage(legacyPath, pointer, lease))
13386
+ await syncDirectory(dirname(path5));
13387
+ }
13388
+ async function cleanupPointerStage(legacyPath, pointer, lease) {
13389
+ const path5 = accountStorePointerPath(legacyPath);
13120
13390
  const stage = `${path5}.${pointer.id}.tmp`;
13121
13391
  if (!await exists(stage))
13122
- return;
13392
+ return false;
13123
13393
  const bytes = await secureRead(stage);
13124
13394
  if (!isDeepStrictEqual(decodeAccountStorePointer(jsonBytes(bytes), legacyPath), pointer))
13125
13395
  throw new AccountMigrationError("pointer stage differs from publication authority");
@@ -13128,7 +13398,7 @@ async function finishPointerPublication(legacyPath, pointer, lease) {
13128
13398
  throw new AccountMigrationError("pointer stage is not the published hard link");
13129
13399
  await lease.assertOwned();
13130
13400
  await unlink(stage);
13131
- await syncDirectory(dirname(path5));
13401
+ return true;
13132
13402
  }
13133
13403
 
13134
13404
  // ../core/dist/account-repository.js
@@ -15756,8 +16026,8 @@ function isRateLimitedForFamily(account, family, now, model) {
15756
16026
  clearExpiredRateLimits(account, now);
15757
16027
  return model != null && isRateLimitedForQuotaKey(account, getQuotaKey(family, model), now) || isRateLimitedForQuotaKey(account, family, now);
15758
16028
  }
15759
- function clearExpiredRateLimits(account, clock) {
15760
- const now = clock();
16029
+ function clearExpiredRateLimits(account, clock2) {
16030
+ const now = clock2();
15761
16031
  const keys = Object.keys(account.rateLimitResetTimes);
15762
16032
  for (const key of keys) {
15763
16033
  const resetTime = account.rateLimitResetTimes[key];
@@ -19767,6 +20037,7 @@ async function fetchWithAgyCliTransport(url, init = {}, options = {}) {
19767
20037
  };
19768
20038
  try {
19769
20039
  options.signal?.addEventListener("abort", abort, { once: true });
20040
+ options.signal?.throwIfAborted();
19770
20041
  socket.write(requestBytes);
19771
20042
  options.onDebug?.(`agy transport request dispatched (${requestBytes.byteLength} bytes)`);
19772
20043
  const { head, leftover } = await waitForHead(socket, timeoutMs, () => {
@@ -20678,19 +20949,35 @@ var loadCommonAuthPiSlot = memoize(() => Promise.resolve().then(() => (init_pi_s
20678
20949
 
20679
20950
  // ../core/dist/credential-redaction.js
20680
20951
  var MARKER = "[credential]";
20681
- function redactCredentialText(text2, credentials) {
20952
+ function maskSensitiveIdentifier(value) {
20953
+ if (typeof value !== "string" || value.length === 0)
20954
+ return "";
20955
+ if (value.length <= 8)
20956
+ return "****";
20957
+ return `${value.slice(0, 4)}****${value.slice(-4)}`;
20958
+ }
20959
+ function redactProjectIdText(text2, projectIds) {
20960
+ const identifiers = [...new Set(projectIds ?? [])].filter((projectId) => projectId.length > 0).sort((left, right) => right.length - left.length);
20961
+ if (identifiers.length > 0) {
20962
+ const expression = new RegExp(identifiers.map((projectId) => projectId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), "g");
20963
+ text2 = text2.replace(expression, (projectId) => maskSensitiveIdentifier(projectId));
20964
+ }
20965
+ return text2.replace(/(\bproject(?:[\s_-]*id)?\s*[:=]\s*)([a-z0-9_*][a-z0-9_*-]*)/gi, (match, label, value) => /^(?:unknown|n\/?a)$/i.test(value) || value.includes("****") ? match : `${label}${maskSensitiveIdentifier(value)}`);
20966
+ }
20967
+ function redactCredentialText(text2, credentials, projectIds) {
20968
+ text2 = redactProjectIdText(text2, projectIds);
20682
20969
  for (const credential of typeof credentials === "string" ? [credentials] : credentials ?? []) {
20683
20970
  if (credential)
20684
20971
  text2 = text2.split(credential).join(MARKER);
20685
20972
  }
20686
20973
  return text2.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g, MARKER).replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi, MARKER);
20687
20974
  }
20688
- function scrub2(value, credentials, seen = /* @__PURE__ */ new WeakSet()) {
20975
+ function scrub2(value, credentials, projectIds, seen = /* @__PURE__ */ new WeakSet()) {
20689
20976
  if (typeof value === "string")
20690
- return redactCredentialText(value, credentials);
20977
+ return redactCredentialText(value, credentials, projectIds);
20691
20978
  if (!value || typeof value !== "object")
20692
20979
  return value;
20693
- if (!containsCredential(value, credentials))
20980
+ if (!containsCredential(value, credentials, projectIds))
20694
20981
  return value;
20695
20982
  if (seen.has(value))
20696
20983
  return "[Circular]";
@@ -20698,32 +20985,35 @@ function scrub2(value, credentials, seen = /* @__PURE__ */ new WeakSet()) {
20698
20985
  const safe = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
20699
20986
  for (const key of Reflect.ownKeys(value)) {
20700
20987
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
20701
- if (key === "cause" && (!("value" in descriptor) || containsCredential(descriptor.value, credentials)))
20988
+ if (key === "cause" && (!("value" in descriptor) || containsCredential(descriptor.value, credentials, projectIds)))
20702
20989
  continue;
20703
- Object.defineProperty(safe, key, "value" in descriptor ? { ...descriptor, value: scrub2(descriptor.value, credentials, seen) } : descriptor);
20990
+ Object.defineProperty(safe, key, "value" in descriptor ? {
20991
+ ...descriptor,
20992
+ value: scrub2(descriptor.value, credentials, projectIds, seen)
20993
+ } : descriptor);
20704
20994
  }
20705
20995
  return safe;
20706
20996
  }
20707
- function containsCredential(value, credentials, seen = /* @__PURE__ */ new WeakSet()) {
20997
+ function containsCredential(value, credentials, projectIds, seen = /* @__PURE__ */ new WeakSet()) {
20708
20998
  if (typeof value === "string")
20709
- return redactCredentialText(value, credentials) !== value;
20999
+ return redactCredentialText(value, credentials, projectIds) !== value;
20710
21000
  if (!value || typeof value !== "object" || seen.has(value))
20711
21001
  return false;
20712
21002
  seen.add(value);
20713
21003
  return Reflect.ownKeys(value).some((key) => {
20714
21004
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
20715
- return "value" in descriptor && containsCredential(descriptor.value, credentials, seen);
21005
+ return "value" in descriptor && containsCredential(descriptor.value, credentials, projectIds, seen);
20716
21006
  });
20717
21007
  }
20718
- function redactCredentialError(error, credentials) {
21008
+ function redactCredentialError(error, credentials, projectIds) {
20719
21009
  const source = error instanceof Error || error instanceof DOMException ? error : void 0;
20720
- const message = redactCredentialText(source?.message ?? String(error), credentials);
21010
+ const message = redactCredentialText(source?.message ?? String(error), credentials, projectIds);
20721
21011
  const fields = source ? Reflect.ownKeys(source).map((key) => ({
20722
21012
  key,
20723
21013
  descriptor: Object.getOwnPropertyDescriptor(source, key)
20724
21014
  })) : [];
20725
21015
  const cause = fields.find(({ key }) => key === "cause")?.descriptor;
20726
- const secretCause = cause && (!("value" in cause) || containsCredential(cause.value, credentials));
21016
+ const secretCause = cause && (!("value" in cause) || containsCredential(cause.value, credentials, projectIds));
20727
21017
  try {
20728
21018
  if (source) {
20729
21019
  if (message !== source.message)
@@ -20735,7 +21025,7 @@ function redactCredentialError(error, credentials) {
20735
21025
  for (const { key, descriptor } of fields) {
20736
21026
  if (key === "message" || key === "cause" || !("value" in descriptor))
20737
21027
  continue;
20738
- const value = scrub2(descriptor.value, credentials);
21028
+ const value = scrub2(descriptor.value, credentials, projectIds);
20739
21029
  if (value !== descriptor.value)
20740
21030
  Object.defineProperty(source, key, { ...descriptor, value });
20741
21031
  }
@@ -20746,7 +21036,7 @@ function redactCredentialError(error, credentials) {
20746
21036
  } catch {
20747
21037
  }
20748
21038
  const safe = new Error(message);
20749
- safe.name = redactCredentialText(source?.name ?? "Error", credentials);
21039
+ safe.name = redactCredentialText(source?.name ?? "Error", credentials, projectIds);
20750
21040
  for (const { key, descriptor } of fields) {
20751
21041
  if (key === "message" || key === "cause" || !("value" in descriptor))
20752
21042
  continue;
@@ -20754,32 +21044,32 @@ function redactCredentialError(error, credentials) {
20754
21044
  ...descriptor,
20755
21045
  configurable: true,
20756
21046
  writable: true,
20757
- value: scrub2(descriptor.value, credentials)
21047
+ value: scrub2(descriptor.value, credentials, projectIds)
20758
21048
  });
20759
21049
  }
20760
21050
  if (cause && !secretCause && "value" in cause)
20761
21051
  safe.cause = cause.value;
20762
21052
  return safe;
20763
21053
  }
20764
- function redactDiagnosticText(text2, credentials, parsed) {
20765
- const direct = redactCredentialText(text2, credentials);
21054
+ function redactDiagnosticText(text2, credentials, projectIds, parsed) {
21055
+ const direct = redactCredentialText(text2, credentials, projectIds);
20766
21056
  if (direct !== text2 || !text2.includes("\\u"))
20767
21057
  return direct;
20768
21058
  try {
20769
21059
  const canonical4 = JSON.stringify(parsed ?? JSON.parse(text2));
20770
- const safe = redactCredentialText(canonical4, credentials);
21060
+ const safe = redactCredentialText(canonical4, credentials, projectIds);
20771
21061
  return safe === canonical4 ? text2 : safe;
20772
21062
  } catch {
20773
21063
  return text2;
20774
21064
  }
20775
21065
  }
20776
- function redactCredentialFrame(frame, credentials) {
21066
+ function redactCredentialFrame(frame, credentials, projectIds) {
20777
21067
  if (!frame.includes('"error"') && !frame.includes("\\u"))
20778
21068
  return frame;
20779
21069
  try {
20780
21070
  const value = JSON.parse(frame);
20781
21071
  if (value?.type === "error" || value?.error || value?.response?.error) {
20782
- return redactDiagnosticText(frame, credentials, value);
21072
+ return redactDiagnosticText(frame, credentials, projectIds, value);
20783
21073
  }
20784
21074
  } catch {
20785
21075
  }
@@ -20794,26 +21084,26 @@ function preserveResponseMetadata2(response, original) {
20794
21084
  }
20795
21085
  return response;
20796
21086
  }
20797
- async function redactCredentialResponse(response, credentials, bufferedBody) {
21087
+ async function redactCredentialResponse(response, credentials, bufferedBody, projectIds) {
20798
21088
  const init = {
20799
21089
  status: response.status,
20800
21090
  statusText: response.statusText,
20801
21091
  headers: new Headers(response.headers)
20802
21092
  };
20803
21093
  if (!response.ok) {
20804
- init.statusText = redactCredentialText(init.statusText, credentials);
21094
+ init.statusText = redactCredentialText(init.statusText, credentials, projectIds);
20805
21095
  let metadataChanged = init.statusText !== response.statusText;
20806
21096
  for (const [key, value] of init.headers) {
20807
- const safe = redactCredentialText(value, credentials);
21097
+ const safe = redactCredentialText(value, credentials, projectIds);
20808
21098
  if (safe !== value) {
20809
21099
  init.headers.set(key, safe);
20810
21100
  metadataChanged = true;
20811
21101
  }
20812
21102
  }
20813
21103
  const text2 = bufferedBody ?? (response.body ? await response.text().catch((error) => {
20814
- throw redactCredentialError(error, credentials);
21104
+ throw redactCredentialError(error, credentials, projectIds);
20815
21105
  }) : null);
20816
- const redacted = text2 === null ? null : redactDiagnosticText(text2, credentials);
21106
+ const redacted = text2 === null ? null : redactDiagnosticText(text2, credentials, projectIds);
20817
21107
  if ((bufferedBody !== void 0 || !response.body) && redacted === text2 && !metadataChanged)
20818
21108
  return response;
20819
21109
  if (response.body)
@@ -20827,7 +21117,7 @@ async function redactCredentialResponse(response, credentials, bufferedBody) {
20827
21117
  const decoder = new TextDecoder();
20828
21118
  const encoder = new TextEncoder();
20829
21119
  let pending = "";
20830
- const redact3 = (event) => event.replace(/^data: ?([^\r\n]*)/gm, (line, data) => line.slice(0, line.length - data.length) + redactCredentialFrame(data, credentials));
21120
+ const redact3 = (event) => event.replace(/^data: ?([^\r\n]*)/gm, (line, data) => line.slice(0, line.length - data.length) + redactCredentialFrame(data, credentials, projectIds));
20831
21121
  const body = new ReadableStream({
20832
21122
  async pull(controller) {
20833
21123
  try {
@@ -20856,14 +21146,14 @@ async function redactCredentialResponse(response, credentials, bufferedBody) {
20856
21146
  }
20857
21147
  } catch (error) {
20858
21148
  reader.releaseLock();
20859
- controller.error(redactCredentialError(error, credentials));
21149
+ controller.error(redactCredentialError(error, credentials, projectIds));
20860
21150
  }
20861
21151
  },
20862
21152
  async cancel(reason) {
20863
21153
  try {
20864
21154
  await reader.cancel(reason);
20865
21155
  } catch (error) {
20866
- throw redactCredentialError(error, credentials);
21156
+ throw redactCredentialError(error, credentials, projectIds);
20867
21157
  } finally {
20868
21158
  reader.releaseLock();
20869
21159
  }
@@ -20885,6 +21175,155 @@ function getPiAntigravityVaultDir() {
20885
21175
  return join6(dirname11(getPiAntigravityAuthFile()), "antigravity-auth-vault");
20886
21176
  }
20887
21177
 
21178
+ // ../core/dist/pre-response-deadline.js
21179
+ var PRE_RESPONSE_DEADLINE_MS = 6e5;
21180
+ var PRE_RESPONSE_TIMEOUT_MESSAGE = "Antigravity did not begin a response within the pre-response time limit. Check your connection and try again later.";
21181
+ var PreResponseTimeoutError = class extends Error {
21182
+ code = 412;
21183
+ status = "FAILED_PRECONDITION";
21184
+ reason = "PRE_RESPONSE_TIMEOUT";
21185
+ constructor() {
21186
+ super(PRE_RESPONSE_TIMEOUT_MESSAGE);
21187
+ this.name = "PreResponseTimeoutError";
21188
+ }
21189
+ };
21190
+ function preResponseTimeoutResponse() {
21191
+ return new Response(JSON.stringify({
21192
+ error: {
21193
+ code: 412,
21194
+ status: "FAILED_PRECONDITION",
21195
+ message: PRE_RESPONSE_TIMEOUT_MESSAGE
21196
+ }
21197
+ }), { status: 412, headers: { "Content-Type": "application/json" } });
21198
+ }
21199
+ var clock = {
21200
+ now: () => performance.now(),
21201
+ schedule(callback, delayMs) {
21202
+ const timer = setTimeout(callback, delayMs);
21203
+ timer.unref?.();
21204
+ return () => clearTimeout(timer);
21205
+ }
21206
+ };
21207
+ var PreResponseDeadline = class {
21208
+ caller;
21209
+ time;
21210
+ signal;
21211
+ controller = new AbortController();
21212
+ expiresAt;
21213
+ active = true;
21214
+ cancelTimer;
21215
+ detachCaller;
21216
+ detachSignals = [];
21217
+ constructor(caller, time = clock) {
21218
+ this.caller = caller;
21219
+ this.time = time;
21220
+ this.expiresAt = time.now() + PRE_RESPONSE_DEADLINE_MS;
21221
+ this.signal = this.controller.signal;
21222
+ const abort = () => {
21223
+ this.cancelTimer?.();
21224
+ this.controller.abort(caller?.reason);
21225
+ };
21226
+ this.detachCaller = () => caller?.removeEventListener("abort", abort);
21227
+ if (caller?.aborted)
21228
+ abort();
21229
+ else
21230
+ caller?.addEventListener("abort", abort, { once: true });
21231
+ this.arm();
21232
+ }
21233
+ remainingMs() {
21234
+ return Math.max(0, this.expiresAt - this.time.now());
21235
+ }
21236
+ follow(signal) {
21237
+ if (!signal || signal === this.signal)
21238
+ return;
21239
+ const abort = () => this.controller.abort(signal.reason);
21240
+ if (signal.aborted)
21241
+ abort();
21242
+ else
21243
+ signal.addEventListener("abort", abort, { once: true });
21244
+ this.detachSignals.push(() => signal.removeEventListener("abort", abort));
21245
+ this.check();
21246
+ }
21247
+ arm() {
21248
+ if (this.signal.aborted)
21249
+ return;
21250
+ this.cancelTimer = this.time.schedule(() => {
21251
+ if (this.remainingMs() > 0)
21252
+ this.arm();
21253
+ else
21254
+ this.expire();
21255
+ }, this.remainingMs());
21256
+ }
21257
+ expire() {
21258
+ this.cancelTimer?.();
21259
+ this.controller.abort(new PreResponseTimeoutError());
21260
+ }
21261
+ check() {
21262
+ this.caller?.throwIfAborted();
21263
+ if (this.active && this.remainingMs() <= 0 && !this.signal.aborted)
21264
+ this.expire();
21265
+ this.signal.throwIfAborted();
21266
+ }
21267
+ acceptHeaders() {
21268
+ this.check();
21269
+ this.acceptTerminalResponse();
21270
+ }
21271
+ acceptTerminalResponse() {
21272
+ this.active = false;
21273
+ this.cancelTimer?.();
21274
+ this.cancelTimer = void 0;
21275
+ }
21276
+ resume() {
21277
+ this.active = true;
21278
+ this.check();
21279
+ this.arm();
21280
+ }
21281
+ /** Cancel a response that arrives after its sender lost the abort race. */
21282
+ open(work) {
21283
+ return this.wait(() => {
21284
+ const pending = work();
21285
+ void pending.then((response) => {
21286
+ if (this.signal.aborted)
21287
+ void response.body?.cancel().catch(() => {
21288
+ });
21289
+ }, () => {
21290
+ });
21291
+ return pending;
21292
+ });
21293
+ }
21294
+ /** Interrupt even prerequisites that cannot themselves accept an AbortSignal. */
21295
+ async wait(work) {
21296
+ this.check();
21297
+ let abort = () => {
21298
+ };
21299
+ const cancelled = new Promise((_, reject) => {
21300
+ abort = () => reject(this.caller?.aborted ? this.caller.reason : this.signal.reason);
21301
+ this.signal.addEventListener("abort", abort, { once: true });
21302
+ });
21303
+ try {
21304
+ const result = await Promise.race([
21305
+ Promise.resolve().then(() => {
21306
+ this.check();
21307
+ return work();
21308
+ }),
21309
+ cancelled
21310
+ ]);
21311
+ this.check();
21312
+ return result;
21313
+ } finally {
21314
+ this.signal.removeEventListener("abort", abort);
21315
+ }
21316
+ }
21317
+ dispose() {
21318
+ this.cancelTimer?.();
21319
+ this.cancelTimer = void 0;
21320
+ this.detachCaller();
21321
+ for (const detach of this.detachSignals)
21322
+ detach();
21323
+ this.detachSignals.length = 0;
21324
+ }
21325
+ };
21326
+
20888
21327
  // ../core/dist/project.js
20889
21328
  var log3 = createLogger("project");
20890
21329
  var PROJECT_CONTEXT_CACHE_TTL_MS = 30 * 60 * 1e3;
@@ -22614,6 +23053,17 @@ function getAntigravityVaultEnrollmentName(host) {
22614
23053
  }
22615
23054
  }
22616
23055
 
23056
+ // ../core/dist/vault-grant-reach.js
23057
+ function emptyVaultRosterCause(reach) {
23058
+ if (reach === void 0)
23059
+ return "unknown";
23060
+ if (reach.grants === 0)
23061
+ return "no-grant";
23062
+ return "grant-reaches-nothing";
23063
+ }
23064
+ var VAULT_RECLASSIFY_COMMAND = "ck auth reclassify --from-registry";
23065
+ var VAULT_STATUS_COMMAND = "ck auth status";
23066
+
22617
23067
  // ../core/dist/vault-provider-state.js
22618
23068
  import { readFile as readFile7 } from "node:fs/promises";
22619
23069
  var VAULT_PROVIDER_STATE_SCHEMA_VERSION = 1;
@@ -23147,6 +23597,8 @@ function createAntigravityVaultAccountSource(options) {
23147
23597
  assertOpen();
23148
23598
  await consumer.accept(ref.routeId);
23149
23599
  },
23600
+ grantReach: () => closed ? void 0 : consumer.grantReach(),
23601
+ emptyRosterCause: () => closed || consumer.snapshot()?.rows.length !== 0 ? "unknown" : emptyVaultRosterCause(consumer.grantReach()),
23150
23602
  close: () => {
23151
23603
  if (closed)
23152
23604
  return;
@@ -24245,9 +24697,7 @@ function writeConsoleLog2(level, ...args) {
24245
24697
  }
24246
24698
  }
24247
24699
  function redactSensitive(value) {
24248
- if (typeof value !== "string" || value.length === 0) return "";
24249
- if (value.length <= 8) return "****";
24250
- return `${value.slice(0, 4)}****${value.slice(-4)}`;
24700
+ return maskSensitiveIdentifier(value);
24251
24701
  }
24252
24702
  var SENSITIVE_FIELD_PATTERN = /token|refresh|access|project|fingerprint|deviceId|sessionId|sessionToken|secret|password|apiKey|clientSecret/i;
24253
24703
  function redactSensitiveFields(value) {
@@ -26331,7 +26781,8 @@ var AntigravityConfigSchema = z.object({
26331
26781
  // Rate Limiting
26332
26782
  // =========================================================================
26333
26783
  /**
26334
- * Maximum time in seconds to wait when all accounts are rate-limited.
26784
+ * Cumulative wait budget in seconds while no account is eligible, shared by
26785
+ * rate-limit and soft-quota waits. Selecting an eligible account resets it.
26335
26786
  * If the minimum wait time across all accounts exceeds this threshold,
26336
26787
  * the plugin fails fast with an error instead of hanging.
26337
26788
  *
@@ -29917,9 +30368,7 @@ function hashText2(value) {
29917
30368
  return createHash12("sha256").update(value).digest("hex");
29918
30369
  }
29919
30370
  function maskIdentifier(value) {
29920
- if (typeof value !== "string" || value.length === 0) return void 0;
29921
- if (value.length <= 8) return "****";
29922
- return `${value.slice(0, 4)}****${value.slice(-4)}`;
30371
+ return maskSensitiveIdentifier(value) || void 0;
29923
30372
  }
29924
30373
  function redactProjectId(value) {
29925
30374
  return maskIdentifier(value);
@@ -33037,7 +33486,6 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
33037
33486
  let resolvedProjectId = projectId?.trim() || "";
33038
33487
  let toolDebugMissing = 0;
33039
33488
  const toolDebugSummaries = [];
33040
- let toolDebugPayload;
33041
33489
  let sessionId;
33042
33490
  let needsSignedThinkingWarmup = false;
33043
33491
  let thinkingRecoveryMessage;
@@ -33465,11 +33913,6 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
33465
33913
  toolDebugMissing = geminiResult.toolDebugMissing;
33466
33914
  toolDebugSummaries.push(...geminiResult.toolDebugSummaries);
33467
33915
  }
33468
- try {
33469
- toolDebugPayload = JSON.stringify(requestPayload.tools);
33470
- } catch {
33471
- toolDebugPayload = void 0;
33472
- }
33473
33916
  const enableToolHardening = options?.claudeToolHardening ?? true;
33474
33917
  if (enableToolHardening && isClaude && Array.isArray(requestPayload.tools) && requestPayload.tools.length > 0) {
33475
33918
  requestPayload.tools = injectParameterSignatures(
@@ -33707,7 +34150,6 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
33707
34150
  sessionId,
33708
34151
  toolDebugMissing,
33709
34152
  toolDebugSummary: toolDebugSummaries.slice(0, 20).join(" | "),
33710
- toolDebugPayload,
33711
34153
  needsSignedThinkingWarmup,
33712
34154
  headerStyle: "antigravity",
33713
34155
  thinkingRecoveryMessage
@@ -33775,7 +34217,7 @@ function buildThinkingWarmupBody(bodyText, isClaudeThinking) {
33775
34217
  }
33776
34218
  return safeStringify(parsed);
33777
34219
  }
33778
- async function transformAntigravityResponseIn(wire, response, streaming, debugContext, requestedModel, projectId, endpoint, effectiveModel, sessionId, toolDebugMissing, toolDebugSummary, toolDebugPayload, debugLines, dumpContext) {
34220
+ async function transformAntigravityResponseIn(wire, response, streaming, debugContext, requestedModel, projectId, endpoint, effectiveModel, sessionId, toolDebugMissing, toolDebugSummary, debugLines, dumpContext) {
33779
34221
  const contentType = response.headers.get("content-type") ?? "";
33780
34222
  const isJsonResponse = contentType.includes("application/json");
33781
34223
  const isEventStreamResponse = contentType.includes("text/event-stream");
@@ -33848,20 +34290,23 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
33848
34290
  errorBody = { error: { message: text2 } };
33849
34291
  }
33850
34292
  if (errorBody?.error) {
33851
- const rawErrorMessage = typeof errorBody.error.message === "string" && errorBody.error.message.length > 0 ? errorBody.error.message : "Unknown error";
34293
+ const upstreamErrorMessage = typeof errorBody.error.message === "string" && errorBody.error.message.length > 0 ? errorBody.error.message : "Unknown error";
34294
+ const rawErrorMessage = redactProjectIdText(upstreamErrorMessage, [
34295
+ projectId ?? ""
34296
+ ]);
33852
34297
  const errorType = detectErrorType(rawErrorMessage);
34298
+ const safeProjectId = maskSensitiveIdentifier(projectId) || "Unknown";
33853
34299
  const debugInfo = `
33854
34300
 
33855
34301
  [Debug Info]
33856
34302
  Requested Model: ${requestedModel || "Unknown"}
33857
34303
  Effective Model: ${effectiveModel || "Unknown"}
33858
- Project: ${projectId || "Unknown"}
34304
+ Project: ${safeProjectId}
33859
34305
  Endpoint: ${endpoint || "Unknown"}
33860
34306
  Status: ${response.status}
33861
34307
  Request ID: ${headers.get("x-request-id") || "N/A"}${toolDebugMissing !== void 0 ? `
33862
34308
  Tool Debug Missing: ${toolDebugMissing}` : ""}${toolDebugSummary ? `
33863
- Tool Debug Summary: ${toolDebugSummary}` : ""}${toolDebugPayload ? `
33864
- Tool Debug Payload: ${toolDebugPayload}` : ""}`;
34309
+ Tool Debug Summary: ${toolDebugSummary}` : ""}`;
33865
34310
  const injectedDebug = debugText ? `
33866
34311
 
33867
34312
  ${debugText}` : "";
@@ -35177,12 +35622,11 @@ function createRequestExecutor(deps) {
35177
35622
  log16.debug("routing-report-failed", { sessionId, error: String(error) });
35178
35623
  }
35179
35624
  };
35180
- async function execute(input2, init, options = {}, selectedCredentials = /* @__PURE__ */ new Set()) {
35625
+ async function execute(input2, init, options, selectedCredentials, selectedProjectIds, deadline, waitPolicy) {
35181
35626
  const assertAdmission = async () => {
35182
- init?.signal?.throwIfAborted();
35183
- await deps.assertAdmission?.();
35184
- init?.signal?.throwIfAborted();
35627
+ await deadline.wait(() => deps.assertAdmission?.());
35185
35628
  };
35629
+ const logResponseBody2 = (...args) => deadline.wait(() => debug.logResponseBody(...args));
35186
35630
  await assertAdmission();
35187
35631
  if (typeof input2 !== "string") {
35188
35632
  if (input2 instanceof Request) {
@@ -35193,7 +35637,7 @@ function createRequestExecutor(deps) {
35193
35637
  headers.set(k, v);
35194
35638
  });
35195
35639
  }
35196
- const bodyBuffer = req.body ? await req.clone().arrayBuffer() : void 0;
35640
+ const bodyBuffer = req.body ? await deadline.wait(() => req.clone().arrayBuffer()) : void 0;
35197
35641
  init = {
35198
35642
  method: init?.method ?? req.method,
35199
35643
  headers,
@@ -35245,7 +35689,10 @@ function createRequestExecutor(deps) {
35245
35689
  thinkingBudget: registered.thinkingConfig?.thinkingBudget
35246
35690
  };
35247
35691
  }
35248
- const transport = options.transport ?? defaultTransport2;
35692
+ const sender = options.transport ?? defaultTransport2;
35693
+ const transport = (url, sendInit, sendOptions) => deadline.open(
35694
+ () => sender(url, sendInit, { ...sendOptions, signal: deadline.signal })
35695
+ );
35249
35696
  const requestSessionIdentity = options.session ?? extractOpenCodeSessionIdentity(init?.headers);
35250
35697
  const agyRequestScope = agySessionRegistry.beginRequest(
35251
35698
  agyMetadataIdentity(requestSessionIdentity, kind)
@@ -35260,7 +35707,7 @@ function createRequestExecutor(deps) {
35260
35707
  const urlString2 = typeof input2 === "string" ? input2 : toUrlString(input2);
35261
35708
  const modelFromUrl = extractModelFromUrl(urlString2) ?? "unknown";
35262
35709
  return createNoAccountResponse(
35263
- credentials.domain === "vault" ? VAULT_ACCOUNT_REMEDY : "No Antigravity accounts configured. Run `opencode auth login`.",
35710
+ credentials.domain === "vault" ? credentials.emptyRosterRefusal?.() ?? VAULT_ACCOUNT_REMEDY : "No Antigravity accounts configured. Run `opencode auth login`.",
35264
35711
  modelFromUrl
35265
35712
  );
35266
35713
  }
@@ -35270,7 +35717,13 @@ function createRequestExecutor(deps) {
35270
35717
  const debugLines = [];
35271
35718
  const pushDebug = (line) => {
35272
35719
  if (!debug.isDebugEnabled()) return;
35273
- debugLines.push(redactCredentialText(line, [...selectedCredentials]));
35720
+ debugLines.push(
35721
+ redactCredentialText(
35722
+ line,
35723
+ [...selectedCredentials],
35724
+ [...selectedProjectIds]
35725
+ )
35726
+ );
35274
35727
  };
35275
35728
  pushDebug(`request=${urlString}`);
35276
35729
  if (requestSessionIdentity.sessionId) {
@@ -35289,6 +35742,7 @@ function createRequestExecutor(deps) {
35289
35742
  let lastError = null;
35290
35743
  const abortSignal = init?.signal ?? void 0;
35291
35744
  const checkAborted = () => {
35745
+ deadline.check();
35292
35746
  if (abortSignal?.aborted) {
35293
35747
  throw abortSignal.reason instanceof Error ? abortSignal.reason : new Error("Aborted");
35294
35748
  }
@@ -35318,8 +35772,9 @@ function createRequestExecutor(deps) {
35318
35772
  }
35319
35773
  }
35320
35774
  try {
35321
- await notify?.(message, variant2);
35775
+ await deadline.wait(() => notify?.(message, variant2));
35322
35776
  } catch {
35777
+ checkAborted();
35323
35778
  }
35324
35779
  };
35325
35780
  let accountSwitchCount = 0;
@@ -35327,6 +35782,8 @@ function createRequestExecutor(deps) {
35327
35782
  let previousAccountIndex = -1;
35328
35783
  let needsCacheWarmup = false;
35329
35784
  let localRecaptureUsed = false;
35785
+ const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1e3;
35786
+ let allAccountsBlockedAt;
35330
35787
  while (true) {
35331
35788
  await assertAdmission();
35332
35789
  checkAborted();
@@ -35407,6 +35864,10 @@ function createRequestExecutor(deps) {
35407
35864
  account = null;
35408
35865
  }
35409
35866
  if (!account) {
35867
+ allAccountsBlockedAt ??= Date.now();
35868
+ const blockedSince = allAccountsBlockedAt;
35869
+ const remainingWaitMs = () => maxWaitMs > 0 ? Math.max(0, maxWaitMs - (Date.now() - blockedSince)) : Number.POSITIVE_INFINITY;
35870
+ const quotaWins = remainingWaitMs() <= deadline.remainingMs();
35410
35871
  if (accountManager.areAllAccountsOverSoftQuota(
35411
35872
  family,
35412
35873
  config.soft_quota_threshold_percent,
@@ -35420,8 +35881,12 @@ function createRequestExecutor(deps) {
35420
35881
  softQuotaCacheTtlMs,
35421
35882
  model
35422
35883
  );
35423
- const maxWaitMs2 = (config.max_rate_limit_wait_seconds ?? 300) * 1e3;
35424
- if (softQuotaWaitMs === null || maxWaitMs2 > 0 && softQuotaWaitMs > maxWaitMs2) {
35884
+ waitPolicy.refusal = quotaWins ? () => createNativeGoogleErrorResponse({
35885
+ status: 412,
35886
+ reason: "soft_quota",
35887
+ resetAfterMs: softQuotaWaitMs
35888
+ }) : void 0;
35889
+ if (softQuotaWaitMs === null || remainingWaitMs() <= 0 || maxWaitMs > 0 && softQuotaWaitMs > maxWaitMs) {
35425
35890
  const waitTimeFormatted = softQuotaWaitMs ? formatWaitTime(softQuotaWaitMs) : "unknown";
35426
35891
  await showToast(
35427
35892
  `All accounts over ${threshold}% quota threshold. Resets in ${waitTimeFormatted}.`,
@@ -35443,11 +35908,16 @@ function createRequestExecutor(deps) {
35443
35908
  );
35444
35909
  retryState.markSoftQuotaToastShown();
35445
35910
  }
35446
- await sleep4(softQuotaWaitMs, abortSignal);
35911
+ await sleep4(Math.min(softQuotaWaitMs, remainingWaitMs()), abortSignal);
35447
35912
  continue;
35448
35913
  }
35449
35914
  const minWaitMs = accountManager.getMinWaitTimeForFamily(family, model);
35450
35915
  const waitMs = minWaitMs || 6e4;
35916
+ waitPolicy.refusal = quotaWins ? () => createNativeGoogleErrorResponse({
35917
+ status: 412,
35918
+ reason: "pool_unavailable",
35919
+ resetAfterMs: minWaitMs > 0 ? minWaitMs : void 0
35920
+ }) : void 0;
35451
35921
  pushDebug(
35452
35922
  `all-rate-limited family=${family} accounts=${accountCount} waitMs=${waitMs}`
35453
35923
  );
@@ -35462,8 +35932,7 @@ function createRequestExecutor(deps) {
35462
35932
  accountManager.getAccountsSnapshot()
35463
35933
  );
35464
35934
  }
35465
- const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1e3;
35466
- if (maxWaitMs > 0 && waitMs > maxWaitMs) {
35935
+ if (remainingWaitMs() <= 0 || maxWaitMs > 0 && waitMs > maxWaitMs) {
35467
35936
  const waitTimeFormatted = formatWaitTime(waitMs);
35468
35937
  await showToast(
35469
35938
  `Rate limited for ${waitTimeFormatted}. Try again later or add another account.`,
@@ -35485,9 +35954,11 @@ function createRequestExecutor(deps) {
35485
35954
  );
35486
35955
  retryState.markRateLimitToastShown();
35487
35956
  }
35488
- await sleep4(waitMs, abortSignal);
35957
+ await sleep4(Math.min(waitMs, remainingWaitMs()), abortSignal);
35489
35958
  continue;
35490
35959
  }
35960
+ allAccountsBlockedAt = void 0;
35961
+ waitPolicy.refusal = void 0;
35491
35962
  retryState.resetAllAccountsBlockedToasts();
35492
35963
  pushDebug(
35493
35964
  `selected idx=${account.index} email=${account.email ?? ""} family=${family} accounts=${accountCount} strategy=${config.account_selection_strategy}`
@@ -35526,9 +35997,22 @@ function createRequestExecutor(deps) {
35526
35997
  throw new Error("Local credentials were not resolved");
35527
35998
  await assertAdmission();
35528
35999
  if (auth.access) selectedCredentials.add(auth.access);
35529
- const context = await credentials.ensureProject(auth).catch((error) => {
35530
- throw redactCredentialError(error, [...selectedCredentials]);
36000
+ const packedProject = parseRefreshParts(auth.refresh);
36001
+ for (const projectId of [
36002
+ packedProject.projectId,
36003
+ packedProject.managedProjectId
36004
+ ]) {
36005
+ if (projectId) selectedProjectIds.add(projectId);
36006
+ }
36007
+ const context = await deadline.wait(() => credentials.ensureProject(auth)).catch((error) => {
36008
+ throw redactCredentialError(
36009
+ error,
36010
+ [...selectedCredentials],
36011
+ [...selectedProjectIds]
36012
+ );
35531
36013
  });
36014
+ if (context.effectiveProjectId)
36015
+ selectedProjectIds.add(context.effectiveProjectId);
35532
36016
  await assertAdmission();
35533
36017
  const projectAuth = {
35534
36018
  ...context.auth,
@@ -35538,8 +36022,9 @@ function createRequestExecutor(deps) {
35538
36022
  if (persistProject && projectAuth.refresh !== auth.refresh) {
35539
36023
  credentials.updateFromAuth(account, projectAuth);
35540
36024
  try {
35541
- await credentials.saveToDisk();
36025
+ await deadline.wait(() => credentials.saveToDisk());
35542
36026
  } catch (error) {
36027
+ checkAborted();
35543
36028
  log16.error("Failed to persist project context", {
35544
36029
  error: String(error)
35545
36030
  });
@@ -35558,7 +36043,9 @@ function createRequestExecutor(deps) {
35558
36043
  if (accessTokenExpired(authRecord)) {
35559
36044
  try {
35560
36045
  await assertAdmission();
35561
- const refreshed = await credentials.refresh(account);
36046
+ const refreshed = await deadline.wait(
36047
+ () => credentials.refresh(account)
36048
+ );
35562
36049
  if (!refreshed) {
35563
36050
  const { failures, shouldCooldown, cooldownMs } = retryState.trackAccountFailure(account.index);
35564
36051
  trackers.health.recordFailure(account.index);
@@ -35592,13 +36079,15 @@ function createRequestExecutor(deps) {
35592
36079
  authRecord = refreshed;
35593
36080
  grantCheck = captureFor(authRecord);
35594
36081
  try {
35595
- await credentials.saveToDisk();
36082
+ await deadline.wait(() => credentials.saveToDisk());
35596
36083
  } catch (error) {
36084
+ checkAborted();
35597
36085
  log16.error("Failed to persist refreshed auth", {
35598
36086
  error: String(error)
35599
36087
  });
35600
36088
  }
35601
36089
  } catch (error) {
36090
+ checkAborted();
35602
36091
  if (credentials.isInvalidGrant(error)) {
35603
36092
  const removed = credentials.removeAccount(account);
35604
36093
  if (removed) {
@@ -35606,8 +36095,9 @@ function createRequestExecutor(deps) {
35606
36095
  "Removed revoked account from pool - reauthenticate via `opencode auth login`"
35607
36096
  );
35608
36097
  try {
35609
- await credentials.saveToDiskReplace();
36098
+ await deadline.wait(() => credentials.saveToDiskReplace());
35610
36099
  } catch (persistError) {
36100
+ checkAborted();
35611
36101
  log16.error("Failed to persist revoked account removal", {
35612
36102
  error: String(persistError)
35613
36103
  });
@@ -35615,8 +36105,9 @@ function createRequestExecutor(deps) {
35615
36105
  }
35616
36106
  if (accountManager.getAccountCount() === 0) {
35617
36107
  try {
35618
- await credentials.clearStoredAuth();
36108
+ await deadline.wait(() => credentials.clearStoredAuth());
35619
36109
  } catch (storeError) {
36110
+ checkAborted();
35620
36111
  log16.error(
35621
36112
  "Failed to clear stored Antigravity OAuth credentials",
35622
36113
  {
@@ -35664,6 +36155,7 @@ function createRequestExecutor(deps) {
35664
36155
  localGrant = await prepareLocalGrant(authRecord, grantCheck);
35665
36156
  retryState.resetAccountFailureState(account.index);
35666
36157
  } catch (error) {
36158
+ checkAborted();
35667
36159
  const { failures, shouldCooldown, cooldownMs } = retryState.trackAccountFailure(account.index);
35668
36160
  trackers.health.recordFailure(account.index);
35669
36161
  lastError = error instanceof Error ? error : new Error(String(error));
@@ -35685,10 +36177,12 @@ function createRequestExecutor(deps) {
35685
36177
  const credentialForAuxiliarySend = async (sendInit, preparedProjectId) => {
35686
36178
  await assertAdmission();
35687
36179
  if (credentials.domain === "vault") {
35688
- const admission = await credentials.admit({
35689
- account: selected,
35690
- signal: abortSignal
35691
- });
36180
+ const admission = await deadline.wait(
36181
+ () => credentials.admit({
36182
+ account: selected,
36183
+ signal: abortSignal
36184
+ })
36185
+ );
35692
36186
  selectedCredentials.add(admission.accessToken);
35693
36187
  if (admission.projectId !== preparedProjectId) {
35694
36188
  throw new Error(
@@ -35704,7 +36198,7 @@ function createRequestExecutor(deps) {
35704
36198
  "Local credentials were not resolved for the selected account"
35705
36199
  );
35706
36200
  }
35707
- await localGrant.captured.check();
36201
+ await deadline.wait(() => localGrant.captured.check());
35708
36202
  await assertAdmission();
35709
36203
  return { init: sendInit };
35710
36204
  };
@@ -35746,21 +36240,25 @@ function createRequestExecutor(deps) {
35746
36240
  onDebug: pushDebug
35747
36241
  });
35748
36242
  reportVault401(warmupSend.admission, warmupResponse.status);
35749
- const transformed = await wire.transformResponse(
35750
- warmupResponse,
35751
- true,
35752
- warmupDebugContext,
35753
- prepared.requestedModel,
35754
- projectId,
35755
- warmupUrl,
35756
- prepared.effectiveModel,
35757
- prepared.sessionId
36243
+ const transformed = await deadline.wait(
36244
+ () => wire.transformResponse(
36245
+ warmupResponse,
36246
+ true,
36247
+ warmupDebugContext,
36248
+ prepared.requestedModel,
36249
+ projectId,
36250
+ warmupUrl,
36251
+ prepared.effectiveModel,
36252
+ prepared.sessionId
36253
+ )
35758
36254
  );
35759
- await transformed.text();
36255
+ await deadline.wait(() => transformed.text());
35760
36256
  warmupState.markSuccess(prepared.sessionId);
35761
36257
  pushDebug("thinking-warmup: done");
35762
36258
  } catch (error) {
35763
36259
  warmupState.clearWarmupAttempt(prepared.sessionId);
36260
+ if (error instanceof PreResponseTimeoutError) throw error;
36261
+ checkAborted();
35764
36262
  if (isLocalGrantError(error)) throw error;
35765
36263
  pushDebug(
35766
36264
  `thinking-warmup: failed ${error instanceof Error ? error.message : String(error)}`
@@ -35789,14 +36287,16 @@ function createRequestExecutor(deps) {
35789
36287
  reportVault401(probeSend.admission, probeResponse.status);
35790
36288
  if (probeResponse.body) {
35791
36289
  const reader = probeResponse.body.getReader();
35792
- await reader.read();
35793
- await reader.cancel();
36290
+ await deadline.wait(() => reader.read());
36291
+ await deadline.wait(() => reader.cancel());
35794
36292
  }
35795
36293
  const status = probeResponse.status;
35796
36294
  if (status >= 400) {
35797
36295
  let errorSnippet = "";
35798
36296
  try {
35799
- const errText = await probeResponse.text().catch(() => "");
36297
+ const errText = await deadline.wait(
36298
+ () => probeResponse.text().catch(() => "")
36299
+ );
35800
36300
  errorSnippet = errText.slice(0, 200);
35801
36301
  } catch {
35802
36302
  }
@@ -35809,6 +36309,8 @@ function createRequestExecutor(deps) {
35809
36309
  );
35810
36310
  }
35811
36311
  } catch (error) {
36312
+ if (error instanceof PreResponseTimeoutError) throw error;
36313
+ checkAborted();
35812
36314
  if (isLocalGrantError(error)) {
35813
36315
  needsCacheWarmup = true;
35814
36316
  throw error;
@@ -35849,10 +36351,12 @@ function createRequestExecutor(deps) {
35849
36351
  let sendAccessToken;
35850
36352
  let sendProjectId;
35851
36353
  if (credentials.domain === "vault") {
35852
- sendAdmission = rotatedAdmission ?? await credentials.admit({
35853
- account,
35854
- signal: abortSignal
35855
- });
36354
+ sendAdmission = rotatedAdmission ?? await deadline.wait(
36355
+ () => credentials.admit({
36356
+ account,
36357
+ signal: abortSignal
36358
+ })
36359
+ );
35856
36360
  rotatedAdmission = void 0;
35857
36361
  sendAccessToken = sendAdmission.accessToken;
35858
36362
  sendProjectId = sendAdmission.projectId;
@@ -35864,6 +36368,7 @@ function createRequestExecutor(deps) {
35864
36368
  "Local credentials were not resolved for the selected account"
35865
36369
  );
35866
36370
  }
36371
+ if (sendProjectId) selectedProjectIds.add(sendProjectId);
35867
36372
  selectedCredentials.add(sendAccessToken);
35868
36373
  const prepared = prepareAgyWireRequest(wire, {
35869
36374
  input: input2,
@@ -35917,7 +36422,6 @@ function createRequestExecutor(deps) {
35917
36422
  sessionId: prepared.sessionId,
35918
36423
  toolDebugMissing: prepared.toolDebugMissing,
35919
36424
  toolDebugSummary: prepared.toolDebugSummary,
35920
- toolDebugPayload: prepared.toolDebugPayload,
35921
36425
  dumpContext
35922
36426
  });
35923
36427
  await runThinkingWarmup(prepared, sendProjectId);
@@ -35940,7 +36444,7 @@ function createRequestExecutor(deps) {
35940
36444
  "Local credentials were not resolved for the selected account"
35941
36445
  );
35942
36446
  }
35943
- await localGrant.captured.check();
36447
+ await deadline.wait(() => localGrant.captured.check());
35944
36448
  await assertAdmission();
35945
36449
  }
35946
36450
  pushDebug(
@@ -35952,6 +36456,7 @@ function createRequestExecutor(deps) {
35952
36456
  prepared.init,
35953
36457
  { signal: abortSignal, onDebug: pushDebug }
35954
36458
  );
36459
+ if (response.ok) deadline.acceptHeaders();
35955
36460
  apiRequestCount++;
35956
36461
  accountManager.recordRequest(account.index, family);
35957
36462
  const requestCounts = accountManager.getDailyRequestCounts(
@@ -35968,17 +36473,22 @@ function createRequestExecutor(deps) {
35968
36473
  noteGeminiDumpResponse(dumpContext, response);
35969
36474
  if (credentials.domain === "vault" && sendAdmission && response.status === 401) {
35970
36475
  try {
35971
- await sendAdmission.report401(response.status);
36476
+ await deadline.wait(
36477
+ () => sendAdmission.report401(response.status)
36478
+ );
35972
36479
  } catch (error) {
36480
+ checkAborted();
35973
36481
  log16.debug("send-admission-401-report-failed", {
35974
36482
  error: String(error)
35975
36483
  });
35976
36484
  }
35977
36485
  if (!vault401Retried) {
35978
- const next = await credentials.admit({
35979
- account,
35980
- signal: abortSignal
35981
- });
36486
+ const next = await deadline.wait(
36487
+ () => credentials.admit({
36488
+ account,
36489
+ signal: abortSignal
36490
+ })
36491
+ );
35982
36492
  if (next.credentialId === sendAdmission.credentialId && next.accountIdentity === sendAdmission.accountIdentity && next.recordVersion > sendAdmission.recordVersion) {
35983
36493
  vault401Retried = true;
35984
36494
  rotatedAdmission = next;
@@ -36016,13 +36526,16 @@ function createRequestExecutor(deps) {
36016
36526
  );
36017
36527
  const bodyInfo = await (async () => {
36018
36528
  try {
36019
- const text2 = await response.clone().text();
36529
+ const text2 = await deadline.wait(
36530
+ () => response.clone().text()
36531
+ );
36020
36532
  try {
36021
36533
  return JSON.parse(text2);
36022
36534
  } catch {
36023
36535
  return null;
36024
36536
  }
36025
36537
  } catch {
36538
+ checkAborted();
36026
36539
  return null;
36027
36540
  }
36028
36541
  })();
@@ -36106,7 +36619,7 @@ function createRequestExecutor(deps) {
36106
36619
  effectiveDelayMs,
36107
36620
  reasonInfo
36108
36621
  );
36109
- await debug.logResponseBody(debugContext, response, 429);
36622
+ await logResponseBody2(debugContext, response, 429);
36110
36623
  trackers.health.recordRateLimit(account.index);
36111
36624
  const _accountLabel = account.email || `Account ${account.index + 1}`;
36112
36625
  if (backoff.attempt === 1 && rateLimitReason !== "QUOTA_EXHAUSTED") {
@@ -36189,7 +36702,9 @@ function createRequestExecutor(deps) {
36189
36702
  retryState.resetRateLimitState(account.index, quotaKey);
36190
36703
  retryState.resetAccountFailureState(account.index);
36191
36704
  if (response.status === 403) {
36192
- const errorBodyText = await response.clone().text().catch(() => "");
36705
+ const errorBodyText = await deadline.wait(
36706
+ () => response.clone().text().catch(() => "")
36707
+ );
36193
36708
  const extracted = classifyAccessError(errorBodyText);
36194
36709
  if (extracted.accountIneligible) {
36195
36710
  const ineligibleReason = extracted.message ?? "Google marked this account as ineligible for Antigravity.";
@@ -36251,11 +36766,7 @@ function createRequestExecutor(deps) {
36251
36766
  }
36252
36767
  const shouldRetryEndpoint = response.status === 403 || response.status === 404 || response.status >= 500;
36253
36768
  if (shouldRetryEndpoint && i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
36254
- await debug.logResponseBody(
36255
- debugContext,
36256
- response,
36257
- response.status
36258
- );
36769
+ await logResponseBody2(debugContext, response, response.status);
36259
36770
  lastFailure = createFailureContext(response);
36260
36771
  continue;
36261
36772
  }
@@ -36312,21 +36823,13 @@ function createRequestExecutor(deps) {
36312
36823
  note: response.ok ? "Success" : `Error ${response.status}`
36313
36824
  });
36314
36825
  if (response.ok && !prepared.streaming) {
36315
- await debug.logResponseBody(
36316
- debugContext,
36317
- response,
36318
- response.status
36319
- );
36826
+ await logResponseBody2(debugContext, response, response.status);
36320
36827
  }
36321
36828
  if (!response.ok) {
36322
- await debug.logResponseBody(
36323
- debugContext,
36324
- response,
36325
- response.status
36326
- );
36829
+ await logResponseBody2(debugContext, response, response.status);
36327
36830
  if (response.status === 400) {
36328
36831
  const cloned = response.clone();
36329
- const bodyText = await cloned.text();
36832
+ const bodyText = await deadline.wait(() => cloned.text());
36330
36833
  if (bodyText.includes("Prompt is too long") || bodyText.includes("prompt_too_long")) {
36331
36834
  await showToast(
36332
36835
  "Context too long - use /compact to reduce size",
@@ -36341,7 +36844,7 @@ function createRequestExecutor(deps) {
36341
36844
  const maxAttempts = config.empty_response_max_attempts ?? 4;
36342
36845
  const retryDelayMs = config.empty_response_retry_delay_ms ?? 2e3;
36343
36846
  const clonedForCheck = response.clone();
36344
- const bodyText = await clonedForCheck.text();
36847
+ const bodyText = await deadline.wait(() => clonedForCheck.text());
36345
36848
  if (isEmptyResponseBody(bodyText)) {
36346
36849
  const emptyAttemptKey = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
36347
36850
  const currentAttempts = retryState.recordEmptyResponseAttempt(emptyAttemptKey);
@@ -36349,6 +36852,7 @@ function createRequestExecutor(deps) {
36349
36852
  `empty-response: attempt ${currentAttempts}/${maxAttempts}`
36350
36853
  );
36351
36854
  if (currentAttempts < maxAttempts) {
36855
+ deadline.resume();
36352
36856
  await showToast(
36353
36857
  `Empty response received. Retrying (${currentAttempts}/${maxAttempts})...`,
36354
36858
  "warning"
@@ -36365,20 +36869,21 @@ function createRequestExecutor(deps) {
36365
36869
  const _emptyAttemptKeyClean = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
36366
36870
  retryState.clearEmptyResponseAttempts();
36367
36871
  }
36368
- const transformedResponse = await wire.transformResponse(
36369
- response,
36370
- prepared.streaming,
36371
- debugContext,
36372
- prepared.requestedModel,
36373
- prepared.projectId,
36374
- prepared.endpoint,
36375
- prepared.effectiveModel,
36376
- prepared.sessionId,
36377
- prepared.toolDebugMissing,
36378
- prepared.toolDebugSummary,
36379
- prepared.toolDebugPayload,
36380
- debugLines,
36381
- dumpContext
36872
+ const transformedResponse = await deadline.wait(
36873
+ () => wire.transformResponse(
36874
+ response,
36875
+ prepared.streaming,
36876
+ debugContext,
36877
+ prepared.requestedModel,
36878
+ prepared.projectId,
36879
+ prepared.endpoint,
36880
+ prepared.effectiveModel,
36881
+ prepared.sessionId,
36882
+ prepared.toolDebugMissing,
36883
+ prepared.toolDebugSummary,
36884
+ debugLines,
36885
+ dumpContext
36886
+ )
36382
36887
  );
36383
36888
  const contextError = transformedResponse.headers.get(
36384
36889
  "x-antigravity-context-error"
@@ -36436,6 +36941,8 @@ function createRequestExecutor(deps) {
36436
36941
  }
36437
36942
  return transformedResponse;
36438
36943
  } catch (error) {
36944
+ if (error instanceof PreResponseTimeoutError) throw error;
36945
+ checkAborted();
36439
36946
  if (tokenConsumed && (!isLocalGrantError(error) || !physicalAttemptStarted)) {
36440
36947
  trackers.token.refund(account.index);
36441
36948
  tokenConsumed = false;
@@ -36444,7 +36951,8 @@ function createRequestExecutor(deps) {
36444
36951
  if (error instanceof LocalGrantSupersededError && !localRecaptureUsed) {
36445
36952
  localRecaptureUsed = true;
36446
36953
  try {
36447
- await localGrant.captured.resolveCurrent();
36954
+ const originalGrant = localGrant.captured;
36955
+ await deadline.wait(() => originalGrant.resolveCurrent());
36448
36956
  const auth = credentials.toAuthDetails(account);
36449
36957
  if (!auth.access || accessTokenExpired(auth))
36450
36958
  return createNativeGoogleErrorResponse({
@@ -36469,6 +36977,7 @@ function createRequestExecutor(deps) {
36469
36977
  }
36470
36978
  if (error instanceof Error && error.message === "THINKING_RECOVERY_NEEDED") {
36471
36979
  if (!forceThinkingRecovery) {
36980
+ deadline.resume();
36472
36981
  pushDebug(
36473
36982
  "thinking-recovery: API error detected, retrying with forced recovery"
36474
36983
  );
@@ -36537,7 +37046,6 @@ function createRequestExecutor(deps) {
36537
37046
  lastFailure.sessionId,
36538
37047
  lastFailure.toolDebugMissing,
36539
37048
  lastFailure.toolDebugSummary,
36540
- lastFailure.toolDebugPayload,
36541
37049
  debugLines,
36542
37050
  lastFailure.dumpContext
36543
37051
  );
@@ -36560,7 +37068,6 @@ function createRequestExecutor(deps) {
36560
37068
  lastFailure.sessionId,
36561
37069
  lastFailure.toolDebugMissing,
36562
37070
  lastFailure.toolDebugSummary,
36563
- lastFailure.toolDebugPayload,
36564
37071
  debugLines,
36565
37072
  lastFailure.dumpContext
36566
37073
  );
@@ -36584,7 +37091,6 @@ function createRequestExecutor(deps) {
36584
37091
  lastFailure.sessionId,
36585
37092
  lastFailure.toolDebugMissing,
36586
37093
  lastFailure.toolDebugSummary,
36587
- lastFailure.toolDebugPayload,
36588
37094
  debugLines,
36589
37095
  lastFailure.dumpContext
36590
37096
  );
@@ -36628,20 +37134,42 @@ function createRequestExecutor(deps) {
36628
37134
  const cancellation = createRequestCancellation(
36629
37135
  requestedSignal ? [requestedSignal, shutdown.signal] : [shutdown.signal]
36630
37136
  );
37137
+ const deadline = new PreResponseDeadline(
37138
+ cancellation.signal,
37139
+ deps.preResponseClock
37140
+ );
37141
+ log16.debug("pre-response-start", { limitMs: PRE_RESPONSE_DEADLINE_MS });
37142
+ const waitPolicy = {};
36631
37143
  const selectedCredentials = /* @__PURE__ */ new Set();
36632
- const pending = execute(
36633
- input2,
36634
- { ...init, signal: cancellation.signal },
36635
- requestOptions,
36636
- selectedCredentials
36637
- ).then(
37144
+ const selectedProjectIds = /* @__PURE__ */ new Set();
37145
+ const pending = deadline.wait(
37146
+ () => execute(
37147
+ input2,
37148
+ { ...init, signal: deadline.signal },
37149
+ requestOptions ?? {},
37150
+ selectedCredentials,
37151
+ selectedProjectIds,
37152
+ deadline,
37153
+ waitPolicy
37154
+ )
37155
+ ).catch((error) => {
37156
+ cancellation.signal.throwIfAborted();
37157
+ if (error instanceof PreResponseTimeoutError) {
37158
+ log16.debug("pre-response-timeout", { reason: error.reason });
37159
+ return waitPolicy.refusal?.() ?? preResponseTimeoutResponse();
37160
+ }
37161
+ throw error;
37162
+ }).then(
36638
37163
  async (response) => {
37164
+ deadline.acceptTerminalResponse();
36639
37165
  if (bufferedOverflow.has(response)) {
37166
+ deadline.dispose();
36640
37167
  cancellation.release();
36641
37168
  return redactCredentialResponse(
36642
37169
  response,
36643
37170
  [...selectedCredentials],
36644
- bufferedOverflow.get(response)
37171
+ bufferedOverflow.get(response),
37172
+ [...selectedProjectIds]
36645
37173
  );
36646
37174
  }
36647
37175
  const retained = await retainResponseLifetime(
@@ -36650,18 +37178,31 @@ function createRequestExecutor(deps) {
36650
37178
  );
36651
37179
  inFlight.add(retained.settled);
36652
37180
  void retained.settled.then(() => inFlight.delete(retained.settled));
37181
+ void retained.settled.then(() => deadline.dispose());
36653
37182
  return redactCredentialResponse(
36654
37183
  preserveResponseMetadata2(retained.response, response),
36655
- [...selectedCredentials]
37184
+ [...selectedCredentials],
37185
+ void 0,
37186
+ [...selectedProjectIds]
36656
37187
  );
36657
37188
  },
36658
37189
  (error) => {
37190
+ deadline.dispose();
36659
37191
  cancellation.release();
36660
- throw redactCredentialError(error, [...selectedCredentials]);
37192
+ throw redactCredentialError(
37193
+ error,
37194
+ [...selectedCredentials],
37195
+ [...selectedProjectIds]
37196
+ );
36661
37197
  }
36662
37198
  ).catch((error) => {
37199
+ deadline.dispose();
36663
37200
  cancellation.release();
36664
- throw redactCredentialError(error, [...selectedCredentials]);
37201
+ throw redactCredentialError(
37202
+ error,
37203
+ [...selectedCredentials],
37204
+ [...selectedProjectIds]
37205
+ );
36665
37206
  });
36666
37207
  inFlight.add(pending);
36667
37208
  void pending.then(
@@ -37861,6 +38402,9 @@ function createVaultAccountPool(options) {
37861
38402
  admitted: (row, attribution) => state.admitted(row, attribution)
37862
38403
  } : void 0
37863
38404
  );
38405
+ const refusal3 = options.emptyRosterRefusal;
38406
+ if (refusal3)
38407
+ credentials.emptyRosterRefusal = () => refusal3(source.emptyRosterCause?.() ?? "unknown");
37864
38408
  const rowsFromSource = async () => {
37865
38409
  const rows = vaultAccountRows(source.routes());
37866
38410
  if (state) {
@@ -38138,7 +38682,7 @@ function createOpenCodeVaultCustody(options) {
38138
38682
  const roster = await (await loadClaustrum()).readVaultRoster(
38139
38683
  paths.rosterFile
38140
38684
  );
38141
- return roster?.rows.length === 0 ? noVaultAccountsGuidance() : [];
38685
+ return roster?.rows.length === 0 ? noVaultAccountsGuidance(source?.grantReach()) : [];
38142
38686
  } catch {
38143
38687
  return [];
38144
38688
  }
@@ -38381,11 +38925,37 @@ function pendingExistsGuidance() {
38381
38925
  "Or the vault operator clears it now: find its ID with ck auth enroll list, run ck auth enroll deny --request-id <id>, then request vault access again here."
38382
38926
  ];
38383
38927
  }
38384
- function noVaultAccountsGuidance() {
38385
- return [
38386
- `Vault access is approved, but the vault serves ${OPENCODE_VAULT_ENROLLMENT_NAME} no Antigravity accounts.`,
38387
- `The vault operator grants read access with: ${OPENCODE_VAULT_GRANT_COMMAND}`
38388
- ];
38928
+ function noVaultAccountsGuidance(reach) {
38929
+ return emptyRosterGuidance(emptyVaultRosterCause(reach));
38930
+ }
38931
+ function emptyRosterGuidance(cause) {
38932
+ switch (cause) {
38933
+ case "no-grant":
38934
+ return [
38935
+ `Vault access is approved. The vault has not granted ${OPENCODE_VAULT_ENROLLMENT_NAME} read access.`,
38936
+ `The vault operator grants it with: ${OPENCODE_VAULT_GRANT_COMMAND}`
38937
+ ];
38938
+ case "grant-reaches-nothing":
38939
+ return [
38940
+ `Vault access is approved. ${OPENCODE_VAULT_ENROLLMENT_NAME} has read access, but it reaches no Antigravity login in the vault.`,
38941
+ `The vault operator updates the vault's logins with: ${VAULT_RECLASSIFY_COMMAND}`,
38942
+ `Then they check them with: ${VAULT_STATUS_COMMAND}`
38943
+ ];
38944
+ case "unknown":
38945
+ return [
38946
+ `Vault access is approved, but the vault serves ${OPENCODE_VAULT_ENROLLMENT_NAME} no Antigravity accounts.`,
38947
+ `The vault operator grants read access with: ${OPENCODE_VAULT_GRANT_COMMAND}`
38948
+ ];
38949
+ }
38950
+ }
38951
+ function openCodeEmptyVaultRosterRefusal(cause) {
38952
+ return cause === "unknown" ? void 0 : emptyRosterGuidance(cause).join("\n");
38953
+ }
38954
+ function createOpenCodeVaultAccountPool(options) {
38955
+ return createVaultAccountPool({
38956
+ ...options,
38957
+ emptyRosterRefusal: openCodeEmptyVaultRosterRefusal
38958
+ });
38389
38959
  }
38390
38960
  function enrollmentGuidance(status) {
38391
38961
  if (status.state === "pending")
@@ -39148,6 +39718,7 @@ function createGaJobExecutor(executor, overrides = {}) {
39148
39718
  if (typeof init?.body !== "string" || !authorization?.startsWith("Bearer ") || !signal) {
39149
39719
  throw new Error("The prepared Antigravity send is incomplete");
39150
39720
  }
39721
+ signal.throwIfAborted();
39151
39722
  return send({
39152
39723
  envelope: JSON.parse(init.body),
39153
39724
  auth: { access: authorization.slice("Bearer ".length) },
@@ -39406,7 +39977,7 @@ async function createGaVaultLocationServices(input2) {
39406
39977
  const location = start.runtime;
39407
39978
  const routes = createGaRouteBook();
39408
39979
  const vaultLogger = location.logger.createLogger("vault-state");
39409
- const pool = createVaultAccountPool({
39980
+ const pool = createOpenCodeVaultAccountPool({
39410
39981
  source,
39411
39982
  durable: {
39412
39983
  source,
@@ -41565,6 +42136,7 @@ function createGaRawSender(overrides = {}) {
41565
42136
  if (send) return (input2) => send(input2);
41566
42137
  const observe = overrides.observeRawSenderSignal;
41567
42138
  return (input2) => {
42139
+ input2.signal.throwIfAborted();
41568
42140
  const transportOptions = {
41569
42141
  signal: input2.signal,
41570
42142
  idleTimeoutMs: GA_RAW_IDLE_TIMEOUT_MS
@@ -41605,7 +42177,8 @@ function isGaGoogleContentRequest(request) {
41605
42177
  }
41606
42178
  }
41607
42179
  function gaPreHeaderFailureResponse(error) {
41608
- const message = error instanceof Error && error.message ? error.message : "Antigravity request failed before a response arrived";
42180
+ const rawMessage = error instanceof Error && error.message ? error.message : "Antigravity request failed before a response arrived";
42181
+ const message = redactProjectIdText(rawMessage);
41609
42182
  return new Response(
41610
42183
  JSON.stringify({ error: { code: 502, message, status: "UNAVAILABLE" } }),
41611
42184
  { status: 502, headers: { "content-type": "application/json" } }
@@ -42554,7 +43127,7 @@ import { createHash as createHash20, randomUUID as randomUUID21 } from "node:cry
42554
43127
  import { join as join31, resolve as resolve17 } from "node:path";
42555
43128
 
42556
43129
  // src/cli.ts
42557
- import { execFile as execFile2 } from "node:child_process";
43130
+ import { execFile } from "node:child_process";
42558
43131
  import { realpathSync as realpathSync3 } from "node:fs";
42559
43132
  import { resolve as resolve14 } from "node:path";
42560
43133
  import { createInterface } from "node:readline/promises";
@@ -42894,7 +43467,10 @@ function isLostMarkerRaceError2(error) {
42894
43467
  const code2 = error?.code;
42895
43468
  return code2 === "ENOENT" || !windowsPrivateFiles2 && (code2 === "EINVAL" || code2 === "ENOTDIR");
42896
43469
  }
42897
- async function acquireRefreshFileLock2(options) {
43470
+ function acquireRefreshFileLock2(options) {
43471
+ return acquireRefreshFileLockWithClock2({ ...options, now: Date.now });
43472
+ }
43473
+ async function acquireRefreshFileLockWithClock2(options) {
42898
43474
  const lockPath = lockPathFor2(options.path, options.name);
42899
43475
  const legacyOwnerPath = join17(lockPath, "owner.json");
42900
43476
  const ownerId = randomUUID16();
@@ -43828,6 +44404,31 @@ async function readClaustrumEnrollmentStatus2(paths, proposedName) {
43828
44404
  }
43829
44405
  return statusFromState2(state);
43830
44406
  }
44407
+ async function enrollmentAuthority3(paths, proposedName) {
44408
+ let status;
44409
+ try {
44410
+ status = await readClaustrumEnrollmentStatus2(paths, proposedName);
44411
+ } catch (error) {
44412
+ if (!(error instanceof ClaustrumConsumerError2) || error.kind !== "invalid-state" && error.kind !== "invalid-token") {
44413
+ return "unreadable";
44414
+ }
44415
+ try {
44416
+ const stateValue = await readBoundedJson2(paths.statePath);
44417
+ if (stateValue === void 0)
44418
+ return "unreadable";
44419
+ const state = decodeEnrollmentState2(stateValue);
44420
+ return state.phase === "approved" && state.proposedName === proposedName ? "vault" : "unreadable";
44421
+ } catch {
44422
+ return "unreadable";
44423
+ }
44424
+ }
44425
+ if ("proposedName" in status && status.proposedName !== proposedName)
44426
+ return "unreadable";
44427
+ if (status.state === "approved" || status.state === "blocked" && status.code === "missing_token") {
44428
+ return "vault";
44429
+ }
44430
+ return "local";
44431
+ }
43831
44432
  function statusFromState2(state) {
43832
44433
  if (state.phase === "pending") {
43833
44434
  return {
@@ -44068,30 +44669,126 @@ async function resetClaustrumEnrollmentState2(paths, proposedName) {
44068
44669
  }
44069
44670
 
44070
44671
  // src/common-auth-embedded/setup/command-runner.js
44071
- import { execFile } from "node:child_process";
44672
+ import { spawn } from "node:child_process";
44673
+ var STDERR_TAIL_MAX_BYTES = 4 * 1024;
44674
+ var STDOUT_MAX_BYTES = 1024 * 1024;
44675
+ var ByteTail = class {
44676
+ buffer = Buffer.alloc(STDERR_TAIL_MAX_BYTES);
44677
+ start = 0;
44678
+ length = 0;
44679
+ truncated = false;
44680
+ get didTruncate() {
44681
+ return this.truncated;
44682
+ }
44683
+ push(chunk) {
44684
+ if (chunk.length >= STDERR_TAIL_MAX_BYTES) {
44685
+ if (chunk.length > STDERR_TAIL_MAX_BYTES || this.length > 0)
44686
+ this.truncated = true;
44687
+ chunk.copy(this.buffer, 0, chunk.length - STDERR_TAIL_MAX_BYTES);
44688
+ this.start = 0;
44689
+ this.length = STDERR_TAIL_MAX_BYTES;
44690
+ return;
44691
+ }
44692
+ const overflow = Math.max(0, this.length + chunk.length - STDERR_TAIL_MAX_BYTES);
44693
+ if (overflow > 0)
44694
+ this.truncated = true;
44695
+ this.start = (this.start + overflow) % STDERR_TAIL_MAX_BYTES;
44696
+ this.length -= overflow;
44697
+ const writeAt = (this.start + this.length) % STDERR_TAIL_MAX_BYTES;
44698
+ const firstLength = Math.min(chunk.length, STDERR_TAIL_MAX_BYTES - writeAt);
44699
+ chunk.copy(this.buffer, writeAt, 0, firstLength);
44700
+ if (firstLength < chunk.length)
44701
+ chunk.copy(this.buffer, 0, firstLength);
44702
+ this.length += chunk.length;
44703
+ }
44704
+ toString() {
44705
+ const bytes = Buffer.alloc(this.length);
44706
+ const firstLength = Math.min(this.length, STDERR_TAIL_MAX_BYTES - this.start);
44707
+ this.buffer.copy(bytes, 0, this.start, this.start + firstLength);
44708
+ if (firstLength < this.length)
44709
+ this.buffer.copy(bytes, firstLength, 0, this.length - firstLength);
44710
+ let start = 0;
44711
+ while (start < bytes.length) {
44712
+ const byte = bytes[start];
44713
+ if (byte === void 0 || (byte & 192) !== 128)
44714
+ break;
44715
+ start++;
44716
+ }
44717
+ return bytes.subarray(start).toString("utf8");
44718
+ }
44719
+ };
44072
44720
  var defaultCommandRunner = {
44073
44721
  run(file, args, options = {}) {
44074
44722
  return new Promise((resolve18) => {
44075
44723
  const started = performance.now();
44076
44724
  const timeoutMs = options.timeoutMs ?? 15e3;
44077
- execFile(file, [...args], {
44078
- env: options.env ?? process.env,
44079
- timeout: timeoutMs,
44080
- windowsHide: true,
44081
- windowsVerbatimArguments: options.windowsVerbatimArguments,
44082
- maxBuffer: 1024 * 1024
44083
- }, (error, stdout, stderr) => {
44084
- const durationMs = performance.now() - started;
44725
+ const stderr = new ByteTail();
44726
+ const stdout = [];
44727
+ let stdoutLength = 0;
44728
+ let outputExceeded = false;
44729
+ let spawnError = false;
44730
+ let timedOut = false;
44731
+ let child;
44732
+ try {
44733
+ child = spawn(file, [...args], {
44734
+ env: options.env ?? process.env,
44735
+ windowsHide: true,
44736
+ windowsVerbatimArguments: options.windowsVerbatimArguments,
44737
+ stdio: ["ignore", "pipe", "pipe"]
44738
+ });
44739
+ } catch {
44740
+ resolve18({
44741
+ exitCode: 1,
44742
+ stdout: "",
44743
+ stderr: "",
44744
+ spawnError: true,
44745
+ signal: null,
44746
+ timedOut: false,
44747
+ durationMs: performance.now() - started
44748
+ });
44749
+ return;
44750
+ }
44751
+ const timer = timeoutMs > 0 ? setTimeout(() => {
44752
+ timedOut = true;
44753
+ child.kill("SIGTERM");
44754
+ }, timeoutMs) : void 0;
44755
+ child.stdout?.on("data", (chunk) => {
44756
+ const remaining = STDOUT_MAX_BYTES - stdoutLength;
44757
+ const length = Math.min(remaining, chunk.length);
44758
+ if (length > 0) {
44759
+ stdout.push(chunk.subarray(0, length));
44760
+ stdoutLength += length;
44761
+ }
44762
+ if (chunk.length > remaining) {
44763
+ outputExceeded = true;
44764
+ child.kill("SIGTERM");
44765
+ }
44766
+ });
44767
+ child.stderr?.on("data", (chunk) => stderr.push(chunk));
44768
+ let settled = false;
44769
+ const settle = (code2, signal) => {
44770
+ if (settled)
44771
+ return;
44772
+ settled = true;
44773
+ if (timer)
44774
+ clearTimeout(timer);
44085
44775
  resolve18({
44086
- exitCode: error ? typeof error.code === "number" ? error.code : 1 : 0,
44087
- stdout: String(stdout ?? ""),
44088
- stderr: String(stderr ?? ""),
44089
- signal: error?.signal ?? null,
44090
- // Buffer-limit and spawn errors have string codes, not timeout kills.
44091
- timedOut: error?.killed === true && typeof error.code !== "string" && error.signal === "SIGTERM" && durationMs >= timeoutMs && timeoutMs > 0,
44092
- durationMs
44776
+ exitCode: spawnError ? 1 : outputExceeded ? 1 : code2 ?? 1,
44777
+ stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
44778
+ stderr: stderr.toString(),
44779
+ stderrTruncated: stderr.didTruncate,
44780
+ ...spawnError ? { spawnError: true } : {},
44781
+ signal: signal ?? null,
44782
+ timedOut,
44783
+ durationMs: performance.now() - started
44093
44784
  });
44785
+ };
44786
+ child.once("error", () => {
44787
+ spawnError = true;
44788
+ if (child.pid === void 0)
44789
+ settle(null, null);
44094
44790
  });
44791
+ child.once("close", (code2, signal) => settle(code2, signal));
44095
44792
  });
44096
44793
  }
44097
44794
  };
@@ -44108,6 +44805,56 @@ function runResolvedCommand(runner, platform, file, args, env3, timeoutMs = 15e3
44108
44805
  return runner.run(file, args, { env: env3, timeoutMs });
44109
44806
  }
44110
44807
 
44808
+ // src/common-auth-embedded/setup/command-error.js
44809
+ var PI_INSTALL_ERROR_MESSAGE = "Pi install failed; run pi install after checking your npm connection.";
44810
+ function utf8Tail(value) {
44811
+ const bytes = Buffer.from(value, "utf8");
44812
+ if (bytes.length <= STDERR_TAIL_MAX_BYTES)
44813
+ return value;
44814
+ let start = bytes.length - STDERR_TAIL_MAX_BYTES;
44815
+ while (start < bytes.length) {
44816
+ const byte = bytes[start];
44817
+ if (byte === void 0 || (byte & 192) !== 128)
44818
+ break;
44819
+ start++;
44820
+ }
44821
+ return bytes.subarray(start).toString("utf8");
44822
+ }
44823
+ function dropPartialLine(tail) {
44824
+ const newline = tail.indexOf("\n");
44825
+ return newline < 0 ? "" : tail.slice(newline + 1);
44826
+ }
44827
+ var SetupCommandError = class extends Error {
44828
+ step = "pi-install";
44829
+ exitCode;
44830
+ signal;
44831
+ stderrTail;
44832
+ constructor(details) {
44833
+ super(PI_INSTALL_ERROR_MESSAGE);
44834
+ this.name = "SetupCommandError";
44835
+ this.exitCode = details.exitCode;
44836
+ this.signal = details.signal;
44837
+ const tail = details.stderrTruncated ? dropPartialLine(details.stderrTail) : details.stderrTail;
44838
+ const redacted = redact2(tail);
44839
+ this.stderrTail = utf8Tail(typeof redacted === "string" ? redacted : "");
44840
+ }
44841
+ };
44842
+ var HOST_LABELS = { opencode: "OpenCode", pi: "Pi" };
44843
+ var OUTCOME_TEXT = {
44844
+ enrolled: "connected to the vault",
44845
+ "not-enrolled": "not connected",
44846
+ unknown: "unknown, check with ck auth status"
44847
+ };
44848
+ function setupEnrollmentLine({ host, outcome }) {
44849
+ return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}`;
44850
+ }
44851
+ var recordedEnrollment = /* @__PURE__ */ new WeakMap();
44852
+ function recordSetupEnrollment(failure2, enrollment) {
44853
+ if (typeof failure2 !== "object" && typeof failure2 !== "function" || !failure2)
44854
+ return;
44855
+ recordedEnrollment.set(failure2, Object.freeze(enrollment.map((entry) => Object.freeze({ ...entry }))));
44856
+ }
44857
+
44111
44858
  // src/common-auth-embedded/setup/detect.js
44112
44859
  import { accessSync, constants as constants3, existsSync as existsSync11, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync5 } from "node:fs";
44113
44860
  import { mkdtemp, rm as rm6 } from "node:fs/promises";
@@ -44581,6 +45328,9 @@ async function assertHostsStopped(fence, env3) {
44581
45328
  }
44582
45329
 
44583
45330
  // src/common-auth-embedded/setup/enroll.js
45331
+ var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
45332
+ var HostNotEnrolledError = class extends Error {
45333
+ };
44584
45334
  async function connectSetupHost(plugin2, host, io, terminal, fence) {
44585
45335
  const { name, paths: input2 } = plugin2.vault.hosts[host];
44586
45336
  const paths = hostEnrollmentPaths2(input2);
@@ -44589,7 +45339,7 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
44589
45339
  connectionFile: plugin2.vault.connectionFile,
44590
45340
  handshakeTimeoutMs: 2e3
44591
45341
  }).catch(() => {
44592
- throw new Error("Claustrum connection failed; start ck and rerun setup.");
45342
+ throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.");
44593
45343
  });
44594
45344
  try {
44595
45345
  const manager = new ClaustrumEnrollmentManager2({
@@ -44619,10 +45369,10 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
44619
45369
  return;
44620
45370
  }
44621
45371
  if (status.state !== "pending" && status.state !== "busy")
44622
- throw new Error("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
45372
+ throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
44623
45373
  if (status.state === "pending" && status.requestId && status.requestId !== printedRequest) {
44624
45374
  if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
44625
- throw new Error("Invalid enrollment request id.");
45375
+ throw new HostNotEnrolledError("Invalid enrollment request id.");
44626
45376
  printedRequest = status.requestId;
44627
45377
  printLine2(terminal, "Waiting for approval. In another terminal, run:");
44628
45378
  printLine2(terminal, ` ck auth enroll approve --request-id ${status.requestId} --name ${name}`);
@@ -44630,11 +45380,13 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
44630
45380
  }
44631
45381
  await (io.wait ?? delay)(1e3);
44632
45382
  }
44633
- throw new Error("Claustrum approval is still pending; approve with ck and rerun setup.");
45383
+ throw new HostNotEnrolledError("Claustrum approval is still pending; approve with ck and rerun setup.");
44634
45384
  } catch (error) {
44635
45385
  if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError)
44636
45386
  throw error;
44637
- throw new Error("Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.");
45387
+ if (error instanceof HostNotEnrolledError)
45388
+ throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE);
45389
+ throw new Error(ENROLLMENT_INCOMPLETE_MESSAGE);
44638
45390
  } finally {
44639
45391
  client.close();
44640
45392
  }
@@ -44826,8 +45578,13 @@ async function registerOpenCode(writes, beforeWrite) {
44826
45578
  async function registerPi(plugin2, executable, io = {}) {
44827
45579
  const { platform, env: env3 } = setupPaths(io);
44828
45580
  const result = await runResolvedCommand(io.runner ?? defaultCommandRunner, platform, executable, ["install", `npm:${plugin2.packages.pi}@${plugin2.version}`], env3);
44829
- if (result.exitCode !== 0)
44830
- throw new Error("Pi install failed; run pi install after checking your npm connection.");
45581
+ if (result.exitCode !== 0 || result.timedOut)
45582
+ throw new SetupCommandError({
45583
+ exitCode: result.spawnError ? null : result.exitCode,
45584
+ signal: result.signal ?? null,
45585
+ stderrTail: result.stderr,
45586
+ stderrTruncated: result.stderrTruncated ?? false
45587
+ });
44831
45588
  }
44832
45589
 
44833
45590
  // src/common-auth-embedded/setup/command.js
@@ -44875,6 +45632,22 @@ function validatePlugin(plugin2) {
44875
45632
  throw new Error("Setup requires lowercase vault names containing only letters, digits and dashes.");
44876
45633
  }
44877
45634
  }
45635
+ async function enrollmentReport(plugin2, hosts, recorded) {
45636
+ const report = [];
45637
+ for (const host of hosts) {
45638
+ let outcome = recorded.get(host) ?? "not-enrolled";
45639
+ if (outcome === "unknown") {
45640
+ const { name, paths } = plugin2.vault.hosts[host];
45641
+ const authority = await enrollmentAuthority3(hostEnrollmentPaths2(paths), name).catch(() => "unreadable");
45642
+ if (authority === "vault")
45643
+ outcome = "enrolled";
45644
+ else if (authority === "local")
45645
+ outcome = "not-enrolled";
45646
+ }
45647
+ report.push({ host, outcome });
45648
+ }
45649
+ return report;
45650
+ }
44878
45651
  async function runSetup(plugin2, argv = [], io = {}) {
44879
45652
  const options = flags(argv);
44880
45653
  validatePlugin(plugin2);
@@ -44984,23 +45757,45 @@ ${write.content}`);
44984
45757
  hosts: Object.freeze([...hosts]),
44985
45758
  piAgentDir: detection.pi.directory
44986
45759
  };
44987
- for (const host of hosts) {
44988
- await stopped();
44989
- await plugin2.beforeSignIn?.(host, context);
44990
- await stopped();
44991
- if (useVault)
44992
- await connectSetupHost(plugin2, host, io, terminal, stopped);
44993
- else
44994
- await plugin2.signInLocal(host, context);
44995
- await stopped();
44996
- await plugin2.beforeRegister?.(host, mode, context);
44997
- await stopped();
44998
- if (host === "opencode")
44999
- await registerOpenCode(writes, stopped);
45000
- else
45001
- await registerPi(plugin2, detection.pi.executable, io);
45002
- await stopped();
45003
- await plugin2.migrate(host, context);
45760
+ const enrollment = /* @__PURE__ */ new Map();
45761
+ try {
45762
+ for (const host of hosts) {
45763
+ await stopped();
45764
+ await plugin2.beforeSignIn?.(host, context);
45765
+ await stopped();
45766
+ if (useVault) {
45767
+ enrollment.set(host, "unknown");
45768
+ try {
45769
+ await connectSetupHost(plugin2, host, io, terminal, stopped);
45770
+ } catch (error) {
45771
+ if (error instanceof HostNotEnrolledError)
45772
+ enrollment.set(host, "not-enrolled");
45773
+ throw error;
45774
+ }
45775
+ enrollment.set(host, "enrolled");
45776
+ } else
45777
+ await plugin2.signInLocal(host, context);
45778
+ await stopped();
45779
+ await plugin2.beforeRegister?.(host, mode, context);
45780
+ await stopped();
45781
+ if (host === "opencode")
45782
+ await registerOpenCode(writes, stopped);
45783
+ else
45784
+ await registerPi(plugin2, detection.pi.executable, io);
45785
+ await stopped();
45786
+ await plugin2.migrate(host, context);
45787
+ }
45788
+ } catch (error) {
45789
+ if (enrollment.size === 0)
45790
+ throw error;
45791
+ try {
45792
+ const report = await enrollmentReport(plugin2, hosts, enrollment);
45793
+ recordSetupEnrollment(error, report);
45794
+ for (const entry of report)
45795
+ printLine2(terminal, setupEnrollmentLine(entry));
45796
+ } catch {
45797
+ }
45798
+ throw error;
45004
45799
  }
45005
45800
  }
45006
45801
  printLine2(terminal, `${options.dryRun ? "Planned" : "Configured"} ${plugin2.displayName} for ${hosts.join(", ")} (${mode}).`);
@@ -45666,7 +46461,7 @@ async function runCli(argv, deps) {
45666
46461
  return 1;
45667
46462
  }
45668
46463
  }
45669
- var execFileAsync = promisify(execFile2);
46464
+ var execFileAsync = promisify(execFile);
45670
46465
  async function openBrowserDefault(url) {
45671
46466
  if (process.platform === "win32") {
45672
46467
  await execFileAsync("cmd", ["/c", "start", "", url]);
@@ -50692,7 +51487,7 @@ function resolvePluginDependencies(overrides = {}) {
50692
51487
  authorize: overrides.oauth?.authorize ?? authorizeAntigravity,
50693
51488
  exchange: overrides.oauth?.exchange ?? exchangeAntigravity
50694
51489
  };
50695
- const clock = {
51490
+ const clock2 = {
50696
51491
  now: overrides.clock?.now ?? (() => Date.now()),
50697
51492
  random: overrides.clock?.random ?? Math.random,
50698
51493
  sleep: overrides.clock?.sleep ?? defaultSleep
@@ -50702,7 +51497,7 @@ function resolvePluginDependencies(overrides = {}) {
50702
51497
  agyTransport,
50703
51498
  filesystemRoots: roots,
50704
51499
  oauth,
50705
- clock
51500
+ clock: clock2
50706
51501
  };
50707
51502
  }
50708
51503
  async function defaultSleep(ms, signal) {
@@ -51561,7 +52356,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
51561
52356
  if (vaultPool && vaultPool.source === source) return vaultPool;
51562
52357
  vaultPool = {
51563
52358
  source,
51564
- pool: createVaultAccountPool({
52359
+ pool: createOpenCodeVaultAccountPool({
51565
52360
  source,
51566
52361
  durable: { source, readState: () => vaultCustody.readState() }
51567
52362
  })