@cortexkit/opencode-antigravity-auth 3.0.6 → 3.0.8

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 (211) hide show
  1. package/dist/cli.js +1621 -183
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +228 -62
  4. package/dist/index.js +2728 -883
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +291 -104
  7. package/dist/server.js +2255 -390
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/claustrum/availability.d.ts +89 -0
  11. package/dist/src/common-auth-embedded/claustrum/availability.js +106 -0
  12. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +41 -1
  13. package/dist/src/common-auth-embedded/claustrum/consumer.js +152 -6
  14. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +135 -14
  15. package/dist/src/common-auth-embedded/claustrum/custody.js +311 -16
  16. package/dist/src/common-auth-embedded/claustrum/errors.d.ts +1 -0
  17. package/dist/src/common-auth-embedded/claustrum/index.d.ts +5 -3
  18. package/dist/src/common-auth-embedded/claustrum/index.js +4 -1
  19. package/dist/src/common-auth-embedded/claustrum/insula.d.ts +48 -0
  20. package/dist/src/common-auth-embedded/claustrum/insula.js +286 -21
  21. package/dist/src/common-auth-embedded/claustrum/watch.d.ts +141 -0
  22. package/dist/src/common-auth-embedded/claustrum/watch.js +254 -0
  23. package/dist/src/common-auth-embedded/fs/private-files.js +10 -2
  24. package/dist/src/common-auth-embedded/fs/refresh-file-lock.d.ts +8 -2
  25. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +6 -1
  26. package/dist/src/common-auth-embedded/pi-slot/lock.js +7 -3
  27. package/dist/src/common-auth-embedded/quota/format.d.ts +17 -3
  28. package/dist/src/common-auth-embedded/quota/format.js +203 -18
  29. package/dist/src/common-auth-embedded/quota/index.d.ts +2 -2
  30. package/dist/src/common-auth-embedded/quota/index.js +1 -1
  31. package/dist/src/common-auth-embedded/quota/projection.d.ts +16 -0
  32. package/dist/src/common-auth-embedded/setup/command-error.d.ts +32 -0
  33. package/dist/src/common-auth-embedded/setup/command-error.js +79 -0
  34. package/dist/src/common-auth-embedded/setup/command-runner.js +118 -24
  35. package/dist/src/common-auth-embedded/setup/command.js +75 -19
  36. package/dist/src/common-auth-embedded/setup/enroll.js +17 -5
  37. package/dist/src/common-auth-embedded/setup/index.d.ts +2 -1
  38. package/dist/src/common-auth-embedded/setup/index.js +1 -0
  39. package/dist/src/common-auth-embedded/setup/register.js +8 -2
  40. package/dist/src/common-auth-embedded/setup/types.d.ts +14 -0
  41. package/dist/src/common-auth-embedded/source-output.json +142 -94
  42. package/dist/src/common-auth-embedded/store/pool.d.ts +1 -1
  43. package/dist/src/common-auth-embedded/store/pool.js +0 -1
  44. package/dist/src/common-auth-embedded/store/refresh-lock.d.ts +0 -1
  45. package/dist/src/common-auth-embedded/store/refresh-lock.js +0 -1
  46. package/dist/src/ga/server/index.d.ts +2 -0
  47. package/dist/src/ga/server/index.d.ts.map +1 -1
  48. package/dist/src/ga/server/index.js +18 -3
  49. package/dist/src/ga/server/index.js.map +1 -1
  50. package/dist/src/ga/tui/host-ga.d.ts.map +1 -1
  51. package/dist/src/ga/tui/host-ga.js +37 -3
  52. package/dist/src/ga/tui/host-ga.js.map +1 -1
  53. package/dist/src/plugin/auth-loader.d.ts +2 -1
  54. package/dist/src/plugin/auth-loader.d.ts.map +1 -1
  55. package/dist/src/plugin/auth-loader.js +5 -4
  56. package/dist/src/plugin/auth-loader.js.map +1 -1
  57. package/dist/src/plugin/config/schema.d.ts.map +1 -1
  58. package/dist/src/plugin/config/schema.js +2 -1
  59. package/dist/src/plugin/config/schema.js.map +1 -1
  60. package/dist/src/plugin/fetch-interceptor.d.ts +2 -1
  61. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  62. package/dist/src/plugin/fetch-interceptor.js +8 -6
  63. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  64. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  65. package/dist/src/plugin/ga-location-services.js +7 -3
  66. package/dist/src/plugin/ga-location-services.js.map +1 -1
  67. package/dist/src/plugin/gemini-dump.d.ts.map +1 -1
  68. package/dist/src/plugin/gemini-dump.js +2 -5
  69. package/dist/src/plugin/gemini-dump.js.map +1 -1
  70. package/dist/src/plugin/index.d.ts.map +1 -1
  71. package/dist/src/plugin/index.js +3 -3
  72. package/dist/src/plugin/index.js.map +1 -1
  73. package/dist/src/plugin/logging-utils.d.ts.map +1 -1
  74. package/dist/src/plugin/logging-utils.js +2 -5
  75. package/dist/src/plugin/logging-utils.js.map +1 -1
  76. package/dist/src/plugin/request.d.ts +1 -2
  77. package/dist/src/plugin/request.d.ts.map +1 -1
  78. package/dist/src/plugin/request.js +8 -12
  79. package/dist/src/plugin/request.js.map +1 -1
  80. package/dist/src/plugin/shared/after-handoff.d.ts +14 -0
  81. package/dist/src/plugin/shared/after-handoff.d.ts.map +1 -0
  82. package/dist/src/plugin/shared/after-handoff.js +89 -0
  83. package/dist/src/plugin/shared/after-handoff.js.map +1 -0
  84. package/dist/src/plugin/shared/request-services.d.ts +16 -3
  85. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  86. package/dist/src/plugin/shared/request-services.js +193 -90
  87. package/dist/src/plugin/shared/request-services.js.map +1 -1
  88. package/dist/src/plugin/shared/vault-request-credentials.d.ts +13 -4
  89. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  90. package/dist/src/plugin/shared/vault-request-credentials.js +17 -1
  91. package/dist/src/plugin/shared/vault-request-credentials.js.map +1 -1
  92. package/dist/src/plugin/vault-custody.d.ts +16 -1
  93. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  94. package/dist/src/plugin/vault-custody.js +60 -10
  95. package/dist/src/plugin/vault-custody.js.map +1 -1
  96. package/dist/src/sidebar-projection.d.ts +4 -0
  97. package/dist/src/sidebar-projection.d.ts.map +1 -1
  98. package/dist/src/sidebar-projection.js +6 -2
  99. package/dist/src/sidebar-projection.js.map +1 -1
  100. package/dist/src/tui/quota-layout.d.ts +94 -0
  101. package/dist/src/tui/quota-layout.d.ts.map +1 -0
  102. package/dist/src/tui/quota-layout.js +139 -0
  103. package/dist/src/tui/quota-layout.js.map +1 -0
  104. package/dist/src/tui/route-layout.d.ts +8 -0
  105. package/dist/src/tui/route-layout.d.ts.map +1 -0
  106. package/dist/src/tui/route-layout.js +36 -0
  107. package/dist/src/tui/route-layout.js.map +1 -0
  108. package/dist/src/tui.d.ts.map +1 -1
  109. package/dist/src/tui.js +105 -191
  110. package/dist/src/tui.js.map +1 -1
  111. package/dist/tui-build-map.json +60 -31
  112. package/dist/tui-ga-build-map.json +46 -17
  113. package/dist/types/src/common-auth-embedded/claustrum/availability.d.ts +89 -0
  114. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +41 -1
  115. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +135 -14
  116. package/dist/types/src/common-auth-embedded/claustrum/errors.d.ts +1 -0
  117. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +5 -3
  118. package/dist/types/src/common-auth-embedded/claustrum/insula.d.ts +48 -0
  119. package/dist/types/src/common-auth-embedded/claustrum/watch.d.ts +141 -0
  120. package/dist/types/src/common-auth-embedded/fs/refresh-file-lock.d.ts +8 -2
  121. package/dist/types/src/common-auth-embedded/quota/format.d.ts +17 -3
  122. package/dist/types/src/common-auth-embedded/quota/index.d.ts +2 -2
  123. package/dist/types/src/common-auth-embedded/quota/projection.d.ts +16 -0
  124. package/dist/types/src/common-auth-embedded/setup/command-error.d.ts +32 -0
  125. package/dist/types/src/common-auth-embedded/setup/index.d.ts +2 -1
  126. package/dist/types/src/common-auth-embedded/setup/types.d.ts +14 -0
  127. package/dist/types/src/common-auth-embedded/store/pool.d.ts +1 -1
  128. package/dist/types/src/common-auth-embedded/store/refresh-lock.d.ts +0 -1
  129. package/dist/types/src/ga/server/index.d.ts +2 -0
  130. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  131. package/dist/types/src/plugin/auth-loader.d.ts +2 -1
  132. package/dist/types/src/plugin/auth-loader.d.ts.map +1 -1
  133. package/dist/types/src/plugin/config/schema.d.ts.map +1 -1
  134. package/dist/types/src/plugin/fetch-interceptor.d.ts +2 -1
  135. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  136. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  137. package/dist/types/src/plugin/gemini-dump.d.ts.map +1 -1
  138. package/dist/types/src/plugin/index.d.ts.map +1 -1
  139. package/dist/types/src/plugin/logging-utils.d.ts.map +1 -1
  140. package/dist/types/src/plugin/request.d.ts +1 -2
  141. package/dist/types/src/plugin/request.d.ts.map +1 -1
  142. package/dist/types/src/plugin/shared/after-handoff.d.ts +14 -0
  143. package/dist/types/src/plugin/shared/after-handoff.d.ts.map +1 -0
  144. package/dist/types/src/plugin/shared/request-services.d.ts +16 -3
  145. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  146. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +13 -4
  147. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  148. package/dist/types/src/plugin/vault-custody.d.ts +16 -1
  149. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  150. package/package.json +4 -4
  151. package/src/common-auth-embedded/claustrum/availability.d.ts +89 -0
  152. package/src/common-auth-embedded/claustrum/availability.js +106 -0
  153. package/src/common-auth-embedded/claustrum/consumer.d.ts +41 -1
  154. package/src/common-auth-embedded/claustrum/consumer.js +152 -6
  155. package/src/common-auth-embedded/claustrum/custody.d.ts +135 -14
  156. package/src/common-auth-embedded/claustrum/custody.js +311 -16
  157. package/src/common-auth-embedded/claustrum/errors.d.ts +1 -0
  158. package/src/common-auth-embedded/claustrum/index.d.ts +5 -3
  159. package/src/common-auth-embedded/claustrum/index.js +4 -1
  160. package/src/common-auth-embedded/claustrum/insula.d.ts +48 -0
  161. package/src/common-auth-embedded/claustrum/insula.js +286 -21
  162. package/src/common-auth-embedded/claustrum/watch.d.ts +141 -0
  163. package/src/common-auth-embedded/claustrum/watch.js +254 -0
  164. package/src/common-auth-embedded/fs/private-files.js +10 -2
  165. package/src/common-auth-embedded/fs/refresh-file-lock.d.ts +8 -2
  166. package/src/common-auth-embedded/fs/refresh-file-lock.js +6 -1
  167. package/src/common-auth-embedded/pi-slot/lock.js +7 -3
  168. package/src/common-auth-embedded/quota/format.d.ts +17 -3
  169. package/src/common-auth-embedded/quota/format.js +203 -18
  170. package/src/common-auth-embedded/quota/index.d.ts +2 -2
  171. package/src/common-auth-embedded/quota/index.js +1 -1
  172. package/src/common-auth-embedded/quota/projection.d.ts +16 -0
  173. package/src/common-auth-embedded/setup/command-error.d.ts +32 -0
  174. package/src/common-auth-embedded/setup/command-error.js +79 -0
  175. package/src/common-auth-embedded/setup/command-runner.js +118 -24
  176. package/src/common-auth-embedded/setup/command.js +75 -19
  177. package/src/common-auth-embedded/setup/enroll.js +17 -5
  178. package/src/common-auth-embedded/setup/index.d.ts +2 -1
  179. package/src/common-auth-embedded/setup/index.js +1 -0
  180. package/src/common-auth-embedded/setup/register.js +8 -2
  181. package/src/common-auth-embedded/setup/types.d.ts +14 -0
  182. package/src/common-auth-embedded/source-output.json +142 -94
  183. package/src/common-auth-embedded/store/pool.d.ts +1 -1
  184. package/src/common-auth-embedded/store/pool.js +0 -1
  185. package/src/common-auth-embedded/store/refresh-lock.d.ts +0 -1
  186. package/src/common-auth-embedded/store/refresh-lock.js +0 -1
  187. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +10 -2
  188. package/src/tui-compiled/common-auth-embedded/quota/format.js +203 -18
  189. package/src/tui-compiled/common-auth-embedded/quota/index.js +1 -1
  190. package/src/tui-compiled/tui/quota-layout.js +378 -0
  191. package/src/tui-compiled/tui/route-layout.js +30 -0
  192. package/src/tui-compiled/tui.js +245 -501
  193. package/src/tui-ga-compiled/host-ga.js +82 -52
  194. package/src/tui-ga-compiled/shared/6ca47cd4ec33fe72-route-layout.js +30 -0
  195. package/src/tui-ga-compiled/shared/8ae1927e5910ea81-sidebar-projection.js +2 -2
  196. package/src/tui-ga-compiled/shared/aef2402f8fc342f0-format.js +203 -18
  197. package/src/tui-ga-compiled/shared/bf17cbee28e58197-index.js +1 -1
  198. package/src/tui-ga-compiled/shared/dd4c9e1a907f8ef0-quota-layout.js +378 -0
  199. package/src/tui-ga-raw/host-ga.tsx +71 -30
  200. package/src/tui-ga-raw/shared/6ca47cd4ec33fe72-route-layout.js +30 -0
  201. package/src/tui-ga-raw/shared/8ae1927e5910ea81-sidebar-projection.js +2 -2
  202. package/src/tui-ga-raw/shared/aef2402f8fc342f0-format.js +203 -18
  203. package/src/tui-ga-raw/shared/bf17cbee28e58197-index.js +1 -1
  204. package/src/tui-ga-raw/shared/dd4c9e1a907f8ef0-quota-layout.tsx +391 -0
  205. package/src/tui-raw/common-auth-embedded/fs/private-files.js +10 -2
  206. package/src/tui-raw/common-auth-embedded/quota/format.js +203 -18
  207. package/src/tui-raw/common-auth-embedded/quota/index.js +1 -1
  208. package/src/tui-raw/tui/quota-layout.tsx +391 -0
  209. package/src/tui-raw/tui/route-layout.js +30 -0
  210. package/src/tui-raw/tui.tsx +171 -411
  211. package/src/tui.tsx +171 -411
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,16 @@ 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
+ ...limit.windowMinutes === void 0 ? {} : { windowMinutes: limit.windowMinutes },
340
+ part: {
341
+ kind: "window",
342
+ name: quotaWindowName(limit),
343
+ figure: percentLeft(limit.remainingPercent ?? 0),
344
+ remainingPercent,
345
+ checkedAt: limit.checkedAt,
346
+ ...resetDetails(limit.resetsAt, limit.checkedAt, now)
347
+ }
336
348
  };
337
349
  });
338
350
  const budget = quota.budget;
@@ -340,23 +352,119 @@ function quotaWindowParts(quota, options) {
340
352
  const remainingPercent = budget.remainingPercent;
341
353
  const figure = budget.reached ? "credits spent" : remainingPercent !== void 0 ? `credits ${percentLeft(remainingPercent)}` : "credits available";
342
354
  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)
355
+ scope: ALL_SCOPE,
356
+ spent: budget.reached,
357
+ part: {
358
+ kind: "budget",
359
+ name: "credits",
360
+ figure,
361
+ ...remainingPercent === void 0 ? {} : { remainingPercent: clampPercent(remainingPercent) },
362
+ checkedAt: budget.checkedAt,
363
+ ...resetDetails(budget.resetsAt, budget.checkedAt, now)
364
+ }
349
365
  });
350
366
  }
351
367
  if (windows.length > 0) {
352
- const age = now - Math.min(...windows.map((part) => part.checkedAt));
368
+ const age = now - Math.min(...windows.map(({ part }) => part.checkedAt));
353
369
  if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
354
370
  return { windows, age: `checked ${shortSpan(age)} ago` };
355
371
  }
356
372
  }
357
373
  return { windows };
358
374
  }
375
+ function isQuotaStale(quota, options) {
376
+ return scopedWindowParts(quota, options).age !== void 0;
377
+ }
378
+ function scopeDisplayName(scope) {
379
+ const model = scope.slice(scope.indexOf(":") + 1);
380
+ return model.charAt(0).toUpperCase() + model.slice(1);
381
+ }
382
+ function scopeAbbreviations(scopes) {
383
+ const names = [...new Set(scopes.map(scopeDisplayName))];
384
+ const lengths = new Map(names.map((name) => [name, 2]));
385
+ const short = (name) => name.slice(0, lengths.get(name));
386
+ for (; ; ) {
387
+ const byShort = /* @__PURE__ */ new Map();
388
+ for (const name of names) {
389
+ byShort.set(short(name), [...byShort.get(short(name)) ?? [], name]);
390
+ }
391
+ let extended = false;
392
+ for (const group of byShort.values()) {
393
+ if (group.length < 2)
394
+ continue;
395
+ for (const name of group) {
396
+ const length = lengths.get(name) ?? 2;
397
+ if (length < name.length) {
398
+ lengths.set(name, length + 1);
399
+ extended = true;
400
+ }
401
+ }
402
+ }
403
+ if (!extended)
404
+ break;
405
+ }
406
+ return new Map(scopes.map((scope) => [scope, short(scopeDisplayName(scope))]));
407
+ }
408
+ function groupShortNames(groups) {
409
+ const labels = groups.map((group) => group.label.trim() || group.scope);
410
+ const short = scopeAbbreviations(labels);
411
+ return labels.map((label) => short.get(label) ?? label);
412
+ }
413
+ function groupedNarrowPieces(groups, windows) {
414
+ if (!groups || groups.length === 0)
415
+ return void 0;
416
+ const reported = windows.filter(({ part }) => part.kind === "window");
417
+ if (reported.some(({ scope }) => scope === ALL_SCOPE))
418
+ return void 0;
419
+ const candidates = groups.flatMap((group, listed) => {
420
+ const inGroup = reported.filter(({ scope }) => scope === group.scope);
421
+ const groupTightest = inGroup.reduce((least, window) => least === void 0 || (window.part.remainingPercent ?? 0) < (least.part.remainingPercent ?? 0) ? window : least, void 0);
422
+ return groupTightest ? [{ group, listed, window: groupTightest }] : [];
423
+ });
424
+ if (candidates.length === 0)
425
+ return void 0;
426
+ const names = groupShortNames(groups);
427
+ const left = (candidate) => candidate.window.part.remainingPercent ?? 0;
428
+ const shown = [...candidates].sort((a, b) => left(a) - left(b) || a.listed - b.listed).slice(0, NARROW_GROUP_LIMIT).sort((a, b) => a.listed - b.listed);
429
+ return shown.map((candidate, index) => {
430
+ const { windowMinutes } = candidate.window;
431
+ const piece = [
432
+ names[candidate.listed] ?? candidate.group.scope,
433
+ ...windowMinutes === void 0 ? [] : [lengthName(windowMinutes)],
434
+ `${wholePercent(left(candidate))}%`
435
+ ].join(" ");
436
+ return index === shown.length - 1 ? `${piece} left` : piece;
437
+ });
438
+ }
439
+ function narrowTextParts(quota, options) {
440
+ const { windows } = scopedWindowParts(quota, options);
441
+ const grouped = groupedNarrowPieces(quota?.groups, windows);
442
+ if (grouped)
443
+ return grouped;
444
+ const general = windows.filter(({ part, scope }) => part.kind === "window" && scope === ALL_SCOPE);
445
+ const scoped = windows.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE);
446
+ const abbreviations = scopeAbbreviations(scoped.map(({ scope }) => scope));
447
+ const budget = windows.find(({ part }) => part.kind === "budget");
448
+ const budgetLeft = budget?.spent ? 0 : budget?.part.remainingPercent;
449
+ const extras = [
450
+ ...scoped.map(({ scope, part }) => ({
451
+ label: abbreviations.get(scope) ?? scope,
452
+ remaining: part.remainingPercent ?? 0
453
+ })),
454
+ ...budgetLeft === void 0 ? [] : [{ label: "cr", remaining: budgetLeft }]
455
+ ];
456
+ const tightest = extras.reduce((best, item) => best === void 0 || item.remaining < best.remaining ? item : best, void 0);
457
+ const pieces = general.map(({ part }) => `${part.name} ${wholePercent(part.remainingPercent ?? 0)}%`);
458
+ if (tightest) {
459
+ pieces.push(`${tightest.label} ${wholePercent(tightest.remaining)}%`);
460
+ }
461
+ if (pieces.length === 0)
462
+ return windows.map(({ part }) => part.figure);
463
+ return pieces.map((piece, index) => index === pieces.length - 1 ? `${piece} left` : piece);
464
+ }
359
465
  function quotaTextParts(quota, options) {
466
+ if (options.form === "narrow")
467
+ return narrowTextParts(quota, options);
360
468
  const parts = quotaWindowParts(quota, options);
361
469
  const full = (options.form ?? "full") === "full";
362
470
  const text2 = parts.windows.map((part) => {
@@ -371,7 +479,7 @@ function formatQuota(quota, options) {
371
479
  return parts.join(" \xB7 ");
372
480
  return quota && quota.limits.length > 0 ? NO_LIMITS_REPORTED : NO_QUOTA_READING;
373
481
  }
374
- var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED;
482
+ var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED, NARROW_GROUP_LIMIT;
375
483
  var init_format = __esm({
376
484
  "../core/dist/common-auth-embedded/quota/format.js"() {
377
485
  "use strict";
@@ -379,6 +487,7 @@ var init_format = __esm({
379
487
  QUOTA_STALE_AFTER_MS = 15 * 6e4;
380
488
  NO_QUOTA_READING = "no quota reading yet";
381
489
  NO_LIMITS_REPORTED = "no limits reported";
490
+ NARROW_GROUP_LIMIT = 2;
382
491
  }
383
492
  });
384
493
 
@@ -501,6 +610,7 @@ __export(quota_exports, {
501
610
  futureResetAt: () => futureResetAt,
502
611
  isQuotaMap: () => isQuotaMap,
503
612
  isQuotaObservation: () => isQuotaObservation,
613
+ isQuotaStale: () => isQuotaStale,
504
614
  mergeQuotaObservation: () => mergeQuotaObservation,
505
615
  projectQuota: () => projectQuota,
506
616
  quotaCodec: () => quotaCodec2,
@@ -739,19 +849,24 @@ async function replaceWindowsFile(from, to, options = {}) {
739
849
  to = resolve2(to);
740
850
  const now = options.now ?? (() => performance.now());
741
851
  const start = now();
742
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
852
+ const leaseDeadline = options.deadline ?? Infinity;
853
+ let retryDeadline;
743
854
  const delays = [0, 10, 20, 40, 80, 100];
744
855
  let original;
745
856
  let attempts2 = 0;
746
857
  for (const delay3 of delays) {
858
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
747
859
  if (now() >= deadline)
748
860
  break;
749
861
  if (delay3)
750
862
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
751
863
  if (now() >= deadline)
752
864
  break;
865
+ const fenceStart = now();
753
866
  await options.beforeRename?.();
754
- if (now() >= deadline)
867
+ if (retryDeadline !== void 0)
868
+ retryDeadline += now() - fenceStart;
869
+ if (now() >= leaseDeadline)
755
870
  break;
756
871
  attempts2++;
757
872
  try {
@@ -763,6 +878,7 @@ async function replaceWindowsFile(from, to, options = {}) {
763
878
  const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
764
879
  if (!candidate)
765
880
  break;
881
+ retryDeadline ??= now() + 500;
766
882
  }
767
883
  }
768
884
  const error = new PrivateFileError(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
@@ -985,7 +1101,10 @@ function isLostMarkerRaceError(error) {
985
1101
  const code2 = error?.code;
986
1102
  return code2 === "ENOENT" || !windowsPrivateFiles && (code2 === "EINVAL" || code2 === "ENOTDIR");
987
1103
  }
988
- async function acquireRefreshFileLock(options) {
1104
+ function acquireRefreshFileLock(options) {
1105
+ return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
1106
+ }
1107
+ async function acquireRefreshFileLockWithClock(options) {
989
1108
  const lockPath = lockPathFor(options.path, options.name);
990
1109
  const legacyOwnerPath = join4(lockPath, "owner.json");
991
1110
  const ownerId = randomUUID9();
@@ -1707,7 +1826,6 @@ async function acquirePoolLock(spec, defaults, env3) {
1707
1826
  name: spec.name,
1708
1827
  path: spec.path,
1709
1828
  ttlMs: options.ttlMs,
1710
- now: env3.now,
1711
1829
  renew: options.renew,
1712
1830
  onContended: () => emit("contended"),
1713
1831
  ...env3.onRenewalTimer ? {
@@ -4823,7 +4941,6 @@ function openPoolStore(options) {
4823
4941
  ],
4824
4942
  lockDefaults,
4825
4943
  lockEnv: {
4826
- now: options.now ?? Date.now,
4827
4944
  ...options.onLockEvent ? { onLockEvent: options.onLockEvent } : {},
4828
4945
  ...options.onLockStep ? { onLockStep: options.onLockStep } : {},
4829
4946
  ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
@@ -7111,11 +7228,11 @@ var init_doctor = __esm({
7111
7228
 
7112
7229
  // ../core/dist/common-auth-embedded/auth-menu/login.js
7113
7230
  import { execFileSync as defaultExecFileSync, spawn as defaultSpawn } from "node:child_process";
7114
- function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn = defaultSpawn) {
7231
+ function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn2 = defaultSpawn) {
7115
7232
  try {
7116
7233
  if (platform === "win32") {
7117
7234
  const command = `Start-Process '${url.replaceAll("'", "''")}'`;
7118
- const child = spawn("powershell.exe", [
7235
+ const child = spawn2("powershell.exe", [
7119
7236
  "-NoProfile",
7120
7237
  "-NonInteractive",
7121
7238
  "-WindowStyle",
@@ -7936,6 +8053,326 @@ var init_auth_menu = __esm({
7936
8053
  }
7937
8054
  });
7938
8055
 
8056
+ // ../core/dist/common-auth-embedded/claustrum/errors.js
8057
+ var ClaustrumConsumerError;
8058
+ var init_errors2 = __esm({
8059
+ "../core/dist/common-auth-embedded/claustrum/errors.js"() {
8060
+ "use strict";
8061
+ ClaustrumConsumerError = class extends Error {
8062
+ kind;
8063
+ constructor(kind, message) {
8064
+ super(message);
8065
+ this.name = "ClaustrumConsumerError";
8066
+ this.kind = kind;
8067
+ }
8068
+ };
8069
+ }
8070
+ });
8071
+
8072
+ // ../core/dist/common-auth-embedded/claustrum/availability.js
8073
+ import { ClaustrumCredentialError } from "@cortexkit/claustrum-client";
8074
+ import { SocketClosedError, SocketTimeoutError, SubcCallError } from "@cortexkit/subc-client";
8075
+ function classifyVaultFailure(error) {
8076
+ if (error instanceof ClaustrumUnreachableError || error instanceof SocketClosedError || error instanceof SocketTimeoutError)
8077
+ return "unreachable";
8078
+ const code2 = error instanceof ClaustrumCredentialError || error instanceof SubcCallError ? error.code : error instanceof Error && "code" in error ? error.code : void 0;
8079
+ if (typeof code2 !== "string" || !Object.hasOwn(VAULT_FAILURE_CLASSES, code2))
8080
+ return "answered";
8081
+ return VAULT_FAILURE_CLASSES[code2];
8082
+ }
8083
+ var VAULT_FAILURE_CLASSES, ClaustrumUnreachableError;
8084
+ var init_availability = __esm({
8085
+ "../core/dist/common-auth-embedded/claustrum/availability.js"() {
8086
+ "use strict";
8087
+ init_errors2();
8088
+ VAULT_FAILURE_CLASSES = Object.freeze({
8089
+ ECONNREFUSED: "unreachable",
8090
+ ENOENT: "unreachable",
8091
+ ECONNRESET: "unreachable",
8092
+ EPIPE: "unreachable",
8093
+ ETIMEDOUT: "unreachable",
8094
+ transport_error: "unreachable",
8095
+ unavailable: "unreachable",
8096
+ timeout: "unreachable",
8097
+ route_closed: "unreachable",
8098
+ daemon_draining: "unreachable",
8099
+ connection_closed: "unreachable",
8100
+ connection_dropped: "unreachable",
8101
+ request_deadline: "unreachable",
8102
+ deadline_exceeded_no_drop_observed: "unreachable",
8103
+ module_reloading: "unreachable",
8104
+ module_warming: "unreachable",
8105
+ target_unavailable: "unreachable",
8106
+ module_timeout: "unreachable",
8107
+ invalid_response: "answered",
8108
+ invalid_record_version: "answered",
8109
+ invalid_expiry: "answered",
8110
+ invalid_status: "answered",
8111
+ invalid_params: "answered",
8112
+ ttl_unsatisfiable: "answered",
8113
+ not_found: "answered",
8114
+ enrollment_revoked: "answered",
8115
+ enrollment_invalid: "answered",
8116
+ grant_denied: "answered",
8117
+ credential_unavailable: "answered",
8118
+ needs_reauth: "answered",
8119
+ declined: "answered",
8120
+ disabled: "answered",
8121
+ identity_changed: "answered",
8122
+ closed: "answered",
8123
+ client_closed: "answered",
8124
+ pending_exists: "answered",
8125
+ pending_queue_full: "answered",
8126
+ already_consumed: "answered",
8127
+ superseded: "answered",
8128
+ stale_generation: "answered",
8129
+ missing_identity: "answered",
8130
+ invalid_control_body: "answered",
8131
+ unknown_module: "answered",
8132
+ module_removed: "answered",
8133
+ capability_denied: "answered",
8134
+ unknown_channel: "unreachable",
8135
+ stale_route_epoch: "unreachable",
8136
+ capability_forbidden: "answered",
8137
+ capability_unprovided: "answered",
8138
+ capability_ambiguous: "answered",
8139
+ invalid_capability_identifier: "answered",
8140
+ binary_body_required: "answered",
8141
+ binary_call_requires_call_binary: "answered",
8142
+ corr_exhausted: "answered",
8143
+ late_route_cleanup_failed: "answered",
8144
+ reverse_request_capability_not_declared: "answered",
8145
+ stale_route_handle: "answered",
8146
+ reverse_request_unhandled: "answered",
8147
+ handler_error: "answered",
8148
+ health_error: "answered",
8149
+ duplicate_module_id: "answered",
8150
+ route_rejected: "answered",
8151
+ lock_busy: "answered",
8152
+ owner_invalid: "answered",
8153
+ renewal_failed: "answered",
8154
+ unsupported_platform: "answered",
8155
+ EACCES: "answered",
8156
+ EPERM: "answered",
8157
+ ERR_PRIVATE_FILES_SECURITY: "answered"
8158
+ });
8159
+ ClaustrumUnreachableError = class extends ClaustrumConsumerError {
8160
+ constructor() {
8161
+ super("unavailable", "Claustrum scoped operation unavailable");
8162
+ this.name = "ClaustrumUnreachableError";
8163
+ }
8164
+ };
8165
+ }
8166
+ });
8167
+
8168
+ // ../core/dist/common-auth-embedded/claustrum/watch.js
8169
+ var SAFETY_POLL_MS, WATCH_RETRY_MS, RESUBSCRIBE_BACKOFF_MS, ChangeNoticeReader, CoalescedRead, ScopedRosterWatch;
8170
+ var init_watch = __esm({
8171
+ "../core/dist/common-auth-embedded/claustrum/watch.js"() {
8172
+ "use strict";
8173
+ SAFETY_POLL_MS = 5 * 6e4;
8174
+ WATCH_RETRY_MS = 5 * 6e4;
8175
+ RESUBSCRIBE_BACKOFF_MS = 1e3;
8176
+ ChangeNoticeReader = class {
8177
+ #epoch;
8178
+ #seq = 0;
8179
+ /**
8180
+ * Begin a new watch, whose first notice is seq 1 again. The epoch is kept,
8181
+ * so a module restart between two watches still reads as a break.
8182
+ */
8183
+ restart() {
8184
+ this.#seq = 0;
8185
+ }
8186
+ continuous(notice) {
8187
+ const continuous = notice.kind === "changed" && notice.seq === this.#seq + 1 && (this.#epoch === void 0 || notice.epoch === this.#epoch);
8188
+ this.#epoch = notice.epoch;
8189
+ this.#seq = notice.seq;
8190
+ return continuous;
8191
+ }
8192
+ };
8193
+ CoalescedRead = class {
8194
+ #read;
8195
+ #onError;
8196
+ #running;
8197
+ #queued = false;
8198
+ constructor(read, onError) {
8199
+ this.#read = read;
8200
+ this.#onError = onError;
8201
+ }
8202
+ /** The read in flight (including its queued follow-up), if any. */
8203
+ get running() {
8204
+ return this.#running;
8205
+ }
8206
+ request() {
8207
+ if (this.#running) {
8208
+ this.#queued = true;
8209
+ return this.#running;
8210
+ }
8211
+ this.#running = (async () => {
8212
+ do {
8213
+ this.#queued = false;
8214
+ try {
8215
+ await this.#read();
8216
+ } catch (error) {
8217
+ this.#onError(error);
8218
+ }
8219
+ } while (this.#queued);
8220
+ })().finally(() => {
8221
+ this.#running = void 0;
8222
+ });
8223
+ return this.#running;
8224
+ }
8225
+ };
8226
+ ScopedRosterWatch = class {
8227
+ #options;
8228
+ #reader = new ChangeNoticeReader();
8229
+ #reads;
8230
+ #mode = "polling";
8231
+ #watch;
8232
+ #timer;
8233
+ #stopped = false;
8234
+ #latestView;
8235
+ #force = false;
8236
+ /**
8237
+ * How many accepted watches in a row have closed; each one doubles the wait
8238
+ * before the next re-subscribe. Reset once a watch stays up five minutes.
8239
+ */
8240
+ #closes = 0;
8241
+ constructor(options) {
8242
+ this.#options = options;
8243
+ this.#reads = new CoalescedRead(async () => {
8244
+ const force = this.#force;
8245
+ this.#force = false;
8246
+ if (force || this.#latestView !== this.#options.view())
8247
+ await this.#options.discover(this.#latestView ?? "");
8248
+ }, (error) => {
8249
+ if (!this.#stopped)
8250
+ this.#options.onError?.(error);
8251
+ });
8252
+ }
8253
+ get mode() {
8254
+ return this.#mode;
8255
+ }
8256
+ start() {
8257
+ if (this.#stopped || this.#watch || this.#timer)
8258
+ return;
8259
+ if (typeof this.#options.client.watchScoped !== "function") {
8260
+ this.#setMode("fallback", "client-without-watch");
8261
+ return;
8262
+ }
8263
+ void this.#open(false);
8264
+ }
8265
+ stop() {
8266
+ if (this.#stopped)
8267
+ return;
8268
+ this.#stopped = true;
8269
+ if (this.#timer)
8270
+ (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
8271
+ this.#timer = void 0;
8272
+ const watch = this.#watch;
8273
+ this.#watch = void 0;
8274
+ watch?.handle.stop();
8275
+ }
8276
+ #setMode(mode, reason) {
8277
+ if (this.#mode === mode)
8278
+ return;
8279
+ this.#mode = mode;
8280
+ this.#options.logger?.debug("claustrum vault watch", { mode, reason });
8281
+ this.#options.onMode?.(mode);
8282
+ }
8283
+ #later(delay3, run) {
8284
+ this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
8285
+ this.#timer = void 0;
8286
+ if (!this.#stopped)
8287
+ run();
8288
+ }, delay3);
8289
+ this.#timer.unref?.();
8290
+ }
8291
+ async #open(resubscribed) {
8292
+ let token;
8293
+ try {
8294
+ token = await this.#options.enrollmentToken();
8295
+ } catch (error) {
8296
+ if (this.#stopped)
8297
+ return;
8298
+ this.#options.onError?.(error);
8299
+ this.#fallback("token-unreadable");
8300
+ return;
8301
+ }
8302
+ const watchScoped = this.#options.client.watchScoped;
8303
+ if (this.#stopped || this.#watch || !watchScoped)
8304
+ return;
8305
+ this.#reader.restart();
8306
+ this.#force = resubscribed;
8307
+ let watch;
8308
+ let handle;
8309
+ try {
8310
+ handle = watchScoped.call(this.#options.client, (notice) => {
8311
+ if (this.#stopped || !watch || this.#watch !== watch)
8312
+ return;
8313
+ watch.notices++;
8314
+ if (watch.notices === 1) {
8315
+ this.#options.onReachable?.();
8316
+ watch.acceptedAt = (this.#options.now ?? Date.now)();
8317
+ this.#setMode("watching", "accepted");
8318
+ }
8319
+ if (!this.#reader.continuous(notice))
8320
+ this.#force = true;
8321
+ this.#latestView = notice.view;
8322
+ void this.#reads.request();
8323
+ }, { enrollmentToken: token });
8324
+ } catch (error) {
8325
+ this.#options.onError?.(error);
8326
+ this.#fallback("watch-failed");
8327
+ return;
8328
+ }
8329
+ watch = { handle, notices: 0 };
8330
+ this.#watch = watch;
8331
+ this.#setMode("polling", resubscribed ? "resubscribing" : "opening");
8332
+ const opened = watch;
8333
+ handle.closed.then((end) => this.#closed(opened, end), (error) => this.#closed(opened, { kind: "transport_lost", error }));
8334
+ }
8335
+ #closed(watch, end) {
8336
+ if (this.#stopped || this.#watch !== watch)
8337
+ return;
8338
+ this.#watch = void 0;
8339
+ if (end.kind === "stopped")
8340
+ return;
8341
+ if (end.kind === "transport_lost")
8342
+ this.#options.onTransportLost?.();
8343
+ if (end.kind === "unsupported") {
8344
+ this.#setMode("fallback", "vault-without-watch");
8345
+ return;
8346
+ }
8347
+ if (end.kind === "refused") {
8348
+ this.#fallback("refused");
8349
+ try {
8350
+ this.#options.onRefused(end.error);
8351
+ } catch (error) {
8352
+ this.#options.onError?.(error);
8353
+ }
8354
+ return;
8355
+ }
8356
+ if (watch.notices > 0) {
8357
+ const now = (this.#options.now ?? Date.now)();
8358
+ if (watch.acceptedAt !== void 0 && now - watch.acceptedAt >= SAFETY_POLL_MS)
8359
+ this.#closes = 0;
8360
+ const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
8361
+ this.#closes++;
8362
+ this.#setMode("polling", "resubscribing");
8363
+ this.#later(delay3, () => void this.#open(true));
8364
+ return;
8365
+ }
8366
+ this.#fallback(end.kind);
8367
+ }
8368
+ #fallback(reason) {
8369
+ this.#setMode("fallback", reason);
8370
+ this.#later(WATCH_RETRY_MS, () => void this.#open(false));
8371
+ }
8372
+ };
8373
+ }
8374
+ });
8375
+
7939
8376
  // ../core/dist/common-auth-embedded/claustrum/insula.js
7940
8377
  import { resolve as resolve4 } from "node:path";
7941
8378
  import { storeIdentity } from "@cortexkit/claustrum-client";
@@ -7974,12 +8411,95 @@ function insulaUsageTransport(options) {
7974
8411
  clearTimeout(timer);
7975
8412
  client?.close();
7976
8413
  }
8414
+ },
8415
+ watchUsage(onNotice) {
8416
+ let client;
8417
+ let subscription;
8418
+ let stopped = false;
8419
+ const closed = (async () => {
8420
+ let deadline;
8421
+ const timeout = new Promise((_resolve, reject) => {
8422
+ deadline = setTimeout(
8423
+ // Coded as a timeout, so InsulaQuotaSource treats a watch that could
8424
+ // not open in time as an unreachable insula and tries again later,
8425
+ // not as a refusal.
8426
+ () => reject(Object.assign(new Error("insula watch timeout"), {
8427
+ code: "timeout"
8428
+ })),
8429
+ 3e3
8430
+ );
8431
+ deadline.unref?.();
8432
+ });
8433
+ const open13 = (async () => {
8434
+ const handshakeTimeoutMs = Math.min(options.handshakeTimeoutMs ?? 3e3, 3e3);
8435
+ const connected = options.connector ? await options.connector({
8436
+ connectionFile: options.connectionFile,
8437
+ handshakeTimeoutMs
8438
+ }) : await SubcClient.connect({
8439
+ connectionFile: options.connectionFile,
8440
+ handshakeTimeoutMs
8441
+ });
8442
+ client = connected;
8443
+ if (stopped) {
8444
+ connected.close();
8445
+ return;
8446
+ }
8447
+ const route = await connected.routeOpen({ kind: "management_surface", module_id: "insula" }, identity);
8448
+ if (stopped) {
8449
+ connected.close();
8450
+ return;
8451
+ }
8452
+ subscription = connected.subscribe(route, { method: "usage.watch" }, onNotice);
8453
+ })();
8454
+ try {
8455
+ await Promise.race([open13, timeout]);
8456
+ } catch (error) {
8457
+ stopped = true;
8458
+ throw error;
8459
+ } finally {
8460
+ clearTimeout(deadline);
8461
+ }
8462
+ if (subscription)
8463
+ await subscription.closed;
8464
+ })().finally(() => {
8465
+ stopped = true;
8466
+ client?.close();
8467
+ });
8468
+ return {
8469
+ stop() {
8470
+ if (stopped)
8471
+ return;
8472
+ stopped = true;
8473
+ subscription?.unsubscribe();
8474
+ client?.close();
8475
+ },
8476
+ closed
8477
+ };
7977
8478
  }
7978
8479
  };
7979
8480
  }
7980
8481
  function record2(value) {
7981
8482
  return typeof value === "object" && value !== null && !Array.isArray(value);
7982
8483
  }
8484
+ function decodeUsageNotice(body) {
8485
+ let value;
8486
+ try {
8487
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
8488
+ } catch {
8489
+ return void 0;
8490
+ }
8491
+ if (!record2(value) || typeof value.kind !== "string" || typeof value.epoch !== "string" || value.epoch.length === 0 || typeof value.seq !== "number" || !Number.isSafeInteger(value.seq) || value.seq < 1 || value.provider !== void 0 && typeof value.provider !== "string")
8492
+ return void 0;
8493
+ return {
8494
+ kind: value.kind,
8495
+ epoch: value.epoch,
8496
+ seq: value.seq,
8497
+ ...typeof value.provider === "string" && { provider: value.provider }
8498
+ };
8499
+ }
8500
+ function refusalCode(error) {
8501
+ return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : void 0;
8502
+ }
7983
8503
  function acquireInsulaQuotaSource(transport, tokenPath) {
7984
8504
  const key = JSON.stringify([
7985
8505
  resolve4(transport.connectionFile),
@@ -8007,6 +8527,8 @@ var MINUTE, MAX_AGE, sources, attempts, InsulaQuotaSource;
8007
8527
  var init_insula = __esm({
8008
8528
  "../core/dist/common-auth-embedded/claustrum/insula.js"() {
8009
8529
  "use strict";
8530
+ init_availability();
8531
+ init_watch();
8010
8532
  MINUTE = 6e4;
8011
8533
  MAX_AGE = 4 * MINUTE;
8012
8534
  sources = /* @__PURE__ */ new Map();
@@ -8015,14 +8537,52 @@ var init_insula = __esm({
8015
8537
  transport;
8016
8538
  key;
8017
8539
  #entries = [];
8018
- #pending;
8540
+ /** Every usage.get, polled or watch-driven, shares this one slot. */
8541
+ #reads = new CoalescedRead(async () => {
8542
+ try {
8543
+ const reply = await this.transport.getUsage();
8544
+ if (!record2(reply) || !Array.isArray(reply.result) || reply.error !== void 0)
8545
+ throw new Error("unavailable insula usage");
8546
+ this.#entries = reply.result.filter((entry) => record2(entry) && typeof entry.provider === "string");
8547
+ } catch {
8548
+ this.#entries = [];
8549
+ }
8550
+ }, () => {
8551
+ });
8552
+ #reader = new ChangeNoticeReader();
8553
+ #mode = "polling";
8554
+ #watchers = 0;
8555
+ /**
8556
+ * How many registered watchers read every provider. Watchers limited to one
8557
+ * provider are counted per provider in `#providers` instead.
8558
+ */
8559
+ #everyProvider = 0;
8560
+ #providers = /* @__PURE__ */ new Map();
8561
+ #watch;
8562
+ #timer;
8563
+ #timers = {};
8564
+ /**
8565
+ * How many accepted watches in a row have closed; each one doubles the wait
8566
+ * before the next re-subscribe. Reset once a watch brings a second notice.
8567
+ */
8568
+ #closes = 0;
8019
8569
  constructor(transport, key) {
8020
8570
  this.transport = transport;
8021
8571
  this.key = key;
8022
8572
  }
8573
+ /**
8574
+ * The background poll: at most one usage.get per minute per daemon and
8575
+ * enrollment token. While a watch is open it reads nothing, because insula's
8576
+ * notices announce every new reading. If insula stops announcing an account,
8577
+ * that account's last entry grows older than the freshness limit `current()`
8578
+ * applies, `current()` returns nothing for it, and the plugin falls back to
8579
+ * its own provider poll for that account.
8580
+ */
8023
8581
  refresh(now) {
8024
- if (this.#pending)
8025
- return this.#pending;
8582
+ if (this.#reads.running)
8583
+ return this.#reads.running;
8584
+ if (this.#mode === "watching")
8585
+ return Promise.resolve();
8026
8586
  for (const [key, time] of attempts) {
8027
8587
  if (now - time >= MINUTE)
8028
8588
  attempts.delete(key);
@@ -8031,19 +8591,119 @@ var init_insula = __esm({
8031
8591
  if (lastAttempt !== void 0 && now - lastAttempt < MINUTE)
8032
8592
  return Promise.resolve();
8033
8593
  attempts.set(this.key, now);
8034
- this.#pending = (async () => {
8035
- try {
8036
- const reply = await this.transport.getUsage();
8037
- if (!record2(reply) || !Array.isArray(reply.result) || reply.error !== void 0)
8038
- throw new Error("unavailable insula usage");
8039
- this.#entries = reply.result.filter((entry) => record2(entry) && typeof entry.provider === "string");
8040
- } catch {
8041
- this.#entries = [];
8594
+ return this.#reads.request();
8595
+ }
8596
+ /** How this source currently learns about usage changes, for logs. */
8597
+ watchMode() {
8598
+ return this.#mode;
8599
+ }
8600
+ /**
8601
+ * Hold a `usage.watch` open while any watcher wants it, and re-read
8602
+ * usage.get when a notice says something changed. Watchers of one source
8603
+ * share one watch, since insula admits only 64 per process. Returns the
8604
+ * release; the last release closes the watch.
8605
+ */
8606
+ watch(options = {}) {
8607
+ this.#watchers++;
8608
+ const provider2 = options.provider;
8609
+ if (provider2 === void 0)
8610
+ this.#everyProvider++;
8611
+ else
8612
+ this.#providers.set(provider2, (this.#providers.get(provider2) ?? 0) + 1);
8613
+ if (this.#watchers === 1) {
8614
+ this.#timers = options;
8615
+ this.#open();
8616
+ }
8617
+ let released = false;
8618
+ return () => {
8619
+ if (released)
8620
+ return;
8621
+ released = true;
8622
+ if (provider2 === void 0)
8623
+ this.#everyProvider--;
8624
+ else {
8625
+ const left = (this.#providers.get(provider2) ?? 1) - 1;
8626
+ if (left > 0)
8627
+ this.#providers.set(provider2, left);
8628
+ else
8629
+ this.#providers.delete(provider2);
8042
8630
  }
8043
- })().finally(() => {
8044
- this.#pending = void 0;
8045
- });
8046
- return this.#pending;
8631
+ if (--this.#watchers === 0)
8632
+ this.#stopWatch();
8633
+ };
8634
+ }
8635
+ #stopWatch() {
8636
+ if (this.#timer)
8637
+ (this.#timers.clearTimeoutImpl ?? clearTimeout)(this.#timer);
8638
+ this.#timer = void 0;
8639
+ const watch = this.#watch;
8640
+ this.#watch = void 0;
8641
+ watch?.handle?.stop();
8642
+ this.#mode = "polling";
8643
+ }
8644
+ #later(delay3) {
8645
+ this.#timer = (this.#timers.setTimeoutImpl ?? setTimeout)(() => {
8646
+ this.#timer = void 0;
8647
+ if (this.#watchers > 0 && !this.#watch)
8648
+ this.#open();
8649
+ }, delay3);
8650
+ this.#timer.unref?.();
8651
+ }
8652
+ #open() {
8653
+ const watchUsage = this.transport.watchUsage;
8654
+ if (!watchUsage) {
8655
+ this.#mode = "fallback";
8656
+ return;
8657
+ }
8658
+ this.#mode = "polling";
8659
+ this.#reader.restart();
8660
+ const watch = { notices: 0 };
8661
+ this.#watch = watch;
8662
+ let handle;
8663
+ try {
8664
+ handle = watchUsage.call(this.transport, (body) => this.#notice(watch, body));
8665
+ } catch (error) {
8666
+ this.#closed(watch, error);
8667
+ return;
8668
+ }
8669
+ watch.handle = handle;
8670
+ handle.closed.then(() => this.#closed(watch, void 0), (error) => this.#closed(watch, error));
8671
+ }
8672
+ #notice(watch, body) {
8673
+ if (this.#watch !== watch)
8674
+ return;
8675
+ watch.notices++;
8676
+ if (watch.notices === 1)
8677
+ this.#mode = "watching";
8678
+ if (watch.notices === 2)
8679
+ this.#closes = 0;
8680
+ const notice = decodeUsageNotice(body);
8681
+ if (!notice)
8682
+ this.#reader.restart();
8683
+ const continuous = notice ? this.#reader.continuous(notice) : false;
8684
+ if (!continuous || notice?.provider === void 0 || this.#everyProvider > 0 || this.#providers.has(notice.provider))
8685
+ void this.#reads.request();
8686
+ }
8687
+ #closed(watch, error) {
8688
+ if (this.#watch !== watch)
8689
+ return;
8690
+ this.#watch = void 0;
8691
+ const code2 = refusalCode(error);
8692
+ if (code2 === "unknown_method" || code2 === "usage_watch_limit") {
8693
+ this.#mode = "fallback";
8694
+ return;
8695
+ }
8696
+ if (watch.notices > 0) {
8697
+ const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
8698
+ this.#closes++;
8699
+ this.#mode = "polling";
8700
+ this.#later(delay3);
8701
+ return;
8702
+ }
8703
+ this.#mode = "fallback";
8704
+ void this.#reads.request();
8705
+ if (error === void 0 || classifyVaultFailure(error) === "unreachable")
8706
+ this.#later(WATCH_RETRY_MS);
8047
8707
  }
8048
8708
  current(provider2, accountId, now) {
8049
8709
  for (const entry of this.#entries) {
@@ -8110,30 +8770,14 @@ var init_any_signal = __esm({
8110
8770
  }
8111
8771
  });
8112
8772
 
8113
- // ../core/dist/common-auth-embedded/claustrum/errors.js
8114
- var ClaustrumConsumerError;
8115
- var init_errors2 = __esm({
8116
- "../core/dist/common-auth-embedded/claustrum/errors.js"() {
8117
- "use strict";
8118
- ClaustrumConsumerError = class extends Error {
8119
- kind;
8120
- constructor(kind, message) {
8121
- super(message);
8122
- this.name = "ClaustrumConsumerError";
8123
- this.kind = kind;
8124
- }
8125
- };
8126
- }
8127
- });
8128
-
8129
8773
  // ../core/dist/common-auth-embedded/claustrum/enrollment.js
8130
8774
  import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID12 } from "node:crypto";
8131
8775
  import { constants as fsConstants } from "node:fs";
8132
8776
  import { chmod as chmod2, mkdir as mkdir8, open as open6, readFile as readFile6, realpath as realpath3, rename as rename6, stat as stat4, unlink as unlink6 } from "node:fs/promises";
8133
8777
  import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join5, resolve as resolve5 } from "node:path";
8134
- import { ClaustrumCredentialError, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8778
+ import { ClaustrumCredentialError as ClaustrumCredentialError2, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8135
8779
  function classifyEnrollmentError(error) {
8136
- if (!(error instanceof ClaustrumCredentialError))
8780
+ if (!(error instanceof ClaustrumCredentialError2))
8137
8781
  return void 0;
8138
8782
  if (TERMINAL_ENROLLMENT_CODES.has(error.code))
8139
8783
  return { code: error.code, disposition: "terminal" };
@@ -8834,9 +9478,9 @@ var init_host_slot = __esm({
8834
9478
  });
8835
9479
 
8836
9480
  // ../core/dist/common-auth-embedded/claustrum/custody.js
8837
- import { ClaustrumCredentialError as ClaustrumCredentialError2 } from "@cortexkit/claustrum-client";
9481
+ import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
8838
9482
  function isScopedCredentialRotation(served, current) {
8839
- return current !== void 0 && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
9483
+ return current !== void 0 && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
8840
9484
  }
8841
9485
  function scopedRetryReason(served, current) {
8842
9486
  if (current === void 0)
@@ -8895,16 +9539,28 @@ function credentialTypeOf(row, family) {
8895
9539
  return row.refreshAdapter === void 0 ? "api_key" : void 0;
8896
9540
  return void 0;
8897
9541
  }
8898
- var defaultLogger, SERVING_MARGIN_MS, ClaustrumScopedCustody;
9542
+ function grantReachOf(listed) {
9543
+ const { grants, grantTuples } = listed;
9544
+ if (grants === void 0 || grantTuples === void 0)
9545
+ return void 0;
9546
+ return Object.freeze({
9547
+ grants,
9548
+ tuples: Object.freeze(grantTuples.map(({ selectorKind, selector, operation }) => Object.freeze({ selectorKind, selector, operation })))
9549
+ });
9550
+ }
9551
+ var defaultLogger, SERVING_MARGIN_MS, KEPT_RECEIPT_MARGIN_MS, ClaustrumScopedCustody;
8899
9552
  var init_custody = __esm({
8900
9553
  "../core/dist/common-auth-embedded/claustrum/custody.js"() {
8901
9554
  "use strict";
8902
9555
  init_logger();
9556
+ init_availability();
8903
9557
  init_enrollment();
8904
9558
  init_errors2();
8905
9559
  init_host_slot();
9560
+ init_watch();
8906
9561
  defaultLogger = createLogger2("claustrum");
8907
9562
  SERVING_MARGIN_MS = 3e5;
9563
+ KEPT_RECEIPT_MARGIN_MS = 6e4;
8908
9564
  ClaustrumScopedCustody = class {
8909
9565
  #client;
8910
9566
  #readToken;
@@ -8915,7 +9571,20 @@ var init_custody = __esm({
8915
9571
  #logger;
8916
9572
  #provenance = /* @__PURE__ */ new WeakMap();
8917
9573
  #reports = /* @__PURE__ */ new WeakMap();
9574
+ #kept = /* @__PURE__ */ new Map();
9575
+ #keptAttempts = /* @__PURE__ */ new WeakMap();
9576
+ #setTimeout;
9577
+ #clearTimeout;
9578
+ #outage = false;
9579
+ #outageError = new ClaustrumUnreachableError();
9580
+ #probeTimer;
9581
+ #probing = false;
9582
+ #lastProbeAt = -Infinity;
9583
+ #probeDelay = 2e3;
8918
9584
  #closed = false;
9585
+ /** The view of the last successful `discover()`, for `watchRoster`. */
9586
+ #discoveredView;
9587
+ #watches = /* @__PURE__ */ new Set();
8919
9588
  constructor(options) {
8920
9589
  const tokenPath = options.tokenPath;
8921
9590
  if (options.readToken) {
@@ -8931,6 +9600,56 @@ var init_custody = __esm({
8931
9600
  this.#requireAssertion = options.requireAssertion ?? false;
8932
9601
  this.#now = options.now ?? Date.now;
8933
9602
  this.#logger = options.logger ?? defaultLogger;
9603
+ this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
9604
+ this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
9605
+ }
9606
+ /** A watch losing its transport is the same outage as an unreachable read. */
9607
+ transportLost(error) {
9608
+ if (this.#closed || this.#outage)
9609
+ return;
9610
+ this.#outage = true;
9611
+ this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError();
9612
+ this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
9613
+ this.#scheduleProbe();
9614
+ }
9615
+ /** Any vault answer ends transport fallback, even when it refuses access. */
9616
+ reachable() {
9617
+ if (this.#closed || !this.#outage)
9618
+ return;
9619
+ this.#outage = false;
9620
+ if (this.#probeTimer)
9621
+ this.#clearTimeout(this.#probeTimer);
9622
+ this.#probeTimer = void 0;
9623
+ this.#probeDelay = 2e3;
9624
+ for (const kept of this.#kept.values())
9625
+ kept.since = null;
9626
+ (this.#logger.info ?? defaultLogger.info)("vault receipt serving resumed", { reason: "reachable" });
9627
+ }
9628
+ #scheduleProbe() {
9629
+ if (this.#closed || !this.#outage || this.#probeTimer || this.#probing)
9630
+ return;
9631
+ this.#probeTimer = this.#setTimeout(() => {
9632
+ this.#probeTimer = void 0;
9633
+ this.#probe(true);
9634
+ }, this.#probeDelay);
9635
+ this.#probeTimer.unref?.();
9636
+ }
9637
+ #probe(idle = false) {
9638
+ if (this.#closed || !this.#outage || this.#probing)
9639
+ return;
9640
+ if (this.#now() - this.#lastProbeAt < 1e3) {
9641
+ this.#scheduleProbe();
9642
+ return;
9643
+ }
9644
+ this.#lastProbeAt = this.#now();
9645
+ this.#probing = true;
9646
+ void this.#list().catch(() => {
9647
+ if (idle && this.#outage)
9648
+ this.#probeDelay = Math.min(this.#probeDelay * 2, 3e4);
9649
+ }).finally(() => {
9650
+ this.#probing = false;
9651
+ this.#scheduleProbe();
9652
+ });
8934
9653
  }
8935
9654
  #check(signal) {
8936
9655
  if (this.#closed)
@@ -8964,13 +9683,20 @@ var init_custody = __esm({
8964
9683
  ]) : await pending;
8965
9684
  } catch (error) {
8966
9685
  this.#check(signal);
8967
- if (error instanceof ClaustrumCredentialError2)
9686
+ if (classifyVaultFailure(error) === "unreachable")
9687
+ this.transportLost(error);
9688
+ else
9689
+ this.reachable();
9690
+ if (error instanceof ClaustrumCredentialError3)
8968
9691
  throw error;
9692
+ if (classifyVaultFailure(error) === "unreachable")
9693
+ throw new ClaustrumUnreachableError();
8969
9694
  throw new ClaustrumConsumerError("unavailable", "Claustrum scoped operation unavailable");
8970
9695
  } finally {
8971
9696
  removeAbortListener?.();
8972
9697
  }
8973
9698
  this.#check(signal);
9699
+ this.reachable();
8974
9700
  return result;
8975
9701
  }
8976
9702
  /**
@@ -8980,8 +9706,25 @@ var init_custody = __esm({
8980
9706
  * skipped records: they simply are not this consumer's.
8981
9707
  */
8982
9708
  async discover(signal) {
8983
- const token = await this.#token(signal);
8984
- const inventory = await this.#call(() => this.#client.listScoped(token), signal);
9709
+ const inventory = await this.#list(signal);
9710
+ this.#discoveredView = inventory.view;
9711
+ return inventory;
9712
+ }
9713
+ async #list(signal) {
9714
+ let inventory;
9715
+ let token;
9716
+ try {
9717
+ token = await this.#token(signal);
9718
+ } catch (error) {
9719
+ this.#kept.clear();
9720
+ throw error;
9721
+ }
9722
+ try {
9723
+ inventory = await this.#call(() => this.#client.listScoped(token), signal);
9724
+ } catch (error) {
9725
+ this.listFailed(error);
9726
+ throw error;
9727
+ }
8985
9728
  const skipped = [];
8986
9729
  const candidates = [];
8987
9730
  const counts = /* @__PURE__ */ new Map();
@@ -9020,28 +9763,114 @@ var init_custody = __esm({
9020
9763
  }
9021
9764
  for (const record3 of skipped)
9022
9765
  this.#logger.warn("skipped malformed vault record", record3);
9766
+ const grantReach = grantReachOf(inventory);
9023
9767
  return {
9024
9768
  view: inventory.view,
9025
9769
  credentials: Object.freeze(credentials),
9026
- skipped: Object.freeze(skipped)
9770
+ skipped: Object.freeze(skipped),
9771
+ ...grantReach && { grantReach }
9027
9772
  };
9028
9773
  }
9029
9774
  /**
9030
- * Fetch the credential for one physical send and wrap it in a fresh receipt.
9031
- * The vault's served identity (or, without one, the plugin's parse of the
9032
- * token) must equal the roster's when both are present. Without
9033
- * `requireAssertion`, absence on either side proves nothing and does not
9034
- * refuse; the receipt records what the vault asserted separately from what
9035
- * the roster expected. With it, a reply that does not itself name the
9036
- * credential id and the expected account is refused.
9775
+ * Apply a failed account listing: any answer from the vault (a refusal such
9776
+ * as a revoked enrollment's `not_found`) drops every kept receipt, while an
9777
+ * unreachable vault keeps them. A vault watch that ends with the same
9778
+ * refusal calls this too, so both paths treat it alike.
9779
+ */
9780
+ listFailed(error) {
9781
+ if (classifyVaultFailure(error) === "unreachable")
9782
+ this.transportLost(error);
9783
+ else {
9784
+ this.reachable();
9785
+ this.#kept.clear();
9786
+ }
9787
+ }
9788
+ /** Discard bearer material when a route is removed, declined or rebound. */
9789
+ forget(credentialId) {
9790
+ this.#kept.delete(credentialId);
9791
+ }
9792
+ /** Apply an already-held roster; this never fetches credentials or writes it. */
9793
+ retain(identities) {
9794
+ const current = new Map(identities.map((identity) => [identity.credentialId, identity]));
9795
+ for (const [id, kept] of this.#kept) {
9796
+ const identity = current.get(id);
9797
+ if (!identity?.enabled || identity.state !== "active" || identity.credentialType !== kept.attempt.credentialType || identity.accountIdentity !== kept.attempt.expectedAccountIdentity)
9798
+ this.forget(id);
9799
+ }
9800
+ }
9801
+ /** A frozen, non-secret summary for a plugin's status display. */
9802
+ keptReceiptState() {
9803
+ let since = null;
9804
+ for (const [id, kept] of this.#kept) {
9805
+ if (!this.#usable(kept.attempt)) {
9806
+ this.forget(id);
9807
+ continue;
9808
+ }
9809
+ if (kept.since !== null)
9810
+ since = Math.min(since ?? kept.since, kept.since);
9811
+ }
9812
+ return Object.freeze({ active: since !== null, since });
9813
+ }
9814
+ #usable(attempt) {
9815
+ return attempt.expiresAtMs === null ? attempt.credentialType === "api_key" : attempt.expiresAtMs - this.#now() > KEPT_RECEIPT_MARGIN_MS;
9816
+ }
9817
+ /** Ask the vault while reachable; retain one validated receipt in memory only. */
9818
+ async authorize(identity, signal, routeId = "vault") {
9819
+ this.#check(signal);
9820
+ const { credentialId, credentialType, accountIdentity } = identity;
9821
+ let kept = this.#kept.get(credentialId);
9822
+ if (kept && (kept.attempt.credentialType !== credentialType || kept.attempt.expectedAccountIdentity !== accountIdentity)) {
9823
+ this.forget(credentialId);
9824
+ kept = void 0;
9825
+ }
9826
+ let token;
9827
+ try {
9828
+ token = await this.#token(signal);
9829
+ } catch (error) {
9830
+ this.#kept.clear();
9831
+ throw error;
9832
+ }
9833
+ if (this.#outage && kept) {
9834
+ this.#probe();
9835
+ return this.#serveKept(credentialId, kept, token, routeId);
9836
+ }
9837
+ try {
9838
+ const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
9839
+ this.#kept.set(credentialId, { attempt, routeId, since: null });
9840
+ return attempt;
9841
+ } catch (error) {
9842
+ this.#check(signal);
9843
+ if (classifyVaultFailure(error) !== "unreachable") {
9844
+ this.forget(credentialId);
9845
+ throw error;
9846
+ }
9847
+ return this.#serveKept(credentialId, kept, token, routeId, error);
9848
+ }
9849
+ }
9850
+ #serveKept(credentialId, kept, token, routeId, error = this.#outageError) {
9851
+ if (!kept || this.#kept.get(credentialId) !== kept || !this.#usable(kept.attempt)) {
9852
+ this.forget(credentialId);
9853
+ throw error;
9854
+ }
9855
+ if (kept.since === null)
9856
+ kept.since = this.#now();
9857
+ const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, "accessToken", { value: kept.attempt.accessToken, enumerable: false }));
9858
+ this.#provenance.set(attempt, token);
9859
+ this.#keptAttempts.set(attempt, routeId);
9860
+ return attempt;
9861
+ }
9862
+ /**
9863
+ * Fetch and validate a fresh receipt before retaining it. The vault assertion
9864
+ * (or the plugin's token parse) must agree with the roster when both exist.
9865
+ * With requireAssertion, an absent assertion also refuses rather than
9866
+ * treating the roster's expectation as proof of the served account.
9037
9867
  */
9038
- async authorize(identity, signal) {
9868
+ async #authorizeFresh(identity, token, signal) {
9039
9869
  if (!identity.credentialId)
9040
9870
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum dispatch requires a credential id");
9041
9871
  const { credentialId, credentialType, accountIdentity } = identity;
9042
9872
  if (this.#requireAssertion && accountIdentity === void 0)
9043
9873
  throw new ClaustrumConsumerError("identity-unasserted", "Claustrum dispatch requires a known account identity");
9044
- const token = await this.#token(signal);
9045
9874
  const served = await this.#call(() => this.#client.getScoped({
9046
9875
  credentialId,
9047
9876
  enrollmentToken: token,
@@ -9104,6 +9933,18 @@ var init_custody = __esm({
9104
9933
  const token = this.#provenance.get(attempt);
9105
9934
  if (!token)
9106
9935
  throw new ClaustrumConsumerError("no-receipt", "Claustrum failure report requires an original dispatch receipt");
9936
+ const keptRoute = this.#keptAttempts.get(attempt);
9937
+ if (keptRoute !== void 0) {
9938
+ this.forget(attempt.credentialId);
9939
+ this.#logger.debug("scoped 401 not reported", {
9940
+ routeId: keptRoute,
9941
+ reason: "kept-receipt"
9942
+ });
9943
+ return;
9944
+ }
9945
+ const kept = this.#kept.get(attempt.credentialId);
9946
+ if (kept && kept.attempt.recordVersion === attempt.recordVersion)
9947
+ this.forget(attempt.credentialId);
9107
9948
  const pending = this.#reports.get(attempt);
9108
9949
  if (pending)
9109
9950
  return pending;
@@ -9127,10 +9968,70 @@ var init_custody = __esm({
9127
9968
  throw error;
9128
9969
  }
9129
9970
  }
9971
+ /**
9972
+ * Watch this consumer's visible vault accounts instead of listing them on a
9973
+ * short timer. Opens one `watchScoped` on this custody's client and calls
9974
+ * `onView` when the host must run its discovery (see
9975
+ * `ClaustrumRosterWatchOptions`). A claustrum-client without `watchScoped`
9976
+ * (before 0.12.0) or a vault that answers `unknown_method` reports
9977
+ * `fallback` and opens nothing. A watch that closes before any notice was
9978
+ * never accepted: the client reads once to learn why, and the watch reports
9979
+ * `fallback` and tries one new watch after `WATCH_RETRY_MS`, never in a
9980
+ * loop. A watch that closes after notices is re-opened after
9981
+ * `RESUBSCRIBE_BACKOFF_MS`, doubling per close in a row. A lost transport
9982
+ * starts this custody's outage, exactly as an unreachable call does, and
9983
+ * the first notice of a watch ends it. Timers are unreferenced; `close()`
9984
+ * on the returned watch or on this custody stops it.
9985
+ *
9986
+ * The watch keeps no history, so the host still lists on a slow timer while
9987
+ * the mode is `watching`: every `SAFETY_POLL_MS` (five minutes). In any
9988
+ * other mode the host keeps its usual list timer.
9989
+ */
9990
+ watchRoster(options) {
9991
+ this.#check();
9992
+ const watch = new ScopedRosterWatch({
9993
+ client: this.#client,
9994
+ enrollmentToken: () => this.#token(),
9995
+ view: options.view ?? (() => this.#discoveredView),
9996
+ discover: async (view) => {
9997
+ await options.onView(view);
9998
+ },
9999
+ onRefused: (error) => {
10000
+ this.listFailed(error);
10001
+ options.onRefused?.(error);
10002
+ },
10003
+ onTransportLost: () => this.transportLost(),
10004
+ onReachable: () => this.reachable(),
10005
+ onError: options.onError,
10006
+ onMode: options.onMode,
10007
+ logger: this.#logger,
10008
+ now: this.#now,
10009
+ setTimeoutImpl: this.#setTimeout,
10010
+ clearTimeoutImpl: this.#clearTimeout
10011
+ });
10012
+ this.#watches.add(watch);
10013
+ watch.start();
10014
+ return {
10015
+ get mode() {
10016
+ return watch.mode;
10017
+ },
10018
+ close: () => {
10019
+ this.#watches.delete(watch);
10020
+ watch.stop();
10021
+ }
10022
+ };
10023
+ }
9130
10024
  close() {
9131
10025
  if (this.#closed)
9132
10026
  return;
9133
10027
  this.#closed = true;
10028
+ if (this.#probeTimer)
10029
+ this.#clearTimeout(this.#probeTimer);
10030
+ this.#probeTimer = void 0;
10031
+ for (const watch of this.#watches)
10032
+ watch.stop();
10033
+ this.#watches.clear();
10034
+ this.#kept.clear();
9134
10035
  this.#client.close();
9135
10036
  }
9136
10037
  };
@@ -9581,6 +10482,7 @@ var init_consumer = __esm({
9581
10482
  init_errors2();
9582
10483
  init_insula();
9583
10484
  init_roster();
10485
+ init_watch();
9584
10486
  ClaustrumConsumer = class {
9585
10487
  #options;
9586
10488
  #shutdown = new AbortController();
@@ -9589,9 +10491,18 @@ var init_consumer = __esm({
9589
10491
  #connecting;
9590
10492
  #refreshing;
9591
10493
  #roster;
10494
+ /**
10495
+ * The grants named by this instance's latest discovery, with the view that
10496
+ * discovery committed. Memory only: the roster file never carries it.
10497
+ */
10498
+ #grantReach;
9592
10499
  #timer;
9593
10500
  #started = false;
9594
10501
  #insula;
10502
+ #vaultWatch;
10503
+ #releaseInsulaWatch;
10504
+ /** When this instance last completed a discovery, by `now`. */
10505
+ #discoveredAt;
9595
10506
  constructor(options) {
9596
10507
  this.#options = options;
9597
10508
  this.#logger = options.logger ?? createLogger2("claustrum");
@@ -9649,7 +10560,9 @@ var init_consumer = __esm({
9649
10560
  parseIdentity: this.#options.parseIdentity,
9650
10561
  requireAssertion: this.#options.requireAssertion,
9651
10562
  now: this.#options.now,
9652
- logger: this.#logger
10563
+ logger: this.#logger,
10564
+ setTimeoutImpl: this.#options.setTimeoutImpl,
10565
+ clearTimeoutImpl: this.#options.clearTimeoutImpl
9653
10566
  });
9654
10567
  if (this.#options.insula && client.insula) {
9655
10568
  this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
@@ -9665,6 +10578,39 @@ var init_consumer = __esm({
9665
10578
  snapshot() {
9666
10579
  return this.#roster;
9667
10580
  }
10581
+ /**
10582
+ * What this consumer is granted, from its latest discovery, without any I/O.
10583
+ * It explains an empty roster: `grants === 0` means no grant at all, while
10584
+ * `grants > 0` means a grant that reaches no credential (`tuples` names its
10585
+ * selector). Undefined means unknown, never zero: the vault or client is too
10586
+ * old to send it, nothing was discovered yet, or the roster now in memory is
10587
+ * a different view than the one this instance discovered (a peer process
10588
+ * held the discovery lease and its newer roster was served instead).
10589
+ */
10590
+ grantReach() {
10591
+ const latest2 = this.#grantReach;
10592
+ return latest2 && this.#roster?.view === latest2.view ? latest2.reach : void 0;
10593
+ }
10594
+ /** How this consumer currently learns about changes, without I/O. */
10595
+ watchState() {
10596
+ return Object.freeze({
10597
+ vault: this.#vaultWatch?.mode ?? "polling",
10598
+ ...this.#options.insula && {
10599
+ insula: this.#insula?.source.watchMode() ?? "polling"
10600
+ }
10601
+ });
10602
+ }
10603
+ /** Close the watches with the connection they belong to. */
10604
+ #stopWatch() {
10605
+ this.#vaultWatch?.close();
10606
+ this.#vaultWatch = void 0;
10607
+ this.#releaseInsulaWatch?.();
10608
+ this.#releaseInsulaWatch = void 0;
10609
+ }
10610
+ /** Whether any account is using an in-memory outage receipt, without I/O. */
10611
+ keptReceiptState() {
10612
+ return this.#custody?.keptReceiptState() ?? Object.freeze({ active: false, since: null });
10613
+ }
9668
10614
  /** Rows for `/routing`, from the last committed roster. */
9669
10615
  routingRows() {
9670
10616
  return vaultRoutingRows(this.#roster);
@@ -9676,6 +10622,8 @@ var init_consumer = __esm({
9676
10622
  this.#refreshing = (async () => {
9677
10623
  if (!await this.#active()) {
9678
10624
  this.#roster = void 0;
10625
+ this.#grantReach = void 0;
10626
+ this.#stopWatch();
9679
10627
  this.#custody?.close();
9680
10628
  this.#custody = void 0;
9681
10629
  this.#insula?.release();
@@ -9683,9 +10631,15 @@ var init_consumer = __esm({
9683
10631
  return void 0;
9684
10632
  }
9685
10633
  const custody = await this.#getCustody();
10634
+ let discovered;
9686
10635
  const roster = await refreshVaultRoster({
9687
10636
  path: this.#options.rosterPath,
9688
- custody,
10637
+ custody: {
10638
+ discover: async (signal) => {
10639
+ discovered = await custody.discover(signal);
10640
+ return discovered;
10641
+ }
10642
+ },
9689
10643
  isActive: () => this.#active(),
9690
10644
  signal: this.#shutdown.signal,
9691
10645
  projection: () => ({
@@ -9698,14 +10652,28 @@ var init_consumer = __esm({
9698
10652
  this.#assertOpen();
9699
10653
  const changed = roster?.view !== this.#roster?.view;
9700
10654
  this.#roster = roster;
10655
+ custody.retain(roster?.rows ?? []);
10656
+ if (discovered && roster?.view !== void 0)
10657
+ this.#grantReach = discovered.grantReach ? { view: roster.view, reach: discovered.grantReach } : void 0;
9701
10658
  if (roster && changed)
9702
10659
  this.#options.onRoster?.(roster);
10660
+ this.#discoveredAt = (this.#options.now ?? Date.now)();
9703
10661
  return roster;
9704
10662
  })().finally(() => {
9705
10663
  this.#refreshing = void 0;
9706
10664
  });
9707
10665
  return this.#refreshing;
9708
10666
  }
10667
+ /**
10668
+ * Poll in the background and open the vault and insula watches. Until the
10669
+ * vault watch is accepted, and whenever it is unavailable, every tick lists
10670
+ * the vault exactly as before watches existed. While it is open a tick
10671
+ * lists only when five minutes have passed since the last discovery, since
10672
+ * the watch keeps no history; it still checks `isCustodyActive`, so a switch
10673
+ * to local mode closes the connection as quickly as before. Insula is
10674
+ * polled on the tick only while its own watch is not open. A host not in
10675
+ * vault mode makes no request.
10676
+ */
9709
10677
  start() {
9710
10678
  if (this.#started)
9711
10679
  return;
@@ -9713,8 +10681,10 @@ var init_consumer = __esm({
9713
10681
  this.#started = true;
9714
10682
  const tick = async () => {
9715
10683
  try {
9716
- await this.refresh();
10684
+ if (await this.#listDue())
10685
+ await this.refresh();
9717
10686
  await this.refreshInsulaQuota();
10687
+ this.#openWatch();
9718
10688
  } catch (error) {
9719
10689
  if (!this.#shutdown.signal.aborted)
9720
10690
  this.#options.onError?.(error);
@@ -9732,6 +10702,50 @@ var init_consumer = __esm({
9732
10702
  };
9733
10703
  void tick();
9734
10704
  }
10705
+ /** Whether a background tick must list the vault now. */
10706
+ async #listDue() {
10707
+ if (this.#vaultWatch?.mode !== "watching")
10708
+ return true;
10709
+ const now = (this.#options.now ?? Date.now)();
10710
+ if (this.#discoveredAt === void 0 || now - this.#discoveredAt >= SAFETY_POLL_MS)
10711
+ return true;
10712
+ return !await this.#active();
10713
+ }
10714
+ /**
10715
+ * Open the vault and insula watches once a vault connection exists. Only
10716
+ * reached in vault mode: a host in local mode never connects.
10717
+ */
10718
+ #openWatch() {
10719
+ const custody = this.#custody;
10720
+ if (this.#shutdown.signal.aborted || !custody)
10721
+ return;
10722
+ this.#vaultWatch ??= custody.watchRoster({
10723
+ view: () => this.#roster?.view,
10724
+ // The existing discovery, so a watched change commits the roster and
10725
+ // re-applies it to kept receipts exactly as a poll does. A refresh
10726
+ // already in flight may have listed before the change was announced,
10727
+ // so wait for it and list again.
10728
+ onView: async () => {
10729
+ while (this.#refreshing)
10730
+ await this.#refreshing.catch(() => {
10731
+ });
10732
+ await this.refresh();
10733
+ },
10734
+ // Custody has dropped kept receipts, as a poll meeting the same
10735
+ // refusal from list_scoped would.
10736
+ onRefused: (error) => this.#options.onError?.(error),
10737
+ onError: (error) => {
10738
+ if (!this.#shutdown.signal.aborted)
10739
+ this.#options.onError?.(error);
10740
+ }
10741
+ });
10742
+ if (this.#options.insula && this.#insula && !this.#releaseInsulaWatch)
10743
+ this.#releaseInsulaWatch = this.#insula.source.watch({
10744
+ provider: this.#options.insula.provider,
10745
+ setTimeoutImpl: this.#options.setTimeoutImpl,
10746
+ clearTimeoutImpl: this.#options.clearTimeoutImpl
10747
+ });
10748
+ }
9735
10749
  /**
9736
10750
  * Fetch on a background tick, at most once per minute across projects with
9737
10751
  * the same daemon and enrollment token path. Admission must use the cache
@@ -9794,16 +10808,28 @@ var init_consumer = __esm({
9794
10808
  async authorize(routeId, signal) {
9795
10809
  this.#assertOpen(signal);
9796
10810
  const roster = this.#roster ?? await this.#wait(this.refresh(), signal);
9797
- if (!roster || !await this.#active())
10811
+ if (!roster || !await this.#active()) {
10812
+ this.#custody?.close();
10813
+ this.#custody = void 0;
10814
+ this.#stopWatch();
10815
+ this.#insula?.release();
10816
+ this.#insula = void 0;
9798
10817
  throw new ClaustrumConsumerError("not-active", "Claustrum scoped custody is not active");
10818
+ }
9799
10819
  const current = await readVaultRoster(this.#options.rosterPath);
9800
10820
  this.#assertOpen(signal);
9801
10821
  const observed = roster.rows.find((row) => row.routeId === routeId);
9802
10822
  const configured = current?.rows.find((row) => row.routeId === routeId);
9803
- if (configured && !configured.enabled)
10823
+ if (configured && !configured.enabled) {
10824
+ if (observed)
10825
+ this.#custody?.forget(observed.credentialId);
9804
10826
  throw new ClaustrumConsumerError("route-declined", "Claustrum route is disabled");
9805
- if (!observed || !configured || configured.state !== "active" || configured.credentialId !== observed.credentialId || configured.accountIdentity !== observed.accountIdentity)
10827
+ }
10828
+ if (!observed || !configured || configured.state !== "active" || configured.credentialId !== observed.credentialId || configured.accountIdentity !== observed.accountIdentity || configured.credentialType !== observed.credentialType) {
10829
+ if (observed)
10830
+ this.#custody?.forget(observed.credentialId);
9806
10831
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum route is disabled, removed or changed");
10832
+ }
9807
10833
  const custody = await this.#wait(this.#getCustody(), signal);
9808
10834
  const combined = combineAbortSignals([
9809
10835
  this.#shutdown.signal,
@@ -9816,7 +10842,7 @@ var init_consumer = __esm({
9816
10842
  ...configured.accountIdentity !== void 0 && {
9817
10843
  accountIdentity: configured.accountIdentity
9818
10844
  }
9819
- }, combined.signal);
10845
+ }, combined.signal, routeId);
9820
10846
  } finally {
9821
10847
  combined.dispose();
9822
10848
  }
@@ -9839,6 +10865,10 @@ var init_consumer = __esm({
9839
10865
  const signal = options.signal;
9840
10866
  let served = await this.authorize(routeId, signal);
9841
10867
  let response = await dispatch(served, signal);
10868
+ if (response.status === 401 && served.fromKeptReceipt) {
10869
+ await this.reportFailure(served, 401, options.reporterSource ?? "direct");
10870
+ return response;
10871
+ }
9842
10872
  if (response.status === 401 && !signal?.aborted) {
9843
10873
  let current;
9844
10874
  try {
@@ -9866,6 +10896,7 @@ var init_consumer = __esm({
9866
10896
  this.#assertOpen();
9867
10897
  await declineVaultRoute(this.#options.rosterPath, routeId);
9868
10898
  this.#roster = await readVaultRoster(this.#options.rosterPath);
10899
+ this.#custody?.retain(this.#roster?.rows ?? []);
9869
10900
  }
9870
10901
  async accept(routeId) {
9871
10902
  this.#assertOpen();
@@ -9921,10 +10952,12 @@ var init_consumer = __esm({
9921
10952
  if (this.#timer)
9922
10953
  (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
9923
10954
  this.#timer = void 0;
10955
+ this.#stopWatch();
9924
10956
  this.#custody?.close();
9925
10957
  this.#insula?.release();
9926
10958
  this.#insula = void 0;
9927
10959
  this.#roster = void 0;
10960
+ this.#grantReach = void 0;
9928
10961
  }
9929
10962
  };
9930
10963
  }
@@ -9934,21 +10967,31 @@ var init_consumer = __esm({
9934
10967
  var claustrum_exports = {};
9935
10968
  __export(claustrum_exports, {
9936
10969
  CUSTODY_PLACEHOLDER_PREFIX: () => CUSTODY_PLACEHOLDER_PREFIX,
10970
+ ChangeNoticeReader: () => ChangeNoticeReader,
9937
10971
  ClaustrumConsumer: () => ClaustrumConsumer,
9938
10972
  ClaustrumConsumerError: () => ClaustrumConsumerError,
9939
- ClaustrumCredentialError: () => ClaustrumCredentialError3,
10973
+ ClaustrumCredentialError: () => ClaustrumCredentialError4,
9940
10974
  ClaustrumEnrollmentManager: () => ClaustrumEnrollmentManager,
9941
10975
  ClaustrumScopedCustody: () => ClaustrumScopedCustody,
10976
+ ClaustrumUnreachableError: () => ClaustrumUnreachableError,
9942
10977
  DEFAULT_ROUTE_PREFIX: () => DEFAULT_ROUTE_PREFIX,
10978
+ KEPT_RECEIPT_MARGIN_MS: () => KEPT_RECEIPT_MARGIN_MS,
10979
+ RESUBSCRIBE_BACKOFF_MS: () => RESUBSCRIBE_BACKOFF_MS,
9943
10980
  RETRYABLE_ENROLLMENT_CODES: () => RETRYABLE_ENROLLMENT_CODES,
10981
+ SAFETY_POLL_MS: () => SAFETY_POLL_MS,
9944
10982
  SERVING_MARGIN_MS: () => SERVING_MARGIN_MS,
10983
+ ScopedRosterWatch: () => ScopedRosterWatch,
9945
10984
  TERMINAL_ENROLLMENT_CODES: () => TERMINAL_ENROLLMENT_CODES,
10985
+ VAULT_FAILURE_CLASSES: () => VAULT_FAILURE_CLASSES,
10986
+ WATCH_RETRY_MS: () => WATCH_RETRY_MS,
9946
10987
  acceptAccount: () => acceptAccount,
9947
10988
  acceptVaultRoute: () => acceptVaultRoute,
10989
+ acquireInsulaQuotaSource: () => acquireInsulaQuotaSource,
9948
10990
  assertHostSlotMatchesMode: () => assertHostSlotMatchesMode,
9949
10991
  assertNotCustodyPlaceholder: () => assertNotCustodyPlaceholder,
9950
10992
  classifyEnrollmentError: () => classifyEnrollmentError,
9951
10993
  classifyHostSlot: () => classifyHostSlot,
10994
+ classifyVaultFailure: () => classifyVaultFailure,
9952
10995
  connectClaustrumEnrollmentClient: () => connectClaustrumEnrollmentClient,
9953
10996
  connectClaustrumScopedClient: () => connectClaustrumScopedClient,
9954
10997
  custodyPlaceholder: () => custodyPlaceholder,
@@ -9978,7 +11021,7 @@ __export(claustrum_exports, {
9978
11021
  vaultRoutingRows: () => vaultRoutingRows
9979
11022
  });
9980
11023
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
9981
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
11024
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
9982
11025
  async function connectClaustrumScopedClient(options) {
9983
11026
  const client = await ClaustrumClient.connect(options);
9984
11027
  return Object.assign(client, { insula: insulaUsageTransport(options) });
@@ -9987,18 +11030,21 @@ var init_claustrum = __esm({
9987
11030
  "../core/dist/common-auth-embedded/claustrum/index.js"() {
9988
11031
  "use strict";
9989
11032
  init_insula();
11033
+ init_availability();
9990
11034
  init_consumer();
9991
11035
  init_custody();
9992
11036
  init_enrollment();
9993
11037
  init_errors2();
9994
11038
  init_host_slot();
11039
+ init_insula();
9995
11040
  init_interlock();
9996
11041
  init_roster();
11042
+ init_watch();
9997
11043
  }
9998
11044
  });
9999
11045
 
10000
11046
  // ../core/dist/common-auth-embedded/pi-slot/lock.js
10001
- import { rmdirSync, statSync as statSync2 } from "node:fs";
11047
+ import { rmdirSync, statSync as statSync2, utimesSync } from "node:fs";
10002
11048
  import { mkdir as mkdir9, rmdir, stat as stat5, utimes } from "node:fs/promises";
10003
11049
  function sameDirectory(observed, identity) {
10004
11050
  return observed.dev === identity.dev && observed.ino === identity.ino;
@@ -10094,7 +11140,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
10094
11140
  return;
10095
11141
  let observed;
10096
11142
  try {
10097
- observed = await stat5(path5);
11143
+ observed = statSync2(path5);
10098
11144
  } catch (error) {
10099
11145
  retry(error);
10100
11146
  return;
@@ -10108,11 +11154,12 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
10108
11154
  }
10109
11155
  const next = new Date(precision === "s" ? Math.ceil(Date.now() / 1e3) * 1e3 : Date.now());
10110
11156
  try {
10111
- await utimes(path5, next, next);
11157
+ utimesSync(path5, next, next);
10112
11158
  } catch (error) {
10113
11159
  retry(error);
10114
11160
  return;
10115
11161
  }
11162
+ assertFresh();
10116
11163
  if (released)
10117
11164
  return;
10118
11165
  mtime = next.getTime();
@@ -11262,7 +12309,7 @@ function legacyOptional(row, key, predicate, path5) {
11262
12309
  throw new AccountMigrationError(`${path5}.${key} has an invalid type`);
11263
12310
  }
11264
12311
  }
11265
- function parseAccount(value, ordinal, version, clock) {
12312
+ function parseAccount(value, ordinal, version, clock2) {
11266
12313
  const path5 = `accounts[${ordinal}]`;
11267
12314
  const source = object(value, path5);
11268
12315
  if (typeof source.refreshToken !== "string" || !source.refreshToken.trim().length) {
@@ -11289,7 +12336,7 @@ function parseAccount(value, ordinal, version, clock) {
11289
12336
  const quota = hasQuota ? decodeQuotaState(quotaRaw) : void 0;
11290
12337
  const normalized = encodeProviderMetadata(originalMetadata);
11291
12338
  if (version === 1) {
11292
- if (source.isRateLimited && finite(source.rateLimitResetTime) && source.rateLimitResetTime > clock) {
12339
+ if (source.isRateLimited && finite(source.rateLimitResetTime) && source.rateLimitResetTime > clock2) {
11293
12340
  if (originalMetadata.rateLimitResetTimes === null)
11294
12341
  throw new AccountMigrationError(`${path5} has conflicting rate-limit encodings`);
11295
12342
  const resets = { ...originalMetadata.rateLimitResetTimes };
@@ -11306,9 +12353,9 @@ function parseAccount(value, ordinal, version, clock) {
11306
12353
  const gemini = resets.gemini;
11307
12354
  delete resets.claude;
11308
12355
  delete resets.gemini;
11309
- if (claude === null || finite(claude) && claude > clock)
12356
+ if (claude === null || finite(claude) && claude > clock2)
11310
12357
  resets.claude = claude;
11311
- if (gemini === null || finite(gemini) && gemini > clock) {
12358
+ if (gemini === null || finite(gemini) && gemini > clock2) {
11312
12359
  if (Object.hasOwn(resets, "gemini-antigravity") && resets["gemini-antigravity"] !== gemini)
11313
12360
  throw new AccountMigrationError(`${path5} has conflicting rate-limit encodings`);
11314
12361
  resets["gemini-antigravity"] = gemini;
@@ -11842,7 +12889,7 @@ async function syncDirectory(path5, boundary) {
11842
12889
  }
11843
12890
  await boundary?.("after-directory-sync");
11844
12891
  }
11845
- async function exclusiveBytes(path5, bytes, expectedHash, boundary) {
12892
+ async function exclusiveBytes(path5, bytes, expectedHash, boundary, pointerStage = false) {
11846
12893
  let handle;
11847
12894
  try {
11848
12895
  handle = await open(path5, "wx", 384);
@@ -11861,7 +12908,8 @@ async function exclusiveBytes(path5, bytes, expectedHash, boundary) {
11861
12908
  const reopened = await secureRead(path5);
11862
12909
  if (digest(reopened) !== expectedHash || !reopened.equals(bytes))
11863
12910
  throw new AccountMigrationError("exclusive backup or recovery copy differs");
11864
- await syncFile(path5);
12911
+ if (handle === void 0 || !pointerStage)
12912
+ await syncFile(path5);
11865
12913
  await syncDirectory(dirname(path5), boundary);
11866
12914
  }
11867
12915
  async function readJournal(paths) {
@@ -12563,7 +13611,7 @@ function createAccountMigrationFactory(modules) {
12563
13611
  throw new AccountMigrationError("source changed before pointer publication");
12564
13612
  if (!journal)
12565
13613
  throw new AccountMigrationError("capture journal missing");
12566
- await publishGenerationPointer(modules, physical, journal, parentLease, prior, options.onBoundary);
13614
+ await publishGenerationPointer(modules, physical, journal, parentLease, lease, prior, options.onBoundary);
12567
13615
  });
12568
13616
  await options.onBoundary?.("after-capture");
12569
13617
  }
@@ -12908,47 +13956,9 @@ async function initializeFreshAccountStore(modules, options) {
12908
13956
  timeoutMs: 2e3,
12909
13957
  renew: true
12910
13958
  }, 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
- }
13959
+ const journal = await readJournal(physical);
13960
+ if (pointer === void 0)
13961
+ return initializePrivateEmptyGeneration(modules, physical, parentLease, lease, options);
12952
13962
  if (journal?.sourceKind !== "absent" || journal.operation !== "migrate" || journal.status === "inactive")
12953
13963
  throw new AccountMigrationError("fresh resume has no compatible pointed generation");
12954
13964
  await assertPublishedAccountStoreGeneration(physical);
@@ -13024,6 +14034,187 @@ async function initializeFreshAccountStore(modules, options) {
13024
14034
  throw error;
13025
14035
  }
13026
14036
  }
14037
+ async function exclusiveUnpublishedBytes(path5, bytes) {
14038
+ const handle = await open(path5, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
14039
+ try {
14040
+ await handle.writeFile(bytes);
14041
+ } finally {
14042
+ await handle.close();
14043
+ }
14044
+ if (!(await secureRead(path5)).equals(bytes))
14045
+ throw new AccountMigrationError("private stage readback differs");
14046
+ }
14047
+ async function initializePrivateEmptyGeneration(modules, paths, parentLease, managementLease, options) {
14048
+ return modules.fs.withLock(paths.legacyPath, { name: "accounts", ttlMs: 1e4, timeoutMs: 2e3, renew: true }, async (accountsLease) => {
14049
+ const directory = await lstat(paths.storeDir);
14050
+ const assertOwned = async () => {
14051
+ await parentLease.assertOwned();
14052
+ await managementLease.assertOwned();
14053
+ await accountsLease.assertOwned();
14054
+ const current = await lstat(paths.storeDir);
14055
+ if (!current.isDirectory() || current.isSymbolicLink() || current.dev !== directory.dev || current.ino !== directory.ino || !sameFilesystemPath(await realpath(paths.storeDir), paths.storeDir))
14056
+ throw new AccountMigrationError("private generation directory changed");
14057
+ privateMode(current.mode, 448);
14058
+ };
14059
+ const boundary = options.onBoundary;
14060
+ await assertOwned();
14061
+ await assertSourceAbsent(paths);
14062
+ if (await readPointer(paths.legacyPath))
14063
+ throw new AccountMigrationError("private initialization found a competing pointer");
14064
+ if (await readJournal(paths) || await exists(paths.configPath) || await exists(paths.statePath))
14065
+ throw new AccountMigrationError("fresh stage has unrelated artifacts");
14066
+ const journal = {
14067
+ schemaVersion: 1,
14068
+ id: pathGenerationId(paths),
14069
+ legacyPath: paths.legacyPath,
14070
+ storeDir: paths.storeDir,
14071
+ sourceKind: "absent",
14072
+ status: "pending",
14073
+ operation: "migrate",
14074
+ phase: "build",
14075
+ manifest: {
14076
+ sourceVersion: null,
14077
+ normalizationClock: options.now(),
14078
+ accounts: [],
14079
+ routing: { schemaVersion: 1 },
14080
+ effectiveActiveIndex: 0
14081
+ },
14082
+ mapping: [],
14083
+ completedRows: []
14084
+ };
14085
+ await assertOwned();
14086
+ await exclusiveUnpublishedBytes(paths.configPath, Buffer.from('{"version":1,"accounts":[]}\n'));
14087
+ await boundary?.("empty-stage:after-seed");
14088
+ const store = openMigrationStore(modules, paths, options.now, async (step, info) => {
14089
+ await assertOwned();
14090
+ if (!step.includes("config") || await exists(paths.statePath))
14091
+ throw new AccountMigrationError("private empty stage attempted a credential write");
14092
+ await secureRead(paths.configPath);
14093
+ await boundary?.(`public:${info.operation}:${step}`);
14094
+ await assertOwned();
14095
+ });
14096
+ await assertOwned();
14097
+ await store.initialize();
14098
+ await boundary?.("empty-stage:after-initialize");
14099
+ await assertOwned();
14100
+ await store.updateSettings((settings) => {
14101
+ settings[ROUTING_SETTINGS_KEY] = encodeRoutingSettings(journal.manifest.routing);
14102
+ settings[ACCOUNT_STORE_GENERATION_SETTINGS_KEY] = generationJson(journal);
14103
+ settings[MANAGEMENT_SETTINGS_KEY] = {
14104
+ id: journal.id,
14105
+ kind: "migration",
14106
+ targets: [],
14107
+ progress: { step: "build", completedTargets: [] }
14108
+ };
14109
+ return settings;
14110
+ });
14111
+ await boundary?.("empty-stage:after-build-settings");
14112
+ await expectedFreshArtifacts(paths, journal);
14113
+ await assertStateOwnership(paths, journal, true);
14114
+ await verifyImported(store, journal);
14115
+ const snapshot2 = await secureRead(paths.configPath);
14116
+ await verifyImported(store, journal);
14117
+ journal.verification = {
14118
+ manifestSha256: digest(canonical2(manifestJson(journal.manifest))),
14119
+ configSha256: digest(snapshot2),
14120
+ statePresent: false,
14121
+ durability: accountMigrationDurability()
14122
+ };
14123
+ await assertOwned();
14124
+ await assertSourceAbsent(paths);
14125
+ journal.sourceAbsenceVerified = true;
14126
+ await management(store, journal, true);
14127
+ await boundary?.("empty-stage:after-clear-settings");
14128
+ await expectedFreshArtifacts(paths, journal);
14129
+ await currentSuccessor(store, paths, journal);
14130
+ if ((await settingsOf(store))[MANAGEMENT_SETTINGS_KEY] !== void 0)
14131
+ throw new AccountMigrationError("private stage still has management work");
14132
+ journal.phase = "activate";
14133
+ journal.status = "active";
14134
+ decodeAccountMigrationJournal(journalJson(journal));
14135
+ await assertOwned();
14136
+ await exclusiveUnpublishedBytes(paths.migrationPath, Buffer.from(`${JSON.stringify(journalJson(journal), null, 2)}
14137
+ `));
14138
+ await boundary?.("empty-stage:after-journal");
14139
+ await syncFile(paths.configPath);
14140
+ await boundary?.("empty-stage:after-config-sync");
14141
+ await syncFile(paths.migrationPath);
14142
+ await boundary?.("empty-stage:after-journal-sync");
14143
+ for (const [name, path6] of [
14144
+ ["backups", paths.backupsDir],
14145
+ ["retired", paths.retiredDir],
14146
+ ["transfers", paths.transfersDir]
14147
+ ]) {
14148
+ await syncDirectory(path6);
14149
+ await boundary?.(`empty-stage:after-${name}-sync`);
14150
+ }
14151
+ await syncDirectory(paths.storeDir);
14152
+ await boundary?.("empty-stage:after-generation-sync");
14153
+ await boundary?.("pointer:before-publication");
14154
+ const reopened = await readJournal(paths);
14155
+ if (!isDeepStrictEqual(reopened, journal))
14156
+ throw new AccountMigrationError("publication requires its complete synced canonical journal");
14157
+ const pointer = {
14158
+ schemaVersion: 1,
14159
+ id: journal.id,
14160
+ directoryBasename: basename(paths.storeDir)
14161
+ };
14162
+ const path5 = accountStorePointerPath(paths.legacyPath);
14163
+ const stage = `${path5}.${journal.id}.tmp`;
14164
+ const bytes = Buffer.from(`${JSON.stringify(pointer, null, 2)}
14165
+ `);
14166
+ await assertOwned();
14167
+ let stageHandle;
14168
+ try {
14169
+ stageHandle = await open(stage, "wx", 384);
14170
+ } catch (error) {
14171
+ if (errno(error) !== "EEXIST")
14172
+ throw error;
14173
+ }
14174
+ if (stageHandle) {
14175
+ try {
14176
+ await stageHandle.writeFile(bytes);
14177
+ await stageHandle.sync();
14178
+ } finally {
14179
+ await stageHandle.close();
14180
+ }
14181
+ }
14182
+ if (!(await secureRead(stage)).equals(bytes))
14183
+ throw new AccountMigrationError("exclusive pointer stage differs");
14184
+ if (!stageHandle)
14185
+ await syncFile(stage);
14186
+ await boundary?.("empty-stage:after-pointer-stage");
14187
+ await syncDirectory(dirname(path5));
14188
+ await boundary?.("empty-stage:after-parent-prelink-sync");
14189
+ await boundary?.("pointer:before-link");
14190
+ await assertOwned();
14191
+ await assertSourceAbsent(paths);
14192
+ if (await exists(path5))
14193
+ throw new AccountMigrationError("foreign or competing pointer publication refuses overwrite");
14194
+ if (await exists(resolveAccountStorePaths(paths.legacyPath).storeDir))
14195
+ throw new AccountMigrationError("foreign logical store directory appeared before publication");
14196
+ try {
14197
+ await link(stage, path5);
14198
+ } catch (error) {
14199
+ if (errno(error) === "EEXIST")
14200
+ throw new AccountMigrationError("foreign or competing pointer publication refuses overwrite");
14201
+ throw new AccountMigrationError("exclusive pointer hard-link publication failed");
14202
+ }
14203
+ await boundary?.("pointer:after-link-before-parent-sync");
14204
+ await syncDirectory(dirname(path5));
14205
+ if (!isDeepStrictEqual(await readPointer(paths.legacyPath), pointer) || !isDeepStrictEqual(await readJournal(paths), journal))
14206
+ throw new AccountMigrationError("pointer publication readback differs");
14207
+ await expectedFreshArtifacts(paths, journal);
14208
+ await currentSuccessor(store, paths, journal);
14209
+ const admission = await readAccountStoreAdmission(paths.legacyPath, modules, options.now, journal.id);
14210
+ if (admission.status !== "active" || !isDeepStrictEqual(admission.receipt, receipt(journal)))
14211
+ throw new AccountMigrationError("published empty generation is not admitted");
14212
+ await boundary?.("pointer:after-sync-before-stage-cleanup");
14213
+ await cleanupPointerStage(paths.legacyPath, pointer, parentLease);
14214
+ await assertOwned();
14215
+ return { status: "completed", receipt: receipt(journal) };
14216
+ });
14217
+ }
13027
14218
  async function allocateGeneration(legacyPath) {
13028
14219
  if (await exists(resolveAccountStorePaths(legacyPath).storeDir))
13029
14220
  throw new AccountMigrationError("foreign logical directory refuses generation allocation");
@@ -13032,13 +14223,16 @@ async function allocateGeneration(legacyPath) {
13032
14223
  await prepareDirectories(paths);
13033
14224
  return paths;
13034
14225
  }
13035
- async function publishGenerationPointer(modules, paths, journal, parentLease, prior, boundary) {
14226
+ async function publishGenerationPointer(modules, paths, journal, parentLease, managementLease, prior, boundary, journalSavedBy) {
13036
14227
  await parentLease.assertOwned();
14228
+ await managementLease.assertOwned();
13037
14229
  const currentJournal = await readJournal(paths);
13038
14230
  if (!currentJournal || currentJournal.id !== journal.id || !isDeepStrictEqual(journalJson(currentJournal), journalJson(journal)))
13039
14231
  throw new AccountMigrationError("publication requires its complete synced canonical journal");
13040
- await syncFile(paths.migrationPath);
13041
- await syncDirectory(paths.storeDir);
14232
+ if (journalSavedBy !== managementLease) {
14233
+ await syncFile(paths.migrationPath);
14234
+ await syncDirectory(paths.storeDir);
14235
+ }
13042
14236
  const pointer = {
13043
14237
  schemaVersion: 1,
13044
14238
  id: journal.id,
@@ -13049,8 +14243,9 @@ async function publishGenerationPointer(modules, paths, journal, parentLease, pr
13049
14243
  const stage = `${path5}.${journal.id}.tmp`;
13050
14244
  const bytes = Buffer.from(`${JSON.stringify(pointer, null, 2)}
13051
14245
  `);
13052
- await exclusiveBytes(stage, bytes, digest(bytes));
14246
+ await exclusiveBytes(stage, bytes, digest(bytes), void 0, true);
13053
14247
  await parentLease.assertOwned();
14248
+ await managementLease.assertOwned();
13054
14249
  await boundary?.("pointer:before-link");
13055
14250
  if (await exists(resolveAccountStorePaths(paths.legacyPath).storeDir))
13056
14251
  throw new AccountMigrationError("foreign logical store directory appeared before publication");
@@ -13082,6 +14277,7 @@ async function publishGenerationPointer(modules, paths, journal, parentLease, pr
13082
14277
  stageName: () => stageName,
13083
14278
  beforeRename: async () => {
13084
14279
  await parentLease.assertOwned();
14280
+ await managementLease.assertOwned();
13085
14281
  if (!isDeepStrictEqual(await readPointer(paths.legacyPath), prior) || (await readJournal(oldPaths))?.status !== "inactive")
13086
14282
  throw new AccountMigrationError("inactive pointer changed before transition");
13087
14283
  await syncFile(`${path5}.${stageName}.tmp`);
@@ -13091,6 +14287,7 @@ async function publishGenerationPointer(modules, paths, journal, parentLease, pr
13091
14287
  await syncDirectory(dirname(path5));
13092
14288
  }
13093
14289
  await parentLease.assertOwned();
14290
+ await managementLease.assertOwned();
13094
14291
  }
13095
14292
  function withParentTopology(modules, legacyPath, body) {
13096
14293
  return modules.fs.withLock(legacyPath, {
@@ -13117,9 +14314,14 @@ async function finishPointerPublication(legacyPath, pointer, lease) {
13117
14314
  const path5 = accountStorePointerPath(legacyPath);
13118
14315
  await syncFile(path5);
13119
14316
  await syncDirectory(dirname(path5));
14317
+ if (await cleanupPointerStage(legacyPath, pointer, lease))
14318
+ await syncDirectory(dirname(path5));
14319
+ }
14320
+ async function cleanupPointerStage(legacyPath, pointer, lease) {
14321
+ const path5 = accountStorePointerPath(legacyPath);
13120
14322
  const stage = `${path5}.${pointer.id}.tmp`;
13121
14323
  if (!await exists(stage))
13122
- return;
14324
+ return false;
13123
14325
  const bytes = await secureRead(stage);
13124
14326
  if (!isDeepStrictEqual(decodeAccountStorePointer(jsonBytes(bytes), legacyPath), pointer))
13125
14327
  throw new AccountMigrationError("pointer stage differs from publication authority");
@@ -13128,7 +14330,7 @@ async function finishPointerPublication(legacyPath, pointer, lease) {
13128
14330
  throw new AccountMigrationError("pointer stage is not the published hard link");
13129
14331
  await lease.assertOwned();
13130
14332
  await unlink(stage);
13131
- await syncDirectory(dirname(path5));
14333
+ return true;
13132
14334
  }
13133
14335
 
13134
14336
  // ../core/dist/account-repository.js
@@ -15756,8 +16958,8 @@ function isRateLimitedForFamily(account, family, now, model) {
15756
16958
  clearExpiredRateLimits(account, now);
15757
16959
  return model != null && isRateLimitedForQuotaKey(account, getQuotaKey(family, model), now) || isRateLimitedForQuotaKey(account, family, now);
15758
16960
  }
15759
- function clearExpiredRateLimits(account, clock) {
15760
- const now = clock();
16961
+ function clearExpiredRateLimits(account, clock2) {
16962
+ const now = clock2();
15761
16963
  const keys = Object.keys(account.rateLimitResetTimes);
15762
16964
  for (const key of keys) {
15763
16965
  const resetTime = account.rateLimitResetTimes[key];
@@ -19767,6 +20969,7 @@ async function fetchWithAgyCliTransport(url, init = {}, options = {}) {
19767
20969
  };
19768
20970
  try {
19769
20971
  options.signal?.addEventListener("abort", abort, { once: true });
20972
+ options.signal?.throwIfAborted();
19770
20973
  socket.write(requestBytes);
19771
20974
  options.onDebug?.(`agy transport request dispatched (${requestBytes.byteLength} bytes)`);
19772
20975
  const { head, leftover } = await waitForHead(socket, timeoutMs, () => {
@@ -20233,7 +21436,15 @@ function projectAntigravityQuota(quota) {
20233
21436
  });
20234
21437
  }
20235
21438
  }
20236
- return { scope: "all", limits, checkedAt };
21439
+ return {
21440
+ scope: "all",
21441
+ limits,
21442
+ checkedAt,
21443
+ groups: [
21444
+ { scope: "gemini", label: "Gemini" },
21445
+ { scope: "non-gemini", label: "Other models" }
21446
+ ]
21447
+ };
20237
21448
  }
20238
21449
  function formatAntigravityQuota(quota, options) {
20239
21450
  return formatQuota(projectAntigravityQuota(quota), options);
@@ -20678,19 +21889,35 @@ var loadCommonAuthPiSlot = memoize(() => Promise.resolve().then(() => (init_pi_s
20678
21889
 
20679
21890
  // ../core/dist/credential-redaction.js
20680
21891
  var MARKER = "[credential]";
20681
- function redactCredentialText(text2, credentials) {
21892
+ function maskSensitiveIdentifier(value) {
21893
+ if (typeof value !== "string" || value.length === 0)
21894
+ return "";
21895
+ if (value.length <= 8)
21896
+ return "****";
21897
+ return `${value.slice(0, 4)}****${value.slice(-4)}`;
21898
+ }
21899
+ function redactProjectIdText(text2, projectIds) {
21900
+ const identifiers = [...new Set(projectIds ?? [])].filter((projectId) => projectId.length > 0).sort((left, right) => right.length - left.length);
21901
+ if (identifiers.length > 0) {
21902
+ const expression = new RegExp(identifiers.map((projectId) => projectId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), "g");
21903
+ text2 = text2.replace(expression, (projectId) => maskSensitiveIdentifier(projectId));
21904
+ }
21905
+ 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)}`);
21906
+ }
21907
+ function redactCredentialText(text2, credentials, projectIds) {
21908
+ text2 = redactProjectIdText(text2, projectIds);
20682
21909
  for (const credential of typeof credentials === "string" ? [credentials] : credentials ?? []) {
20683
21910
  if (credential)
20684
21911
  text2 = text2.split(credential).join(MARKER);
20685
21912
  }
20686
21913
  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
21914
  }
20688
- function scrub2(value, credentials, seen = /* @__PURE__ */ new WeakSet()) {
21915
+ function scrub2(value, credentials, projectIds, seen = /* @__PURE__ */ new WeakSet()) {
20689
21916
  if (typeof value === "string")
20690
- return redactCredentialText(value, credentials);
21917
+ return redactCredentialText(value, credentials, projectIds);
20691
21918
  if (!value || typeof value !== "object")
20692
21919
  return value;
20693
- if (!containsCredential(value, credentials))
21920
+ if (!containsCredential(value, credentials, projectIds))
20694
21921
  return value;
20695
21922
  if (seen.has(value))
20696
21923
  return "[Circular]";
@@ -20698,32 +21925,35 @@ function scrub2(value, credentials, seen = /* @__PURE__ */ new WeakSet()) {
20698
21925
  const safe = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
20699
21926
  for (const key of Reflect.ownKeys(value)) {
20700
21927
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
20701
- if (key === "cause" && (!("value" in descriptor) || containsCredential(descriptor.value, credentials)))
21928
+ if (key === "cause" && (!("value" in descriptor) || containsCredential(descriptor.value, credentials, projectIds)))
20702
21929
  continue;
20703
- Object.defineProperty(safe, key, "value" in descriptor ? { ...descriptor, value: scrub2(descriptor.value, credentials, seen) } : descriptor);
21930
+ Object.defineProperty(safe, key, "value" in descriptor ? {
21931
+ ...descriptor,
21932
+ value: scrub2(descriptor.value, credentials, projectIds, seen)
21933
+ } : descriptor);
20704
21934
  }
20705
21935
  return safe;
20706
21936
  }
20707
- function containsCredential(value, credentials, seen = /* @__PURE__ */ new WeakSet()) {
21937
+ function containsCredential(value, credentials, projectIds, seen = /* @__PURE__ */ new WeakSet()) {
20708
21938
  if (typeof value === "string")
20709
- return redactCredentialText(value, credentials) !== value;
21939
+ return redactCredentialText(value, credentials, projectIds) !== value;
20710
21940
  if (!value || typeof value !== "object" || seen.has(value))
20711
21941
  return false;
20712
21942
  seen.add(value);
20713
21943
  return Reflect.ownKeys(value).some((key) => {
20714
21944
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
20715
- return "value" in descriptor && containsCredential(descriptor.value, credentials, seen);
21945
+ return "value" in descriptor && containsCredential(descriptor.value, credentials, projectIds, seen);
20716
21946
  });
20717
21947
  }
20718
- function redactCredentialError(error, credentials) {
21948
+ function redactCredentialError(error, credentials, projectIds) {
20719
21949
  const source = error instanceof Error || error instanceof DOMException ? error : void 0;
20720
- const message = redactCredentialText(source?.message ?? String(error), credentials);
21950
+ const message = redactCredentialText(source?.message ?? String(error), credentials, projectIds);
20721
21951
  const fields = source ? Reflect.ownKeys(source).map((key) => ({
20722
21952
  key,
20723
21953
  descriptor: Object.getOwnPropertyDescriptor(source, key)
20724
21954
  })) : [];
20725
21955
  const cause = fields.find(({ key }) => key === "cause")?.descriptor;
20726
- const secretCause = cause && (!("value" in cause) || containsCredential(cause.value, credentials));
21956
+ const secretCause = cause && (!("value" in cause) || containsCredential(cause.value, credentials, projectIds));
20727
21957
  try {
20728
21958
  if (source) {
20729
21959
  if (message !== source.message)
@@ -20735,7 +21965,7 @@ function redactCredentialError(error, credentials) {
20735
21965
  for (const { key, descriptor } of fields) {
20736
21966
  if (key === "message" || key === "cause" || !("value" in descriptor))
20737
21967
  continue;
20738
- const value = scrub2(descriptor.value, credentials);
21968
+ const value = scrub2(descriptor.value, credentials, projectIds);
20739
21969
  if (value !== descriptor.value)
20740
21970
  Object.defineProperty(source, key, { ...descriptor, value });
20741
21971
  }
@@ -20746,7 +21976,7 @@ function redactCredentialError(error, credentials) {
20746
21976
  } catch {
20747
21977
  }
20748
21978
  const safe = new Error(message);
20749
- safe.name = redactCredentialText(source?.name ?? "Error", credentials);
21979
+ safe.name = redactCredentialText(source?.name ?? "Error", credentials, projectIds);
20750
21980
  for (const { key, descriptor } of fields) {
20751
21981
  if (key === "message" || key === "cause" || !("value" in descriptor))
20752
21982
  continue;
@@ -20754,32 +21984,32 @@ function redactCredentialError(error, credentials) {
20754
21984
  ...descriptor,
20755
21985
  configurable: true,
20756
21986
  writable: true,
20757
- value: scrub2(descriptor.value, credentials)
21987
+ value: scrub2(descriptor.value, credentials, projectIds)
20758
21988
  });
20759
21989
  }
20760
21990
  if (cause && !secretCause && "value" in cause)
20761
21991
  safe.cause = cause.value;
20762
21992
  return safe;
20763
21993
  }
20764
- function redactDiagnosticText(text2, credentials, parsed) {
20765
- const direct = redactCredentialText(text2, credentials);
21994
+ function redactDiagnosticText(text2, credentials, projectIds, parsed) {
21995
+ const direct = redactCredentialText(text2, credentials, projectIds);
20766
21996
  if (direct !== text2 || !text2.includes("\\u"))
20767
21997
  return direct;
20768
21998
  try {
20769
21999
  const canonical4 = JSON.stringify(parsed ?? JSON.parse(text2));
20770
- const safe = redactCredentialText(canonical4, credentials);
22000
+ const safe = redactCredentialText(canonical4, credentials, projectIds);
20771
22001
  return safe === canonical4 ? text2 : safe;
20772
22002
  } catch {
20773
22003
  return text2;
20774
22004
  }
20775
22005
  }
20776
- function redactCredentialFrame(frame, credentials) {
22006
+ function redactCredentialFrame(frame, credentials, projectIds) {
20777
22007
  if (!frame.includes('"error"') && !frame.includes("\\u"))
20778
22008
  return frame;
20779
22009
  try {
20780
22010
  const value = JSON.parse(frame);
20781
22011
  if (value?.type === "error" || value?.error || value?.response?.error) {
20782
- return redactDiagnosticText(frame, credentials, value);
22012
+ return redactDiagnosticText(frame, credentials, projectIds, value);
20783
22013
  }
20784
22014
  } catch {
20785
22015
  }
@@ -20794,26 +22024,26 @@ function preserveResponseMetadata2(response, original) {
20794
22024
  }
20795
22025
  return response;
20796
22026
  }
20797
- async function redactCredentialResponse(response, credentials, bufferedBody) {
22027
+ async function redactCredentialResponse(response, credentials, bufferedBody, projectIds) {
20798
22028
  const init = {
20799
22029
  status: response.status,
20800
22030
  statusText: response.statusText,
20801
22031
  headers: new Headers(response.headers)
20802
22032
  };
20803
22033
  if (!response.ok) {
20804
- init.statusText = redactCredentialText(init.statusText, credentials);
22034
+ init.statusText = redactCredentialText(init.statusText, credentials, projectIds);
20805
22035
  let metadataChanged = init.statusText !== response.statusText;
20806
22036
  for (const [key, value] of init.headers) {
20807
- const safe = redactCredentialText(value, credentials);
22037
+ const safe = redactCredentialText(value, credentials, projectIds);
20808
22038
  if (safe !== value) {
20809
22039
  init.headers.set(key, safe);
20810
22040
  metadataChanged = true;
20811
22041
  }
20812
22042
  }
20813
22043
  const text2 = bufferedBody ?? (response.body ? await response.text().catch((error) => {
20814
- throw redactCredentialError(error, credentials);
22044
+ throw redactCredentialError(error, credentials, projectIds);
20815
22045
  }) : null);
20816
- const redacted = text2 === null ? null : redactDiagnosticText(text2, credentials);
22046
+ const redacted = text2 === null ? null : redactDiagnosticText(text2, credentials, projectIds);
20817
22047
  if ((bufferedBody !== void 0 || !response.body) && redacted === text2 && !metadataChanged)
20818
22048
  return response;
20819
22049
  if (response.body)
@@ -20827,7 +22057,7 @@ async function redactCredentialResponse(response, credentials, bufferedBody) {
20827
22057
  const decoder = new TextDecoder();
20828
22058
  const encoder = new TextEncoder();
20829
22059
  let pending = "";
20830
- const redact3 = (event) => event.replace(/^data: ?([^\r\n]*)/gm, (line, data) => line.slice(0, line.length - data.length) + redactCredentialFrame(data, credentials));
22060
+ const redact3 = (event) => event.replace(/^data: ?([^\r\n]*)/gm, (line, data) => line.slice(0, line.length - data.length) + redactCredentialFrame(data, credentials, projectIds));
20831
22061
  const body = new ReadableStream({
20832
22062
  async pull(controller) {
20833
22063
  try {
@@ -20856,14 +22086,14 @@ async function redactCredentialResponse(response, credentials, bufferedBody) {
20856
22086
  }
20857
22087
  } catch (error) {
20858
22088
  reader.releaseLock();
20859
- controller.error(redactCredentialError(error, credentials));
22089
+ controller.error(redactCredentialError(error, credentials, projectIds));
20860
22090
  }
20861
22091
  },
20862
22092
  async cancel(reason) {
20863
22093
  try {
20864
22094
  await reader.cancel(reason);
20865
22095
  } catch (error) {
20866
- throw redactCredentialError(error, credentials);
22096
+ throw redactCredentialError(error, credentials, projectIds);
20867
22097
  } finally {
20868
22098
  reader.releaseLock();
20869
22099
  }
@@ -20885,6 +22115,155 @@ function getPiAntigravityVaultDir() {
20885
22115
  return join6(dirname11(getPiAntigravityAuthFile()), "antigravity-auth-vault");
20886
22116
  }
20887
22117
 
22118
+ // ../core/dist/pre-response-deadline.js
22119
+ var PRE_RESPONSE_DEADLINE_MS = 6e5;
22120
+ var PRE_RESPONSE_TIMEOUT_MESSAGE = "Antigravity did not begin a response within the pre-response time limit. Check your connection and try again later.";
22121
+ var PreResponseTimeoutError = class extends Error {
22122
+ code = 412;
22123
+ status = "FAILED_PRECONDITION";
22124
+ reason = "PRE_RESPONSE_TIMEOUT";
22125
+ constructor() {
22126
+ super(PRE_RESPONSE_TIMEOUT_MESSAGE);
22127
+ this.name = "PreResponseTimeoutError";
22128
+ }
22129
+ };
22130
+ function preResponseTimeoutResponse() {
22131
+ return new Response(JSON.stringify({
22132
+ error: {
22133
+ code: 412,
22134
+ status: "FAILED_PRECONDITION",
22135
+ message: PRE_RESPONSE_TIMEOUT_MESSAGE
22136
+ }
22137
+ }), { status: 412, headers: { "Content-Type": "application/json" } });
22138
+ }
22139
+ var clock = {
22140
+ now: () => performance.now(),
22141
+ schedule(callback, delayMs) {
22142
+ const timer = setTimeout(callback, delayMs);
22143
+ timer.unref?.();
22144
+ return () => clearTimeout(timer);
22145
+ }
22146
+ };
22147
+ var PreResponseDeadline = class {
22148
+ caller;
22149
+ time;
22150
+ signal;
22151
+ controller = new AbortController();
22152
+ expiresAt;
22153
+ active = true;
22154
+ cancelTimer;
22155
+ detachCaller;
22156
+ detachSignals = [];
22157
+ constructor(caller, time = clock) {
22158
+ this.caller = caller;
22159
+ this.time = time;
22160
+ this.expiresAt = time.now() + PRE_RESPONSE_DEADLINE_MS;
22161
+ this.signal = this.controller.signal;
22162
+ const abort = () => {
22163
+ this.cancelTimer?.();
22164
+ this.controller.abort(caller?.reason);
22165
+ };
22166
+ this.detachCaller = () => caller?.removeEventListener("abort", abort);
22167
+ if (caller?.aborted)
22168
+ abort();
22169
+ else
22170
+ caller?.addEventListener("abort", abort, { once: true });
22171
+ this.arm();
22172
+ }
22173
+ remainingMs() {
22174
+ return Math.max(0, this.expiresAt - this.time.now());
22175
+ }
22176
+ follow(signal) {
22177
+ if (!signal || signal === this.signal)
22178
+ return;
22179
+ const abort = () => this.controller.abort(signal.reason);
22180
+ if (signal.aborted)
22181
+ abort();
22182
+ else
22183
+ signal.addEventListener("abort", abort, { once: true });
22184
+ this.detachSignals.push(() => signal.removeEventListener("abort", abort));
22185
+ this.check();
22186
+ }
22187
+ arm() {
22188
+ if (this.signal.aborted)
22189
+ return;
22190
+ this.cancelTimer = this.time.schedule(() => {
22191
+ if (this.remainingMs() > 0)
22192
+ this.arm();
22193
+ else
22194
+ this.expire();
22195
+ }, this.remainingMs());
22196
+ }
22197
+ expire() {
22198
+ this.cancelTimer?.();
22199
+ this.controller.abort(new PreResponseTimeoutError());
22200
+ }
22201
+ check() {
22202
+ this.caller?.throwIfAborted();
22203
+ if (this.active && this.remainingMs() <= 0 && !this.signal.aborted)
22204
+ this.expire();
22205
+ this.signal.throwIfAborted();
22206
+ }
22207
+ acceptHeaders() {
22208
+ this.check();
22209
+ this.acceptTerminalResponse();
22210
+ }
22211
+ acceptTerminalResponse() {
22212
+ this.active = false;
22213
+ this.cancelTimer?.();
22214
+ this.cancelTimer = void 0;
22215
+ }
22216
+ resume() {
22217
+ this.active = true;
22218
+ this.check();
22219
+ this.arm();
22220
+ }
22221
+ /** Cancel a response that arrives after its sender lost the abort race. */
22222
+ open(work) {
22223
+ return this.wait(() => {
22224
+ const pending = work();
22225
+ void pending.then((response) => {
22226
+ if (this.signal.aborted)
22227
+ void response.body?.cancel().catch(() => {
22228
+ });
22229
+ }, () => {
22230
+ });
22231
+ return pending;
22232
+ });
22233
+ }
22234
+ /** Interrupt even prerequisites that cannot themselves accept an AbortSignal. */
22235
+ async wait(work) {
22236
+ this.check();
22237
+ let abort = () => {
22238
+ };
22239
+ const cancelled = new Promise((_, reject) => {
22240
+ abort = () => reject(this.caller?.aborted ? this.caller.reason : this.signal.reason);
22241
+ this.signal.addEventListener("abort", abort, { once: true });
22242
+ });
22243
+ try {
22244
+ const result = await Promise.race([
22245
+ Promise.resolve().then(() => {
22246
+ this.check();
22247
+ return work();
22248
+ }),
22249
+ cancelled
22250
+ ]);
22251
+ this.check();
22252
+ return result;
22253
+ } finally {
22254
+ this.signal.removeEventListener("abort", abort);
22255
+ }
22256
+ }
22257
+ dispose() {
22258
+ this.cancelTimer?.();
22259
+ this.cancelTimer = void 0;
22260
+ this.detachCaller();
22261
+ for (const detach of this.detachSignals)
22262
+ detach();
22263
+ this.detachSignals.length = 0;
22264
+ }
22265
+ };
22266
+
20888
22267
  // ../core/dist/project.js
20889
22268
  var log3 = createLogger("project");
20890
22269
  var PROJECT_CONTEXT_CACHE_TTL_MS = 30 * 60 * 1e3;
@@ -22614,6 +23993,17 @@ function getAntigravityVaultEnrollmentName(host) {
22614
23993
  }
22615
23994
  }
22616
23995
 
23996
+ // ../core/dist/vault-grant-reach.js
23997
+ function emptyVaultRosterCause(reach) {
23998
+ if (reach === void 0)
23999
+ return "unknown";
24000
+ if (reach.grants === 0)
24001
+ return "no-grant";
24002
+ return "grant-reaches-nothing";
24003
+ }
24004
+ var VAULT_RECLASSIFY_COMMAND = "ck auth reclassify --from-registry";
24005
+ var VAULT_STATUS_COMMAND = "ck auth status";
24006
+
22617
24007
  // ../core/dist/vault-provider-state.js
22618
24008
  import { readFile as readFile7 } from "node:fs/promises";
22619
24009
  var VAULT_PROVIDER_STATE_SCHEMA_VERSION = 1;
@@ -22988,7 +24378,8 @@ function admissionFromReceipt(ref, receipt2) {
22988
24378
  accountIdentity: receipt2.assertedAccountIdentity,
22989
24379
  recordVersion: receipt2.recordVersion,
22990
24380
  projectId: receipt2.projectId,
22991
- expiresAtMs: receipt2.expiresAtMs
24381
+ expiresAtMs: receipt2.expiresAtMs,
24382
+ fromKeptReceipt: receipt2.fromKeptReceipt
22992
24383
  };
22993
24384
  Object.defineProperty(admission, "accessToken", {
22994
24385
  value: receipt2.accessToken,
@@ -23061,7 +24452,7 @@ function createAntigravityVaultAccountSource(options) {
23061
24452
  assertOpen();
23062
24453
  entry.reported = true;
23063
24454
  await consumer.reportFailure(entry.receipt, 401, reporterSource ?? options.reporterSource);
23064
- return true;
24455
+ return entry.receipt.fromKeptReceipt !== true;
23065
24456
  };
23066
24457
  const verifyAttribution = async (attribution, signal) => {
23067
24458
  await assertServing(signal);
@@ -23090,10 +24481,15 @@ function createAntigravityVaultAccountSource(options) {
23090
24481
  },
23091
24482
  routes: () => closed ? [] : routeRefs(consumer.snapshot(), isDeclined2),
23092
24483
  admit: admit2,
24484
+ retryAfter401: (served, current, site) => claustrum.decideScopedRetryAfter401(site, issuedEntry(served).receipt, current && issuedEntry(current).receipt, options.logger),
23093
24485
  send: async (ref, dispatch, sendOptions) => {
23094
24486
  const signal = sendOptions.signal;
23095
24487
  let admission = await admit2(ref, signal);
23096
24488
  let response = await dispatch(admission, signal);
24489
+ if (response.status === 401 && admission.fromKeptReceipt) {
24490
+ await reportServedStatus(admission, 401, sendOptions.reporterSource);
24491
+ return response;
24492
+ }
23097
24493
  if (response.status === 401 && !signal?.aborted) {
23098
24494
  let current;
23099
24495
  try {
@@ -23147,6 +24543,8 @@ function createAntigravityVaultAccountSource(options) {
23147
24543
  assertOpen();
23148
24544
  await consumer.accept(ref.routeId);
23149
24545
  },
24546
+ grantReach: () => closed ? void 0 : consumer.grantReach(),
24547
+ emptyRosterCause: () => closed || consumer.snapshot()?.rows.length !== 0 ? "unknown" : emptyVaultRosterCause(consumer.grantReach()),
23150
24548
  close: () => {
23151
24549
  if (closed)
23152
24550
  return;
@@ -23671,19 +25069,24 @@ async function replaceWindowsFile2(from, to, options = {}) {
23671
25069
  to = resolve7(to);
23672
25070
  const now = options.now ?? (() => performance.now());
23673
25071
  const start = now();
23674
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
25072
+ const leaseDeadline = options.deadline ?? Infinity;
25073
+ let retryDeadline;
23675
25074
  const delays = [0, 10, 20, 40, 80, 100];
23676
25075
  let original;
23677
25076
  let attempts2 = 0;
23678
25077
  for (const delay3 of delays) {
25078
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
23679
25079
  if (now() >= deadline)
23680
25080
  break;
23681
25081
  if (delay3)
23682
25082
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
23683
25083
  if (now() >= deadline)
23684
25084
  break;
25085
+ const fenceStart = now();
23685
25086
  await options.beforeRename?.();
23686
- if (now() >= deadline)
25087
+ if (retryDeadline !== void 0)
25088
+ retryDeadline += now() - fenceStart;
25089
+ if (now() >= leaseDeadline)
23687
25090
  break;
23688
25091
  attempts2++;
23689
25092
  try {
@@ -23695,6 +25098,7 @@ async function replaceWindowsFile2(from, to, options = {}) {
23695
25098
  const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
23696
25099
  if (!candidate)
23697
25100
  break;
25101
+ retryDeadline ??= now() + 500;
23698
25102
  }
23699
25103
  }
23700
25104
  const error = new PrivateFileError2(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
@@ -24245,9 +25649,7 @@ function writeConsoleLog2(level, ...args) {
24245
25649
  }
24246
25650
  }
24247
25651
  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)}`;
25652
+ return maskSensitiveIdentifier(value);
24251
25653
  }
24252
25654
  var SENSITIVE_FIELD_PATTERN = /token|refresh|access|project|fingerprint|deviceId|sessionId|sessionToken|secret|password|apiKey|clientSecret/i;
24253
25655
  function redactSensitiveFields(value) {
@@ -26331,7 +27733,8 @@ var AntigravityConfigSchema = z.object({
26331
27733
  // Rate Limiting
26332
27734
  // =========================================================================
26333
27735
  /**
26334
- * Maximum time in seconds to wait when all accounts are rate-limited.
27736
+ * Cumulative wait budget in seconds while no account is eligible, shared by
27737
+ * rate-limit and soft-quota waits. Selecting an eligible account resets it.
26335
27738
  * If the minimum wait time across all accounts exceeds this threshold,
26336
27739
  * the plugin fails fast with an error instead of hanging.
26337
27740
  *
@@ -29917,9 +31320,7 @@ function hashText2(value) {
29917
31320
  return createHash12("sha256").update(value).digest("hex");
29918
31321
  }
29919
31322
  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)}`;
31323
+ return maskSensitiveIdentifier(value) || void 0;
29923
31324
  }
29924
31325
  function redactProjectId(value) {
29925
31326
  return maskIdentifier(value);
@@ -33037,7 +34438,6 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
33037
34438
  let resolvedProjectId = projectId?.trim() || "";
33038
34439
  let toolDebugMissing = 0;
33039
34440
  const toolDebugSummaries = [];
33040
- let toolDebugPayload;
33041
34441
  let sessionId;
33042
34442
  let needsSignedThinkingWarmup = false;
33043
34443
  let thinkingRecoveryMessage;
@@ -33465,11 +34865,6 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
33465
34865
  toolDebugMissing = geminiResult.toolDebugMissing;
33466
34866
  toolDebugSummaries.push(...geminiResult.toolDebugSummaries);
33467
34867
  }
33468
- try {
33469
- toolDebugPayload = JSON.stringify(requestPayload.tools);
33470
- } catch {
33471
- toolDebugPayload = void 0;
33472
- }
33473
34868
  const enableToolHardening = options?.claudeToolHardening ?? true;
33474
34869
  if (enableToolHardening && isClaude && Array.isArray(requestPayload.tools) && requestPayload.tools.length > 0) {
33475
34870
  requestPayload.tools = injectParameterSignatures(
@@ -33707,7 +35102,6 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
33707
35102
  sessionId,
33708
35103
  toolDebugMissing,
33709
35104
  toolDebugSummary: toolDebugSummaries.slice(0, 20).join(" | "),
33710
- toolDebugPayload,
33711
35105
  needsSignedThinkingWarmup,
33712
35106
  headerStyle: "antigravity",
33713
35107
  thinkingRecoveryMessage
@@ -33775,7 +35169,7 @@ function buildThinkingWarmupBody(bodyText, isClaudeThinking) {
33775
35169
  }
33776
35170
  return safeStringify(parsed);
33777
35171
  }
33778
- async function transformAntigravityResponseIn(wire, response, streaming, debugContext, requestedModel, projectId, endpoint, effectiveModel, sessionId, toolDebugMissing, toolDebugSummary, toolDebugPayload, debugLines, dumpContext) {
35172
+ async function transformAntigravityResponseIn(wire, response, streaming, debugContext, requestedModel, projectId, endpoint, effectiveModel, sessionId, toolDebugMissing, toolDebugSummary, debugLines, dumpContext) {
33779
35173
  const contentType = response.headers.get("content-type") ?? "";
33780
35174
  const isJsonResponse = contentType.includes("application/json");
33781
35175
  const isEventStreamResponse = contentType.includes("text/event-stream");
@@ -33848,20 +35242,23 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
33848
35242
  errorBody = { error: { message: text2 } };
33849
35243
  }
33850
35244
  if (errorBody?.error) {
33851
- const rawErrorMessage = typeof errorBody.error.message === "string" && errorBody.error.message.length > 0 ? errorBody.error.message : "Unknown error";
35245
+ const upstreamErrorMessage = typeof errorBody.error.message === "string" && errorBody.error.message.length > 0 ? errorBody.error.message : "Unknown error";
35246
+ const rawErrorMessage = redactProjectIdText(upstreamErrorMessage, [
35247
+ projectId ?? ""
35248
+ ]);
33852
35249
  const errorType = detectErrorType(rawErrorMessage);
35250
+ const safeProjectId = maskSensitiveIdentifier(projectId) || "Unknown";
33853
35251
  const debugInfo = `
33854
35252
 
33855
35253
  [Debug Info]
33856
35254
  Requested Model: ${requestedModel || "Unknown"}
33857
35255
  Effective Model: ${effectiveModel || "Unknown"}
33858
- Project: ${projectId || "Unknown"}
35256
+ Project: ${safeProjectId}
33859
35257
  Endpoint: ${endpoint || "Unknown"}
33860
35258
  Status: ${response.status}
33861
35259
  Request ID: ${headers.get("x-request-id") || "N/A"}${toolDebugMissing !== void 0 ? `
33862
35260
  Tool Debug Missing: ${toolDebugMissing}` : ""}${toolDebugSummary ? `
33863
- Tool Debug Summary: ${toolDebugSummary}` : ""}${toolDebugPayload ? `
33864
- Tool Debug Payload: ${toolDebugPayload}` : ""}`;
35261
+ Tool Debug Summary: ${toolDebugSummary}` : ""}`;
33865
35262
  const injectedDebug = debugText ? `
33866
35263
 
33867
35264
  ${debugText}` : "";
@@ -34978,6 +36375,80 @@ async function retainResponseLifetime(response, cancellation) {
34978
36375
  }
34979
36376
  }
34980
36377
 
36378
+ // src/plugin/shared/after-handoff.ts
36379
+ function createAfterHandoff(work, signals, onFailure) {
36380
+ const controller = new AbortController();
36381
+ const cancellation = createRequestCancellation([
36382
+ ...signals,
36383
+ controller.signal
36384
+ ]);
36385
+ let run;
36386
+ let acknowledged = false;
36387
+ let finished = false;
36388
+ let running = false;
36389
+ let resolveCompletion = () => {
36390
+ };
36391
+ const completion = new Promise((resolve18) => {
36392
+ resolveCompletion = resolve18;
36393
+ });
36394
+ const finish = () => {
36395
+ if (finished) return;
36396
+ finished = true;
36397
+ run = void 0;
36398
+ cancellation.signal.removeEventListener("abort", onAbort);
36399
+ cancellation.release();
36400
+ work.delete(completion);
36401
+ resolveCompletion();
36402
+ };
36403
+ const onAbort = () => {
36404
+ if (!running) finish();
36405
+ };
36406
+ cancellation.signal.addEventListener("abort", onAbort, { once: true });
36407
+ if (cancellation.signal.aborted) onAbort();
36408
+ return {
36409
+ register(callback) {
36410
+ if (finished || run) return;
36411
+ run = callback;
36412
+ work.add(completion);
36413
+ },
36414
+ acknowledge() {
36415
+ if (finished || acknowledged || !run) return;
36416
+ acknowledged = true;
36417
+ void Promise.resolve().then(async () => {
36418
+ if (finished || cancellation.signal.aborted) return;
36419
+ running = true;
36420
+ try {
36421
+ await run?.(cancellation.signal);
36422
+ } catch {
36423
+ try {
36424
+ onFailure();
36425
+ } catch {
36426
+ }
36427
+ } finally {
36428
+ finish();
36429
+ }
36430
+ });
36431
+ },
36432
+ cancel() {
36433
+ controller.abort();
36434
+ onAbort();
36435
+ }
36436
+ };
36437
+ }
36438
+ function publishResponse(dispatch) {
36439
+ return new Promise((resolve18, reject) => {
36440
+ let acknowledge;
36441
+ void Promise.resolve().then(
36442
+ () => dispatch((callback) => {
36443
+ acknowledge = callback;
36444
+ })
36445
+ ).then((response) => {
36446
+ resolve18(response);
36447
+ acknowledge?.();
36448
+ }, reject);
36449
+ });
36450
+ }
36451
+
34981
36452
  // src/plugin/shared/request-services.ts
34982
36453
  var FIRST_RETRY_DELAY_MS = 1e3;
34983
36454
  function prepareAgyWireRequest(wire, request) {
@@ -35177,12 +36648,11 @@ function createRequestExecutor(deps) {
35177
36648
  log16.debug("routing-report-failed", { sessionId, error: String(error) });
35178
36649
  }
35179
36650
  };
35180
- async function execute(input2, init, options = {}, selectedCredentials = /* @__PURE__ */ new Set()) {
36651
+ async function execute(input2, init, options, selectedCredentials, selectedProjectIds, deadline, waitPolicy) {
35181
36652
  const assertAdmission = async () => {
35182
- init?.signal?.throwIfAborted();
35183
- await deps.assertAdmission?.();
35184
- init?.signal?.throwIfAborted();
36653
+ await deadline.wait(() => deps.assertAdmission?.());
35185
36654
  };
36655
+ const logResponseBody2 = (...args) => deadline.wait(() => debug.logResponseBody(...args));
35186
36656
  await assertAdmission();
35187
36657
  if (typeof input2 !== "string") {
35188
36658
  if (input2 instanceof Request) {
@@ -35193,7 +36663,7 @@ function createRequestExecutor(deps) {
35193
36663
  headers.set(k, v);
35194
36664
  });
35195
36665
  }
35196
- const bodyBuffer = req.body ? await req.clone().arrayBuffer() : void 0;
36666
+ const bodyBuffer = req.body ? await deadline.wait(() => req.clone().arrayBuffer()) : void 0;
35197
36667
  init = {
35198
36668
  method: init?.method ?? req.method,
35199
36669
  headers,
@@ -35245,7 +36715,10 @@ function createRequestExecutor(deps) {
35245
36715
  thinkingBudget: registered.thinkingConfig?.thinkingBudget
35246
36716
  };
35247
36717
  }
35248
- const transport = options.transport ?? defaultTransport2;
36718
+ const sender = options.transport ?? defaultTransport2;
36719
+ const transport = (url, sendInit, sendOptions) => deadline.open(
36720
+ () => sender(url, sendInit, { ...sendOptions, signal: deadline.signal })
36721
+ );
35249
36722
  const requestSessionIdentity = options.session ?? extractOpenCodeSessionIdentity(init?.headers);
35250
36723
  const agyRequestScope = agySessionRegistry.beginRequest(
35251
36724
  agyMetadataIdentity(requestSessionIdentity, kind)
@@ -35260,7 +36733,7 @@ function createRequestExecutor(deps) {
35260
36733
  const urlString2 = typeof input2 === "string" ? input2 : toUrlString(input2);
35261
36734
  const modelFromUrl = extractModelFromUrl(urlString2) ?? "unknown";
35262
36735
  return createNoAccountResponse(
35263
- credentials.domain === "vault" ? VAULT_ACCOUNT_REMEDY : "No Antigravity accounts configured. Run `opencode auth login`.",
36736
+ credentials.domain === "vault" ? credentials.emptyRosterRefusal?.() ?? VAULT_ACCOUNT_REMEDY : "No Antigravity accounts configured. Run `opencode auth login`.",
35264
36737
  modelFromUrl
35265
36738
  );
35266
36739
  }
@@ -35270,7 +36743,13 @@ function createRequestExecutor(deps) {
35270
36743
  const debugLines = [];
35271
36744
  const pushDebug = (line) => {
35272
36745
  if (!debug.isDebugEnabled()) return;
35273
- debugLines.push(redactCredentialText(line, [...selectedCredentials]));
36746
+ debugLines.push(
36747
+ redactCredentialText(
36748
+ line,
36749
+ [...selectedCredentials],
36750
+ [...selectedProjectIds]
36751
+ )
36752
+ );
35274
36753
  };
35275
36754
  pushDebug(`request=${urlString}`);
35276
36755
  if (requestSessionIdentity.sessionId) {
@@ -35289,6 +36768,7 @@ function createRequestExecutor(deps) {
35289
36768
  let lastError = null;
35290
36769
  const abortSignal = init?.signal ?? void 0;
35291
36770
  const checkAborted = () => {
36771
+ deadline.check();
35292
36772
  if (abortSignal?.aborted) {
35293
36773
  throw abortSignal.reason instanceof Error ? abortSignal.reason : new Error("Aborted");
35294
36774
  }
@@ -35318,8 +36798,9 @@ function createRequestExecutor(deps) {
35318
36798
  }
35319
36799
  }
35320
36800
  try {
35321
- await notify?.(message, variant2);
36801
+ await deadline.wait(() => notify?.(message, variant2));
35322
36802
  } catch {
36803
+ checkAborted();
35323
36804
  }
35324
36805
  };
35325
36806
  let accountSwitchCount = 0;
@@ -35327,6 +36808,8 @@ function createRequestExecutor(deps) {
35327
36808
  let previousAccountIndex = -1;
35328
36809
  let needsCacheWarmup = false;
35329
36810
  let localRecaptureUsed = false;
36811
+ const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1e3;
36812
+ let allAccountsBlockedAt;
35330
36813
  while (true) {
35331
36814
  await assertAdmission();
35332
36815
  checkAborted();
@@ -35407,6 +36890,10 @@ function createRequestExecutor(deps) {
35407
36890
  account = null;
35408
36891
  }
35409
36892
  if (!account) {
36893
+ allAccountsBlockedAt ??= Date.now();
36894
+ const blockedSince = allAccountsBlockedAt;
36895
+ const remainingWaitMs = () => maxWaitMs > 0 ? Math.max(0, maxWaitMs - (Date.now() - blockedSince)) : Number.POSITIVE_INFINITY;
36896
+ const quotaWins = remainingWaitMs() <= deadline.remainingMs();
35410
36897
  if (accountManager.areAllAccountsOverSoftQuota(
35411
36898
  family,
35412
36899
  config.soft_quota_threshold_percent,
@@ -35420,8 +36907,12 @@ function createRequestExecutor(deps) {
35420
36907
  softQuotaCacheTtlMs,
35421
36908
  model
35422
36909
  );
35423
- const maxWaitMs2 = (config.max_rate_limit_wait_seconds ?? 300) * 1e3;
35424
- if (softQuotaWaitMs === null || maxWaitMs2 > 0 && softQuotaWaitMs > maxWaitMs2) {
36910
+ waitPolicy.refusal = quotaWins ? () => createNativeGoogleErrorResponse({
36911
+ status: 412,
36912
+ reason: "soft_quota",
36913
+ resetAfterMs: softQuotaWaitMs
36914
+ }) : void 0;
36915
+ if (softQuotaWaitMs === null || remainingWaitMs() <= 0 || maxWaitMs > 0 && softQuotaWaitMs > maxWaitMs) {
35425
36916
  const waitTimeFormatted = softQuotaWaitMs ? formatWaitTime(softQuotaWaitMs) : "unknown";
35426
36917
  await showToast(
35427
36918
  `All accounts over ${threshold}% quota threshold. Resets in ${waitTimeFormatted}.`,
@@ -35443,11 +36934,16 @@ function createRequestExecutor(deps) {
35443
36934
  );
35444
36935
  retryState.markSoftQuotaToastShown();
35445
36936
  }
35446
- await sleep4(softQuotaWaitMs, abortSignal);
36937
+ await sleep4(Math.min(softQuotaWaitMs, remainingWaitMs()), abortSignal);
35447
36938
  continue;
35448
36939
  }
35449
36940
  const minWaitMs = accountManager.getMinWaitTimeForFamily(family, model);
35450
36941
  const waitMs = minWaitMs || 6e4;
36942
+ waitPolicy.refusal = quotaWins ? () => createNativeGoogleErrorResponse({
36943
+ status: 412,
36944
+ reason: "pool_unavailable",
36945
+ resetAfterMs: minWaitMs > 0 ? minWaitMs : void 0
36946
+ }) : void 0;
35451
36947
  pushDebug(
35452
36948
  `all-rate-limited family=${family} accounts=${accountCount} waitMs=${waitMs}`
35453
36949
  );
@@ -35462,8 +36958,7 @@ function createRequestExecutor(deps) {
35462
36958
  accountManager.getAccountsSnapshot()
35463
36959
  );
35464
36960
  }
35465
- const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1e3;
35466
- if (maxWaitMs > 0 && waitMs > maxWaitMs) {
36961
+ if (remainingWaitMs() <= 0 || maxWaitMs > 0 && waitMs > maxWaitMs) {
35467
36962
  const waitTimeFormatted = formatWaitTime(waitMs);
35468
36963
  await showToast(
35469
36964
  `Rate limited for ${waitTimeFormatted}. Try again later or add another account.`,
@@ -35485,9 +36980,11 @@ function createRequestExecutor(deps) {
35485
36980
  );
35486
36981
  retryState.markRateLimitToastShown();
35487
36982
  }
35488
- await sleep4(waitMs, abortSignal);
36983
+ await sleep4(Math.min(waitMs, remainingWaitMs()), abortSignal);
35489
36984
  continue;
35490
36985
  }
36986
+ allAccountsBlockedAt = void 0;
36987
+ waitPolicy.refusal = void 0;
35491
36988
  retryState.resetAllAccountsBlockedToasts();
35492
36989
  pushDebug(
35493
36990
  `selected idx=${account.index} email=${account.email ?? ""} family=${family} accounts=${accountCount} strategy=${config.account_selection_strategy}`
@@ -35526,9 +37023,22 @@ function createRequestExecutor(deps) {
35526
37023
  throw new Error("Local credentials were not resolved");
35527
37024
  await assertAdmission();
35528
37025
  if (auth.access) selectedCredentials.add(auth.access);
35529
- const context = await credentials.ensureProject(auth).catch((error) => {
35530
- throw redactCredentialError(error, [...selectedCredentials]);
37026
+ const packedProject = parseRefreshParts(auth.refresh);
37027
+ for (const projectId of [
37028
+ packedProject.projectId,
37029
+ packedProject.managedProjectId
37030
+ ]) {
37031
+ if (projectId) selectedProjectIds.add(projectId);
37032
+ }
37033
+ const context = await deadline.wait(() => credentials.ensureProject(auth)).catch((error) => {
37034
+ throw redactCredentialError(
37035
+ error,
37036
+ [...selectedCredentials],
37037
+ [...selectedProjectIds]
37038
+ );
35531
37039
  });
37040
+ if (context.effectiveProjectId)
37041
+ selectedProjectIds.add(context.effectiveProjectId);
35532
37042
  await assertAdmission();
35533
37043
  const projectAuth = {
35534
37044
  ...context.auth,
@@ -35538,8 +37048,9 @@ function createRequestExecutor(deps) {
35538
37048
  if (persistProject && projectAuth.refresh !== auth.refresh) {
35539
37049
  credentials.updateFromAuth(account, projectAuth);
35540
37050
  try {
35541
- await credentials.saveToDisk();
37051
+ await deadline.wait(() => credentials.saveToDisk());
35542
37052
  } catch (error) {
37053
+ checkAborted();
35543
37054
  log16.error("Failed to persist project context", {
35544
37055
  error: String(error)
35545
37056
  });
@@ -35558,7 +37069,9 @@ function createRequestExecutor(deps) {
35558
37069
  if (accessTokenExpired(authRecord)) {
35559
37070
  try {
35560
37071
  await assertAdmission();
35561
- const refreshed = await credentials.refresh(account);
37072
+ const refreshed = await deadline.wait(
37073
+ () => credentials.refresh(account)
37074
+ );
35562
37075
  if (!refreshed) {
35563
37076
  const { failures, shouldCooldown, cooldownMs } = retryState.trackAccountFailure(account.index);
35564
37077
  trackers.health.recordFailure(account.index);
@@ -35592,13 +37105,15 @@ function createRequestExecutor(deps) {
35592
37105
  authRecord = refreshed;
35593
37106
  grantCheck = captureFor(authRecord);
35594
37107
  try {
35595
- await credentials.saveToDisk();
37108
+ await deadline.wait(() => credentials.saveToDisk());
35596
37109
  } catch (error) {
37110
+ checkAborted();
35597
37111
  log16.error("Failed to persist refreshed auth", {
35598
37112
  error: String(error)
35599
37113
  });
35600
37114
  }
35601
37115
  } catch (error) {
37116
+ checkAborted();
35602
37117
  if (credentials.isInvalidGrant(error)) {
35603
37118
  const removed = credentials.removeAccount(account);
35604
37119
  if (removed) {
@@ -35606,8 +37121,9 @@ function createRequestExecutor(deps) {
35606
37121
  "Removed revoked account from pool - reauthenticate via `opencode auth login`"
35607
37122
  );
35608
37123
  try {
35609
- await credentials.saveToDiskReplace();
37124
+ await deadline.wait(() => credentials.saveToDiskReplace());
35610
37125
  } catch (persistError) {
37126
+ checkAborted();
35611
37127
  log16.error("Failed to persist revoked account removal", {
35612
37128
  error: String(persistError)
35613
37129
  });
@@ -35615,8 +37131,9 @@ function createRequestExecutor(deps) {
35615
37131
  }
35616
37132
  if (accountManager.getAccountCount() === 0) {
35617
37133
  try {
35618
- await credentials.clearStoredAuth();
37134
+ await deadline.wait(() => credentials.clearStoredAuth());
35619
37135
  } catch (storeError) {
37136
+ checkAborted();
35620
37137
  log16.error(
35621
37138
  "Failed to clear stored Antigravity OAuth credentials",
35622
37139
  {
@@ -35664,6 +37181,7 @@ function createRequestExecutor(deps) {
35664
37181
  localGrant = await prepareLocalGrant(authRecord, grantCheck);
35665
37182
  retryState.resetAccountFailureState(account.index);
35666
37183
  } catch (error) {
37184
+ checkAborted();
35667
37185
  const { failures, shouldCooldown, cooldownMs } = retryState.trackAccountFailure(account.index);
35668
37186
  trackers.health.recordFailure(account.index);
35669
37187
  lastError = error instanceof Error ? error : new Error(String(error));
@@ -35685,10 +37203,12 @@ function createRequestExecutor(deps) {
35685
37203
  const credentialForAuxiliarySend = async (sendInit, preparedProjectId) => {
35686
37204
  await assertAdmission();
35687
37205
  if (credentials.domain === "vault") {
35688
- const admission = await credentials.admit({
35689
- account: selected,
35690
- signal: abortSignal
35691
- });
37206
+ const admission = await deadline.wait(
37207
+ () => credentials.admit({
37208
+ account: selected,
37209
+ signal: abortSignal
37210
+ })
37211
+ );
35692
37212
  selectedCredentials.add(admission.accessToken);
35693
37213
  if (admission.projectId !== preparedProjectId) {
35694
37214
  throw new Error(
@@ -35704,7 +37224,7 @@ function createRequestExecutor(deps) {
35704
37224
  "Local credentials were not resolved for the selected account"
35705
37225
  );
35706
37226
  }
35707
- await localGrant.captured.check();
37227
+ await deadline.wait(() => localGrant.captured.check());
35708
37228
  await assertAdmission();
35709
37229
  return { init: sendInit };
35710
37230
  };
@@ -35746,21 +37266,25 @@ function createRequestExecutor(deps) {
35746
37266
  onDebug: pushDebug
35747
37267
  });
35748
37268
  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
37269
+ const transformed = await deadline.wait(
37270
+ () => wire.transformResponse(
37271
+ warmupResponse,
37272
+ true,
37273
+ warmupDebugContext,
37274
+ prepared.requestedModel,
37275
+ projectId,
37276
+ warmupUrl,
37277
+ prepared.effectiveModel,
37278
+ prepared.sessionId
37279
+ )
35758
37280
  );
35759
- await transformed.text();
37281
+ await deadline.wait(() => transformed.text());
35760
37282
  warmupState.markSuccess(prepared.sessionId);
35761
37283
  pushDebug("thinking-warmup: done");
35762
37284
  } catch (error) {
35763
37285
  warmupState.clearWarmupAttempt(prepared.sessionId);
37286
+ if (error instanceof PreResponseTimeoutError) throw error;
37287
+ checkAborted();
35764
37288
  if (isLocalGrantError(error)) throw error;
35765
37289
  pushDebug(
35766
37290
  `thinking-warmup: failed ${error instanceof Error ? error.message : String(error)}`
@@ -35789,14 +37313,16 @@ function createRequestExecutor(deps) {
35789
37313
  reportVault401(probeSend.admission, probeResponse.status);
35790
37314
  if (probeResponse.body) {
35791
37315
  const reader = probeResponse.body.getReader();
35792
- await reader.read();
35793
- await reader.cancel();
37316
+ await deadline.wait(() => reader.read());
37317
+ await deadline.wait(() => reader.cancel());
35794
37318
  }
35795
37319
  const status = probeResponse.status;
35796
37320
  if (status >= 400) {
35797
37321
  let errorSnippet = "";
35798
37322
  try {
35799
- const errText = await probeResponse.text().catch(() => "");
37323
+ const errText = await deadline.wait(
37324
+ () => probeResponse.text().catch(() => "")
37325
+ );
35800
37326
  errorSnippet = errText.slice(0, 200);
35801
37327
  } catch {
35802
37328
  }
@@ -35809,6 +37335,8 @@ function createRequestExecutor(deps) {
35809
37335
  );
35810
37336
  }
35811
37337
  } catch (error) {
37338
+ if (error instanceof PreResponseTimeoutError) throw error;
37339
+ checkAborted();
35812
37340
  if (isLocalGrantError(error)) {
35813
37341
  needsCacheWarmup = true;
35814
37342
  throw error;
@@ -35849,10 +37377,12 @@ function createRequestExecutor(deps) {
35849
37377
  let sendAccessToken;
35850
37378
  let sendProjectId;
35851
37379
  if (credentials.domain === "vault") {
35852
- sendAdmission = rotatedAdmission ?? await credentials.admit({
35853
- account,
35854
- signal: abortSignal
35855
- });
37380
+ sendAdmission = rotatedAdmission ?? await deadline.wait(
37381
+ () => credentials.admit({
37382
+ account,
37383
+ signal: abortSignal
37384
+ })
37385
+ );
35856
37386
  rotatedAdmission = void 0;
35857
37387
  sendAccessToken = sendAdmission.accessToken;
35858
37388
  sendProjectId = sendAdmission.projectId;
@@ -35864,6 +37394,7 @@ function createRequestExecutor(deps) {
35864
37394
  "Local credentials were not resolved for the selected account"
35865
37395
  );
35866
37396
  }
37397
+ if (sendProjectId) selectedProjectIds.add(sendProjectId);
35867
37398
  selectedCredentials.add(sendAccessToken);
35868
37399
  const prepared = prepareAgyWireRequest(wire, {
35869
37400
  input: input2,
@@ -35917,7 +37448,6 @@ function createRequestExecutor(deps) {
35917
37448
  sessionId: prepared.sessionId,
35918
37449
  toolDebugMissing: prepared.toolDebugMissing,
35919
37450
  toolDebugSummary: prepared.toolDebugSummary,
35920
- toolDebugPayload: prepared.toolDebugPayload,
35921
37451
  dumpContext
35922
37452
  });
35923
37453
  await runThinkingWarmup(prepared, sendProjectId);
@@ -35940,7 +37470,7 @@ function createRequestExecutor(deps) {
35940
37470
  "Local credentials were not resolved for the selected account"
35941
37471
  );
35942
37472
  }
35943
- await localGrant.captured.check();
37473
+ await deadline.wait(() => localGrant.captured.check());
35944
37474
  await assertAdmission();
35945
37475
  }
35946
37476
  pushDebug(
@@ -35952,6 +37482,7 @@ function createRequestExecutor(deps) {
35952
37482
  prepared.init,
35953
37483
  { signal: abortSignal, onDebug: pushDebug }
35954
37484
  );
37485
+ if (response.ok) deadline.acceptHeaders();
35955
37486
  apiRequestCount++;
35956
37487
  accountManager.recordRequest(account.index, family);
35957
37488
  const requestCounts = accountManager.getDailyRequestCounts(
@@ -35967,19 +37498,17 @@ function createRequestExecutor(deps) {
35967
37498
  );
35968
37499
  noteGeminiDumpResponse(dumpContext, response);
35969
37500
  if (credentials.domain === "vault" && sendAdmission && response.status === 401) {
35970
- try {
35971
- await sendAdmission.report401(response.status);
35972
- } catch (error) {
35973
- log16.debug("send-admission-401-report-failed", {
35974
- error: String(error)
35975
- });
35976
- }
35977
- if (!vault401Retried) {
35978
- const next = await credentials.admit({
35979
- account,
35980
- signal: abortSignal
35981
- });
35982
- if (next.credentialId === sendAdmission.credentialId && next.accountIdentity === sendAdmission.accountIdentity && next.recordVersion > sendAdmission.recordVersion) {
37501
+ if (!sendAdmission.fromKeptReceipt && !vault401Retried && !abortSignal?.aborted) {
37502
+ let next;
37503
+ try {
37504
+ next = await deadline.wait(
37505
+ () => credentials.admit({ account, signal: abortSignal })
37506
+ );
37507
+ } catch {
37508
+ checkAborted();
37509
+ }
37510
+ const retry = credentials.retryAfter401 ? credentials.retryAfter401(sendAdmission, next, "model") : next && !next.fromKeptReceipt && next.credentialId === sendAdmission.credentialId && next.accountIdentity === sendAdmission.accountIdentity && next.recordVersion > sendAdmission.recordVersion;
37511
+ if (next && retry) {
35983
37512
  vault401Retried = true;
35984
37513
  rotatedAdmission = next;
35985
37514
  void response.body?.cancel().catch(() => {
@@ -35991,6 +37520,16 @@ function createRequestExecutor(deps) {
35991
37520
  continue;
35992
37521
  }
35993
37522
  }
37523
+ try {
37524
+ await deadline.wait(
37525
+ () => sendAdmission.report401(response.status)
37526
+ );
37527
+ } catch (error) {
37528
+ checkAborted();
37529
+ log16.debug("send-admission-401-report-failed", {
37530
+ error: String(error)
37531
+ });
37532
+ }
35994
37533
  }
35995
37534
  const sessionKey = requestSessionIdentity.sessionId;
35996
37535
  if (sessionKey) {
@@ -36016,13 +37555,16 @@ function createRequestExecutor(deps) {
36016
37555
  );
36017
37556
  const bodyInfo = await (async () => {
36018
37557
  try {
36019
- const text2 = await response.clone().text();
37558
+ const text2 = await deadline.wait(
37559
+ () => response.clone().text()
37560
+ );
36020
37561
  try {
36021
37562
  return JSON.parse(text2);
36022
37563
  } catch {
36023
37564
  return null;
36024
37565
  }
36025
37566
  } catch {
37567
+ checkAborted();
36026
37568
  return null;
36027
37569
  }
36028
37570
  })();
@@ -36106,7 +37648,7 @@ function createRequestExecutor(deps) {
36106
37648
  effectiveDelayMs,
36107
37649
  reasonInfo
36108
37650
  );
36109
- await debug.logResponseBody(debugContext, response, 429);
37651
+ await logResponseBody2(debugContext, response, 429);
36110
37652
  trackers.health.recordRateLimit(account.index);
36111
37653
  const _accountLabel = account.email || `Account ${account.index + 1}`;
36112
37654
  if (backoff.attempt === 1 && rateLimitReason !== "QUOTA_EXHAUSTED") {
@@ -36189,7 +37731,9 @@ function createRequestExecutor(deps) {
36189
37731
  retryState.resetRateLimitState(account.index, quotaKey);
36190
37732
  retryState.resetAccountFailureState(account.index);
36191
37733
  if (response.status === 403) {
36192
- const errorBodyText = await response.clone().text().catch(() => "");
37734
+ const errorBodyText = await deadline.wait(
37735
+ () => response.clone().text().catch(() => "")
37736
+ );
36193
37737
  const extracted = classifyAccessError(errorBodyText);
36194
37738
  if (extracted.accountIneligible) {
36195
37739
  const ineligibleReason = extracted.message ?? "Google marked this account as ineligible for Antigravity.";
@@ -36251,11 +37795,7 @@ function createRequestExecutor(deps) {
36251
37795
  }
36252
37796
  const shouldRetryEndpoint = response.status === 403 || response.status === 404 || response.status >= 500;
36253
37797
  if (shouldRetryEndpoint && i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
36254
- await debug.logResponseBody(
36255
- debugContext,
36256
- response,
36257
- response.status
36258
- );
37798
+ await logResponseBody2(debugContext, response, response.status);
36259
37799
  lastFailure = createFailureContext(response);
36260
37800
  continue;
36261
37801
  }
@@ -36264,23 +37804,6 @@ function createRequestExecutor(deps) {
36264
37804
  trackers.health.recordSuccess(account.index);
36265
37805
  if (!advisoryClosing)
36266
37806
  accountManager.markAccountUsed(account.index);
36267
- if (credentials.domain === "local" && !advisoryClosing && credentials.refreshQuotaAfterSuccess) {
36268
- const quotaCancellation = createRequestCancellation(
36269
- init?.signal ? [init.signal, shutdown.signal] : [shutdown.signal]
36270
- );
36271
- const work = credentials.refreshQuotaAfterSuccess(
36272
- account,
36273
- config.quota_refresh_interval_minutes,
36274
- quotaCancellation.signal
36275
- ).catch(() => {
36276
- log16.debug("post-response-advisory-work-failed");
36277
- }).finally(() => quotaCancellation.release());
36278
- advisoryWork.add(work);
36279
- void work.then(
36280
- () => advisoryWork.delete(work),
36281
- () => advisoryWork.delete(work)
36282
- );
36283
- }
36284
37807
  const proactiveThreshold = config.proactive_rotation_threshold_percent ?? 20;
36285
37808
  if (!advisoryClosing && proactiveThreshold > 0 && accountManager.shouldProactivelyRotate(
36286
37809
  family,
@@ -36312,21 +37835,13 @@ function createRequestExecutor(deps) {
36312
37835
  note: response.ok ? "Success" : `Error ${response.status}`
36313
37836
  });
36314
37837
  if (response.ok && !prepared.streaming) {
36315
- await debug.logResponseBody(
36316
- debugContext,
36317
- response,
36318
- response.status
36319
- );
37838
+ await logResponseBody2(debugContext, response, response.status);
36320
37839
  }
36321
37840
  if (!response.ok) {
36322
- await debug.logResponseBody(
36323
- debugContext,
36324
- response,
36325
- response.status
36326
- );
37841
+ await logResponseBody2(debugContext, response, response.status);
36327
37842
  if (response.status === 400) {
36328
37843
  const cloned = response.clone();
36329
- const bodyText = await cloned.text();
37844
+ const bodyText = await deadline.wait(() => cloned.text());
36330
37845
  if (bodyText.includes("Prompt is too long") || bodyText.includes("prompt_too_long")) {
36331
37846
  await showToast(
36332
37847
  "Context too long - use /compact to reduce size",
@@ -36341,7 +37856,7 @@ function createRequestExecutor(deps) {
36341
37856
  const maxAttempts = config.empty_response_max_attempts ?? 4;
36342
37857
  const retryDelayMs = config.empty_response_retry_delay_ms ?? 2e3;
36343
37858
  const clonedForCheck = response.clone();
36344
- const bodyText = await clonedForCheck.text();
37859
+ const bodyText = await deadline.wait(() => clonedForCheck.text());
36345
37860
  if (isEmptyResponseBody(bodyText)) {
36346
37861
  const emptyAttemptKey = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
36347
37862
  const currentAttempts = retryState.recordEmptyResponseAttempt(emptyAttemptKey);
@@ -36349,6 +37864,7 @@ function createRequestExecutor(deps) {
36349
37864
  `empty-response: attempt ${currentAttempts}/${maxAttempts}`
36350
37865
  );
36351
37866
  if (currentAttempts < maxAttempts) {
37867
+ deadline.resume();
36352
37868
  await showToast(
36353
37869
  `Empty response received. Retrying (${currentAttempts}/${maxAttempts})...`,
36354
37870
  "warning"
@@ -36365,20 +37881,21 @@ function createRequestExecutor(deps) {
36365
37881
  const _emptyAttemptKeyClean = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
36366
37882
  retryState.clearEmptyResponseAttempts();
36367
37883
  }
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
37884
+ const transformedResponse = await deadline.wait(
37885
+ () => wire.transformResponse(
37886
+ response,
37887
+ prepared.streaming,
37888
+ debugContext,
37889
+ prepared.requestedModel,
37890
+ prepared.projectId,
37891
+ prepared.endpoint,
37892
+ prepared.effectiveModel,
37893
+ prepared.sessionId,
37894
+ prepared.toolDebugMissing,
37895
+ prepared.toolDebugSummary,
37896
+ debugLines,
37897
+ dumpContext
37898
+ )
36382
37899
  );
36383
37900
  const contextError = transformedResponse.headers.get(
36384
37901
  "x-antigravity-context-error"
@@ -36434,8 +37951,14 @@ function createRequestExecutor(deps) {
36434
37951
  );
36435
37952
  }
36436
37953
  }
37954
+ if (response.ok && transformedResponse.ok && credentials.domain === "local" && !advisoryClosing && credentials.refreshQuotaAfterSuccess) {
37955
+ const refresh = credentials.refreshQuotaAfterSuccess;
37956
+ waitPolicy.quota = (signal) => refresh(account, config.quota_refresh_interval_minutes, signal);
37957
+ }
36437
37958
  return transformedResponse;
36438
37959
  } catch (error) {
37960
+ if (error instanceof PreResponseTimeoutError) throw error;
37961
+ checkAborted();
36439
37962
  if (tokenConsumed && (!isLocalGrantError(error) || !physicalAttemptStarted)) {
36440
37963
  trackers.token.refund(account.index);
36441
37964
  tokenConsumed = false;
@@ -36444,7 +37967,8 @@ function createRequestExecutor(deps) {
36444
37967
  if (error instanceof LocalGrantSupersededError && !localRecaptureUsed) {
36445
37968
  localRecaptureUsed = true;
36446
37969
  try {
36447
- await localGrant.captured.resolveCurrent();
37970
+ const originalGrant = localGrant.captured;
37971
+ await deadline.wait(() => originalGrant.resolveCurrent());
36448
37972
  const auth = credentials.toAuthDetails(account);
36449
37973
  if (!auth.access || accessTokenExpired(auth))
36450
37974
  return createNativeGoogleErrorResponse({
@@ -36469,6 +37993,7 @@ function createRequestExecutor(deps) {
36469
37993
  }
36470
37994
  if (error instanceof Error && error.message === "THINKING_RECOVERY_NEEDED") {
36471
37995
  if (!forceThinkingRecovery) {
37996
+ deadline.resume();
36472
37997
  pushDebug(
36473
37998
  "thinking-recovery: API error detected, retrying with forced recovery"
36474
37999
  );
@@ -36537,7 +38062,6 @@ function createRequestExecutor(deps) {
36537
38062
  lastFailure.sessionId,
36538
38063
  lastFailure.toolDebugMissing,
36539
38064
  lastFailure.toolDebugSummary,
36540
- lastFailure.toolDebugPayload,
36541
38065
  debugLines,
36542
38066
  lastFailure.dumpContext
36543
38067
  );
@@ -36560,7 +38084,6 @@ function createRequestExecutor(deps) {
36560
38084
  lastFailure.sessionId,
36561
38085
  lastFailure.toolDebugMissing,
36562
38086
  lastFailure.toolDebugSummary,
36563
- lastFailure.toolDebugPayload,
36564
38087
  debugLines,
36565
38088
  lastFailure.dumpContext
36566
38089
  );
@@ -36584,7 +38107,6 @@ function createRequestExecutor(deps) {
36584
38107
  lastFailure.sessionId,
36585
38108
  lastFailure.toolDebugMissing,
36586
38109
  lastFailure.toolDebugSummary,
36587
- lastFailure.toolDebugPayload,
36588
38110
  debugLines,
36589
38111
  lastFailure.dumpContext
36590
38112
  );
@@ -36628,20 +38150,48 @@ function createRequestExecutor(deps) {
36628
38150
  const cancellation = createRequestCancellation(
36629
38151
  requestedSignal ? [requestedSignal, shutdown.signal] : [shutdown.signal]
36630
38152
  );
38153
+ const deadline = new PreResponseDeadline(
38154
+ cancellation.signal,
38155
+ deps.preResponseClock
38156
+ );
38157
+ log16.debug("pre-response-start", { limitMs: PRE_RESPONSE_DEADLINE_MS });
38158
+ const handoff = createAfterHandoff(
38159
+ advisoryWork,
38160
+ requestedSignal ? [requestedSignal, shutdown.signal] : [shutdown.signal],
38161
+ () => log16.debug("post-response-advisory-work-failed")
38162
+ );
38163
+ const waitPolicy = {};
36631
38164
  const selectedCredentials = /* @__PURE__ */ new Set();
36632
- const pending = execute(
36633
- input2,
36634
- { ...init, signal: cancellation.signal },
36635
- requestOptions,
36636
- selectedCredentials
36637
- ).then(
38165
+ const selectedProjectIds = /* @__PURE__ */ new Set();
38166
+ const pending = deadline.wait(
38167
+ () => execute(
38168
+ input2,
38169
+ { ...init, signal: deadline.signal },
38170
+ requestOptions ?? {},
38171
+ selectedCredentials,
38172
+ selectedProjectIds,
38173
+ deadline,
38174
+ waitPolicy
38175
+ )
38176
+ ).catch((error) => {
38177
+ cancellation.signal.throwIfAborted();
38178
+ if (error instanceof PreResponseTimeoutError) {
38179
+ log16.debug("pre-response-timeout", { reason: error.reason });
38180
+ return waitPolicy.refusal?.() ?? preResponseTimeoutResponse();
38181
+ }
38182
+ throw error;
38183
+ }).then(
36638
38184
  async (response) => {
38185
+ deadline.acceptTerminalResponse();
36639
38186
  if (bufferedOverflow.has(response)) {
38187
+ handoff.cancel();
38188
+ deadline.dispose();
36640
38189
  cancellation.release();
36641
38190
  return redactCredentialResponse(
36642
38191
  response,
36643
38192
  [...selectedCredentials],
36644
- bufferedOverflow.get(response)
38193
+ bufferedOverflow.get(response),
38194
+ [...selectedProjectIds]
36645
38195
  );
36646
38196
  }
36647
38197
  const retained = await retainResponseLifetime(
@@ -36650,18 +38200,40 @@ function createRequestExecutor(deps) {
36650
38200
  );
36651
38201
  inFlight.add(retained.settled);
36652
38202
  void retained.settled.then(() => inFlight.delete(retained.settled));
36653
- return redactCredentialResponse(
38203
+ void retained.settled.then(() => deadline.dispose());
38204
+ const published = await redactCredentialResponse(
36654
38205
  preserveResponseMetadata2(retained.response, response),
36655
- [...selectedCredentials]
38206
+ [...selectedCredentials],
38207
+ void 0,
38208
+ [...selectedProjectIds]
36656
38209
  );
38210
+ if (published.ok && waitPolicy.quota && requestOptions?.onResponseHandoff) {
38211
+ handoff.register(waitPolicy.quota);
38212
+ requestOptions.onResponseHandoff(handoff.acknowledge);
38213
+ } else {
38214
+ handoff.cancel();
38215
+ }
38216
+ return published;
36657
38217
  },
36658
38218
  (error) => {
38219
+ handoff.cancel();
38220
+ deadline.dispose();
36659
38221
  cancellation.release();
36660
- throw redactCredentialError(error, [...selectedCredentials]);
38222
+ throw redactCredentialError(
38223
+ error,
38224
+ [...selectedCredentials],
38225
+ [...selectedProjectIds]
38226
+ );
36661
38227
  }
36662
38228
  ).catch((error) => {
38229
+ handoff.cancel();
38230
+ deadline.dispose();
36663
38231
  cancellation.release();
36664
- throw redactCredentialError(error, [...selectedCredentials]);
38232
+ throw redactCredentialError(
38233
+ error,
38234
+ [...selectedCredentials],
38235
+ [...selectedProjectIds]
38236
+ );
36665
38237
  });
36666
38238
  inFlight.add(pending);
36667
38239
  void pending.then(
@@ -37630,6 +39202,7 @@ function refreshVaultAccountRow(prior, fresh) {
37630
39202
  else prior.email = fresh.email;
37631
39203
  }
37632
39204
  var VaultSendGrant = class {
39205
+ fromKeptReceipt;
37633
39206
  credentialId;
37634
39207
  accountIdentity;
37635
39208
  recordVersion;
@@ -37644,20 +39217,36 @@ var VaultSendGrant = class {
37644
39217
  this.accountIdentity = admission.accountIdentity;
37645
39218
  this.recordVersion = admission.recordVersion;
37646
39219
  this.projectId = admission.projectId;
39220
+ this.fromKeptReceipt = admission.fromKeptReceipt;
37647
39221
  this.report401 = report;
37648
39222
  }
37649
39223
  };
37650
39224
  function createVaultRequestCredentials(source, onAdmitted) {
39225
+ const issued = /* @__PURE__ */ new WeakMap();
37651
39226
  return {
37652
39227
  domain: "vault",
39228
+ ...source.retryAfter401 && {
39229
+ retryAfter401(served, current, site) {
39230
+ const original = issued.get(served);
39231
+ if (!original)
39232
+ throw new Error("Retry requires an original vault admission");
39233
+ return source.retryAfter401(
39234
+ original,
39235
+ current && issued.get(current),
39236
+ site
39237
+ );
39238
+ }
39239
+ },
37653
39240
  async admit({ account, signal }) {
37654
39241
  const admission = await source.admit(account.route, signal);
37655
39242
  if (onAdmitted)
37656
39243
  onAdmitted.admitted(account, onAdmitted.source.attribution(admission));
37657
- return new VaultSendGrant(
39244
+ const grant = new VaultSendGrant(
37658
39245
  admission,
37659
39246
  (status) => source.reportServedStatus(admission, status)
37660
39247
  );
39248
+ issued.set(grant, admission);
39249
+ return grant;
37661
39250
  }
37662
39251
  };
37663
39252
  }
@@ -37861,6 +39450,9 @@ function createVaultAccountPool(options) {
37861
39450
  admitted: (row, attribution) => state.admitted(row, attribution)
37862
39451
  } : void 0
37863
39452
  );
39453
+ const refusal3 = options.emptyRosterRefusal;
39454
+ if (refusal3)
39455
+ credentials.emptyRosterRefusal = () => refusal3(source.emptyRosterCause?.() ?? "unknown");
37864
39456
  const rowsFromSource = async () => {
37865
39457
  const rows = vaultAccountRows(source.routes());
37866
39458
  if (state) {
@@ -38103,7 +39695,8 @@ function createOpenCodeVaultCustody(options) {
38103
39695
  reporterSource: options.reporterSource,
38104
39696
  state: { path: paths.stateFile, fs: await loadCommonAuthFs() },
38105
39697
  ...options.logger ? { logger: options.logger } : {},
38106
- ...options.now ? { now: options.now } : {}
39698
+ ...options.now ? { now: options.now } : {},
39699
+ ...options.pollIntervalMs !== void 0 ? { pollIntervalMs: options.pollIntervalMs } : {}
38107
39700
  });
38108
39701
  const activeSource = {
38109
39702
  ...created,
@@ -38138,7 +39731,7 @@ function createOpenCodeVaultCustody(options) {
38138
39731
  const roster = await (await loadClaustrum()).readVaultRoster(
38139
39732
  paths.rosterFile
38140
39733
  );
38141
- return roster?.rows.length === 0 ? noVaultAccountsGuidance() : [];
39734
+ return roster?.rows.length === 0 ? noVaultAccountsGuidance(source?.grantReach()) : [];
38142
39735
  } catch {
38143
39736
  return [];
38144
39737
  }
@@ -38381,11 +39974,37 @@ function pendingExistsGuidance() {
38381
39974
  "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
39975
  ];
38383
39976
  }
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
- ];
39977
+ function noVaultAccountsGuidance(reach) {
39978
+ return emptyRosterGuidance(emptyVaultRosterCause(reach));
39979
+ }
39980
+ function emptyRosterGuidance(cause) {
39981
+ switch (cause) {
39982
+ case "no-grant":
39983
+ return [
39984
+ `Vault access is approved. The vault has not granted ${OPENCODE_VAULT_ENROLLMENT_NAME} read access.`,
39985
+ `The vault operator grants it with: ${OPENCODE_VAULT_GRANT_COMMAND}`
39986
+ ];
39987
+ case "grant-reaches-nothing":
39988
+ return [
39989
+ `Vault access is approved. ${OPENCODE_VAULT_ENROLLMENT_NAME} has read access, but it reaches no Antigravity login in the vault.`,
39990
+ `The vault operator updates the vault's logins with: ${VAULT_RECLASSIFY_COMMAND}`,
39991
+ `Then they check them with: ${VAULT_STATUS_COMMAND}`
39992
+ ];
39993
+ case "unknown":
39994
+ return [
39995
+ `Vault access is approved, but the vault serves ${OPENCODE_VAULT_ENROLLMENT_NAME} no Antigravity accounts.`,
39996
+ `The vault operator grants read access with: ${OPENCODE_VAULT_GRANT_COMMAND}`
39997
+ ];
39998
+ }
39999
+ }
40000
+ function openCodeEmptyVaultRosterRefusal(cause) {
40001
+ return cause === "unknown" ? void 0 : emptyRosterGuidance(cause).join("\n");
40002
+ }
40003
+ function createOpenCodeVaultAccountPool(options) {
40004
+ return createVaultAccountPool({
40005
+ ...options,
40006
+ emptyRosterRefusal: openCodeEmptyVaultRosterRefusal
40007
+ });
38389
40008
  }
38390
40009
  function enrollmentGuidance(status) {
38391
40010
  if (status.state === "pending")
@@ -39135,6 +40754,7 @@ function createGaJobExecutor(executor, overrides = {}) {
39135
40754
  {
39136
40755
  kind: job.kind,
39137
40756
  variant: job.variant ?? void 0,
40757
+ ...context.onResponseHandoff ? { onResponseHandoff: context.onResponseHandoff } : {},
39138
40758
  session: {
39139
40759
  sessionId: job.sessionID,
39140
40760
  parentSessionId: job.parentSessionID
@@ -39148,6 +40768,7 @@ function createGaJobExecutor(executor, overrides = {}) {
39148
40768
  if (typeof init?.body !== "string" || !authorization?.startsWith("Bearer ") || !signal) {
39149
40769
  throw new Error("The prepared Antigravity send is incomplete");
39150
40770
  }
40771
+ signal.throwIfAborted();
39151
40772
  return send({
39152
40773
  envelope: JSON.parse(init.body),
39153
40774
  auth: { access: authorization.slice("Bearer ".length) },
@@ -39406,7 +41027,7 @@ async function createGaVaultLocationServices(input2) {
39406
41027
  const location = start.runtime;
39407
41028
  const routes = createGaRouteBook();
39408
41029
  const vaultLogger = location.logger.createLogger("vault-state");
39409
- const pool = createVaultAccountPool({
41030
+ const pool = createOpenCodeVaultAccountPool({
39410
41031
  source,
39411
41032
  durable: {
39412
41033
  source,
@@ -41565,6 +43186,7 @@ function createGaRawSender(overrides = {}) {
41565
43186
  if (send) return (input2) => send(input2);
41566
43187
  const observe = overrides.observeRawSenderSignal;
41567
43188
  return (input2) => {
43189
+ input2.signal.throwIfAborted();
41568
43190
  const transportOptions = {
41569
43191
  signal: input2.signal,
41570
43192
  idleTimeoutMs: GA_RAW_IDLE_TIMEOUT_MS
@@ -41605,7 +43227,8 @@ function isGaGoogleContentRequest(request) {
41605
43227
  }
41606
43228
  }
41607
43229
  function gaPreHeaderFailureResponse(error) {
41608
- const message = error instanceof Error && error.message ? error.message : "Antigravity request failed before a response arrived";
43230
+ const rawMessage = error instanceof Error && error.message ? error.message : "Antigravity request failed before a response arrived";
43231
+ const message = redactProjectIdText(rawMessage);
41609
43232
  return new Response(
41610
43233
  JSON.stringify({ error: { code: 502, message, status: "UNAVAILABLE" } }),
41611
43234
  { status: 502, headers: { "content-type": "application/json" } }
@@ -41697,18 +43320,34 @@ async function startGaLoopbackBridge(options) {
41697
43320
  });
41698
43321
  try {
41699
43322
  let upstream;
43323
+ let acknowledge;
41700
43324
  try {
41701
43325
  upstream = await options.execute(entry.job, {
41702
43326
  signal: controller.signal,
41703
- send: options.send
43327
+ send: options.send,
43328
+ onResponseHandoff: (callback) => {
43329
+ acknowledge = callback;
43330
+ }
41704
43331
  });
41705
43332
  } catch (error) {
43333
+ acknowledge = void 0;
41706
43334
  upstream = gaPreHeaderFailureResponse(error);
41707
43335
  }
41708
- await pipeResponse(upstream, response, (error) => {
41709
- if (!state.released && (state.claimed || !closing))
41710
- state.failure = error;
41711
- });
43336
+ await pipeResponse(
43337
+ upstream,
43338
+ response,
43339
+ (error) => {
43340
+ if (!state.released && (state.claimed || !closing))
43341
+ state.failure = error;
43342
+ },
43343
+ () => {
43344
+ if (!response.destroyed && !controller.signal.aborted && !closing) {
43345
+ const callback = acknowledge;
43346
+ acknowledge = void 0;
43347
+ callback?.();
43348
+ }
43349
+ }
43350
+ );
41712
43351
  } finally {
41713
43352
  running.delete(controller);
41714
43353
  if (!closing && !state.claimed && !state.released) {
@@ -41863,7 +43502,7 @@ function writeResponseHead(response, status, contentType) {
41863
43502
  "cache-control": "no-cache"
41864
43503
  });
41865
43504
  }
41866
- async function pipeResponse(upstream, response, onFailure) {
43505
+ async function pipeResponse(upstream, response, onFailure, onHandoff) {
41867
43506
  const contentType = upstream.headers.get("content-type") ?? "application/octet-stream";
41868
43507
  if (response.destroyed) {
41869
43508
  await upstream.body?.cancel().catch(() => {
@@ -41871,6 +43510,8 @@ async function pipeResponse(upstream, response, onFailure) {
41871
43510
  return;
41872
43511
  }
41873
43512
  writeResponseHead(response, upstream.status, contentType);
43513
+ response.flushHeaders();
43514
+ onHandoff();
41874
43515
  if (!upstream.body) {
41875
43516
  response.end();
41876
43517
  return;
@@ -42554,7 +44195,7 @@ import { createHash as createHash20, randomUUID as randomUUID21 } from "node:cry
42554
44195
  import { join as join31, resolve as resolve17 } from "node:path";
42555
44196
 
42556
44197
  // src/cli.ts
42557
- import { execFile as execFile2 } from "node:child_process";
44198
+ import { execFile } from "node:child_process";
42558
44199
  import { realpathSync as realpathSync3 } from "node:fs";
42559
44200
  import { resolve as resolve14 } from "node:path";
42560
44201
  import { createInterface } from "node:readline/promises";
@@ -42843,7 +44484,7 @@ import { createHash as createHash15, randomBytes as randomBytes6, randomUUID as
42843
44484
  import { constants as fsConstants2 } from "node:fs";
42844
44485
  import { chmod as chmod4, mkdir as mkdir13, open as open10, readFile as readFile11, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
42845
44486
  import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute3, join as join18, resolve as resolve12 } from "node:path";
42846
- import { ClaustrumCredentialError as ClaustrumCredentialError4, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
44487
+ import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
42847
44488
 
42848
44489
  // src/common-auth-embedded/fs/lock-constants.js
42849
44490
  var WRITER_LOCK_CONSTANTS2 = Object.freeze({
@@ -42894,7 +44535,10 @@ function isLostMarkerRaceError2(error) {
42894
44535
  const code2 = error?.code;
42895
44536
  return code2 === "ENOENT" || !windowsPrivateFiles2 && (code2 === "EINVAL" || code2 === "ENOTDIR");
42896
44537
  }
42897
- async function acquireRefreshFileLock2(options) {
44538
+ function acquireRefreshFileLock2(options) {
44539
+ return acquireRefreshFileLockWithClock2({ ...options, now: Date.now });
44540
+ }
44541
+ async function acquireRefreshFileLockWithClock2(options) {
42898
44542
  const lockPath = lockPathFor2(options.path, options.name);
42899
44543
  const legacyOwnerPath = join17(lockPath, "owner.json");
42900
44544
  const ownerId = randomUUID16();
@@ -43522,7 +45166,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
43522
45166
  "pending_queue_full"
43523
45167
  ]);
43524
45168
  function classifyEnrollmentError2(error) {
43525
- if (!(error instanceof ClaustrumCredentialError4))
45169
+ if (!(error instanceof ClaustrumCredentialError5))
43526
45170
  return void 0;
43527
45171
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
43528
45172
  return { code: error.code, disposition: "terminal" };
@@ -43828,6 +45472,31 @@ async function readClaustrumEnrollmentStatus2(paths, proposedName) {
43828
45472
  }
43829
45473
  return statusFromState2(state);
43830
45474
  }
45475
+ async function enrollmentAuthority3(paths, proposedName) {
45476
+ let status;
45477
+ try {
45478
+ status = await readClaustrumEnrollmentStatus2(paths, proposedName);
45479
+ } catch (error) {
45480
+ if (!(error instanceof ClaustrumConsumerError2) || error.kind !== "invalid-state" && error.kind !== "invalid-token") {
45481
+ return "unreadable";
45482
+ }
45483
+ try {
45484
+ const stateValue = await readBoundedJson2(paths.statePath);
45485
+ if (stateValue === void 0)
45486
+ return "unreadable";
45487
+ const state = decodeEnrollmentState2(stateValue);
45488
+ return state.phase === "approved" && state.proposedName === proposedName ? "vault" : "unreadable";
45489
+ } catch {
45490
+ return "unreadable";
45491
+ }
45492
+ }
45493
+ if ("proposedName" in status && status.proposedName !== proposedName)
45494
+ return "unreadable";
45495
+ if (status.state === "approved" || status.state === "blocked" && status.code === "missing_token") {
45496
+ return "vault";
45497
+ }
45498
+ return "local";
45499
+ }
43831
45500
  function statusFromState2(state) {
43832
45501
  if (state.phase === "pending") {
43833
45502
  return {
@@ -44068,30 +45737,126 @@ async function resetClaustrumEnrollmentState2(paths, proposedName) {
44068
45737
  }
44069
45738
 
44070
45739
  // src/common-auth-embedded/setup/command-runner.js
44071
- import { execFile } from "node:child_process";
45740
+ import { spawn } from "node:child_process";
45741
+ var STDERR_TAIL_MAX_BYTES = 4 * 1024;
45742
+ var STDOUT_MAX_BYTES = 1024 * 1024;
45743
+ var ByteTail = class {
45744
+ buffer = Buffer.alloc(STDERR_TAIL_MAX_BYTES);
45745
+ start = 0;
45746
+ length = 0;
45747
+ truncated = false;
45748
+ get didTruncate() {
45749
+ return this.truncated;
45750
+ }
45751
+ push(chunk) {
45752
+ if (chunk.length >= STDERR_TAIL_MAX_BYTES) {
45753
+ if (chunk.length > STDERR_TAIL_MAX_BYTES || this.length > 0)
45754
+ this.truncated = true;
45755
+ chunk.copy(this.buffer, 0, chunk.length - STDERR_TAIL_MAX_BYTES);
45756
+ this.start = 0;
45757
+ this.length = STDERR_TAIL_MAX_BYTES;
45758
+ return;
45759
+ }
45760
+ const overflow = Math.max(0, this.length + chunk.length - STDERR_TAIL_MAX_BYTES);
45761
+ if (overflow > 0)
45762
+ this.truncated = true;
45763
+ this.start = (this.start + overflow) % STDERR_TAIL_MAX_BYTES;
45764
+ this.length -= overflow;
45765
+ const writeAt = (this.start + this.length) % STDERR_TAIL_MAX_BYTES;
45766
+ const firstLength = Math.min(chunk.length, STDERR_TAIL_MAX_BYTES - writeAt);
45767
+ chunk.copy(this.buffer, writeAt, 0, firstLength);
45768
+ if (firstLength < chunk.length)
45769
+ chunk.copy(this.buffer, 0, firstLength);
45770
+ this.length += chunk.length;
45771
+ }
45772
+ toString() {
45773
+ const bytes = Buffer.alloc(this.length);
45774
+ const firstLength = Math.min(this.length, STDERR_TAIL_MAX_BYTES - this.start);
45775
+ this.buffer.copy(bytes, 0, this.start, this.start + firstLength);
45776
+ if (firstLength < this.length)
45777
+ this.buffer.copy(bytes, firstLength, 0, this.length - firstLength);
45778
+ let start = 0;
45779
+ while (start < bytes.length) {
45780
+ const byte = bytes[start];
45781
+ if (byte === void 0 || (byte & 192) !== 128)
45782
+ break;
45783
+ start++;
45784
+ }
45785
+ return bytes.subarray(start).toString("utf8");
45786
+ }
45787
+ };
44072
45788
  var defaultCommandRunner = {
44073
45789
  run(file, args, options = {}) {
44074
45790
  return new Promise((resolve18) => {
44075
45791
  const started = performance.now();
44076
45792
  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;
45793
+ const stderr = new ByteTail();
45794
+ const stdout = [];
45795
+ let stdoutLength = 0;
45796
+ let outputExceeded = false;
45797
+ let spawnError = false;
45798
+ let timedOut = false;
45799
+ let child;
45800
+ try {
45801
+ child = spawn(file, [...args], {
45802
+ env: options.env ?? process.env,
45803
+ windowsHide: true,
45804
+ windowsVerbatimArguments: options.windowsVerbatimArguments,
45805
+ stdio: ["ignore", "pipe", "pipe"]
45806
+ });
45807
+ } catch {
44085
45808
  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
45809
+ exitCode: 1,
45810
+ stdout: "",
45811
+ stderr: "",
45812
+ spawnError: true,
45813
+ signal: null,
45814
+ timedOut: false,
45815
+ durationMs: performance.now() - started
44093
45816
  });
45817
+ return;
45818
+ }
45819
+ const timer = timeoutMs > 0 ? setTimeout(() => {
45820
+ timedOut = true;
45821
+ child.kill("SIGTERM");
45822
+ }, timeoutMs) : void 0;
45823
+ child.stdout?.on("data", (chunk) => {
45824
+ const remaining = STDOUT_MAX_BYTES - stdoutLength;
45825
+ const length = Math.min(remaining, chunk.length);
45826
+ if (length > 0) {
45827
+ stdout.push(chunk.subarray(0, length));
45828
+ stdoutLength += length;
45829
+ }
45830
+ if (chunk.length > remaining) {
45831
+ outputExceeded = true;
45832
+ child.kill("SIGTERM");
45833
+ }
45834
+ });
45835
+ child.stderr?.on("data", (chunk) => stderr.push(chunk));
45836
+ let settled = false;
45837
+ const settle = (code2, signal) => {
45838
+ if (settled)
45839
+ return;
45840
+ settled = true;
45841
+ if (timer)
45842
+ clearTimeout(timer);
45843
+ resolve18({
45844
+ exitCode: spawnError ? 1 : outputExceeded ? 1 : code2 ?? 1,
45845
+ stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
45846
+ stderr: stderr.toString(),
45847
+ stderrTruncated: stderr.didTruncate,
45848
+ ...spawnError ? { spawnError: true } : {},
45849
+ signal: signal ?? null,
45850
+ timedOut,
45851
+ durationMs: performance.now() - started
45852
+ });
45853
+ };
45854
+ child.once("error", () => {
45855
+ spawnError = true;
45856
+ if (child.pid === void 0)
45857
+ settle(null, null);
44094
45858
  });
45859
+ child.once("close", (code2, signal) => settle(code2, signal));
44095
45860
  });
44096
45861
  }
44097
45862
  };
@@ -44108,6 +45873,56 @@ function runResolvedCommand(runner, platform, file, args, env3, timeoutMs = 15e3
44108
45873
  return runner.run(file, args, { env: env3, timeoutMs });
44109
45874
  }
44110
45875
 
45876
+ // src/common-auth-embedded/setup/command-error.js
45877
+ var PI_INSTALL_ERROR_MESSAGE = "Pi install failed; run pi install after checking your npm connection.";
45878
+ function utf8Tail(value) {
45879
+ const bytes = Buffer.from(value, "utf8");
45880
+ if (bytes.length <= STDERR_TAIL_MAX_BYTES)
45881
+ return value;
45882
+ let start = bytes.length - STDERR_TAIL_MAX_BYTES;
45883
+ while (start < bytes.length) {
45884
+ const byte = bytes[start];
45885
+ if (byte === void 0 || (byte & 192) !== 128)
45886
+ break;
45887
+ start++;
45888
+ }
45889
+ return bytes.subarray(start).toString("utf8");
45890
+ }
45891
+ function dropPartialLine(tail) {
45892
+ const newline = tail.indexOf("\n");
45893
+ return newline < 0 ? "" : tail.slice(newline + 1);
45894
+ }
45895
+ var SetupCommandError = class extends Error {
45896
+ step = "pi-install";
45897
+ exitCode;
45898
+ signal;
45899
+ stderrTail;
45900
+ constructor(details) {
45901
+ super(PI_INSTALL_ERROR_MESSAGE);
45902
+ this.name = "SetupCommandError";
45903
+ this.exitCode = details.exitCode;
45904
+ this.signal = details.signal;
45905
+ const tail = details.stderrTruncated ? dropPartialLine(details.stderrTail) : details.stderrTail;
45906
+ const redacted = redact2(tail);
45907
+ this.stderrTail = utf8Tail(typeof redacted === "string" ? redacted : "");
45908
+ }
45909
+ };
45910
+ var HOST_LABELS = { opencode: "OpenCode", pi: "Pi" };
45911
+ var OUTCOME_TEXT = {
45912
+ enrolled: "connected to the vault",
45913
+ "not-enrolled": "not connected",
45914
+ unknown: "unknown, check with ck auth status"
45915
+ };
45916
+ function setupEnrollmentLine({ host, outcome }) {
45917
+ return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}`;
45918
+ }
45919
+ var recordedEnrollment = /* @__PURE__ */ new WeakMap();
45920
+ function recordSetupEnrollment(failure2, enrollment) {
45921
+ if (typeof failure2 !== "object" && typeof failure2 !== "function" || !failure2)
45922
+ return;
45923
+ recordedEnrollment.set(failure2, Object.freeze(enrollment.map((entry) => Object.freeze({ ...entry }))));
45924
+ }
45925
+
44111
45926
  // src/common-auth-embedded/setup/detect.js
44112
45927
  import { accessSync, constants as constants3, existsSync as existsSync11, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync5 } from "node:fs";
44113
45928
  import { mkdtemp, rm as rm6 } from "node:fs/promises";
@@ -44581,6 +46396,9 @@ async function assertHostsStopped(fence, env3) {
44581
46396
  }
44582
46397
 
44583
46398
  // src/common-auth-embedded/setup/enroll.js
46399
+ var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
46400
+ var HostNotEnrolledError = class extends Error {
46401
+ };
44584
46402
  async function connectSetupHost(plugin2, host, io, terminal, fence) {
44585
46403
  const { name, paths: input2 } = plugin2.vault.hosts[host];
44586
46404
  const paths = hostEnrollmentPaths2(input2);
@@ -44589,7 +46407,7 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
44589
46407
  connectionFile: plugin2.vault.connectionFile,
44590
46408
  handshakeTimeoutMs: 2e3
44591
46409
  }).catch(() => {
44592
- throw new Error("Claustrum connection failed; start ck and rerun setup.");
46410
+ throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.");
44593
46411
  });
44594
46412
  try {
44595
46413
  const manager = new ClaustrumEnrollmentManager2({
@@ -44619,10 +46437,10 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
44619
46437
  return;
44620
46438
  }
44621
46439
  if (status.state !== "pending" && status.state !== "busy")
44622
- throw new Error("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
46440
+ throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
44623
46441
  if (status.state === "pending" && status.requestId && status.requestId !== printedRequest) {
44624
46442
  if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
44625
- throw new Error("Invalid enrollment request id.");
46443
+ throw new HostNotEnrolledError("Invalid enrollment request id.");
44626
46444
  printedRequest = status.requestId;
44627
46445
  printLine2(terminal, "Waiting for approval. In another terminal, run:");
44628
46446
  printLine2(terminal, ` ck auth enroll approve --request-id ${status.requestId} --name ${name}`);
@@ -44630,11 +46448,13 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
44630
46448
  }
44631
46449
  await (io.wait ?? delay)(1e3);
44632
46450
  }
44633
- throw new Error("Claustrum approval is still pending; approve with ck and rerun setup.");
46451
+ throw new HostNotEnrolledError("Claustrum approval is still pending; approve with ck and rerun setup.");
44634
46452
  } catch (error) {
44635
46453
  if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError)
44636
46454
  throw error;
44637
- throw new Error("Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.");
46455
+ if (error instanceof HostNotEnrolledError)
46456
+ throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE);
46457
+ throw new Error(ENROLLMENT_INCOMPLETE_MESSAGE);
44638
46458
  } finally {
44639
46459
  client.close();
44640
46460
  }
@@ -44826,8 +46646,13 @@ async function registerOpenCode(writes, beforeWrite) {
44826
46646
  async function registerPi(plugin2, executable, io = {}) {
44827
46647
  const { platform, env: env3 } = setupPaths(io);
44828
46648
  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.");
46649
+ if (result.exitCode !== 0 || result.timedOut)
46650
+ throw new SetupCommandError({
46651
+ exitCode: result.spawnError ? null : result.exitCode,
46652
+ signal: result.signal ?? null,
46653
+ stderrTail: result.stderr,
46654
+ stderrTruncated: result.stderrTruncated ?? false
46655
+ });
44831
46656
  }
44832
46657
 
44833
46658
  // src/common-auth-embedded/setup/command.js
@@ -44875,6 +46700,22 @@ function validatePlugin(plugin2) {
44875
46700
  throw new Error("Setup requires lowercase vault names containing only letters, digits and dashes.");
44876
46701
  }
44877
46702
  }
46703
+ async function enrollmentReport(plugin2, hosts, recorded) {
46704
+ const report = [];
46705
+ for (const host of hosts) {
46706
+ let outcome = recorded.get(host) ?? "not-enrolled";
46707
+ if (outcome === "unknown") {
46708
+ const { name, paths } = plugin2.vault.hosts[host];
46709
+ const authority = await enrollmentAuthority3(hostEnrollmentPaths2(paths), name).catch(() => "unreadable");
46710
+ if (authority === "vault")
46711
+ outcome = "enrolled";
46712
+ else if (authority === "local")
46713
+ outcome = "not-enrolled";
46714
+ }
46715
+ report.push({ host, outcome });
46716
+ }
46717
+ return report;
46718
+ }
44878
46719
  async function runSetup(plugin2, argv = [], io = {}) {
44879
46720
  const options = flags(argv);
44880
46721
  validatePlugin(plugin2);
@@ -44984,23 +46825,45 @@ ${write.content}`);
44984
46825
  hosts: Object.freeze([...hosts]),
44985
46826
  piAgentDir: detection.pi.directory
44986
46827
  };
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);
46828
+ const enrollment = /* @__PURE__ */ new Map();
46829
+ try {
46830
+ for (const host of hosts) {
46831
+ await stopped();
46832
+ await plugin2.beforeSignIn?.(host, context);
46833
+ await stopped();
46834
+ if (useVault) {
46835
+ enrollment.set(host, "unknown");
46836
+ try {
46837
+ await connectSetupHost(plugin2, host, io, terminal, stopped);
46838
+ } catch (error) {
46839
+ if (error instanceof HostNotEnrolledError)
46840
+ enrollment.set(host, "not-enrolled");
46841
+ throw error;
46842
+ }
46843
+ enrollment.set(host, "enrolled");
46844
+ } else
46845
+ await plugin2.signInLocal(host, context);
46846
+ await stopped();
46847
+ await plugin2.beforeRegister?.(host, mode, context);
46848
+ await stopped();
46849
+ if (host === "opencode")
46850
+ await registerOpenCode(writes, stopped);
46851
+ else
46852
+ await registerPi(plugin2, detection.pi.executable, io);
46853
+ await stopped();
46854
+ await plugin2.migrate(host, context);
46855
+ }
46856
+ } catch (error) {
46857
+ if (enrollment.size === 0)
46858
+ throw error;
46859
+ try {
46860
+ const report = await enrollmentReport(plugin2, hosts, enrollment);
46861
+ recordSetupEnrollment(error, report);
46862
+ for (const entry of report)
46863
+ printLine2(terminal, setupEnrollmentLine(entry));
46864
+ } catch {
46865
+ }
46866
+ throw error;
45004
46867
  }
45005
46868
  }
45006
46869
  printLine2(terminal, `${options.dryRun ? "Planned" : "Configured"} ${plugin2.displayName} for ${hosts.join(", ")} (${mode}).`);
@@ -45666,7 +47529,7 @@ async function runCli(argv, deps) {
45666
47529
  return 1;
45667
47530
  }
45668
47531
  }
45669
- var execFileAsync = promisify(execFile2);
47532
+ var execFileAsync = promisify(execFile);
45670
47533
  async function openBrowserDefault(url) {
45671
47534
  if (process.platform === "win32") {
45672
47535
  await execFileAsync("cmd", ["/c", "start", "", url]);
@@ -49915,7 +51778,7 @@ function createAuthLoader({
49915
51778
  // through the OLD interceptor after an OAuth add. The wrapper
49916
51779
  // matches the host's `LoaderResult.fetch` signature exactly
49917
51780
  // (no `this` binding) so behavior is preserved.
49918
- fetch: async (input2, init) => {
51781
+ fetch: (input2, init) => publishResponse(async (onResponseHandoff) => {
49919
51782
  assertOpen();
49920
51783
  const authority = await readAuthority2?.() ?? "local";
49921
51784
  assertOpen();
@@ -49929,7 +51792,7 @@ function createAuthLoader({
49929
51792
  });
49930
51793
  const vaultRuntime = await vaultFetchRuntime;
49931
51794
  assertOpen();
49932
- return vaultRuntime.fetch(input2, init);
51795
+ return vaultRuntime.fetch(input2, init, onResponseHandoff);
49933
51796
  }
49934
51797
  if (localUnavailable) {
49935
51798
  return fetchWithoutLocalAccounts(input2, init, fetchImpl);
@@ -49953,8 +51816,8 @@ function createAuthLoader({
49953
51816
  return fetchWithoutLocalAccounts(input2, init, fetchImpl);
49954
51817
  if (currentRequestSource !== "local" || !fetchRuntime)
49955
51818
  throw new Error("The local account runtime is unavailable");
49956
- return fetchRuntime.fetch(input2, init);
49957
- }
51819
+ return fetchRuntime.fetch(input2, init, onResponseHandoff);
51820
+ })
49958
51821
  };
49959
51822
  }
49960
51823
  reloadRuntime = async (getAuth) => {
@@ -50692,7 +52555,7 @@ function resolvePluginDependencies(overrides = {}) {
50692
52555
  authorize: overrides.oauth?.authorize ?? authorizeAntigravity,
50693
52556
  exchange: overrides.oauth?.exchange ?? exchangeAntigravity
50694
52557
  };
50695
- const clock = {
52558
+ const clock2 = {
50696
52559
  now: overrides.clock?.now ?? (() => Date.now()),
50697
52560
  random: overrides.clock?.random ?? Math.random,
50698
52561
  sleep: overrides.clock?.sleep ?? defaultSleep
@@ -50702,7 +52565,7 @@ function resolvePluginDependencies(overrides = {}) {
50702
52565
  agyTransport,
50703
52566
  filesystemRoots: roots,
50704
52567
  oauth,
50705
- clock
52568
+ clock: clock2
50706
52569
  };
50707
52570
  }
50708
52571
  async function defaultSleep(ms, signal) {
@@ -50934,9 +52797,11 @@ function createFetchInterceptor(context) {
50934
52797
  body: { type: "oauth", refresh: "", access: "", expires: 0 }
50935
52798
  });
50936
52799
  },
50937
- refreshQuotaAfterSuccess: async (account, intervalMinutes) => {
52800
+ refreshQuotaAfterSuccess: async (account, intervalMinutes, signal) => {
52801
+ signal?.throwIfAborted();
50938
52802
  await context.assertAdmission?.();
50939
- await refreshQuotaAfterSuccess(account, intervalMinutes);
52803
+ signal?.throwIfAborted();
52804
+ await refreshQuotaAfterSuccess(account, intervalMinutes, signal);
50940
52805
  }
50941
52806
  },
50942
52807
  // The trackers the manager selects with: its own for a store-backed
@@ -50955,7 +52820,7 @@ function createFetchInterceptor(context) {
50955
52820
  let retired = false;
50956
52821
  let retirePromise;
50957
52822
  const entering = /* @__PURE__ */ new Set();
50958
- async function intercept(input2, init) {
52823
+ async function intercept(input2, init, onResponseHandoff) {
50959
52824
  await context.assertAdmission?.();
50960
52825
  if (disposed) throw new Error("The local request runtime is disposed");
50961
52826
  if (accountSource.kind === "pool-file") {
@@ -50963,9 +52828,9 @@ function createFetchInterceptor(context) {
50963
52828
  if (disposed) throw new Error("The local request runtime is disposed");
50964
52829
  if (!isOAuthAuth(latestAuth)) return upstreamFetch(input2, init);
50965
52830
  }
50966
- return executor.execute(input2, init);
52831
+ return executor.execute(input2, init, { onResponseHandoff });
50967
52832
  }
50968
- async function fetch(input2, init) {
52833
+ async function fetch(input2, init, onResponseHandoff) {
50969
52834
  if (disposed) {
50970
52835
  return upstreamFetch(input2, init);
50971
52836
  }
@@ -50973,7 +52838,7 @@ function createFetchInterceptor(context) {
50973
52838
  return upstreamFetch(input2, init);
50974
52839
  }
50975
52840
  if (retired) throw new Error("The local request runtime is retired");
50976
- const pending = intercept(input2, init);
52841
+ const pending = intercept(input2, init, onResponseHandoff);
50977
52842
  entering.add(pending);
50978
52843
  void pending.then(
50979
52844
  () => entering.delete(pending),
@@ -51561,7 +53426,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
51561
53426
  if (vaultPool && vaultPool.source === source) return vaultPool;
51562
53427
  vaultPool = {
51563
53428
  source,
51564
- pool: createVaultAccountPool({
53429
+ pool: createOpenCodeVaultAccountPool({
51565
53430
  source,
51566
53431
  durable: { source, readState: () => vaultCustody.readState() }
51567
53432
  })