@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/cli.js CHANGED
@@ -294,8 +294,11 @@ function quotaWindowName(limit) {
294
294
  function clampPercent(remaining) {
295
295
  return Math.min(100, Math.max(0, remaining));
296
296
  }
297
+ function wholePercent(remaining) {
298
+ return Math.round(clampPercent(remaining));
299
+ }
297
300
  function percentLeft(remaining) {
298
- return `${Math.round(clampPercent(remaining))}% left`;
301
+ return `${wholePercent(remaining)}% left`;
299
302
  }
300
303
  function resetDetails(resetsAt, checkedAt, now) {
301
304
  const at = resetsAt === void 0 ? Number.NaN : Date.parse(resetsAt);
@@ -321,6 +324,11 @@ function displayOrder(left, right) {
321
324
  return left.label < right.label ? -1 : left.label > right.label ? 1 : 0;
322
325
  }
323
326
  function quotaWindowParts(quota, options) {
327
+ const { windows, age } = scopedWindowParts(quota, options);
328
+ const parts = windows.map(({ part }) => part);
329
+ return age === void 0 ? { windows: parts } : { windows: parts, age };
330
+ }
331
+ function scopedWindowParts(quota, options) {
324
332
  if (!quota)
325
333
  return { windows: [] };
326
334
  const { now } = options;
@@ -328,12 +336,16 @@ function quotaWindowParts(quota, options) {
328
336
  const windows = readings.map((limit) => {
329
337
  const remainingPercent = clampPercent(limit.remainingPercent ?? 0);
330
338
  return {
331
- kind: "window",
332
- name: quotaWindowName(limit),
333
- figure: percentLeft(limit.remainingPercent ?? 0),
334
- remainingPercent,
335
- checkedAt: limit.checkedAt,
336
- ...resetDetails(limit.resetsAt, limit.checkedAt, now)
339
+ scope: limit.scope,
340
+ ...limit.windowMinutes === void 0 ? {} : { windowMinutes: limit.windowMinutes },
341
+ part: {
342
+ kind: "window",
343
+ name: quotaWindowName(limit),
344
+ figure: percentLeft(limit.remainingPercent ?? 0),
345
+ remainingPercent,
346
+ checkedAt: limit.checkedAt,
347
+ ...resetDetails(limit.resetsAt, limit.checkedAt, now)
348
+ }
337
349
  };
338
350
  });
339
351
  const budget = quota.budget;
@@ -341,23 +353,119 @@ function quotaWindowParts(quota, options) {
341
353
  const remainingPercent = budget.remainingPercent;
342
354
  const figure = budget.reached ? "credits spent" : remainingPercent !== void 0 ? `credits ${percentLeft(remainingPercent)}` : "credits available";
343
355
  windows.push({
344
- kind: "budget",
345
- name: "credits",
346
- figure,
347
- ...remainingPercent === void 0 ? {} : { remainingPercent: clampPercent(remainingPercent) },
348
- checkedAt: budget.checkedAt,
349
- ...resetDetails(budget.resetsAt, budget.checkedAt, now)
356
+ scope: ALL_SCOPE,
357
+ spent: budget.reached,
358
+ part: {
359
+ kind: "budget",
360
+ name: "credits",
361
+ figure,
362
+ ...remainingPercent === void 0 ? {} : { remainingPercent: clampPercent(remainingPercent) },
363
+ checkedAt: budget.checkedAt,
364
+ ...resetDetails(budget.resetsAt, budget.checkedAt, now)
365
+ }
350
366
  });
351
367
  }
352
368
  if (windows.length > 0) {
353
- const age = now - Math.min(...windows.map((part) => part.checkedAt));
369
+ const age = now - Math.min(...windows.map(({ part }) => part.checkedAt));
354
370
  if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
355
371
  return { windows, age: `checked ${shortSpan(age)} ago` };
356
372
  }
357
373
  }
358
374
  return { windows };
359
375
  }
376
+ function isQuotaStale(quota, options) {
377
+ return scopedWindowParts(quota, options).age !== void 0;
378
+ }
379
+ function scopeDisplayName(scope) {
380
+ const model = scope.slice(scope.indexOf(":") + 1);
381
+ return model.charAt(0).toUpperCase() + model.slice(1);
382
+ }
383
+ function scopeAbbreviations(scopes) {
384
+ const names = [...new Set(scopes.map(scopeDisplayName))];
385
+ const lengths = new Map(names.map((name) => [name, 2]));
386
+ const short = (name) => name.slice(0, lengths.get(name));
387
+ for (; ; ) {
388
+ const byShort = /* @__PURE__ */ new Map();
389
+ for (const name of names) {
390
+ byShort.set(short(name), [...byShort.get(short(name)) ?? [], name]);
391
+ }
392
+ let extended = false;
393
+ for (const group of byShort.values()) {
394
+ if (group.length < 2)
395
+ continue;
396
+ for (const name of group) {
397
+ const length = lengths.get(name) ?? 2;
398
+ if (length < name.length) {
399
+ lengths.set(name, length + 1);
400
+ extended = true;
401
+ }
402
+ }
403
+ }
404
+ if (!extended)
405
+ break;
406
+ }
407
+ return new Map(scopes.map((scope) => [scope, short(scopeDisplayName(scope))]));
408
+ }
409
+ function groupShortNames(groups) {
410
+ const labels = groups.map((group) => group.label.trim() || group.scope);
411
+ const short = scopeAbbreviations(labels);
412
+ return labels.map((label) => short.get(label) ?? label);
413
+ }
414
+ function groupedNarrowPieces(groups, windows) {
415
+ if (!groups || groups.length === 0)
416
+ return void 0;
417
+ const reported = windows.filter(({ part }) => part.kind === "window");
418
+ if (reported.some(({ scope }) => scope === ALL_SCOPE))
419
+ return void 0;
420
+ const candidates = groups.flatMap((group, listed) => {
421
+ const inGroup = reported.filter(({ scope }) => scope === group.scope);
422
+ const groupTightest = inGroup.reduce((least, window) => least === void 0 || (window.part.remainingPercent ?? 0) < (least.part.remainingPercent ?? 0) ? window : least, void 0);
423
+ return groupTightest ? [{ group, listed, window: groupTightest }] : [];
424
+ });
425
+ if (candidates.length === 0)
426
+ return void 0;
427
+ const names = groupShortNames(groups);
428
+ const left = (candidate) => candidate.window.part.remainingPercent ?? 0;
429
+ 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);
430
+ return shown.map((candidate, index) => {
431
+ const { windowMinutes } = candidate.window;
432
+ const piece = [
433
+ names[candidate.listed] ?? candidate.group.scope,
434
+ ...windowMinutes === void 0 ? [] : [lengthName(windowMinutes)],
435
+ `${wholePercent(left(candidate))}%`
436
+ ].join(" ");
437
+ return index === shown.length - 1 ? `${piece} left` : piece;
438
+ });
439
+ }
440
+ function narrowTextParts(quota, options) {
441
+ const { windows } = scopedWindowParts(quota, options);
442
+ const grouped = groupedNarrowPieces(quota?.groups, windows);
443
+ if (grouped)
444
+ return grouped;
445
+ const general = windows.filter(({ part, scope }) => part.kind === "window" && scope === ALL_SCOPE);
446
+ const scoped = windows.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE);
447
+ const abbreviations = scopeAbbreviations(scoped.map(({ scope }) => scope));
448
+ const budget = windows.find(({ part }) => part.kind === "budget");
449
+ const budgetLeft = budget?.spent ? 0 : budget?.part.remainingPercent;
450
+ const extras = [
451
+ ...scoped.map(({ scope, part }) => ({
452
+ label: abbreviations.get(scope) ?? scope,
453
+ remaining: part.remainingPercent ?? 0
454
+ })),
455
+ ...budgetLeft === void 0 ? [] : [{ label: "cr", remaining: budgetLeft }]
456
+ ];
457
+ const tightest = extras.reduce((best, item) => best === void 0 || item.remaining < best.remaining ? item : best, void 0);
458
+ const pieces = general.map(({ part }) => `${part.name} ${wholePercent(part.remainingPercent ?? 0)}%`);
459
+ if (tightest) {
460
+ pieces.push(`${tightest.label} ${wholePercent(tightest.remaining)}%`);
461
+ }
462
+ if (pieces.length === 0)
463
+ return windows.map(({ part }) => part.figure);
464
+ return pieces.map((piece, index) => index === pieces.length - 1 ? `${piece} left` : piece);
465
+ }
360
466
  function quotaTextParts(quota, options) {
467
+ if (options.form === "narrow")
468
+ return narrowTextParts(quota, options);
361
469
  const parts = quotaWindowParts(quota, options);
362
470
  const full = (options.form ?? "full") === "full";
363
471
  const text2 = parts.windows.map((part) => {
@@ -372,7 +480,7 @@ function formatQuota(quota, options) {
372
480
  return parts.join(" \xB7 ");
373
481
  return quota && quota.limits.length > 0 ? NO_LIMITS_REPORTED : NO_QUOTA_READING;
374
482
  }
375
- var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED;
483
+ var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED, NARROW_GROUP_LIMIT;
376
484
  var init_format = __esm({
377
485
  "../core/dist/common-auth-embedded/quota/format.js"() {
378
486
  "use strict";
@@ -380,6 +488,7 @@ var init_format = __esm({
380
488
  QUOTA_STALE_AFTER_MS = 15 * 6e4;
381
489
  NO_QUOTA_READING = "no quota reading yet";
382
490
  NO_LIMITS_REPORTED = "no limits reported";
491
+ NARROW_GROUP_LIMIT = 2;
383
492
  }
384
493
  });
385
494
 
@@ -502,6 +611,7 @@ __export(quota_exports, {
502
611
  futureResetAt: () => futureResetAt,
503
612
  isQuotaMap: () => isQuotaMap,
504
613
  isQuotaObservation: () => isQuotaObservation,
614
+ isQuotaStale: () => isQuotaStale,
505
615
  mergeQuotaObservation: () => mergeQuotaObservation,
506
616
  projectQuota: () => projectQuota,
507
617
  quotaCodec: () => quotaCodec2,
@@ -740,19 +850,24 @@ async function replaceWindowsFile(from, to, options = {}) {
740
850
  to = resolve2(to);
741
851
  const now = options.now ?? (() => performance.now());
742
852
  const start = now();
743
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
853
+ const leaseDeadline = options.deadline ?? Infinity;
854
+ let retryDeadline;
744
855
  const delays = [0, 10, 20, 40, 80, 100];
745
856
  let original;
746
857
  let attempts2 = 0;
747
858
  for (const delay3 of delays) {
859
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
748
860
  if (now() >= deadline)
749
861
  break;
750
862
  if (delay3)
751
863
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
752
864
  if (now() >= deadline)
753
865
  break;
866
+ const fenceStart = now();
754
867
  await options.beforeRename?.();
755
- if (now() >= deadline)
868
+ if (retryDeadline !== void 0)
869
+ retryDeadline += now() - fenceStart;
870
+ if (now() >= leaseDeadline)
756
871
  break;
757
872
  attempts2++;
758
873
  try {
@@ -764,6 +879,7 @@ async function replaceWindowsFile(from, to, options = {}) {
764
879
  const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
765
880
  if (!candidate)
766
881
  break;
882
+ retryDeadline ??= now() + 500;
767
883
  }
768
884
  }
769
885
  const error = new PrivateFileError(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
@@ -986,7 +1102,10 @@ function isLostMarkerRaceError(error) {
986
1102
  const code2 = error?.code;
987
1103
  return code2 === "ENOENT" || !windowsPrivateFiles && (code2 === "EINVAL" || code2 === "ENOTDIR");
988
1104
  }
989
- async function acquireRefreshFileLock(options) {
1105
+ function acquireRefreshFileLock(options) {
1106
+ return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
1107
+ }
1108
+ async function acquireRefreshFileLockWithClock(options) {
990
1109
  const lockPath = lockPathFor(options.path, options.name);
991
1110
  const legacyOwnerPath = join4(lockPath, "owner.json");
992
1111
  const ownerId = randomUUID7();
@@ -1708,7 +1827,6 @@ async function acquirePoolLock(spec, defaults, env3) {
1708
1827
  name: spec.name,
1709
1828
  path: spec.path,
1710
1829
  ttlMs: options.ttlMs,
1711
- now: env3.now,
1712
1830
  renew: options.renew,
1713
1831
  onContended: () => emit("contended"),
1714
1832
  ...env3.onRenewalTimer ? {
@@ -4824,7 +4942,6 @@ function openPoolStore(options) {
4824
4942
  ],
4825
4943
  lockDefaults,
4826
4944
  lockEnv: {
4827
- now: options.now ?? Date.now,
4828
4945
  ...options.onLockEvent ? { onLockEvent: options.onLockEvent } : {},
4829
4946
  ...options.onLockStep ? { onLockStep: options.onLockStep } : {},
4830
4947
  ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
@@ -7112,11 +7229,11 @@ var init_doctor = __esm({
7112
7229
 
7113
7230
  // ../core/dist/common-auth-embedded/auth-menu/login.js
7114
7231
  import { execFileSync as defaultExecFileSync, spawn as defaultSpawn } from "node:child_process";
7115
- function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn = defaultSpawn) {
7232
+ function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn2 = defaultSpawn) {
7116
7233
  try {
7117
7234
  if (platform === "win32") {
7118
7235
  const command = `Start-Process '${url.replaceAll("'", "''")}'`;
7119
- const child = spawn("powershell.exe", [
7236
+ const child = spawn2("powershell.exe", [
7120
7237
  "-NoProfile",
7121
7238
  "-NonInteractive",
7122
7239
  "-WindowStyle",
@@ -7937,6 +8054,326 @@ var init_auth_menu = __esm({
7937
8054
  }
7938
8055
  });
7939
8056
 
8057
+ // ../core/dist/common-auth-embedded/claustrum/errors.js
8058
+ var ClaustrumConsumerError;
8059
+ var init_errors2 = __esm({
8060
+ "../core/dist/common-auth-embedded/claustrum/errors.js"() {
8061
+ "use strict";
8062
+ ClaustrumConsumerError = class extends Error {
8063
+ kind;
8064
+ constructor(kind, message) {
8065
+ super(message);
8066
+ this.name = "ClaustrumConsumerError";
8067
+ this.kind = kind;
8068
+ }
8069
+ };
8070
+ }
8071
+ });
8072
+
8073
+ // ../core/dist/common-auth-embedded/claustrum/availability.js
8074
+ import { ClaustrumCredentialError } from "@cortexkit/claustrum-client";
8075
+ import { SocketClosedError, SocketTimeoutError, SubcCallError } from "@cortexkit/subc-client";
8076
+ function classifyVaultFailure(error) {
8077
+ if (error instanceof ClaustrumUnreachableError || error instanceof SocketClosedError || error instanceof SocketTimeoutError)
8078
+ return "unreachable";
8079
+ const code2 = error instanceof ClaustrumCredentialError || error instanceof SubcCallError ? error.code : error instanceof Error && "code" in error ? error.code : void 0;
8080
+ if (typeof code2 !== "string" || !Object.hasOwn(VAULT_FAILURE_CLASSES, code2))
8081
+ return "answered";
8082
+ return VAULT_FAILURE_CLASSES[code2];
8083
+ }
8084
+ var VAULT_FAILURE_CLASSES, ClaustrumUnreachableError;
8085
+ var init_availability = __esm({
8086
+ "../core/dist/common-auth-embedded/claustrum/availability.js"() {
8087
+ "use strict";
8088
+ init_errors2();
8089
+ VAULT_FAILURE_CLASSES = Object.freeze({
8090
+ ECONNREFUSED: "unreachable",
8091
+ ENOENT: "unreachable",
8092
+ ECONNRESET: "unreachable",
8093
+ EPIPE: "unreachable",
8094
+ ETIMEDOUT: "unreachable",
8095
+ transport_error: "unreachable",
8096
+ unavailable: "unreachable",
8097
+ timeout: "unreachable",
8098
+ route_closed: "unreachable",
8099
+ daemon_draining: "unreachable",
8100
+ connection_closed: "unreachable",
8101
+ connection_dropped: "unreachable",
8102
+ request_deadline: "unreachable",
8103
+ deadline_exceeded_no_drop_observed: "unreachable",
8104
+ module_reloading: "unreachable",
8105
+ module_warming: "unreachable",
8106
+ target_unavailable: "unreachable",
8107
+ module_timeout: "unreachable",
8108
+ invalid_response: "answered",
8109
+ invalid_record_version: "answered",
8110
+ invalid_expiry: "answered",
8111
+ invalid_status: "answered",
8112
+ invalid_params: "answered",
8113
+ ttl_unsatisfiable: "answered",
8114
+ not_found: "answered",
8115
+ enrollment_revoked: "answered",
8116
+ enrollment_invalid: "answered",
8117
+ grant_denied: "answered",
8118
+ credential_unavailable: "answered",
8119
+ needs_reauth: "answered",
8120
+ declined: "answered",
8121
+ disabled: "answered",
8122
+ identity_changed: "answered",
8123
+ closed: "answered",
8124
+ client_closed: "answered",
8125
+ pending_exists: "answered",
8126
+ pending_queue_full: "answered",
8127
+ already_consumed: "answered",
8128
+ superseded: "answered",
8129
+ stale_generation: "answered",
8130
+ missing_identity: "answered",
8131
+ invalid_control_body: "answered",
8132
+ unknown_module: "answered",
8133
+ module_removed: "answered",
8134
+ capability_denied: "answered",
8135
+ unknown_channel: "unreachable",
8136
+ stale_route_epoch: "unreachable",
8137
+ capability_forbidden: "answered",
8138
+ capability_unprovided: "answered",
8139
+ capability_ambiguous: "answered",
8140
+ invalid_capability_identifier: "answered",
8141
+ binary_body_required: "answered",
8142
+ binary_call_requires_call_binary: "answered",
8143
+ corr_exhausted: "answered",
8144
+ late_route_cleanup_failed: "answered",
8145
+ reverse_request_capability_not_declared: "answered",
8146
+ stale_route_handle: "answered",
8147
+ reverse_request_unhandled: "answered",
8148
+ handler_error: "answered",
8149
+ health_error: "answered",
8150
+ duplicate_module_id: "answered",
8151
+ route_rejected: "answered",
8152
+ lock_busy: "answered",
8153
+ owner_invalid: "answered",
8154
+ renewal_failed: "answered",
8155
+ unsupported_platform: "answered",
8156
+ EACCES: "answered",
8157
+ EPERM: "answered",
8158
+ ERR_PRIVATE_FILES_SECURITY: "answered"
8159
+ });
8160
+ ClaustrumUnreachableError = class extends ClaustrumConsumerError {
8161
+ constructor() {
8162
+ super("unavailable", "Claustrum scoped operation unavailable");
8163
+ this.name = "ClaustrumUnreachableError";
8164
+ }
8165
+ };
8166
+ }
8167
+ });
8168
+
8169
+ // ../core/dist/common-auth-embedded/claustrum/watch.js
8170
+ var SAFETY_POLL_MS, WATCH_RETRY_MS, RESUBSCRIBE_BACKOFF_MS, ChangeNoticeReader, CoalescedRead, ScopedRosterWatch;
8171
+ var init_watch = __esm({
8172
+ "../core/dist/common-auth-embedded/claustrum/watch.js"() {
8173
+ "use strict";
8174
+ SAFETY_POLL_MS = 5 * 6e4;
8175
+ WATCH_RETRY_MS = 5 * 6e4;
8176
+ RESUBSCRIBE_BACKOFF_MS = 1e3;
8177
+ ChangeNoticeReader = class {
8178
+ #epoch;
8179
+ #seq = 0;
8180
+ /**
8181
+ * Begin a new watch, whose first notice is seq 1 again. The epoch is kept,
8182
+ * so a module restart between two watches still reads as a break.
8183
+ */
8184
+ restart() {
8185
+ this.#seq = 0;
8186
+ }
8187
+ continuous(notice) {
8188
+ const continuous = notice.kind === "changed" && notice.seq === this.#seq + 1 && (this.#epoch === void 0 || notice.epoch === this.#epoch);
8189
+ this.#epoch = notice.epoch;
8190
+ this.#seq = notice.seq;
8191
+ return continuous;
8192
+ }
8193
+ };
8194
+ CoalescedRead = class {
8195
+ #read;
8196
+ #onError;
8197
+ #running;
8198
+ #queued = false;
8199
+ constructor(read, onError) {
8200
+ this.#read = read;
8201
+ this.#onError = onError;
8202
+ }
8203
+ /** The read in flight (including its queued follow-up), if any. */
8204
+ get running() {
8205
+ return this.#running;
8206
+ }
8207
+ request() {
8208
+ if (this.#running) {
8209
+ this.#queued = true;
8210
+ return this.#running;
8211
+ }
8212
+ this.#running = (async () => {
8213
+ do {
8214
+ this.#queued = false;
8215
+ try {
8216
+ await this.#read();
8217
+ } catch (error) {
8218
+ this.#onError(error);
8219
+ }
8220
+ } while (this.#queued);
8221
+ })().finally(() => {
8222
+ this.#running = void 0;
8223
+ });
8224
+ return this.#running;
8225
+ }
8226
+ };
8227
+ ScopedRosterWatch = class {
8228
+ #options;
8229
+ #reader = new ChangeNoticeReader();
8230
+ #reads;
8231
+ #mode = "polling";
8232
+ #watch;
8233
+ #timer;
8234
+ #stopped = false;
8235
+ #latestView;
8236
+ #force = false;
8237
+ /**
8238
+ * How many accepted watches in a row have closed; each one doubles the wait
8239
+ * before the next re-subscribe. Reset once a watch stays up five minutes.
8240
+ */
8241
+ #closes = 0;
8242
+ constructor(options) {
8243
+ this.#options = options;
8244
+ this.#reads = new CoalescedRead(async () => {
8245
+ const force = this.#force;
8246
+ this.#force = false;
8247
+ if (force || this.#latestView !== this.#options.view())
8248
+ await this.#options.discover(this.#latestView ?? "");
8249
+ }, (error) => {
8250
+ if (!this.#stopped)
8251
+ this.#options.onError?.(error);
8252
+ });
8253
+ }
8254
+ get mode() {
8255
+ return this.#mode;
8256
+ }
8257
+ start() {
8258
+ if (this.#stopped || this.#watch || this.#timer)
8259
+ return;
8260
+ if (typeof this.#options.client.watchScoped !== "function") {
8261
+ this.#setMode("fallback", "client-without-watch");
8262
+ return;
8263
+ }
8264
+ void this.#open(false);
8265
+ }
8266
+ stop() {
8267
+ if (this.#stopped)
8268
+ return;
8269
+ this.#stopped = true;
8270
+ if (this.#timer)
8271
+ (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
8272
+ this.#timer = void 0;
8273
+ const watch = this.#watch;
8274
+ this.#watch = void 0;
8275
+ watch?.handle.stop();
8276
+ }
8277
+ #setMode(mode, reason) {
8278
+ if (this.#mode === mode)
8279
+ return;
8280
+ this.#mode = mode;
8281
+ this.#options.logger?.debug("claustrum vault watch", { mode, reason });
8282
+ this.#options.onMode?.(mode);
8283
+ }
8284
+ #later(delay3, run) {
8285
+ this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
8286
+ this.#timer = void 0;
8287
+ if (!this.#stopped)
8288
+ run();
8289
+ }, delay3);
8290
+ this.#timer.unref?.();
8291
+ }
8292
+ async #open(resubscribed) {
8293
+ let token;
8294
+ try {
8295
+ token = await this.#options.enrollmentToken();
8296
+ } catch (error) {
8297
+ if (this.#stopped)
8298
+ return;
8299
+ this.#options.onError?.(error);
8300
+ this.#fallback("token-unreadable");
8301
+ return;
8302
+ }
8303
+ const watchScoped = this.#options.client.watchScoped;
8304
+ if (this.#stopped || this.#watch || !watchScoped)
8305
+ return;
8306
+ this.#reader.restart();
8307
+ this.#force = resubscribed;
8308
+ let watch;
8309
+ let handle;
8310
+ try {
8311
+ handle = watchScoped.call(this.#options.client, (notice) => {
8312
+ if (this.#stopped || !watch || this.#watch !== watch)
8313
+ return;
8314
+ watch.notices++;
8315
+ if (watch.notices === 1) {
8316
+ this.#options.onReachable?.();
8317
+ watch.acceptedAt = (this.#options.now ?? Date.now)();
8318
+ this.#setMode("watching", "accepted");
8319
+ }
8320
+ if (!this.#reader.continuous(notice))
8321
+ this.#force = true;
8322
+ this.#latestView = notice.view;
8323
+ void this.#reads.request();
8324
+ }, { enrollmentToken: token });
8325
+ } catch (error) {
8326
+ this.#options.onError?.(error);
8327
+ this.#fallback("watch-failed");
8328
+ return;
8329
+ }
8330
+ watch = { handle, notices: 0 };
8331
+ this.#watch = watch;
8332
+ this.#setMode("polling", resubscribed ? "resubscribing" : "opening");
8333
+ const opened = watch;
8334
+ handle.closed.then((end) => this.#closed(opened, end), (error) => this.#closed(opened, { kind: "transport_lost", error }));
8335
+ }
8336
+ #closed(watch, end) {
8337
+ if (this.#stopped || this.#watch !== watch)
8338
+ return;
8339
+ this.#watch = void 0;
8340
+ if (end.kind === "stopped")
8341
+ return;
8342
+ if (end.kind === "transport_lost")
8343
+ this.#options.onTransportLost?.();
8344
+ if (end.kind === "unsupported") {
8345
+ this.#setMode("fallback", "vault-without-watch");
8346
+ return;
8347
+ }
8348
+ if (end.kind === "refused") {
8349
+ this.#fallback("refused");
8350
+ try {
8351
+ this.#options.onRefused(end.error);
8352
+ } catch (error) {
8353
+ this.#options.onError?.(error);
8354
+ }
8355
+ return;
8356
+ }
8357
+ if (watch.notices > 0) {
8358
+ const now = (this.#options.now ?? Date.now)();
8359
+ if (watch.acceptedAt !== void 0 && now - watch.acceptedAt >= SAFETY_POLL_MS)
8360
+ this.#closes = 0;
8361
+ const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
8362
+ this.#closes++;
8363
+ this.#setMode("polling", "resubscribing");
8364
+ this.#later(delay3, () => void this.#open(true));
8365
+ return;
8366
+ }
8367
+ this.#fallback(end.kind);
8368
+ }
8369
+ #fallback(reason) {
8370
+ this.#setMode("fallback", reason);
8371
+ this.#later(WATCH_RETRY_MS, () => void this.#open(false));
8372
+ }
8373
+ };
8374
+ }
8375
+ });
8376
+
7940
8377
  // ../core/dist/common-auth-embedded/claustrum/insula.js
7941
8378
  import { resolve as resolve4 } from "node:path";
7942
8379
  import { storeIdentity } from "@cortexkit/claustrum-client";
@@ -7975,12 +8412,95 @@ function insulaUsageTransport(options) {
7975
8412
  clearTimeout(timer);
7976
8413
  client?.close();
7977
8414
  }
8415
+ },
8416
+ watchUsage(onNotice) {
8417
+ let client;
8418
+ let subscription;
8419
+ let stopped = false;
8420
+ const closed = (async () => {
8421
+ let deadline;
8422
+ const timeout = new Promise((_resolve, reject) => {
8423
+ deadline = setTimeout(
8424
+ // Coded as a timeout, so InsulaQuotaSource treats a watch that could
8425
+ // not open in time as an unreachable insula and tries again later,
8426
+ // not as a refusal.
8427
+ () => reject(Object.assign(new Error("insula watch timeout"), {
8428
+ code: "timeout"
8429
+ })),
8430
+ 3e3
8431
+ );
8432
+ deadline.unref?.();
8433
+ });
8434
+ const open12 = (async () => {
8435
+ const handshakeTimeoutMs = Math.min(options.handshakeTimeoutMs ?? 3e3, 3e3);
8436
+ const connected = options.connector ? await options.connector({
8437
+ connectionFile: options.connectionFile,
8438
+ handshakeTimeoutMs
8439
+ }) : await SubcClient.connect({
8440
+ connectionFile: options.connectionFile,
8441
+ handshakeTimeoutMs
8442
+ });
8443
+ client = connected;
8444
+ if (stopped) {
8445
+ connected.close();
8446
+ return;
8447
+ }
8448
+ const route = await connected.routeOpen({ kind: "management_surface", module_id: "insula" }, identity);
8449
+ if (stopped) {
8450
+ connected.close();
8451
+ return;
8452
+ }
8453
+ subscription = connected.subscribe(route, { method: "usage.watch" }, onNotice);
8454
+ })();
8455
+ try {
8456
+ await Promise.race([open12, timeout]);
8457
+ } catch (error) {
8458
+ stopped = true;
8459
+ throw error;
8460
+ } finally {
8461
+ clearTimeout(deadline);
8462
+ }
8463
+ if (subscription)
8464
+ await subscription.closed;
8465
+ })().finally(() => {
8466
+ stopped = true;
8467
+ client?.close();
8468
+ });
8469
+ return {
8470
+ stop() {
8471
+ if (stopped)
8472
+ return;
8473
+ stopped = true;
8474
+ subscription?.unsubscribe();
8475
+ client?.close();
8476
+ },
8477
+ closed
8478
+ };
7978
8479
  }
7979
8480
  };
7980
8481
  }
7981
8482
  function record2(value) {
7982
8483
  return typeof value === "object" && value !== null && !Array.isArray(value);
7983
8484
  }
8485
+ function decodeUsageNotice(body) {
8486
+ let value;
8487
+ try {
8488
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
8489
+ } catch {
8490
+ return void 0;
8491
+ }
8492
+ 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")
8493
+ return void 0;
8494
+ return {
8495
+ kind: value.kind,
8496
+ epoch: value.epoch,
8497
+ seq: value.seq,
8498
+ ...typeof value.provider === "string" && { provider: value.provider }
8499
+ };
8500
+ }
8501
+ function refusalCode(error) {
8502
+ return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : void 0;
8503
+ }
7984
8504
  function acquireInsulaQuotaSource(transport, tokenPath) {
7985
8505
  const key = JSON.stringify([
7986
8506
  resolve4(transport.connectionFile),
@@ -8008,6 +8528,8 @@ var MINUTE, MAX_AGE, sources, attempts, InsulaQuotaSource;
8008
8528
  var init_insula = __esm({
8009
8529
  "../core/dist/common-auth-embedded/claustrum/insula.js"() {
8010
8530
  "use strict";
8531
+ init_availability();
8532
+ init_watch();
8011
8533
  MINUTE = 6e4;
8012
8534
  MAX_AGE = 4 * MINUTE;
8013
8535
  sources = /* @__PURE__ */ new Map();
@@ -8016,14 +8538,52 @@ var init_insula = __esm({
8016
8538
  transport;
8017
8539
  key;
8018
8540
  #entries = [];
8019
- #pending;
8541
+ /** Every usage.get, polled or watch-driven, shares this one slot. */
8542
+ #reads = new CoalescedRead(async () => {
8543
+ try {
8544
+ const reply = await this.transport.getUsage();
8545
+ if (!record2(reply) || !Array.isArray(reply.result) || reply.error !== void 0)
8546
+ throw new Error("unavailable insula usage");
8547
+ this.#entries = reply.result.filter((entry) => record2(entry) && typeof entry.provider === "string");
8548
+ } catch {
8549
+ this.#entries = [];
8550
+ }
8551
+ }, () => {
8552
+ });
8553
+ #reader = new ChangeNoticeReader();
8554
+ #mode = "polling";
8555
+ #watchers = 0;
8556
+ /**
8557
+ * How many registered watchers read every provider. Watchers limited to one
8558
+ * provider are counted per provider in `#providers` instead.
8559
+ */
8560
+ #everyProvider = 0;
8561
+ #providers = /* @__PURE__ */ new Map();
8562
+ #watch;
8563
+ #timer;
8564
+ #timers = {};
8565
+ /**
8566
+ * How many accepted watches in a row have closed; each one doubles the wait
8567
+ * before the next re-subscribe. Reset once a watch brings a second notice.
8568
+ */
8569
+ #closes = 0;
8020
8570
  constructor(transport, key) {
8021
8571
  this.transport = transport;
8022
8572
  this.key = key;
8023
8573
  }
8574
+ /**
8575
+ * The background poll: at most one usage.get per minute per daemon and
8576
+ * enrollment token. While a watch is open it reads nothing, because insula's
8577
+ * notices announce every new reading. If insula stops announcing an account,
8578
+ * that account's last entry grows older than the freshness limit `current()`
8579
+ * applies, `current()` returns nothing for it, and the plugin falls back to
8580
+ * its own provider poll for that account.
8581
+ */
8024
8582
  refresh(now) {
8025
- if (this.#pending)
8026
- return this.#pending;
8583
+ if (this.#reads.running)
8584
+ return this.#reads.running;
8585
+ if (this.#mode === "watching")
8586
+ return Promise.resolve();
8027
8587
  for (const [key, time] of attempts) {
8028
8588
  if (now - time >= MINUTE)
8029
8589
  attempts.delete(key);
@@ -8032,19 +8592,119 @@ var init_insula = __esm({
8032
8592
  if (lastAttempt !== void 0 && now - lastAttempt < MINUTE)
8033
8593
  return Promise.resolve();
8034
8594
  attempts.set(this.key, now);
8035
- this.#pending = (async () => {
8036
- try {
8037
- const reply = await this.transport.getUsage();
8038
- if (!record2(reply) || !Array.isArray(reply.result) || reply.error !== void 0)
8039
- throw new Error("unavailable insula usage");
8040
- this.#entries = reply.result.filter((entry) => record2(entry) && typeof entry.provider === "string");
8041
- } catch {
8042
- this.#entries = [];
8595
+ return this.#reads.request();
8596
+ }
8597
+ /** How this source currently learns about usage changes, for logs. */
8598
+ watchMode() {
8599
+ return this.#mode;
8600
+ }
8601
+ /**
8602
+ * Hold a `usage.watch` open while any watcher wants it, and re-read
8603
+ * usage.get when a notice says something changed. Watchers of one source
8604
+ * share one watch, since insula admits only 64 per process. Returns the
8605
+ * release; the last release closes the watch.
8606
+ */
8607
+ watch(options = {}) {
8608
+ this.#watchers++;
8609
+ const provider2 = options.provider;
8610
+ if (provider2 === void 0)
8611
+ this.#everyProvider++;
8612
+ else
8613
+ this.#providers.set(provider2, (this.#providers.get(provider2) ?? 0) + 1);
8614
+ if (this.#watchers === 1) {
8615
+ this.#timers = options;
8616
+ this.#open();
8617
+ }
8618
+ let released = false;
8619
+ return () => {
8620
+ if (released)
8621
+ return;
8622
+ released = true;
8623
+ if (provider2 === void 0)
8624
+ this.#everyProvider--;
8625
+ else {
8626
+ const left = (this.#providers.get(provider2) ?? 1) - 1;
8627
+ if (left > 0)
8628
+ this.#providers.set(provider2, left);
8629
+ else
8630
+ this.#providers.delete(provider2);
8043
8631
  }
8044
- })().finally(() => {
8045
- this.#pending = void 0;
8046
- });
8047
- return this.#pending;
8632
+ if (--this.#watchers === 0)
8633
+ this.#stopWatch();
8634
+ };
8635
+ }
8636
+ #stopWatch() {
8637
+ if (this.#timer)
8638
+ (this.#timers.clearTimeoutImpl ?? clearTimeout)(this.#timer);
8639
+ this.#timer = void 0;
8640
+ const watch = this.#watch;
8641
+ this.#watch = void 0;
8642
+ watch?.handle?.stop();
8643
+ this.#mode = "polling";
8644
+ }
8645
+ #later(delay3) {
8646
+ this.#timer = (this.#timers.setTimeoutImpl ?? setTimeout)(() => {
8647
+ this.#timer = void 0;
8648
+ if (this.#watchers > 0 && !this.#watch)
8649
+ this.#open();
8650
+ }, delay3);
8651
+ this.#timer.unref?.();
8652
+ }
8653
+ #open() {
8654
+ const watchUsage = this.transport.watchUsage;
8655
+ if (!watchUsage) {
8656
+ this.#mode = "fallback";
8657
+ return;
8658
+ }
8659
+ this.#mode = "polling";
8660
+ this.#reader.restart();
8661
+ const watch = { notices: 0 };
8662
+ this.#watch = watch;
8663
+ let handle;
8664
+ try {
8665
+ handle = watchUsage.call(this.transport, (body) => this.#notice(watch, body));
8666
+ } catch (error) {
8667
+ this.#closed(watch, error);
8668
+ return;
8669
+ }
8670
+ watch.handle = handle;
8671
+ handle.closed.then(() => this.#closed(watch, void 0), (error) => this.#closed(watch, error));
8672
+ }
8673
+ #notice(watch, body) {
8674
+ if (this.#watch !== watch)
8675
+ return;
8676
+ watch.notices++;
8677
+ if (watch.notices === 1)
8678
+ this.#mode = "watching";
8679
+ if (watch.notices === 2)
8680
+ this.#closes = 0;
8681
+ const notice = decodeUsageNotice(body);
8682
+ if (!notice)
8683
+ this.#reader.restart();
8684
+ const continuous = notice ? this.#reader.continuous(notice) : false;
8685
+ if (!continuous || notice?.provider === void 0 || this.#everyProvider > 0 || this.#providers.has(notice.provider))
8686
+ void this.#reads.request();
8687
+ }
8688
+ #closed(watch, error) {
8689
+ if (this.#watch !== watch)
8690
+ return;
8691
+ this.#watch = void 0;
8692
+ const code2 = refusalCode(error);
8693
+ if (code2 === "unknown_method" || code2 === "usage_watch_limit") {
8694
+ this.#mode = "fallback";
8695
+ return;
8696
+ }
8697
+ if (watch.notices > 0) {
8698
+ const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
8699
+ this.#closes++;
8700
+ this.#mode = "polling";
8701
+ this.#later(delay3);
8702
+ return;
8703
+ }
8704
+ this.#mode = "fallback";
8705
+ void this.#reads.request();
8706
+ if (error === void 0 || classifyVaultFailure(error) === "unreachable")
8707
+ this.#later(WATCH_RETRY_MS);
8048
8708
  }
8049
8709
  current(provider2, accountId, now) {
8050
8710
  for (const entry of this.#entries) {
@@ -8111,30 +8771,14 @@ var init_any_signal = __esm({
8111
8771
  }
8112
8772
  });
8113
8773
 
8114
- // ../core/dist/common-auth-embedded/claustrum/errors.js
8115
- var ClaustrumConsumerError;
8116
- var init_errors2 = __esm({
8117
- "../core/dist/common-auth-embedded/claustrum/errors.js"() {
8118
- "use strict";
8119
- ClaustrumConsumerError = class extends Error {
8120
- kind;
8121
- constructor(kind, message) {
8122
- super(message);
8123
- this.name = "ClaustrumConsumerError";
8124
- this.kind = kind;
8125
- }
8126
- };
8127
- }
8128
- });
8129
-
8130
8774
  // ../core/dist/common-auth-embedded/claustrum/enrollment.js
8131
8775
  import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID10 } from "node:crypto";
8132
8776
  import { constants as fsConstants } from "node:fs";
8133
8777
  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";
8134
8778
  import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join5, resolve as resolve5 } from "node:path";
8135
- import { ClaustrumCredentialError, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8779
+ import { ClaustrumCredentialError as ClaustrumCredentialError2, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8136
8780
  function classifyEnrollmentError(error) {
8137
- if (!(error instanceof ClaustrumCredentialError))
8781
+ if (!(error instanceof ClaustrumCredentialError2))
8138
8782
  return void 0;
8139
8783
  if (TERMINAL_ENROLLMENT_CODES.has(error.code))
8140
8784
  return { code: error.code, disposition: "terminal" };
@@ -8835,9 +9479,9 @@ var init_host_slot = __esm({
8835
9479
  });
8836
9480
 
8837
9481
  // ../core/dist/common-auth-embedded/claustrum/custody.js
8838
- import { ClaustrumCredentialError as ClaustrumCredentialError2 } from "@cortexkit/claustrum-client";
9482
+ import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
8839
9483
  function isScopedCredentialRotation(served, current) {
8840
- return current !== void 0 && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
9484
+ return current !== void 0 && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
8841
9485
  }
8842
9486
  function scopedRetryReason(served, current) {
8843
9487
  if (current === void 0)
@@ -8896,16 +9540,28 @@ function credentialTypeOf(row, family) {
8896
9540
  return row.refreshAdapter === void 0 ? "api_key" : void 0;
8897
9541
  return void 0;
8898
9542
  }
8899
- var defaultLogger, SERVING_MARGIN_MS, ClaustrumScopedCustody;
9543
+ function grantReachOf(listed) {
9544
+ const { grants, grantTuples } = listed;
9545
+ if (grants === void 0 || grantTuples === void 0)
9546
+ return void 0;
9547
+ return Object.freeze({
9548
+ grants,
9549
+ tuples: Object.freeze(grantTuples.map(({ selectorKind, selector, operation }) => Object.freeze({ selectorKind, selector, operation })))
9550
+ });
9551
+ }
9552
+ var defaultLogger, SERVING_MARGIN_MS, KEPT_RECEIPT_MARGIN_MS, ClaustrumScopedCustody;
8900
9553
  var init_custody = __esm({
8901
9554
  "../core/dist/common-auth-embedded/claustrum/custody.js"() {
8902
9555
  "use strict";
8903
9556
  init_logger();
9557
+ init_availability();
8904
9558
  init_enrollment();
8905
9559
  init_errors2();
8906
9560
  init_host_slot();
9561
+ init_watch();
8907
9562
  defaultLogger = createLogger2("claustrum");
8908
9563
  SERVING_MARGIN_MS = 3e5;
9564
+ KEPT_RECEIPT_MARGIN_MS = 6e4;
8909
9565
  ClaustrumScopedCustody = class {
8910
9566
  #client;
8911
9567
  #readToken;
@@ -8916,7 +9572,20 @@ var init_custody = __esm({
8916
9572
  #logger;
8917
9573
  #provenance = /* @__PURE__ */ new WeakMap();
8918
9574
  #reports = /* @__PURE__ */ new WeakMap();
9575
+ #kept = /* @__PURE__ */ new Map();
9576
+ #keptAttempts = /* @__PURE__ */ new WeakMap();
9577
+ #setTimeout;
9578
+ #clearTimeout;
9579
+ #outage = false;
9580
+ #outageError = new ClaustrumUnreachableError();
9581
+ #probeTimer;
9582
+ #probing = false;
9583
+ #lastProbeAt = -Infinity;
9584
+ #probeDelay = 2e3;
8919
9585
  #closed = false;
9586
+ /** The view of the last successful `discover()`, for `watchRoster`. */
9587
+ #discoveredView;
9588
+ #watches = /* @__PURE__ */ new Set();
8920
9589
  constructor(options) {
8921
9590
  const tokenPath = options.tokenPath;
8922
9591
  if (options.readToken) {
@@ -8932,6 +9601,56 @@ var init_custody = __esm({
8932
9601
  this.#requireAssertion = options.requireAssertion ?? false;
8933
9602
  this.#now = options.now ?? Date.now;
8934
9603
  this.#logger = options.logger ?? defaultLogger;
9604
+ this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
9605
+ this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
9606
+ }
9607
+ /** A watch losing its transport is the same outage as an unreachable read. */
9608
+ transportLost(error) {
9609
+ if (this.#closed || this.#outage)
9610
+ return;
9611
+ this.#outage = true;
9612
+ this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError();
9613
+ this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
9614
+ this.#scheduleProbe();
9615
+ }
9616
+ /** Any vault answer ends transport fallback, even when it refuses access. */
9617
+ reachable() {
9618
+ if (this.#closed || !this.#outage)
9619
+ return;
9620
+ this.#outage = false;
9621
+ if (this.#probeTimer)
9622
+ this.#clearTimeout(this.#probeTimer);
9623
+ this.#probeTimer = void 0;
9624
+ this.#probeDelay = 2e3;
9625
+ for (const kept of this.#kept.values())
9626
+ kept.since = null;
9627
+ (this.#logger.info ?? defaultLogger.info)("vault receipt serving resumed", { reason: "reachable" });
9628
+ }
9629
+ #scheduleProbe() {
9630
+ if (this.#closed || !this.#outage || this.#probeTimer || this.#probing)
9631
+ return;
9632
+ this.#probeTimer = this.#setTimeout(() => {
9633
+ this.#probeTimer = void 0;
9634
+ this.#probe(true);
9635
+ }, this.#probeDelay);
9636
+ this.#probeTimer.unref?.();
9637
+ }
9638
+ #probe(idle = false) {
9639
+ if (this.#closed || !this.#outage || this.#probing)
9640
+ return;
9641
+ if (this.#now() - this.#lastProbeAt < 1e3) {
9642
+ this.#scheduleProbe();
9643
+ return;
9644
+ }
9645
+ this.#lastProbeAt = this.#now();
9646
+ this.#probing = true;
9647
+ void this.#list().catch(() => {
9648
+ if (idle && this.#outage)
9649
+ this.#probeDelay = Math.min(this.#probeDelay * 2, 3e4);
9650
+ }).finally(() => {
9651
+ this.#probing = false;
9652
+ this.#scheduleProbe();
9653
+ });
8935
9654
  }
8936
9655
  #check(signal) {
8937
9656
  if (this.#closed)
@@ -8965,13 +9684,20 @@ var init_custody = __esm({
8965
9684
  ]) : await pending;
8966
9685
  } catch (error) {
8967
9686
  this.#check(signal);
8968
- if (error instanceof ClaustrumCredentialError2)
9687
+ if (classifyVaultFailure(error) === "unreachable")
9688
+ this.transportLost(error);
9689
+ else
9690
+ this.reachable();
9691
+ if (error instanceof ClaustrumCredentialError3)
8969
9692
  throw error;
9693
+ if (classifyVaultFailure(error) === "unreachable")
9694
+ throw new ClaustrumUnreachableError();
8970
9695
  throw new ClaustrumConsumerError("unavailable", "Claustrum scoped operation unavailable");
8971
9696
  } finally {
8972
9697
  removeAbortListener?.();
8973
9698
  }
8974
9699
  this.#check(signal);
9700
+ this.reachable();
8975
9701
  return result;
8976
9702
  }
8977
9703
  /**
@@ -8981,8 +9707,25 @@ var init_custody = __esm({
8981
9707
  * skipped records: they simply are not this consumer's.
8982
9708
  */
8983
9709
  async discover(signal) {
8984
- const token = await this.#token(signal);
8985
- const inventory = await this.#call(() => this.#client.listScoped(token), signal);
9710
+ const inventory = await this.#list(signal);
9711
+ this.#discoveredView = inventory.view;
9712
+ return inventory;
9713
+ }
9714
+ async #list(signal) {
9715
+ let inventory;
9716
+ let token;
9717
+ try {
9718
+ token = await this.#token(signal);
9719
+ } catch (error) {
9720
+ this.#kept.clear();
9721
+ throw error;
9722
+ }
9723
+ try {
9724
+ inventory = await this.#call(() => this.#client.listScoped(token), signal);
9725
+ } catch (error) {
9726
+ this.listFailed(error);
9727
+ throw error;
9728
+ }
8986
9729
  const skipped = [];
8987
9730
  const candidates = [];
8988
9731
  const counts = /* @__PURE__ */ new Map();
@@ -9021,28 +9764,114 @@ var init_custody = __esm({
9021
9764
  }
9022
9765
  for (const record3 of skipped)
9023
9766
  this.#logger.warn("skipped malformed vault record", record3);
9767
+ const grantReach = grantReachOf(inventory);
9024
9768
  return {
9025
9769
  view: inventory.view,
9026
9770
  credentials: Object.freeze(credentials),
9027
- skipped: Object.freeze(skipped)
9771
+ skipped: Object.freeze(skipped),
9772
+ ...grantReach && { grantReach }
9028
9773
  };
9029
9774
  }
9030
9775
  /**
9031
- * Fetch the credential for one physical send and wrap it in a fresh receipt.
9032
- * The vault's served identity (or, without one, the plugin's parse of the
9033
- * token) must equal the roster's when both are present. Without
9034
- * `requireAssertion`, absence on either side proves nothing and does not
9035
- * refuse; the receipt records what the vault asserted separately from what
9036
- * the roster expected. With it, a reply that does not itself name the
9037
- * credential id and the expected account is refused.
9776
+ * Apply a failed account listing: any answer from the vault (a refusal such
9777
+ * as a revoked enrollment's `not_found`) drops every kept receipt, while an
9778
+ * unreachable vault keeps them. A vault watch that ends with the same
9779
+ * refusal calls this too, so both paths treat it alike.
9038
9780
  */
9039
- async authorize(identity, signal) {
9781
+ listFailed(error) {
9782
+ if (classifyVaultFailure(error) === "unreachable")
9783
+ this.transportLost(error);
9784
+ else {
9785
+ this.reachable();
9786
+ this.#kept.clear();
9787
+ }
9788
+ }
9789
+ /** Discard bearer material when a route is removed, declined or rebound. */
9790
+ forget(credentialId) {
9791
+ this.#kept.delete(credentialId);
9792
+ }
9793
+ /** Apply an already-held roster; this never fetches credentials or writes it. */
9794
+ retain(identities) {
9795
+ const current = new Map(identities.map((identity) => [identity.credentialId, identity]));
9796
+ for (const [id, kept] of this.#kept) {
9797
+ const identity = current.get(id);
9798
+ if (!identity?.enabled || identity.state !== "active" || identity.credentialType !== kept.attempt.credentialType || identity.accountIdentity !== kept.attempt.expectedAccountIdentity)
9799
+ this.forget(id);
9800
+ }
9801
+ }
9802
+ /** A frozen, non-secret summary for a plugin's status display. */
9803
+ keptReceiptState() {
9804
+ let since = null;
9805
+ for (const [id, kept] of this.#kept) {
9806
+ if (!this.#usable(kept.attempt)) {
9807
+ this.forget(id);
9808
+ continue;
9809
+ }
9810
+ if (kept.since !== null)
9811
+ since = Math.min(since ?? kept.since, kept.since);
9812
+ }
9813
+ return Object.freeze({ active: since !== null, since });
9814
+ }
9815
+ #usable(attempt) {
9816
+ return attempt.expiresAtMs === null ? attempt.credentialType === "api_key" : attempt.expiresAtMs - this.#now() > KEPT_RECEIPT_MARGIN_MS;
9817
+ }
9818
+ /** Ask the vault while reachable; retain one validated receipt in memory only. */
9819
+ async authorize(identity, signal, routeId = "vault") {
9820
+ this.#check(signal);
9821
+ const { credentialId, credentialType, accountIdentity } = identity;
9822
+ let kept = this.#kept.get(credentialId);
9823
+ if (kept && (kept.attempt.credentialType !== credentialType || kept.attempt.expectedAccountIdentity !== accountIdentity)) {
9824
+ this.forget(credentialId);
9825
+ kept = void 0;
9826
+ }
9827
+ let token;
9828
+ try {
9829
+ token = await this.#token(signal);
9830
+ } catch (error) {
9831
+ this.#kept.clear();
9832
+ throw error;
9833
+ }
9834
+ if (this.#outage && kept) {
9835
+ this.#probe();
9836
+ return this.#serveKept(credentialId, kept, token, routeId);
9837
+ }
9838
+ try {
9839
+ const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
9840
+ this.#kept.set(credentialId, { attempt, routeId, since: null });
9841
+ return attempt;
9842
+ } catch (error) {
9843
+ this.#check(signal);
9844
+ if (classifyVaultFailure(error) !== "unreachable") {
9845
+ this.forget(credentialId);
9846
+ throw error;
9847
+ }
9848
+ return this.#serveKept(credentialId, kept, token, routeId, error);
9849
+ }
9850
+ }
9851
+ #serveKept(credentialId, kept, token, routeId, error = this.#outageError) {
9852
+ if (!kept || this.#kept.get(credentialId) !== kept || !this.#usable(kept.attempt)) {
9853
+ this.forget(credentialId);
9854
+ throw error;
9855
+ }
9856
+ if (kept.since === null)
9857
+ kept.since = this.#now();
9858
+ const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, "accessToken", { value: kept.attempt.accessToken, enumerable: false }));
9859
+ this.#provenance.set(attempt, token);
9860
+ this.#keptAttempts.set(attempt, routeId);
9861
+ return attempt;
9862
+ }
9863
+ /**
9864
+ * Fetch and validate a fresh receipt before retaining it. The vault assertion
9865
+ * (or the plugin's token parse) must agree with the roster when both exist.
9866
+ * With requireAssertion, an absent assertion also refuses rather than
9867
+ * treating the roster's expectation as proof of the served account.
9868
+ */
9869
+ async #authorizeFresh(identity, token, signal) {
9040
9870
  if (!identity.credentialId)
9041
9871
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum dispatch requires a credential id");
9042
9872
  const { credentialId, credentialType, accountIdentity } = identity;
9043
9873
  if (this.#requireAssertion && accountIdentity === void 0)
9044
9874
  throw new ClaustrumConsumerError("identity-unasserted", "Claustrum dispatch requires a known account identity");
9045
- const token = await this.#token(signal);
9046
9875
  const served = await this.#call(() => this.#client.getScoped({
9047
9876
  credentialId,
9048
9877
  enrollmentToken: token,
@@ -9105,6 +9934,18 @@ var init_custody = __esm({
9105
9934
  const token = this.#provenance.get(attempt);
9106
9935
  if (!token)
9107
9936
  throw new ClaustrumConsumerError("no-receipt", "Claustrum failure report requires an original dispatch receipt");
9937
+ const keptRoute = this.#keptAttempts.get(attempt);
9938
+ if (keptRoute !== void 0) {
9939
+ this.forget(attempt.credentialId);
9940
+ this.#logger.debug("scoped 401 not reported", {
9941
+ routeId: keptRoute,
9942
+ reason: "kept-receipt"
9943
+ });
9944
+ return;
9945
+ }
9946
+ const kept = this.#kept.get(attempt.credentialId);
9947
+ if (kept && kept.attempt.recordVersion === attempt.recordVersion)
9948
+ this.forget(attempt.credentialId);
9108
9949
  const pending = this.#reports.get(attempt);
9109
9950
  if (pending)
9110
9951
  return pending;
@@ -9128,10 +9969,70 @@ var init_custody = __esm({
9128
9969
  throw error;
9129
9970
  }
9130
9971
  }
9972
+ /**
9973
+ * Watch this consumer's visible vault accounts instead of listing them on a
9974
+ * short timer. Opens one `watchScoped` on this custody's client and calls
9975
+ * `onView` when the host must run its discovery (see
9976
+ * `ClaustrumRosterWatchOptions`). A claustrum-client without `watchScoped`
9977
+ * (before 0.12.0) or a vault that answers `unknown_method` reports
9978
+ * `fallback` and opens nothing. A watch that closes before any notice was
9979
+ * never accepted: the client reads once to learn why, and the watch reports
9980
+ * `fallback` and tries one new watch after `WATCH_RETRY_MS`, never in a
9981
+ * loop. A watch that closes after notices is re-opened after
9982
+ * `RESUBSCRIBE_BACKOFF_MS`, doubling per close in a row. A lost transport
9983
+ * starts this custody's outage, exactly as an unreachable call does, and
9984
+ * the first notice of a watch ends it. Timers are unreferenced; `close()`
9985
+ * on the returned watch or on this custody stops it.
9986
+ *
9987
+ * The watch keeps no history, so the host still lists on a slow timer while
9988
+ * the mode is `watching`: every `SAFETY_POLL_MS` (five minutes). In any
9989
+ * other mode the host keeps its usual list timer.
9990
+ */
9991
+ watchRoster(options) {
9992
+ this.#check();
9993
+ const watch = new ScopedRosterWatch({
9994
+ client: this.#client,
9995
+ enrollmentToken: () => this.#token(),
9996
+ view: options.view ?? (() => this.#discoveredView),
9997
+ discover: async (view) => {
9998
+ await options.onView(view);
9999
+ },
10000
+ onRefused: (error) => {
10001
+ this.listFailed(error);
10002
+ options.onRefused?.(error);
10003
+ },
10004
+ onTransportLost: () => this.transportLost(),
10005
+ onReachable: () => this.reachable(),
10006
+ onError: options.onError,
10007
+ onMode: options.onMode,
10008
+ logger: this.#logger,
10009
+ now: this.#now,
10010
+ setTimeoutImpl: this.#setTimeout,
10011
+ clearTimeoutImpl: this.#clearTimeout
10012
+ });
10013
+ this.#watches.add(watch);
10014
+ watch.start();
10015
+ return {
10016
+ get mode() {
10017
+ return watch.mode;
10018
+ },
10019
+ close: () => {
10020
+ this.#watches.delete(watch);
10021
+ watch.stop();
10022
+ }
10023
+ };
10024
+ }
9131
10025
  close() {
9132
10026
  if (this.#closed)
9133
10027
  return;
9134
10028
  this.#closed = true;
10029
+ if (this.#probeTimer)
10030
+ this.#clearTimeout(this.#probeTimer);
10031
+ this.#probeTimer = void 0;
10032
+ for (const watch of this.#watches)
10033
+ watch.stop();
10034
+ this.#watches.clear();
10035
+ this.#kept.clear();
9135
10036
  this.#client.close();
9136
10037
  }
9137
10038
  };
@@ -9582,6 +10483,7 @@ var init_consumer = __esm({
9582
10483
  init_errors2();
9583
10484
  init_insula();
9584
10485
  init_roster();
10486
+ init_watch();
9585
10487
  ClaustrumConsumer = class {
9586
10488
  #options;
9587
10489
  #shutdown = new AbortController();
@@ -9590,9 +10492,18 @@ var init_consumer = __esm({
9590
10492
  #connecting;
9591
10493
  #refreshing;
9592
10494
  #roster;
10495
+ /**
10496
+ * The grants named by this instance's latest discovery, with the view that
10497
+ * discovery committed. Memory only: the roster file never carries it.
10498
+ */
10499
+ #grantReach;
9593
10500
  #timer;
9594
10501
  #started = false;
9595
10502
  #insula;
10503
+ #vaultWatch;
10504
+ #releaseInsulaWatch;
10505
+ /** When this instance last completed a discovery, by `now`. */
10506
+ #discoveredAt;
9596
10507
  constructor(options) {
9597
10508
  this.#options = options;
9598
10509
  this.#logger = options.logger ?? createLogger2("claustrum");
@@ -9650,7 +10561,9 @@ var init_consumer = __esm({
9650
10561
  parseIdentity: this.#options.parseIdentity,
9651
10562
  requireAssertion: this.#options.requireAssertion,
9652
10563
  now: this.#options.now,
9653
- logger: this.#logger
10564
+ logger: this.#logger,
10565
+ setTimeoutImpl: this.#options.setTimeoutImpl,
10566
+ clearTimeoutImpl: this.#options.clearTimeoutImpl
9654
10567
  });
9655
10568
  if (this.#options.insula && client.insula) {
9656
10569
  this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
@@ -9666,6 +10579,39 @@ var init_consumer = __esm({
9666
10579
  snapshot() {
9667
10580
  return this.#roster;
9668
10581
  }
10582
+ /**
10583
+ * What this consumer is granted, from its latest discovery, without any I/O.
10584
+ * It explains an empty roster: `grants === 0` means no grant at all, while
10585
+ * `grants > 0` means a grant that reaches no credential (`tuples` names its
10586
+ * selector). Undefined means unknown, never zero: the vault or client is too
10587
+ * old to send it, nothing was discovered yet, or the roster now in memory is
10588
+ * a different view than the one this instance discovered (a peer process
10589
+ * held the discovery lease and its newer roster was served instead).
10590
+ */
10591
+ grantReach() {
10592
+ const latest2 = this.#grantReach;
10593
+ return latest2 && this.#roster?.view === latest2.view ? latest2.reach : void 0;
10594
+ }
10595
+ /** How this consumer currently learns about changes, without I/O. */
10596
+ watchState() {
10597
+ return Object.freeze({
10598
+ vault: this.#vaultWatch?.mode ?? "polling",
10599
+ ...this.#options.insula && {
10600
+ insula: this.#insula?.source.watchMode() ?? "polling"
10601
+ }
10602
+ });
10603
+ }
10604
+ /** Close the watches with the connection they belong to. */
10605
+ #stopWatch() {
10606
+ this.#vaultWatch?.close();
10607
+ this.#vaultWatch = void 0;
10608
+ this.#releaseInsulaWatch?.();
10609
+ this.#releaseInsulaWatch = void 0;
10610
+ }
10611
+ /** Whether any account is using an in-memory outage receipt, without I/O. */
10612
+ keptReceiptState() {
10613
+ return this.#custody?.keptReceiptState() ?? Object.freeze({ active: false, since: null });
10614
+ }
9669
10615
  /** Rows for `/routing`, from the last committed roster. */
9670
10616
  routingRows() {
9671
10617
  return vaultRoutingRows(this.#roster);
@@ -9677,6 +10623,8 @@ var init_consumer = __esm({
9677
10623
  this.#refreshing = (async () => {
9678
10624
  if (!await this.#active()) {
9679
10625
  this.#roster = void 0;
10626
+ this.#grantReach = void 0;
10627
+ this.#stopWatch();
9680
10628
  this.#custody?.close();
9681
10629
  this.#custody = void 0;
9682
10630
  this.#insula?.release();
@@ -9684,9 +10632,15 @@ var init_consumer = __esm({
9684
10632
  return void 0;
9685
10633
  }
9686
10634
  const custody = await this.#getCustody();
10635
+ let discovered;
9687
10636
  const roster = await refreshVaultRoster({
9688
10637
  path: this.#options.rosterPath,
9689
- custody,
10638
+ custody: {
10639
+ discover: async (signal) => {
10640
+ discovered = await custody.discover(signal);
10641
+ return discovered;
10642
+ }
10643
+ },
9690
10644
  isActive: () => this.#active(),
9691
10645
  signal: this.#shutdown.signal,
9692
10646
  projection: () => ({
@@ -9699,14 +10653,28 @@ var init_consumer = __esm({
9699
10653
  this.#assertOpen();
9700
10654
  const changed = roster?.view !== this.#roster?.view;
9701
10655
  this.#roster = roster;
10656
+ custody.retain(roster?.rows ?? []);
10657
+ if (discovered && roster?.view !== void 0)
10658
+ this.#grantReach = discovered.grantReach ? { view: roster.view, reach: discovered.grantReach } : void 0;
9702
10659
  if (roster && changed)
9703
10660
  this.#options.onRoster?.(roster);
10661
+ this.#discoveredAt = (this.#options.now ?? Date.now)();
9704
10662
  return roster;
9705
10663
  })().finally(() => {
9706
10664
  this.#refreshing = void 0;
9707
10665
  });
9708
10666
  return this.#refreshing;
9709
10667
  }
10668
+ /**
10669
+ * Poll in the background and open the vault and insula watches. Until the
10670
+ * vault watch is accepted, and whenever it is unavailable, every tick lists
10671
+ * the vault exactly as before watches existed. While it is open a tick
10672
+ * lists only when five minutes have passed since the last discovery, since
10673
+ * the watch keeps no history; it still checks `isCustodyActive`, so a switch
10674
+ * to local mode closes the connection as quickly as before. Insula is
10675
+ * polled on the tick only while its own watch is not open. A host not in
10676
+ * vault mode makes no request.
10677
+ */
9710
10678
  start() {
9711
10679
  if (this.#started)
9712
10680
  return;
@@ -9714,8 +10682,10 @@ var init_consumer = __esm({
9714
10682
  this.#started = true;
9715
10683
  const tick = async () => {
9716
10684
  try {
9717
- await this.refresh();
10685
+ if (await this.#listDue())
10686
+ await this.refresh();
9718
10687
  await this.refreshInsulaQuota();
10688
+ this.#openWatch();
9719
10689
  } catch (error) {
9720
10690
  if (!this.#shutdown.signal.aborted)
9721
10691
  this.#options.onError?.(error);
@@ -9733,6 +10703,50 @@ var init_consumer = __esm({
9733
10703
  };
9734
10704
  void tick();
9735
10705
  }
10706
+ /** Whether a background tick must list the vault now. */
10707
+ async #listDue() {
10708
+ if (this.#vaultWatch?.mode !== "watching")
10709
+ return true;
10710
+ const now = (this.#options.now ?? Date.now)();
10711
+ if (this.#discoveredAt === void 0 || now - this.#discoveredAt >= SAFETY_POLL_MS)
10712
+ return true;
10713
+ return !await this.#active();
10714
+ }
10715
+ /**
10716
+ * Open the vault and insula watches once a vault connection exists. Only
10717
+ * reached in vault mode: a host in local mode never connects.
10718
+ */
10719
+ #openWatch() {
10720
+ const custody = this.#custody;
10721
+ if (this.#shutdown.signal.aborted || !custody)
10722
+ return;
10723
+ this.#vaultWatch ??= custody.watchRoster({
10724
+ view: () => this.#roster?.view,
10725
+ // The existing discovery, so a watched change commits the roster and
10726
+ // re-applies it to kept receipts exactly as a poll does. A refresh
10727
+ // already in flight may have listed before the change was announced,
10728
+ // so wait for it and list again.
10729
+ onView: async () => {
10730
+ while (this.#refreshing)
10731
+ await this.#refreshing.catch(() => {
10732
+ });
10733
+ await this.refresh();
10734
+ },
10735
+ // Custody has dropped kept receipts, as a poll meeting the same
10736
+ // refusal from list_scoped would.
10737
+ onRefused: (error) => this.#options.onError?.(error),
10738
+ onError: (error) => {
10739
+ if (!this.#shutdown.signal.aborted)
10740
+ this.#options.onError?.(error);
10741
+ }
10742
+ });
10743
+ if (this.#options.insula && this.#insula && !this.#releaseInsulaWatch)
10744
+ this.#releaseInsulaWatch = this.#insula.source.watch({
10745
+ provider: this.#options.insula.provider,
10746
+ setTimeoutImpl: this.#options.setTimeoutImpl,
10747
+ clearTimeoutImpl: this.#options.clearTimeoutImpl
10748
+ });
10749
+ }
9736
10750
  /**
9737
10751
  * Fetch on a background tick, at most once per minute across projects with
9738
10752
  * the same daemon and enrollment token path. Admission must use the cache
@@ -9795,16 +10809,28 @@ var init_consumer = __esm({
9795
10809
  async authorize(routeId, signal) {
9796
10810
  this.#assertOpen(signal);
9797
10811
  const roster = this.#roster ?? await this.#wait(this.refresh(), signal);
9798
- if (!roster || !await this.#active())
10812
+ if (!roster || !await this.#active()) {
10813
+ this.#custody?.close();
10814
+ this.#custody = void 0;
10815
+ this.#stopWatch();
10816
+ this.#insula?.release();
10817
+ this.#insula = void 0;
9799
10818
  throw new ClaustrumConsumerError("not-active", "Claustrum scoped custody is not active");
10819
+ }
9800
10820
  const current = await readVaultRoster(this.#options.rosterPath);
9801
10821
  this.#assertOpen(signal);
9802
10822
  const observed = roster.rows.find((row) => row.routeId === routeId);
9803
10823
  const configured = current?.rows.find((row) => row.routeId === routeId);
9804
- if (configured && !configured.enabled)
10824
+ if (configured && !configured.enabled) {
10825
+ if (observed)
10826
+ this.#custody?.forget(observed.credentialId);
9805
10827
  throw new ClaustrumConsumerError("route-declined", "Claustrum route is disabled");
9806
- if (!observed || !configured || configured.state !== "active" || configured.credentialId !== observed.credentialId || configured.accountIdentity !== observed.accountIdentity)
10828
+ }
10829
+ if (!observed || !configured || configured.state !== "active" || configured.credentialId !== observed.credentialId || configured.accountIdentity !== observed.accountIdentity || configured.credentialType !== observed.credentialType) {
10830
+ if (observed)
10831
+ this.#custody?.forget(observed.credentialId);
9807
10832
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum route is disabled, removed or changed");
10833
+ }
9808
10834
  const custody = await this.#wait(this.#getCustody(), signal);
9809
10835
  const combined = combineAbortSignals([
9810
10836
  this.#shutdown.signal,
@@ -9817,7 +10843,7 @@ var init_consumer = __esm({
9817
10843
  ...configured.accountIdentity !== void 0 && {
9818
10844
  accountIdentity: configured.accountIdentity
9819
10845
  }
9820
- }, combined.signal);
10846
+ }, combined.signal, routeId);
9821
10847
  } finally {
9822
10848
  combined.dispose();
9823
10849
  }
@@ -9840,6 +10866,10 @@ var init_consumer = __esm({
9840
10866
  const signal = options.signal;
9841
10867
  let served = await this.authorize(routeId, signal);
9842
10868
  let response = await dispatch(served, signal);
10869
+ if (response.status === 401 && served.fromKeptReceipt) {
10870
+ await this.reportFailure(served, 401, options.reporterSource ?? "direct");
10871
+ return response;
10872
+ }
9843
10873
  if (response.status === 401 && !signal?.aborted) {
9844
10874
  let current;
9845
10875
  try {
@@ -9867,6 +10897,7 @@ var init_consumer = __esm({
9867
10897
  this.#assertOpen();
9868
10898
  await declineVaultRoute(this.#options.rosterPath, routeId);
9869
10899
  this.#roster = await readVaultRoster(this.#options.rosterPath);
10900
+ this.#custody?.retain(this.#roster?.rows ?? []);
9870
10901
  }
9871
10902
  async accept(routeId) {
9872
10903
  this.#assertOpen();
@@ -9922,10 +10953,12 @@ var init_consumer = __esm({
9922
10953
  if (this.#timer)
9923
10954
  (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
9924
10955
  this.#timer = void 0;
10956
+ this.#stopWatch();
9925
10957
  this.#custody?.close();
9926
10958
  this.#insula?.release();
9927
10959
  this.#insula = void 0;
9928
10960
  this.#roster = void 0;
10961
+ this.#grantReach = void 0;
9929
10962
  }
9930
10963
  };
9931
10964
  }
@@ -9935,21 +10968,31 @@ var init_consumer = __esm({
9935
10968
  var claustrum_exports = {};
9936
10969
  __export(claustrum_exports, {
9937
10970
  CUSTODY_PLACEHOLDER_PREFIX: () => CUSTODY_PLACEHOLDER_PREFIX,
10971
+ ChangeNoticeReader: () => ChangeNoticeReader,
9938
10972
  ClaustrumConsumer: () => ClaustrumConsumer,
9939
10973
  ClaustrumConsumerError: () => ClaustrumConsumerError,
9940
- ClaustrumCredentialError: () => ClaustrumCredentialError3,
10974
+ ClaustrumCredentialError: () => ClaustrumCredentialError4,
9941
10975
  ClaustrumEnrollmentManager: () => ClaustrumEnrollmentManager,
9942
10976
  ClaustrumScopedCustody: () => ClaustrumScopedCustody,
10977
+ ClaustrumUnreachableError: () => ClaustrumUnreachableError,
9943
10978
  DEFAULT_ROUTE_PREFIX: () => DEFAULT_ROUTE_PREFIX,
10979
+ KEPT_RECEIPT_MARGIN_MS: () => KEPT_RECEIPT_MARGIN_MS,
10980
+ RESUBSCRIBE_BACKOFF_MS: () => RESUBSCRIBE_BACKOFF_MS,
9944
10981
  RETRYABLE_ENROLLMENT_CODES: () => RETRYABLE_ENROLLMENT_CODES,
10982
+ SAFETY_POLL_MS: () => SAFETY_POLL_MS,
9945
10983
  SERVING_MARGIN_MS: () => SERVING_MARGIN_MS,
10984
+ ScopedRosterWatch: () => ScopedRosterWatch,
9946
10985
  TERMINAL_ENROLLMENT_CODES: () => TERMINAL_ENROLLMENT_CODES,
10986
+ VAULT_FAILURE_CLASSES: () => VAULT_FAILURE_CLASSES,
10987
+ WATCH_RETRY_MS: () => WATCH_RETRY_MS,
9947
10988
  acceptAccount: () => acceptAccount,
9948
10989
  acceptVaultRoute: () => acceptVaultRoute,
10990
+ acquireInsulaQuotaSource: () => acquireInsulaQuotaSource,
9949
10991
  assertHostSlotMatchesMode: () => assertHostSlotMatchesMode,
9950
10992
  assertNotCustodyPlaceholder: () => assertNotCustodyPlaceholder,
9951
10993
  classifyEnrollmentError: () => classifyEnrollmentError,
9952
10994
  classifyHostSlot: () => classifyHostSlot,
10995
+ classifyVaultFailure: () => classifyVaultFailure,
9953
10996
  connectClaustrumEnrollmentClient: () => connectClaustrumEnrollmentClient,
9954
10997
  connectClaustrumScopedClient: () => connectClaustrumScopedClient,
9955
10998
  custodyPlaceholder: () => custodyPlaceholder,
@@ -9979,7 +11022,7 @@ __export(claustrum_exports, {
9979
11022
  vaultRoutingRows: () => vaultRoutingRows
9980
11023
  });
9981
11024
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
9982
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
11025
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
9983
11026
  async function connectClaustrumScopedClient(options) {
9984
11027
  const client = await ClaustrumClient.connect(options);
9985
11028
  return Object.assign(client, { insula: insulaUsageTransport(options) });
@@ -9988,18 +11031,21 @@ var init_claustrum = __esm({
9988
11031
  "../core/dist/common-auth-embedded/claustrum/index.js"() {
9989
11032
  "use strict";
9990
11033
  init_insula();
11034
+ init_availability();
9991
11035
  init_consumer();
9992
11036
  init_custody();
9993
11037
  init_enrollment();
9994
11038
  init_errors2();
9995
11039
  init_host_slot();
11040
+ init_insula();
9996
11041
  init_interlock();
9997
11042
  init_roster();
11043
+ init_watch();
9998
11044
  }
9999
11045
  });
10000
11046
 
10001
11047
  // ../core/dist/common-auth-embedded/pi-slot/lock.js
10002
- import { rmdirSync, statSync as statSync2 } from "node:fs";
11048
+ import { rmdirSync, statSync as statSync2, utimesSync } from "node:fs";
10003
11049
  import { mkdir as mkdir9, rmdir, stat as stat5, utimes } from "node:fs/promises";
10004
11050
  function sameDirectory(observed, identity) {
10005
11051
  return observed.dev === identity.dev && observed.ino === identity.ino;
@@ -10095,7 +11141,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
10095
11141
  return;
10096
11142
  let observed;
10097
11143
  try {
10098
- observed = await stat5(path2);
11144
+ observed = statSync2(path2);
10099
11145
  } catch (error) {
10100
11146
  retry(error);
10101
11147
  return;
@@ -10109,11 +11155,12 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
10109
11155
  }
10110
11156
  const next = new Date(precision === "s" ? Math.ceil(Date.now() / 1e3) * 1e3 : Date.now());
10111
11157
  try {
10112
- await utimes(path2, next, next);
11158
+ utimesSync(path2, next, next);
10113
11159
  } catch (error) {
10114
11160
  retry(error);
10115
11161
  return;
10116
11162
  }
11163
+ assertFresh();
10117
11164
  if (released)
10118
11165
  return;
10119
11166
  mtime = next.getTime();
@@ -10555,7 +11602,7 @@ var init_pi_slot = __esm({
10555
11602
  });
10556
11603
 
10557
11604
  // src/cli.ts
10558
- import { execFile as execFile2 } from "node:child_process";
11605
+ import { execFile } from "node:child_process";
10559
11606
  import { realpathSync as realpathSync2 } from "node:fs";
10560
11607
  import { resolve as resolve12 } from "node:path";
10561
11608
  import { createInterface } from "node:readline/promises";
@@ -11839,7 +12886,7 @@ async function syncDirectory(path2, boundary) {
11839
12886
  }
11840
12887
  await boundary?.("after-directory-sync");
11841
12888
  }
11842
- async function exclusiveBytes(path2, bytes, expectedHash, boundary) {
12889
+ async function exclusiveBytes(path2, bytes, expectedHash, boundary, pointerStage = false) {
11843
12890
  let handle;
11844
12891
  try {
11845
12892
  handle = await open(path2, "wx", 384);
@@ -11858,7 +12905,8 @@ async function exclusiveBytes(path2, bytes, expectedHash, boundary) {
11858
12905
  const reopened = await secureRead(path2);
11859
12906
  if (digest(reopened) !== expectedHash || !reopened.equals(bytes))
11860
12907
  throw new AccountMigrationError("exclusive backup or recovery copy differs");
11861
- await syncFile(path2);
12908
+ if (handle === void 0 || !pointerStage)
12909
+ await syncFile(path2);
11862
12910
  await syncDirectory(dirname(path2), boundary);
11863
12911
  }
11864
12912
  async function readJournal(paths) {
@@ -12560,7 +13608,7 @@ function createAccountMigrationFactory(modules) {
12560
13608
  throw new AccountMigrationError("source changed before pointer publication");
12561
13609
  if (!journal)
12562
13610
  throw new AccountMigrationError("capture journal missing");
12563
- await publishGenerationPointer(modules, physical, journal, parentLease, prior, options.onBoundary);
13611
+ await publishGenerationPointer(modules, physical, journal, parentLease, lease, prior, options.onBoundary);
12564
13612
  });
12565
13613
  await options.onBoundary?.("after-capture");
12566
13614
  }
@@ -12905,47 +13953,9 @@ async function initializeFreshAccountStore(modules, options) {
12905
13953
  timeoutMs: 2e3,
12906
13954
  renew: true
12907
13955
  }, async (lease) => {
12908
- let journal = await readJournal(physical);
12909
- if (pointer === void 0) {
12910
- await options.onBoundary?.("before-capture");
12911
- await assertSourceAbsent(physical);
12912
- await modules.fs.withLock(physical.legacyPath, {
12913
- name: "accounts",
12914
- ttlMs: 1e4,
12915
- timeoutMs: 2e3,
12916
- renew: true
12917
- }, async (accountsLease) => {
12918
- await assertSourceAbsent(physical);
12919
- await accountsLease.assertOwned();
12920
- await lease.assertOwned();
12921
- if (journal !== void 0 || await exists(physical.configPath) || await exists(physical.statePath))
12922
- throw new AccountMigrationError("fresh stage has unrelated artifacts");
12923
- journal = {
12924
- schemaVersion: 1,
12925
- id: pathGenerationId(physical),
12926
- legacyPath: physical.legacyPath,
12927
- storeDir: physical.storeDir,
12928
- sourceKind: "absent",
12929
- status: "pending",
12930
- operation: "migrate",
12931
- phase: "capture",
12932
- manifest: {
12933
- sourceVersion: null,
12934
- normalizationClock: options.now(),
12935
- accounts: [],
12936
- routing: { schemaVersion: 1 },
12937
- effectiveActiveIndex: 0
12938
- },
12939
- mapping: [],
12940
- completedRows: []
12941
- };
12942
- await saveJournal(modules, physical, lease, journal, true, options.onBoundary);
12943
- await options.onBoundary?.("pointer:before-publication");
12944
- await assertSourceAbsent(physical);
12945
- await publishGenerationPointer(modules, physical, journal, parentLease, void 0, options.onBoundary);
12946
- await options.onBoundary?.("pointer:after-publication");
12947
- });
12948
- }
13956
+ const journal = await readJournal(physical);
13957
+ if (pointer === void 0)
13958
+ return initializePrivateEmptyGeneration(modules, physical, parentLease, lease, options);
12949
13959
  if (journal?.sourceKind !== "absent" || journal.operation !== "migrate" || journal.status === "inactive")
12950
13960
  throw new AccountMigrationError("fresh resume has no compatible pointed generation");
12951
13961
  await assertPublishedAccountStoreGeneration(physical);
@@ -13021,6 +14031,187 @@ async function initializeFreshAccountStore(modules, options) {
13021
14031
  throw error;
13022
14032
  }
13023
14033
  }
14034
+ async function exclusiveUnpublishedBytes(path2, bytes) {
14035
+ const handle = await open(path2, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
14036
+ try {
14037
+ await handle.writeFile(bytes);
14038
+ } finally {
14039
+ await handle.close();
14040
+ }
14041
+ if (!(await secureRead(path2)).equals(bytes))
14042
+ throw new AccountMigrationError("private stage readback differs");
14043
+ }
14044
+ async function initializePrivateEmptyGeneration(modules, paths, parentLease, managementLease, options) {
14045
+ return modules.fs.withLock(paths.legacyPath, { name: "accounts", ttlMs: 1e4, timeoutMs: 2e3, renew: true }, async (accountsLease) => {
14046
+ const directory = await lstat(paths.storeDir);
14047
+ const assertOwned = async () => {
14048
+ await parentLease.assertOwned();
14049
+ await managementLease.assertOwned();
14050
+ await accountsLease.assertOwned();
14051
+ const current = await lstat(paths.storeDir);
14052
+ if (!current.isDirectory() || current.isSymbolicLink() || current.dev !== directory.dev || current.ino !== directory.ino || !sameFilesystemPath(await realpath(paths.storeDir), paths.storeDir))
14053
+ throw new AccountMigrationError("private generation directory changed");
14054
+ privateMode(current.mode, 448);
14055
+ };
14056
+ const boundary = options.onBoundary;
14057
+ await assertOwned();
14058
+ await assertSourceAbsent(paths);
14059
+ if (await readPointer(paths.legacyPath))
14060
+ throw new AccountMigrationError("private initialization found a competing pointer");
14061
+ if (await readJournal(paths) || await exists(paths.configPath) || await exists(paths.statePath))
14062
+ throw new AccountMigrationError("fresh stage has unrelated artifacts");
14063
+ const journal = {
14064
+ schemaVersion: 1,
14065
+ id: pathGenerationId(paths),
14066
+ legacyPath: paths.legacyPath,
14067
+ storeDir: paths.storeDir,
14068
+ sourceKind: "absent",
14069
+ status: "pending",
14070
+ operation: "migrate",
14071
+ phase: "build",
14072
+ manifest: {
14073
+ sourceVersion: null,
14074
+ normalizationClock: options.now(),
14075
+ accounts: [],
14076
+ routing: { schemaVersion: 1 },
14077
+ effectiveActiveIndex: 0
14078
+ },
14079
+ mapping: [],
14080
+ completedRows: []
14081
+ };
14082
+ await assertOwned();
14083
+ await exclusiveUnpublishedBytes(paths.configPath, Buffer.from('{"version":1,"accounts":[]}\n'));
14084
+ await boundary?.("empty-stage:after-seed");
14085
+ const store = openMigrationStore(modules, paths, options.now, async (step, info) => {
14086
+ await assertOwned();
14087
+ if (!step.includes("config") || await exists(paths.statePath))
14088
+ throw new AccountMigrationError("private empty stage attempted a credential write");
14089
+ await secureRead(paths.configPath);
14090
+ await boundary?.(`public:${info.operation}:${step}`);
14091
+ await assertOwned();
14092
+ });
14093
+ await assertOwned();
14094
+ await store.initialize();
14095
+ await boundary?.("empty-stage:after-initialize");
14096
+ await assertOwned();
14097
+ await store.updateSettings((settings) => {
14098
+ settings[ROUTING_SETTINGS_KEY] = encodeRoutingSettings(journal.manifest.routing);
14099
+ settings[ACCOUNT_STORE_GENERATION_SETTINGS_KEY] = generationJson(journal);
14100
+ settings[MANAGEMENT_SETTINGS_KEY] = {
14101
+ id: journal.id,
14102
+ kind: "migration",
14103
+ targets: [],
14104
+ progress: { step: "build", completedTargets: [] }
14105
+ };
14106
+ return settings;
14107
+ });
14108
+ await boundary?.("empty-stage:after-build-settings");
14109
+ await expectedFreshArtifacts(paths, journal);
14110
+ await assertStateOwnership(paths, journal, true);
14111
+ await verifyImported(store, journal);
14112
+ const snapshot2 = await secureRead(paths.configPath);
14113
+ await verifyImported(store, journal);
14114
+ journal.verification = {
14115
+ manifestSha256: digest(canonical2(manifestJson(journal.manifest))),
14116
+ configSha256: digest(snapshot2),
14117
+ statePresent: false,
14118
+ durability: accountMigrationDurability()
14119
+ };
14120
+ await assertOwned();
14121
+ await assertSourceAbsent(paths);
14122
+ journal.sourceAbsenceVerified = true;
14123
+ await management(store, journal, true);
14124
+ await boundary?.("empty-stage:after-clear-settings");
14125
+ await expectedFreshArtifacts(paths, journal);
14126
+ await currentSuccessor(store, paths, journal);
14127
+ if ((await settingsOf(store))[MANAGEMENT_SETTINGS_KEY] !== void 0)
14128
+ throw new AccountMigrationError("private stage still has management work");
14129
+ journal.phase = "activate";
14130
+ journal.status = "active";
14131
+ decodeAccountMigrationJournal(journalJson(journal));
14132
+ await assertOwned();
14133
+ await exclusiveUnpublishedBytes(paths.migrationPath, Buffer.from(`${JSON.stringify(journalJson(journal), null, 2)}
14134
+ `));
14135
+ await boundary?.("empty-stage:after-journal");
14136
+ await syncFile(paths.configPath);
14137
+ await boundary?.("empty-stage:after-config-sync");
14138
+ await syncFile(paths.migrationPath);
14139
+ await boundary?.("empty-stage:after-journal-sync");
14140
+ for (const [name, path3] of [
14141
+ ["backups", paths.backupsDir],
14142
+ ["retired", paths.retiredDir],
14143
+ ["transfers", paths.transfersDir]
14144
+ ]) {
14145
+ await syncDirectory(path3);
14146
+ await boundary?.(`empty-stage:after-${name}-sync`);
14147
+ }
14148
+ await syncDirectory(paths.storeDir);
14149
+ await boundary?.("empty-stage:after-generation-sync");
14150
+ await boundary?.("pointer:before-publication");
14151
+ const reopened = await readJournal(paths);
14152
+ if (!isDeepStrictEqual(reopened, journal))
14153
+ throw new AccountMigrationError("publication requires its complete synced canonical journal");
14154
+ const pointer = {
14155
+ schemaVersion: 1,
14156
+ id: journal.id,
14157
+ directoryBasename: basename(paths.storeDir)
14158
+ };
14159
+ const path2 = accountStorePointerPath(paths.legacyPath);
14160
+ const stage = `${path2}.${journal.id}.tmp`;
14161
+ const bytes = Buffer.from(`${JSON.stringify(pointer, null, 2)}
14162
+ `);
14163
+ await assertOwned();
14164
+ let stageHandle;
14165
+ try {
14166
+ stageHandle = await open(stage, "wx", 384);
14167
+ } catch (error) {
14168
+ if (errno(error) !== "EEXIST")
14169
+ throw error;
14170
+ }
14171
+ if (stageHandle) {
14172
+ try {
14173
+ await stageHandle.writeFile(bytes);
14174
+ await stageHandle.sync();
14175
+ } finally {
14176
+ await stageHandle.close();
14177
+ }
14178
+ }
14179
+ if (!(await secureRead(stage)).equals(bytes))
14180
+ throw new AccountMigrationError("exclusive pointer stage differs");
14181
+ if (!stageHandle)
14182
+ await syncFile(stage);
14183
+ await boundary?.("empty-stage:after-pointer-stage");
14184
+ await syncDirectory(dirname(path2));
14185
+ await boundary?.("empty-stage:after-parent-prelink-sync");
14186
+ await boundary?.("pointer:before-link");
14187
+ await assertOwned();
14188
+ await assertSourceAbsent(paths);
14189
+ if (await exists(path2))
14190
+ throw new AccountMigrationError("foreign or competing pointer publication refuses overwrite");
14191
+ if (await exists(resolveAccountStorePaths(paths.legacyPath).storeDir))
14192
+ throw new AccountMigrationError("foreign logical store directory appeared before publication");
14193
+ try {
14194
+ await link(stage, path2);
14195
+ } catch (error) {
14196
+ if (errno(error) === "EEXIST")
14197
+ throw new AccountMigrationError("foreign or competing pointer publication refuses overwrite");
14198
+ throw new AccountMigrationError("exclusive pointer hard-link publication failed");
14199
+ }
14200
+ await boundary?.("pointer:after-link-before-parent-sync");
14201
+ await syncDirectory(dirname(path2));
14202
+ if (!isDeepStrictEqual(await readPointer(paths.legacyPath), pointer) || !isDeepStrictEqual(await readJournal(paths), journal))
14203
+ throw new AccountMigrationError("pointer publication readback differs");
14204
+ await expectedFreshArtifacts(paths, journal);
14205
+ await currentSuccessor(store, paths, journal);
14206
+ const admission = await readAccountStoreAdmission(paths.legacyPath, modules, options.now, journal.id);
14207
+ if (admission.status !== "active" || !isDeepStrictEqual(admission.receipt, receipt(journal)))
14208
+ throw new AccountMigrationError("published empty generation is not admitted");
14209
+ await boundary?.("pointer:after-sync-before-stage-cleanup");
14210
+ await cleanupPointerStage(paths.legacyPath, pointer, parentLease);
14211
+ await assertOwned();
14212
+ return { status: "completed", receipt: receipt(journal) };
14213
+ });
14214
+ }
13024
14215
  async function allocateGeneration(legacyPath) {
13025
14216
  if (await exists(resolveAccountStorePaths(legacyPath).storeDir))
13026
14217
  throw new AccountMigrationError("foreign logical directory refuses generation allocation");
@@ -13029,13 +14220,16 @@ async function allocateGeneration(legacyPath) {
13029
14220
  await prepareDirectories(paths);
13030
14221
  return paths;
13031
14222
  }
13032
- async function publishGenerationPointer(modules, paths, journal, parentLease, prior, boundary) {
14223
+ async function publishGenerationPointer(modules, paths, journal, parentLease, managementLease, prior, boundary, journalSavedBy) {
13033
14224
  await parentLease.assertOwned();
14225
+ await managementLease.assertOwned();
13034
14226
  const currentJournal = await readJournal(paths);
13035
14227
  if (!currentJournal || currentJournal.id !== journal.id || !isDeepStrictEqual(journalJson(currentJournal), journalJson(journal)))
13036
14228
  throw new AccountMigrationError("publication requires its complete synced canonical journal");
13037
- await syncFile(paths.migrationPath);
13038
- await syncDirectory(paths.storeDir);
14229
+ if (journalSavedBy !== managementLease) {
14230
+ await syncFile(paths.migrationPath);
14231
+ await syncDirectory(paths.storeDir);
14232
+ }
13039
14233
  const pointer = {
13040
14234
  schemaVersion: 1,
13041
14235
  id: journal.id,
@@ -13046,8 +14240,9 @@ async function publishGenerationPointer(modules, paths, journal, parentLease, pr
13046
14240
  const stage = `${path2}.${journal.id}.tmp`;
13047
14241
  const bytes = Buffer.from(`${JSON.stringify(pointer, null, 2)}
13048
14242
  `);
13049
- await exclusiveBytes(stage, bytes, digest(bytes));
14243
+ await exclusiveBytes(stage, bytes, digest(bytes), void 0, true);
13050
14244
  await parentLease.assertOwned();
14245
+ await managementLease.assertOwned();
13051
14246
  await boundary?.("pointer:before-link");
13052
14247
  if (await exists(resolveAccountStorePaths(paths.legacyPath).storeDir))
13053
14248
  throw new AccountMigrationError("foreign logical store directory appeared before publication");
@@ -13079,6 +14274,7 @@ async function publishGenerationPointer(modules, paths, journal, parentLease, pr
13079
14274
  stageName: () => stageName,
13080
14275
  beforeRename: async () => {
13081
14276
  await parentLease.assertOwned();
14277
+ await managementLease.assertOwned();
13082
14278
  if (!isDeepStrictEqual(await readPointer(paths.legacyPath), prior) || (await readJournal(oldPaths))?.status !== "inactive")
13083
14279
  throw new AccountMigrationError("inactive pointer changed before transition");
13084
14280
  await syncFile(`${path2}.${stageName}.tmp`);
@@ -13088,6 +14284,7 @@ async function publishGenerationPointer(modules, paths, journal, parentLease, pr
13088
14284
  await syncDirectory(dirname(path2));
13089
14285
  }
13090
14286
  await parentLease.assertOwned();
14287
+ await managementLease.assertOwned();
13091
14288
  }
13092
14289
  function withParentTopology(modules, legacyPath, body) {
13093
14290
  return modules.fs.withLock(legacyPath, {
@@ -13114,9 +14311,14 @@ async function finishPointerPublication(legacyPath, pointer, lease) {
13114
14311
  const path2 = accountStorePointerPath(legacyPath);
13115
14312
  await syncFile(path2);
13116
14313
  await syncDirectory(dirname(path2));
14314
+ if (await cleanupPointerStage(legacyPath, pointer, lease))
14315
+ await syncDirectory(dirname(path2));
14316
+ }
14317
+ async function cleanupPointerStage(legacyPath, pointer, lease) {
14318
+ const path2 = accountStorePointerPath(legacyPath);
13117
14319
  const stage = `${path2}.${pointer.id}.tmp`;
13118
14320
  if (!await exists(stage))
13119
- return;
14321
+ return false;
13120
14322
  const bytes = await secureRead(stage);
13121
14323
  if (!isDeepStrictEqual(decodeAccountStorePointer(jsonBytes(bytes), legacyPath), pointer))
13122
14324
  throw new AccountMigrationError("pointer stage differs from publication authority");
@@ -13125,7 +14327,7 @@ async function finishPointerPublication(legacyPath, pointer, lease) {
13125
14327
  throw new AccountMigrationError("pointer stage is not the published hard link");
13126
14328
  await lease.assertOwned();
13127
14329
  await unlink(stage);
13128
- await syncDirectory(dirname(path2));
14330
+ return true;
13129
14331
  }
13130
14332
 
13131
14333
  // ../core/dist/account-repository.js
@@ -16442,6 +17644,7 @@ async function fetchWithAgyCliTransport(url, init = {}, options = {}) {
16442
17644
  };
16443
17645
  try {
16444
17646
  options.signal?.addEventListener("abort", abort, { once: true });
17647
+ options.signal?.throwIfAborted();
16445
17648
  socket.write(requestBytes);
16446
17649
  options.onDebug?.(`agy transport request dispatched (${requestBytes.byteLength} bytes)`);
16447
17650
  const { head, leftover } = await waitForHead(socket, timeoutMs, () => {
@@ -16844,6 +18047,15 @@ async function loadCommonAuthStoreModules() {
16844
18047
  }
16845
18048
  var loadCommonAuthPiSlot = memoize(() => Promise.resolve().then(() => (init_pi_slot(), pi_slot_exports)));
16846
18049
 
18050
+ // ../core/dist/credential-redaction.js
18051
+ function maskSensitiveIdentifier(value) {
18052
+ if (typeof value !== "string" || value.length === 0)
18053
+ return "";
18054
+ if (value.length <= 8)
18055
+ return "****";
18056
+ return `${value.slice(0, 4)}****${value.slice(-4)}`;
18057
+ }
18058
+
16847
18059
  // ../core/dist/pi-paths.js
16848
18060
  import { homedir } from "node:os";
16849
18061
  import { dirname as dirname11, join as join6 } from "node:path";
@@ -17889,19 +19101,24 @@ async function replaceWindowsFile2(from, to, options = {}) {
17889
19101
  to = resolve7(to);
17890
19102
  const now = options.now ?? (() => performance.now());
17891
19103
  const start = now();
17892
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
19104
+ const leaseDeadline = options.deadline ?? Infinity;
19105
+ let retryDeadline;
17893
19106
  const delays = [0, 10, 20, 40, 80, 100];
17894
19107
  let original;
17895
19108
  let attempts2 = 0;
17896
19109
  for (const delay3 of delays) {
19110
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
17897
19111
  if (now() >= deadline)
17898
19112
  break;
17899
19113
  if (delay3)
17900
19114
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
17901
19115
  if (now() >= deadline)
17902
19116
  break;
19117
+ const fenceStart = now();
17903
19118
  await options.beforeRename?.();
17904
- if (now() >= deadline)
19119
+ if (retryDeadline !== void 0)
19120
+ retryDeadline += now() - fenceStart;
19121
+ if (now() >= leaseDeadline)
17905
19122
  break;
17906
19123
  attempts2++;
17907
19124
  try {
@@ -17913,6 +19130,7 @@ async function replaceWindowsFile2(from, to, options = {}) {
17913
19130
  const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
17914
19131
  if (!candidate)
17915
19132
  break;
19133
+ retryDeadline ??= now() + 500;
17916
19134
  }
17917
19135
  }
17918
19136
  const error = new PrivateFileError2(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
@@ -18439,9 +19657,7 @@ function writeConsoleLog2(level, ...args) {
18439
19657
  }
18440
19658
  }
18441
19659
  function redactSensitive(value) {
18442
- if (typeof value !== "string" || value.length === 0) return "";
18443
- if (value.length <= 8) return "****";
18444
- return `${value.slice(0, 4)}****${value.slice(-4)}`;
19660
+ return maskSensitiveIdentifier(value);
18445
19661
  }
18446
19662
  var SENSITIVE_FIELD_PATTERN = /token|refresh|access|project|fingerprint|deviceId|sessionId|sessionToken|secret|password|apiKey|clientSecret/i;
18447
19663
  function redactSensitiveFields(value) {
@@ -20321,7 +21537,7 @@ import { createHash as createHash9, randomBytes as randomBytes3, randomUUID as r
20321
21537
  import { constants as fsConstants2 } from "node:fs";
20322
21538
  import { chmod as chmod3, mkdir as mkdir12, open as open10, readFile as readFile9, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
20323
21539
  import { basename as basename4, dirname as dirname16, extname as extname2, isAbsolute as isAbsolute3, join as join10, resolve as resolve10 } from "node:path";
20324
- import { ClaustrumCredentialError as ClaustrumCredentialError4, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
21540
+ import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
20325
21541
 
20326
21542
  // src/common-auth-embedded/fs/lock-constants.js
20327
21543
  var WRITER_LOCK_CONSTANTS2 = Object.freeze({
@@ -20372,7 +21588,10 @@ function isLostMarkerRaceError2(error) {
20372
21588
  const code2 = error?.code;
20373
21589
  return code2 === "ENOENT" || !windowsPrivateFiles2 && (code2 === "EINVAL" || code2 === "ENOTDIR");
20374
21590
  }
20375
- async function acquireRefreshFileLock2(options) {
21591
+ function acquireRefreshFileLock2(options) {
21592
+ return acquireRefreshFileLockWithClock2({ ...options, now: Date.now });
21593
+ }
21594
+ async function acquireRefreshFileLockWithClock2(options) {
20376
21595
  const lockPath = lockPathFor2(options.path, options.name);
20377
21596
  const legacyOwnerPath = join9(lockPath, "owner.json");
20378
21597
  const ownerId = randomUUID13();
@@ -21000,7 +22219,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
21000
22219
  "pending_queue_full"
21001
22220
  ]);
21002
22221
  function classifyEnrollmentError2(error) {
21003
- if (!(error instanceof ClaustrumCredentialError4))
22222
+ if (!(error instanceof ClaustrumCredentialError5))
21004
22223
  return void 0;
21005
22224
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
21006
22225
  return { code: error.code, disposition: "terminal" };
@@ -21306,6 +22525,31 @@ async function readClaustrumEnrollmentStatus2(paths, proposedName) {
21306
22525
  }
21307
22526
  return statusFromState2(state);
21308
22527
  }
22528
+ async function enrollmentAuthority2(paths, proposedName) {
22529
+ let status;
22530
+ try {
22531
+ status = await readClaustrumEnrollmentStatus2(paths, proposedName);
22532
+ } catch (error) {
22533
+ if (!(error instanceof ClaustrumConsumerError2) || error.kind !== "invalid-state" && error.kind !== "invalid-token") {
22534
+ return "unreadable";
22535
+ }
22536
+ try {
22537
+ const stateValue = await readBoundedJson2(paths.statePath);
22538
+ if (stateValue === void 0)
22539
+ return "unreadable";
22540
+ const state = decodeEnrollmentState2(stateValue);
22541
+ return state.phase === "approved" && state.proposedName === proposedName ? "vault" : "unreadable";
22542
+ } catch {
22543
+ return "unreadable";
22544
+ }
22545
+ }
22546
+ if ("proposedName" in status && status.proposedName !== proposedName)
22547
+ return "unreadable";
22548
+ if (status.state === "approved" || status.state === "blocked" && status.code === "missing_token") {
22549
+ return "vault";
22550
+ }
22551
+ return "local";
22552
+ }
21309
22553
  function statusFromState2(state) {
21310
22554
  if (state.phase === "pending") {
21311
22555
  return {
@@ -21546,30 +22790,126 @@ async function resetClaustrumEnrollmentState2(paths, proposedName) {
21546
22790
  }
21547
22791
 
21548
22792
  // src/common-auth-embedded/setup/command-runner.js
21549
- import { execFile } from "node:child_process";
22793
+ import { spawn } from "node:child_process";
22794
+ var STDERR_TAIL_MAX_BYTES = 4 * 1024;
22795
+ var STDOUT_MAX_BYTES = 1024 * 1024;
22796
+ var ByteTail = class {
22797
+ buffer = Buffer.alloc(STDERR_TAIL_MAX_BYTES);
22798
+ start = 0;
22799
+ length = 0;
22800
+ truncated = false;
22801
+ get didTruncate() {
22802
+ return this.truncated;
22803
+ }
22804
+ push(chunk) {
22805
+ if (chunk.length >= STDERR_TAIL_MAX_BYTES) {
22806
+ if (chunk.length > STDERR_TAIL_MAX_BYTES || this.length > 0)
22807
+ this.truncated = true;
22808
+ chunk.copy(this.buffer, 0, chunk.length - STDERR_TAIL_MAX_BYTES);
22809
+ this.start = 0;
22810
+ this.length = STDERR_TAIL_MAX_BYTES;
22811
+ return;
22812
+ }
22813
+ const overflow = Math.max(0, this.length + chunk.length - STDERR_TAIL_MAX_BYTES);
22814
+ if (overflow > 0)
22815
+ this.truncated = true;
22816
+ this.start = (this.start + overflow) % STDERR_TAIL_MAX_BYTES;
22817
+ this.length -= overflow;
22818
+ const writeAt = (this.start + this.length) % STDERR_TAIL_MAX_BYTES;
22819
+ const firstLength = Math.min(chunk.length, STDERR_TAIL_MAX_BYTES - writeAt);
22820
+ chunk.copy(this.buffer, writeAt, 0, firstLength);
22821
+ if (firstLength < chunk.length)
22822
+ chunk.copy(this.buffer, 0, firstLength);
22823
+ this.length += chunk.length;
22824
+ }
22825
+ toString() {
22826
+ const bytes = Buffer.alloc(this.length);
22827
+ const firstLength = Math.min(this.length, STDERR_TAIL_MAX_BYTES - this.start);
22828
+ this.buffer.copy(bytes, 0, this.start, this.start + firstLength);
22829
+ if (firstLength < this.length)
22830
+ this.buffer.copy(bytes, firstLength, 0, this.length - firstLength);
22831
+ let start = 0;
22832
+ while (start < bytes.length) {
22833
+ const byte = bytes[start];
22834
+ if (byte === void 0 || (byte & 192) !== 128)
22835
+ break;
22836
+ start++;
22837
+ }
22838
+ return bytes.subarray(start).toString("utf8");
22839
+ }
22840
+ };
21550
22841
  var defaultCommandRunner = {
21551
22842
  run(file, args, options = {}) {
21552
22843
  return new Promise((resolve13) => {
21553
22844
  const started = performance.now();
21554
22845
  const timeoutMs = options.timeoutMs ?? 15e3;
21555
- execFile(file, [...args], {
21556
- env: options.env ?? process.env,
21557
- timeout: timeoutMs,
21558
- windowsHide: true,
21559
- windowsVerbatimArguments: options.windowsVerbatimArguments,
21560
- maxBuffer: 1024 * 1024
21561
- }, (error, stdout, stderr) => {
21562
- const durationMs = performance.now() - started;
22846
+ const stderr = new ByteTail();
22847
+ const stdout = [];
22848
+ let stdoutLength = 0;
22849
+ let outputExceeded = false;
22850
+ let spawnError = false;
22851
+ let timedOut = false;
22852
+ let child;
22853
+ try {
22854
+ child = spawn(file, [...args], {
22855
+ env: options.env ?? process.env,
22856
+ windowsHide: true,
22857
+ windowsVerbatimArguments: options.windowsVerbatimArguments,
22858
+ stdio: ["ignore", "pipe", "pipe"]
22859
+ });
22860
+ } catch {
22861
+ resolve13({
22862
+ exitCode: 1,
22863
+ stdout: "",
22864
+ stderr: "",
22865
+ spawnError: true,
22866
+ signal: null,
22867
+ timedOut: false,
22868
+ durationMs: performance.now() - started
22869
+ });
22870
+ return;
22871
+ }
22872
+ const timer = timeoutMs > 0 ? setTimeout(() => {
22873
+ timedOut = true;
22874
+ child.kill("SIGTERM");
22875
+ }, timeoutMs) : void 0;
22876
+ child.stdout?.on("data", (chunk) => {
22877
+ const remaining = STDOUT_MAX_BYTES - stdoutLength;
22878
+ const length = Math.min(remaining, chunk.length);
22879
+ if (length > 0) {
22880
+ stdout.push(chunk.subarray(0, length));
22881
+ stdoutLength += length;
22882
+ }
22883
+ if (chunk.length > remaining) {
22884
+ outputExceeded = true;
22885
+ child.kill("SIGTERM");
22886
+ }
22887
+ });
22888
+ child.stderr?.on("data", (chunk) => stderr.push(chunk));
22889
+ let settled = false;
22890
+ const settle = (code2, signal) => {
22891
+ if (settled)
22892
+ return;
22893
+ settled = true;
22894
+ if (timer)
22895
+ clearTimeout(timer);
21563
22896
  resolve13({
21564
- exitCode: error ? typeof error.code === "number" ? error.code : 1 : 0,
21565
- stdout: String(stdout ?? ""),
21566
- stderr: String(stderr ?? ""),
21567
- signal: error?.signal ?? null,
21568
- // Buffer-limit and spawn errors have string codes, not timeout kills.
21569
- timedOut: error?.killed === true && typeof error.code !== "string" && error.signal === "SIGTERM" && durationMs >= timeoutMs && timeoutMs > 0,
21570
- durationMs
22897
+ exitCode: spawnError ? 1 : outputExceeded ? 1 : code2 ?? 1,
22898
+ stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
22899
+ stderr: stderr.toString(),
22900
+ stderrTruncated: stderr.didTruncate,
22901
+ ...spawnError ? { spawnError: true } : {},
22902
+ signal: signal ?? null,
22903
+ timedOut,
22904
+ durationMs: performance.now() - started
21571
22905
  });
22906
+ };
22907
+ child.once("error", () => {
22908
+ spawnError = true;
22909
+ if (child.pid === void 0)
22910
+ settle(null, null);
21572
22911
  });
22912
+ child.once("close", (code2, signal) => settle(code2, signal));
21573
22913
  });
21574
22914
  }
21575
22915
  };
@@ -21586,6 +22926,56 @@ function runResolvedCommand(runner, platform, file, args, env3, timeoutMs = 15e3
21586
22926
  return runner.run(file, args, { env: env3, timeoutMs });
21587
22927
  }
21588
22928
 
22929
+ // src/common-auth-embedded/setup/command-error.js
22930
+ var PI_INSTALL_ERROR_MESSAGE = "Pi install failed; run pi install after checking your npm connection.";
22931
+ function utf8Tail(value) {
22932
+ const bytes = Buffer.from(value, "utf8");
22933
+ if (bytes.length <= STDERR_TAIL_MAX_BYTES)
22934
+ return value;
22935
+ let start = bytes.length - STDERR_TAIL_MAX_BYTES;
22936
+ while (start < bytes.length) {
22937
+ const byte = bytes[start];
22938
+ if (byte === void 0 || (byte & 192) !== 128)
22939
+ break;
22940
+ start++;
22941
+ }
22942
+ return bytes.subarray(start).toString("utf8");
22943
+ }
22944
+ function dropPartialLine(tail) {
22945
+ const newline = tail.indexOf("\n");
22946
+ return newline < 0 ? "" : tail.slice(newline + 1);
22947
+ }
22948
+ var SetupCommandError = class extends Error {
22949
+ step = "pi-install";
22950
+ exitCode;
22951
+ signal;
22952
+ stderrTail;
22953
+ constructor(details) {
22954
+ super(PI_INSTALL_ERROR_MESSAGE);
22955
+ this.name = "SetupCommandError";
22956
+ this.exitCode = details.exitCode;
22957
+ this.signal = details.signal;
22958
+ const tail = details.stderrTruncated ? dropPartialLine(details.stderrTail) : details.stderrTail;
22959
+ const redacted = redact2(tail);
22960
+ this.stderrTail = utf8Tail(typeof redacted === "string" ? redacted : "");
22961
+ }
22962
+ };
22963
+ var HOST_LABELS = { opencode: "OpenCode", pi: "Pi" };
22964
+ var OUTCOME_TEXT = {
22965
+ enrolled: "connected to the vault",
22966
+ "not-enrolled": "not connected",
22967
+ unknown: "unknown, check with ck auth status"
22968
+ };
22969
+ function setupEnrollmentLine({ host, outcome }) {
22970
+ return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}`;
22971
+ }
22972
+ var recordedEnrollment = /* @__PURE__ */ new WeakMap();
22973
+ function recordSetupEnrollment(failure, enrollment) {
22974
+ if (typeof failure !== "object" && typeof failure !== "function" || !failure)
22975
+ return;
22976
+ recordedEnrollment.set(failure, Object.freeze(enrollment.map((entry) => Object.freeze({ ...entry }))));
22977
+ }
22978
+
21589
22979
  // src/common-auth-embedded/setup/detect.js
21590
22980
  import { accessSync, constants as constants3, existsSync as existsSync5, readFileSync as readFileSync3, realpathSync, statSync as statSync5 } from "node:fs";
21591
22981
  import { mkdtemp, rm as rm6 } from "node:fs/promises";
@@ -22059,6 +23449,9 @@ async function assertHostsStopped(fence, env3) {
22059
23449
  }
22060
23450
 
22061
23451
  // src/common-auth-embedded/setup/enroll.js
23452
+ var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
23453
+ var HostNotEnrolledError = class extends Error {
23454
+ };
22062
23455
  async function connectSetupHost(plugin, host, io, terminal, fence) {
22063
23456
  const { name, paths: input } = plugin.vault.hosts[host];
22064
23457
  const paths = hostEnrollmentPaths2(input);
@@ -22067,7 +23460,7 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
22067
23460
  connectionFile: plugin.vault.connectionFile,
22068
23461
  handshakeTimeoutMs: 2e3
22069
23462
  }).catch(() => {
22070
- throw new Error("Claustrum connection failed; start ck and rerun setup.");
23463
+ throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.");
22071
23464
  });
22072
23465
  try {
22073
23466
  const manager = new ClaustrumEnrollmentManager2({
@@ -22097,10 +23490,10 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
22097
23490
  return;
22098
23491
  }
22099
23492
  if (status.state !== "pending" && status.state !== "busy")
22100
- throw new Error("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
23493
+ throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
22101
23494
  if (status.state === "pending" && status.requestId && status.requestId !== printedRequest) {
22102
23495
  if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
22103
- throw new Error("Invalid enrollment request id.");
23496
+ throw new HostNotEnrolledError("Invalid enrollment request id.");
22104
23497
  printedRequest = status.requestId;
22105
23498
  printLine2(terminal, "Waiting for approval. In another terminal, run:");
22106
23499
  printLine2(terminal, ` ck auth enroll approve --request-id ${status.requestId} --name ${name}`);
@@ -22108,11 +23501,13 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
22108
23501
  }
22109
23502
  await (io.wait ?? delay)(1e3);
22110
23503
  }
22111
- throw new Error("Claustrum approval is still pending; approve with ck and rerun setup.");
23504
+ throw new HostNotEnrolledError("Claustrum approval is still pending; approve with ck and rerun setup.");
22112
23505
  } catch (error) {
22113
23506
  if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError)
22114
23507
  throw error;
22115
- throw new Error("Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.");
23508
+ if (error instanceof HostNotEnrolledError)
23509
+ throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE);
23510
+ throw new Error(ENROLLMENT_INCOMPLETE_MESSAGE);
22116
23511
  } finally {
22117
23512
  client.close();
22118
23513
  }
@@ -22304,8 +23699,13 @@ async function registerOpenCode(writes, beforeWrite) {
22304
23699
  async function registerPi(plugin, executable, io = {}) {
22305
23700
  const { platform, env: env3 } = setupPaths(io);
22306
23701
  const result = await runResolvedCommand(io.runner ?? defaultCommandRunner, platform, executable, ["install", `npm:${plugin.packages.pi}@${plugin.version}`], env3);
22307
- if (result.exitCode !== 0)
22308
- throw new Error("Pi install failed; run pi install after checking your npm connection.");
23702
+ if (result.exitCode !== 0 || result.timedOut)
23703
+ throw new SetupCommandError({
23704
+ exitCode: result.spawnError ? null : result.exitCode,
23705
+ signal: result.signal ?? null,
23706
+ stderrTail: result.stderr,
23707
+ stderrTruncated: result.stderrTruncated ?? false
23708
+ });
22309
23709
  }
22310
23710
 
22311
23711
  // src/common-auth-embedded/setup/command.js
@@ -22353,6 +23753,22 @@ function validatePlugin(plugin) {
22353
23753
  throw new Error("Setup requires lowercase vault names containing only letters, digits and dashes.");
22354
23754
  }
22355
23755
  }
23756
+ async function enrollmentReport(plugin, hosts, recorded) {
23757
+ const report = [];
23758
+ for (const host of hosts) {
23759
+ let outcome = recorded.get(host) ?? "not-enrolled";
23760
+ if (outcome === "unknown") {
23761
+ const { name, paths } = plugin.vault.hosts[host];
23762
+ const authority = await enrollmentAuthority2(hostEnrollmentPaths2(paths), name).catch(() => "unreadable");
23763
+ if (authority === "vault")
23764
+ outcome = "enrolled";
23765
+ else if (authority === "local")
23766
+ outcome = "not-enrolled";
23767
+ }
23768
+ report.push({ host, outcome });
23769
+ }
23770
+ return report;
23771
+ }
22356
23772
  async function runSetup(plugin, argv = [], io = {}) {
22357
23773
  const options = flags(argv);
22358
23774
  validatePlugin(plugin);
@@ -22462,23 +23878,45 @@ ${write.content}`);
22462
23878
  hosts: Object.freeze([...hosts]),
22463
23879
  piAgentDir: detection.pi.directory
22464
23880
  };
22465
- for (const host of hosts) {
22466
- await stopped();
22467
- await plugin.beforeSignIn?.(host, context);
22468
- await stopped();
22469
- if (useVault)
22470
- await connectSetupHost(plugin, host, io, terminal, stopped);
22471
- else
22472
- await plugin.signInLocal(host, context);
22473
- await stopped();
22474
- await plugin.beforeRegister?.(host, mode, context);
22475
- await stopped();
22476
- if (host === "opencode")
22477
- await registerOpenCode(writes, stopped);
22478
- else
22479
- await registerPi(plugin, detection.pi.executable, io);
22480
- await stopped();
22481
- await plugin.migrate(host, context);
23881
+ const enrollment = /* @__PURE__ */ new Map();
23882
+ try {
23883
+ for (const host of hosts) {
23884
+ await stopped();
23885
+ await plugin.beforeSignIn?.(host, context);
23886
+ await stopped();
23887
+ if (useVault) {
23888
+ enrollment.set(host, "unknown");
23889
+ try {
23890
+ await connectSetupHost(plugin, host, io, terminal, stopped);
23891
+ } catch (error) {
23892
+ if (error instanceof HostNotEnrolledError)
23893
+ enrollment.set(host, "not-enrolled");
23894
+ throw error;
23895
+ }
23896
+ enrollment.set(host, "enrolled");
23897
+ } else
23898
+ await plugin.signInLocal(host, context);
23899
+ await stopped();
23900
+ await plugin.beforeRegister?.(host, mode, context);
23901
+ await stopped();
23902
+ if (host === "opencode")
23903
+ await registerOpenCode(writes, stopped);
23904
+ else
23905
+ await registerPi(plugin, detection.pi.executable, io);
23906
+ await stopped();
23907
+ await plugin.migrate(host, context);
23908
+ }
23909
+ } catch (error) {
23910
+ if (enrollment.size === 0)
23911
+ throw error;
23912
+ try {
23913
+ const report = await enrollmentReport(plugin, hosts, enrollment);
23914
+ recordSetupEnrollment(error, report);
23915
+ for (const entry of report)
23916
+ printLine2(terminal, setupEnrollmentLine(entry));
23917
+ } catch {
23918
+ }
23919
+ throw error;
22482
23920
  }
22483
23921
  }
22484
23922
  printLine2(terminal, `${options.dryRun ? "Planned" : "Configured"} ${plugin.displayName} for ${hosts.join(", ")} (${mode}).`);
@@ -23128,7 +24566,7 @@ async function runCli(argv, deps) {
23128
24566
  return 1;
23129
24567
  }
23130
24568
  }
23131
- var execFileAsync = promisify(execFile2);
24569
+ var execFileAsync = promisify(execFile);
23132
24570
  async function openBrowserDefault(url) {
23133
24571
  if (process.platform === "win32") {
23134
24572
  await execFileAsync("cmd", ["/c", "start", "", url]);