@cortexkit/opencode-antigravity-auth 3.0.6 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/dist/cli.js +620 -120
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +128 -44
  4. package/dist/index.js +1469 -675
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +154 -73
  7. package/dist/server.js +1075 -280
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +11 -1
  11. package/dist/src/common-auth-embedded/claustrum/consumer.js +38 -1
  12. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +29 -0
  13. package/dist/src/common-auth-embedded/claustrum/custody.js +17 -0
  14. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  15. package/dist/src/common-auth-embedded/fs/refresh-file-lock.d.ts +8 -2
  16. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +6 -1
  17. package/dist/src/common-auth-embedded/pi-slot/lock.js +7 -3
  18. package/dist/src/common-auth-embedded/quota/format.d.ts +14 -3
  19. package/dist/src/common-auth-embedded/quota/format.js +135 -18
  20. package/dist/src/common-auth-embedded/quota/index.d.ts +1 -1
  21. package/dist/src/common-auth-embedded/quota/index.js +1 -1
  22. package/dist/src/common-auth-embedded/setup/command-error.d.ts +32 -0
  23. package/dist/src/common-auth-embedded/setup/command-error.js +79 -0
  24. package/dist/src/common-auth-embedded/setup/command-runner.js +118 -24
  25. package/dist/src/common-auth-embedded/setup/command.js +75 -19
  26. package/dist/src/common-auth-embedded/setup/enroll.js +17 -5
  27. package/dist/src/common-auth-embedded/setup/index.d.ts +2 -1
  28. package/dist/src/common-auth-embedded/setup/index.js +1 -0
  29. package/dist/src/common-auth-embedded/setup/register.js +8 -2
  30. package/dist/src/common-auth-embedded/setup/types.d.ts +14 -0
  31. package/dist/src/common-auth-embedded/source-output.json +92 -76
  32. package/dist/src/common-auth-embedded/store/pool.d.ts +1 -1
  33. package/dist/src/common-auth-embedded/store/pool.js +0 -1
  34. package/dist/src/common-auth-embedded/store/refresh-lock.d.ts +0 -1
  35. package/dist/src/common-auth-embedded/store/refresh-lock.js +0 -1
  36. package/dist/src/ga/server/index.d.ts.map +1 -1
  37. package/dist/src/ga/server/index.js +4 -2
  38. package/dist/src/ga/server/index.js.map +1 -1
  39. package/dist/src/ga/tui/host-ga.d.ts.map +1 -1
  40. package/dist/src/ga/tui/host-ga.js +37 -3
  41. package/dist/src/ga/tui/host-ga.js.map +1 -1
  42. package/dist/src/plugin/config/schema.d.ts.map +1 -1
  43. package/dist/src/plugin/config/schema.js +2 -1
  44. package/dist/src/plugin/config/schema.js.map +1 -1
  45. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  46. package/dist/src/plugin/ga-location-services.js +4 -3
  47. package/dist/src/plugin/ga-location-services.js.map +1 -1
  48. package/dist/src/plugin/gemini-dump.d.ts.map +1 -1
  49. package/dist/src/plugin/gemini-dump.js +2 -5
  50. package/dist/src/plugin/gemini-dump.js.map +1 -1
  51. package/dist/src/plugin/index.d.ts.map +1 -1
  52. package/dist/src/plugin/index.js +3 -3
  53. package/dist/src/plugin/index.js.map +1 -1
  54. package/dist/src/plugin/logging-utils.d.ts.map +1 -1
  55. package/dist/src/plugin/logging-utils.js +2 -5
  56. package/dist/src/plugin/logging-utils.js.map +1 -1
  57. package/dist/src/plugin/request.d.ts +1 -2
  58. package/dist/src/plugin/request.d.ts.map +1 -1
  59. package/dist/src/plugin/request.js +8 -12
  60. package/dist/src/plugin/request.js.map +1 -1
  61. package/dist/src/plugin/shared/request-services.d.ts +8 -1
  62. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  63. package/dist/src/plugin/shared/request-services.js +140 -58
  64. package/dist/src/plugin/shared/request-services.js.map +1 -1
  65. package/dist/src/plugin/shared/vault-request-credentials.d.ts +12 -3
  66. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  67. package/dist/src/plugin/shared/vault-request-credentials.js +3 -0
  68. package/dist/src/plugin/shared/vault-request-credentials.js.map +1 -1
  69. package/dist/src/plugin/vault-custody.d.ts +14 -1
  70. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  71. package/dist/src/plugin/vault-custody.js +57 -10
  72. package/dist/src/plugin/vault-custody.js.map +1 -1
  73. package/dist/src/sidebar-projection.d.ts +4 -0
  74. package/dist/src/sidebar-projection.d.ts.map +1 -1
  75. package/dist/src/sidebar-projection.js +6 -2
  76. package/dist/src/sidebar-projection.js.map +1 -1
  77. package/dist/src/tui/quota-layout.d.ts +94 -0
  78. package/dist/src/tui/quota-layout.d.ts.map +1 -0
  79. package/dist/src/tui/quota-layout.js +139 -0
  80. package/dist/src/tui/quota-layout.js.map +1 -0
  81. package/dist/src/tui/route-layout.d.ts +8 -0
  82. package/dist/src/tui/route-layout.d.ts.map +1 -0
  83. package/dist/src/tui/route-layout.js +36 -0
  84. package/dist/src/tui/route-layout.js.map +1 -0
  85. package/dist/src/tui.d.ts.map +1 -1
  86. package/dist/src/tui.js +26 -128
  87. package/dist/src/tui.js.map +1 -1
  88. package/dist/tui-build-map.json +42 -13
  89. package/dist/tui-ga-build-map.json +46 -17
  90. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +11 -1
  91. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +29 -0
  92. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  93. package/dist/types/src/common-auth-embedded/fs/refresh-file-lock.d.ts +8 -2
  94. package/dist/types/src/common-auth-embedded/quota/format.d.ts +14 -3
  95. package/dist/types/src/common-auth-embedded/quota/index.d.ts +1 -1
  96. package/dist/types/src/common-auth-embedded/setup/command-error.d.ts +32 -0
  97. package/dist/types/src/common-auth-embedded/setup/index.d.ts +2 -1
  98. package/dist/types/src/common-auth-embedded/setup/types.d.ts +14 -0
  99. package/dist/types/src/common-auth-embedded/store/pool.d.ts +1 -1
  100. package/dist/types/src/common-auth-embedded/store/refresh-lock.d.ts +0 -1
  101. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  102. package/dist/types/src/plugin/config/schema.d.ts.map +1 -1
  103. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  104. package/dist/types/src/plugin/gemini-dump.d.ts.map +1 -1
  105. package/dist/types/src/plugin/index.d.ts.map +1 -1
  106. package/dist/types/src/plugin/logging-utils.d.ts.map +1 -1
  107. package/dist/types/src/plugin/request.d.ts +1 -2
  108. package/dist/types/src/plugin/request.d.ts.map +1 -1
  109. package/dist/types/src/plugin/shared/request-services.d.ts +8 -1
  110. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  111. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +12 -3
  112. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  113. package/dist/types/src/plugin/vault-custody.d.ts +14 -1
  114. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  115. package/package.json +3 -3
  116. package/src/common-auth-embedded/claustrum/consumer.d.ts +11 -1
  117. package/src/common-auth-embedded/claustrum/consumer.js +38 -1
  118. package/src/common-auth-embedded/claustrum/custody.d.ts +29 -0
  119. package/src/common-auth-embedded/claustrum/custody.js +17 -0
  120. package/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  121. package/src/common-auth-embedded/fs/refresh-file-lock.d.ts +8 -2
  122. package/src/common-auth-embedded/fs/refresh-file-lock.js +6 -1
  123. package/src/common-auth-embedded/pi-slot/lock.js +7 -3
  124. package/src/common-auth-embedded/quota/format.d.ts +14 -3
  125. package/src/common-auth-embedded/quota/format.js +135 -18
  126. package/src/common-auth-embedded/quota/index.d.ts +1 -1
  127. package/src/common-auth-embedded/quota/index.js +1 -1
  128. package/src/common-auth-embedded/setup/command-error.d.ts +32 -0
  129. package/src/common-auth-embedded/setup/command-error.js +79 -0
  130. package/src/common-auth-embedded/setup/command-runner.js +118 -24
  131. package/src/common-auth-embedded/setup/command.js +75 -19
  132. package/src/common-auth-embedded/setup/enroll.js +17 -5
  133. package/src/common-auth-embedded/setup/index.d.ts +2 -1
  134. package/src/common-auth-embedded/setup/index.js +1 -0
  135. package/src/common-auth-embedded/setup/register.js +8 -2
  136. package/src/common-auth-embedded/setup/types.d.ts +14 -0
  137. package/src/common-auth-embedded/source-output.json +92 -76
  138. package/src/common-auth-embedded/store/pool.d.ts +1 -1
  139. package/src/common-auth-embedded/store/pool.js +0 -1
  140. package/src/common-auth-embedded/store/refresh-lock.d.ts +0 -1
  141. package/src/common-auth-embedded/store/refresh-lock.js +0 -1
  142. package/src/tui-compiled/common-auth-embedded/quota/format.js +135 -18
  143. package/src/tui-compiled/common-auth-embedded/quota/index.js +1 -1
  144. package/src/tui-compiled/tui/quota-layout.js +378 -0
  145. package/src/tui-compiled/tui/route-layout.js +30 -0
  146. package/src/tui-compiled/tui.js +145 -427
  147. package/src/tui-ga-compiled/host-ga.js +82 -52
  148. package/src/tui-ga-compiled/shared/6ca47cd4ec33fe72-route-layout.js +30 -0
  149. package/src/tui-ga-compiled/shared/8ae1927e5910ea81-sidebar-projection.js +2 -2
  150. package/src/tui-ga-compiled/shared/aef2402f8fc342f0-format.js +135 -18
  151. package/src/tui-ga-compiled/shared/bf17cbee28e58197-index.js +1 -1
  152. package/src/tui-ga-compiled/shared/dd4c9e1a907f8ef0-quota-layout.js +378 -0
  153. package/src/tui-ga-raw/host-ga.tsx +71 -30
  154. package/src/tui-ga-raw/shared/6ca47cd4ec33fe72-route-layout.js +30 -0
  155. package/src/tui-ga-raw/shared/8ae1927e5910ea81-sidebar-projection.js +2 -2
  156. package/src/tui-ga-raw/shared/aef2402f8fc342f0-format.js +135 -18
  157. package/src/tui-ga-raw/shared/bf17cbee28e58197-index.js +1 -1
  158. package/src/tui-ga-raw/shared/dd4c9e1a907f8ef0-quota-layout.tsx +391 -0
  159. package/src/tui-raw/common-auth-embedded/quota/format.js +135 -18
  160. package/src/tui-raw/common-auth-embedded/quota/index.js +1 -1
  161. package/src/tui-raw/tui/quota-layout.tsx +391 -0
  162. package/src/tui-raw/tui/route-layout.js +30 -0
  163. package/src/tui-raw/tui.tsx +50 -309
  164. package/src/tui.tsx +50 -309
package/dist/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,15 @@ 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
+ part: {
341
+ kind: "window",
342
+ name: quotaWindowName(limit),
343
+ figure: percentLeft(limit.remainingPercent ?? 0),
344
+ remainingPercent,
345
+ checkedAt: limit.checkedAt,
346
+ ...resetDetails(limit.resetsAt, limit.checkedAt, now)
347
+ }
337
348
  };
338
349
  });
339
350
  const budget = quota.budget;
@@ -341,23 +352,85 @@ function quotaWindowParts(quota, options) {
341
352
  const remainingPercent = budget.remainingPercent;
342
353
  const figure = budget.reached ? "credits spent" : remainingPercent !== void 0 ? `credits ${percentLeft(remainingPercent)}` : "credits available";
343
354
  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)
355
+ scope: ALL_SCOPE,
356
+ spent: budget.reached,
357
+ part: {
358
+ kind: "budget",
359
+ name: "credits",
360
+ figure,
361
+ ...remainingPercent === void 0 ? {} : { remainingPercent: clampPercent(remainingPercent) },
362
+ checkedAt: budget.checkedAt,
363
+ ...resetDetails(budget.resetsAt, budget.checkedAt, now)
364
+ }
350
365
  });
351
366
  }
352
367
  if (windows.length > 0) {
353
- const age = now - Math.min(...windows.map((part) => part.checkedAt));
368
+ const age = now - Math.min(...windows.map(({ part }) => part.checkedAt));
354
369
  if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
355
370
  return { windows, age: `checked ${shortSpan(age)} ago` };
356
371
  }
357
372
  }
358
373
  return { windows };
359
374
  }
375
+ function isQuotaStale(quota, options) {
376
+ return scopedWindowParts(quota, options).age !== void 0;
377
+ }
378
+ function scopeDisplayName(scope) {
379
+ const model = scope.slice(scope.indexOf(":") + 1);
380
+ return model.charAt(0).toUpperCase() + model.slice(1);
381
+ }
382
+ function scopeAbbreviations(scopes) {
383
+ const names = [...new Set(scopes.map(scopeDisplayName))];
384
+ const lengths = new Map(names.map((name) => [name, 2]));
385
+ const short = (name) => name.slice(0, lengths.get(name));
386
+ for (; ; ) {
387
+ const byShort = /* @__PURE__ */ new Map();
388
+ for (const name of names) {
389
+ byShort.set(short(name), [...byShort.get(short(name)) ?? [], name]);
390
+ }
391
+ let extended = false;
392
+ for (const group of byShort.values()) {
393
+ if (group.length < 2)
394
+ continue;
395
+ for (const name of group) {
396
+ const length = lengths.get(name) ?? 2;
397
+ if (length < name.length) {
398
+ lengths.set(name, length + 1);
399
+ extended = true;
400
+ }
401
+ }
402
+ }
403
+ if (!extended)
404
+ break;
405
+ }
406
+ return new Map(scopes.map((scope) => [scope, short(scopeDisplayName(scope))]));
407
+ }
408
+ function narrowTextParts(quota, options) {
409
+ const { windows } = scopedWindowParts(quota, options);
410
+ const general = windows.filter(({ part, scope }) => part.kind === "window" && scope === ALL_SCOPE);
411
+ const scoped = windows.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE);
412
+ const abbreviations = scopeAbbreviations(scoped.map(({ scope }) => scope));
413
+ const budget = windows.find(({ part }) => part.kind === "budget");
414
+ const budgetLeft = budget?.spent ? 0 : budget?.part.remainingPercent;
415
+ const extras = [
416
+ ...scoped.map(({ scope, part }) => ({
417
+ label: abbreviations.get(scope) ?? scope,
418
+ remaining: part.remainingPercent ?? 0
419
+ })),
420
+ ...budgetLeft === void 0 ? [] : [{ label: "cr", remaining: budgetLeft }]
421
+ ];
422
+ const tightest = extras.reduce((best, item) => best === void 0 || item.remaining < best.remaining ? item : best, void 0);
423
+ const pieces = general.map(({ part }) => `${part.name} ${wholePercent(part.remainingPercent ?? 0)}%`);
424
+ if (tightest) {
425
+ pieces.push(`${tightest.label} ${wholePercent(tightest.remaining)}%`);
426
+ }
427
+ if (pieces.length === 0)
428
+ return windows.map(({ part }) => part.figure);
429
+ return pieces.map((piece, index) => index === pieces.length - 1 ? `${piece} left` : piece);
430
+ }
360
431
  function quotaTextParts(quota, options) {
432
+ if (options.form === "narrow")
433
+ return narrowTextParts(quota, options);
361
434
  const parts = quotaWindowParts(quota, options);
362
435
  const full = (options.form ?? "full") === "full";
363
436
  const text2 = parts.windows.map((part) => {
@@ -502,6 +575,7 @@ __export(quota_exports, {
502
575
  futureResetAt: () => futureResetAt,
503
576
  isQuotaMap: () => isQuotaMap,
504
577
  isQuotaObservation: () => isQuotaObservation,
578
+ isQuotaStale: () => isQuotaStale,
505
579
  mergeQuotaObservation: () => mergeQuotaObservation,
506
580
  projectQuota: () => projectQuota,
507
581
  quotaCodec: () => quotaCodec2,
@@ -986,7 +1060,10 @@ function isLostMarkerRaceError(error) {
986
1060
  const code2 = error?.code;
987
1061
  return code2 === "ENOENT" || !windowsPrivateFiles && (code2 === "EINVAL" || code2 === "ENOTDIR");
988
1062
  }
989
- async function acquireRefreshFileLock(options) {
1063
+ function acquireRefreshFileLock(options) {
1064
+ return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
1065
+ }
1066
+ async function acquireRefreshFileLockWithClock(options) {
990
1067
  const lockPath = lockPathFor(options.path, options.name);
991
1068
  const legacyOwnerPath = join4(lockPath, "owner.json");
992
1069
  const ownerId = randomUUID7();
@@ -1708,7 +1785,6 @@ async function acquirePoolLock(spec, defaults, env3) {
1708
1785
  name: spec.name,
1709
1786
  path: spec.path,
1710
1787
  ttlMs: options.ttlMs,
1711
- now: env3.now,
1712
1788
  renew: options.renew,
1713
1789
  onContended: () => emit("contended"),
1714
1790
  ...env3.onRenewalTimer ? {
@@ -4824,7 +4900,6 @@ function openPoolStore(options) {
4824
4900
  ],
4825
4901
  lockDefaults,
4826
4902
  lockEnv: {
4827
- now: options.now ?? Date.now,
4828
4903
  ...options.onLockEvent ? { onLockEvent: options.onLockEvent } : {},
4829
4904
  ...options.onLockStep ? { onLockStep: options.onLockStep } : {},
4830
4905
  ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
@@ -7112,11 +7187,11 @@ var init_doctor = __esm({
7112
7187
 
7113
7188
  // ../core/dist/common-auth-embedded/auth-menu/login.js
7114
7189
  import { execFileSync as defaultExecFileSync, spawn as defaultSpawn } from "node:child_process";
7115
- function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn = defaultSpawn) {
7190
+ function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn2 = defaultSpawn) {
7116
7191
  try {
7117
7192
  if (platform === "win32") {
7118
7193
  const command = `Start-Process '${url.replaceAll("'", "''")}'`;
7119
- const child = spawn("powershell.exe", [
7194
+ const child = spawn2("powershell.exe", [
7120
7195
  "-NoProfile",
7121
7196
  "-NonInteractive",
7122
7197
  "-WindowStyle",
@@ -8896,6 +8971,15 @@ function credentialTypeOf(row, family) {
8896
8971
  return row.refreshAdapter === void 0 ? "api_key" : void 0;
8897
8972
  return void 0;
8898
8973
  }
8974
+ function grantReachOf(listed) {
8975
+ const { grants, grantTuples } = listed;
8976
+ if (grants === void 0 || grantTuples === void 0)
8977
+ return void 0;
8978
+ return Object.freeze({
8979
+ grants,
8980
+ tuples: Object.freeze(grantTuples.map(({ selectorKind, selector, operation }) => Object.freeze({ selectorKind, selector, operation })))
8981
+ });
8982
+ }
8899
8983
  var defaultLogger, SERVING_MARGIN_MS, ClaustrumScopedCustody;
8900
8984
  var init_custody = __esm({
8901
8985
  "../core/dist/common-auth-embedded/claustrum/custody.js"() {
@@ -9021,10 +9105,12 @@ var init_custody = __esm({
9021
9105
  }
9022
9106
  for (const record3 of skipped)
9023
9107
  this.#logger.warn("skipped malformed vault record", record3);
9108
+ const grantReach = grantReachOf(inventory);
9024
9109
  return {
9025
9110
  view: inventory.view,
9026
9111
  credentials: Object.freeze(credentials),
9027
- skipped: Object.freeze(skipped)
9112
+ skipped: Object.freeze(skipped),
9113
+ ...grantReach && { grantReach }
9028
9114
  };
9029
9115
  }
9030
9116
  /**
@@ -9590,6 +9676,11 @@ var init_consumer = __esm({
9590
9676
  #connecting;
9591
9677
  #refreshing;
9592
9678
  #roster;
9679
+ /**
9680
+ * The grants named by this instance's latest discovery, with the view that
9681
+ * discovery committed. Memory only: the roster file never carries it.
9682
+ */
9683
+ #grantReach;
9593
9684
  #timer;
9594
9685
  #started = false;
9595
9686
  #insula;
@@ -9666,6 +9757,19 @@ var init_consumer = __esm({
9666
9757
  snapshot() {
9667
9758
  return this.#roster;
9668
9759
  }
9760
+ /**
9761
+ * What this consumer is granted, from its latest discovery, without any I/O.
9762
+ * It explains an empty roster: `grants === 0` means no grant at all, while
9763
+ * `grants > 0` means a grant that reaches no credential (`tuples` names its
9764
+ * selector). Undefined means unknown, never zero: the vault or client is too
9765
+ * old to send it, nothing was discovered yet, or the roster now in memory is
9766
+ * a different view than the one this instance discovered (a peer process
9767
+ * held the discovery lease and its newer roster was served instead).
9768
+ */
9769
+ grantReach() {
9770
+ const latest2 = this.#grantReach;
9771
+ return latest2 && this.#roster?.view === latest2.view ? latest2.reach : void 0;
9772
+ }
9669
9773
  /** Rows for `/routing`, from the last committed roster. */
9670
9774
  routingRows() {
9671
9775
  return vaultRoutingRows(this.#roster);
@@ -9677,6 +9781,7 @@ var init_consumer = __esm({
9677
9781
  this.#refreshing = (async () => {
9678
9782
  if (!await this.#active()) {
9679
9783
  this.#roster = void 0;
9784
+ this.#grantReach = void 0;
9680
9785
  this.#custody?.close();
9681
9786
  this.#custody = void 0;
9682
9787
  this.#insula?.release();
@@ -9684,9 +9789,15 @@ var init_consumer = __esm({
9684
9789
  return void 0;
9685
9790
  }
9686
9791
  const custody = await this.#getCustody();
9792
+ let discovered;
9687
9793
  const roster = await refreshVaultRoster({
9688
9794
  path: this.#options.rosterPath,
9689
- custody,
9795
+ custody: {
9796
+ discover: async (signal) => {
9797
+ discovered = await custody.discover(signal);
9798
+ return discovered;
9799
+ }
9800
+ },
9690
9801
  isActive: () => this.#active(),
9691
9802
  signal: this.#shutdown.signal,
9692
9803
  projection: () => ({
@@ -9699,6 +9810,8 @@ var init_consumer = __esm({
9699
9810
  this.#assertOpen();
9700
9811
  const changed = roster?.view !== this.#roster?.view;
9701
9812
  this.#roster = roster;
9813
+ if (discovered && roster?.view !== void 0)
9814
+ this.#grantReach = discovered.grantReach ? { view: roster.view, reach: discovered.grantReach } : void 0;
9702
9815
  if (roster && changed)
9703
9816
  this.#options.onRoster?.(roster);
9704
9817
  return roster;
@@ -9926,6 +10039,7 @@ var init_consumer = __esm({
9926
10039
  this.#insula?.release();
9927
10040
  this.#insula = void 0;
9928
10041
  this.#roster = void 0;
10042
+ this.#grantReach = void 0;
9929
10043
  }
9930
10044
  };
9931
10045
  }
@@ -9999,7 +10113,7 @@ var init_claustrum = __esm({
9999
10113
  });
10000
10114
 
10001
10115
  // ../core/dist/common-auth-embedded/pi-slot/lock.js
10002
- import { rmdirSync, statSync as statSync2 } from "node:fs";
10116
+ import { rmdirSync, statSync as statSync2, utimesSync } from "node:fs";
10003
10117
  import { mkdir as mkdir9, rmdir, stat as stat5, utimes } from "node:fs/promises";
10004
10118
  function sameDirectory(observed, identity) {
10005
10119
  return observed.dev === identity.dev && observed.ino === identity.ino;
@@ -10095,7 +10209,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
10095
10209
  return;
10096
10210
  let observed;
10097
10211
  try {
10098
- observed = await stat5(path2);
10212
+ observed = statSync2(path2);
10099
10213
  } catch (error) {
10100
10214
  retry(error);
10101
10215
  return;
@@ -10109,11 +10223,12 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
10109
10223
  }
10110
10224
  const next = new Date(precision === "s" ? Math.ceil(Date.now() / 1e3) * 1e3 : Date.now());
10111
10225
  try {
10112
- await utimes(path2, next, next);
10226
+ utimesSync(path2, next, next);
10113
10227
  } catch (error) {
10114
10228
  retry(error);
10115
10229
  return;
10116
10230
  }
10231
+ assertFresh();
10117
10232
  if (released)
10118
10233
  return;
10119
10234
  mtime = next.getTime();
@@ -10555,7 +10670,7 @@ var init_pi_slot = __esm({
10555
10670
  });
10556
10671
 
10557
10672
  // src/cli.ts
10558
- import { execFile as execFile2 } from "node:child_process";
10673
+ import { execFile } from "node:child_process";
10559
10674
  import { realpathSync as realpathSync2 } from "node:fs";
10560
10675
  import { resolve as resolve12 } from "node:path";
10561
10676
  import { createInterface } from "node:readline/promises";
@@ -11839,7 +11954,7 @@ async function syncDirectory(path2, boundary) {
11839
11954
  }
11840
11955
  await boundary?.("after-directory-sync");
11841
11956
  }
11842
- async function exclusiveBytes(path2, bytes, expectedHash, boundary) {
11957
+ async function exclusiveBytes(path2, bytes, expectedHash, boundary, pointerStage = false) {
11843
11958
  let handle;
11844
11959
  try {
11845
11960
  handle = await open(path2, "wx", 384);
@@ -11858,7 +11973,8 @@ async function exclusiveBytes(path2, bytes, expectedHash, boundary) {
11858
11973
  const reopened = await secureRead(path2);
11859
11974
  if (digest(reopened) !== expectedHash || !reopened.equals(bytes))
11860
11975
  throw new AccountMigrationError("exclusive backup or recovery copy differs");
11861
- await syncFile(path2);
11976
+ if (handle === void 0 || !pointerStage)
11977
+ await syncFile(path2);
11862
11978
  await syncDirectory(dirname(path2), boundary);
11863
11979
  }
11864
11980
  async function readJournal(paths) {
@@ -12560,7 +12676,7 @@ function createAccountMigrationFactory(modules) {
12560
12676
  throw new AccountMigrationError("source changed before pointer publication");
12561
12677
  if (!journal)
12562
12678
  throw new AccountMigrationError("capture journal missing");
12563
- await publishGenerationPointer(modules, physical, journal, parentLease, prior, options.onBoundary);
12679
+ await publishGenerationPointer(modules, physical, journal, parentLease, lease, prior, options.onBoundary);
12564
12680
  });
12565
12681
  await options.onBoundary?.("after-capture");
12566
12682
  }
@@ -12905,47 +13021,9 @@ async function initializeFreshAccountStore(modules, options) {
12905
13021
  timeoutMs: 2e3,
12906
13022
  renew: true
12907
13023
  }, 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
- }
13024
+ const journal = await readJournal(physical);
13025
+ if (pointer === void 0)
13026
+ return initializePrivateEmptyGeneration(modules, physical, parentLease, lease, options);
12949
13027
  if (journal?.sourceKind !== "absent" || journal.operation !== "migrate" || journal.status === "inactive")
12950
13028
  throw new AccountMigrationError("fresh resume has no compatible pointed generation");
12951
13029
  await assertPublishedAccountStoreGeneration(physical);
@@ -13021,6 +13099,187 @@ async function initializeFreshAccountStore(modules, options) {
13021
13099
  throw error;
13022
13100
  }
13023
13101
  }
13102
+ async function exclusiveUnpublishedBytes(path2, bytes) {
13103
+ const handle = await open(path2, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
13104
+ try {
13105
+ await handle.writeFile(bytes);
13106
+ } finally {
13107
+ await handle.close();
13108
+ }
13109
+ if (!(await secureRead(path2)).equals(bytes))
13110
+ throw new AccountMigrationError("private stage readback differs");
13111
+ }
13112
+ async function initializePrivateEmptyGeneration(modules, paths, parentLease, managementLease, options) {
13113
+ return modules.fs.withLock(paths.legacyPath, { name: "accounts", ttlMs: 1e4, timeoutMs: 2e3, renew: true }, async (accountsLease) => {
13114
+ const directory = await lstat(paths.storeDir);
13115
+ const assertOwned = async () => {
13116
+ await parentLease.assertOwned();
13117
+ await managementLease.assertOwned();
13118
+ await accountsLease.assertOwned();
13119
+ const current = await lstat(paths.storeDir);
13120
+ if (!current.isDirectory() || current.isSymbolicLink() || current.dev !== directory.dev || current.ino !== directory.ino || !sameFilesystemPath(await realpath(paths.storeDir), paths.storeDir))
13121
+ throw new AccountMigrationError("private generation directory changed");
13122
+ privateMode(current.mode, 448);
13123
+ };
13124
+ const boundary = options.onBoundary;
13125
+ await assertOwned();
13126
+ await assertSourceAbsent(paths);
13127
+ if (await readPointer(paths.legacyPath))
13128
+ throw new AccountMigrationError("private initialization found a competing pointer");
13129
+ if (await readJournal(paths) || await exists(paths.configPath) || await exists(paths.statePath))
13130
+ throw new AccountMigrationError("fresh stage has unrelated artifacts");
13131
+ const journal = {
13132
+ schemaVersion: 1,
13133
+ id: pathGenerationId(paths),
13134
+ legacyPath: paths.legacyPath,
13135
+ storeDir: paths.storeDir,
13136
+ sourceKind: "absent",
13137
+ status: "pending",
13138
+ operation: "migrate",
13139
+ phase: "build",
13140
+ manifest: {
13141
+ sourceVersion: null,
13142
+ normalizationClock: options.now(),
13143
+ accounts: [],
13144
+ routing: { schemaVersion: 1 },
13145
+ effectiveActiveIndex: 0
13146
+ },
13147
+ mapping: [],
13148
+ completedRows: []
13149
+ };
13150
+ await assertOwned();
13151
+ await exclusiveUnpublishedBytes(paths.configPath, Buffer.from('{"version":1,"accounts":[]}\n'));
13152
+ await boundary?.("empty-stage:after-seed");
13153
+ const store = openMigrationStore(modules, paths, options.now, async (step, info) => {
13154
+ await assertOwned();
13155
+ if (!step.includes("config") || await exists(paths.statePath))
13156
+ throw new AccountMigrationError("private empty stage attempted a credential write");
13157
+ await secureRead(paths.configPath);
13158
+ await boundary?.(`public:${info.operation}:${step}`);
13159
+ await assertOwned();
13160
+ });
13161
+ await assertOwned();
13162
+ await store.initialize();
13163
+ await boundary?.("empty-stage:after-initialize");
13164
+ await assertOwned();
13165
+ await store.updateSettings((settings) => {
13166
+ settings[ROUTING_SETTINGS_KEY] = encodeRoutingSettings(journal.manifest.routing);
13167
+ settings[ACCOUNT_STORE_GENERATION_SETTINGS_KEY] = generationJson(journal);
13168
+ settings[MANAGEMENT_SETTINGS_KEY] = {
13169
+ id: journal.id,
13170
+ kind: "migration",
13171
+ targets: [],
13172
+ progress: { step: "build", completedTargets: [] }
13173
+ };
13174
+ return settings;
13175
+ });
13176
+ await boundary?.("empty-stage:after-build-settings");
13177
+ await expectedFreshArtifacts(paths, journal);
13178
+ await assertStateOwnership(paths, journal, true);
13179
+ await verifyImported(store, journal);
13180
+ const snapshot2 = await secureRead(paths.configPath);
13181
+ await verifyImported(store, journal);
13182
+ journal.verification = {
13183
+ manifestSha256: digest(canonical2(manifestJson(journal.manifest))),
13184
+ configSha256: digest(snapshot2),
13185
+ statePresent: false,
13186
+ durability: accountMigrationDurability()
13187
+ };
13188
+ await assertOwned();
13189
+ await assertSourceAbsent(paths);
13190
+ journal.sourceAbsenceVerified = true;
13191
+ await management(store, journal, true);
13192
+ await boundary?.("empty-stage:after-clear-settings");
13193
+ await expectedFreshArtifacts(paths, journal);
13194
+ await currentSuccessor(store, paths, journal);
13195
+ if ((await settingsOf(store))[MANAGEMENT_SETTINGS_KEY] !== void 0)
13196
+ throw new AccountMigrationError("private stage still has management work");
13197
+ journal.phase = "activate";
13198
+ journal.status = "active";
13199
+ decodeAccountMigrationJournal(journalJson(journal));
13200
+ await assertOwned();
13201
+ await exclusiveUnpublishedBytes(paths.migrationPath, Buffer.from(`${JSON.stringify(journalJson(journal), null, 2)}
13202
+ `));
13203
+ await boundary?.("empty-stage:after-journal");
13204
+ await syncFile(paths.configPath);
13205
+ await boundary?.("empty-stage:after-config-sync");
13206
+ await syncFile(paths.migrationPath);
13207
+ await boundary?.("empty-stage:after-journal-sync");
13208
+ for (const [name, path3] of [
13209
+ ["backups", paths.backupsDir],
13210
+ ["retired", paths.retiredDir],
13211
+ ["transfers", paths.transfersDir]
13212
+ ]) {
13213
+ await syncDirectory(path3);
13214
+ await boundary?.(`empty-stage:after-${name}-sync`);
13215
+ }
13216
+ await syncDirectory(paths.storeDir);
13217
+ await boundary?.("empty-stage:after-generation-sync");
13218
+ await boundary?.("pointer:before-publication");
13219
+ const reopened = await readJournal(paths);
13220
+ if (!isDeepStrictEqual(reopened, journal))
13221
+ throw new AccountMigrationError("publication requires its complete synced canonical journal");
13222
+ const pointer = {
13223
+ schemaVersion: 1,
13224
+ id: journal.id,
13225
+ directoryBasename: basename(paths.storeDir)
13226
+ };
13227
+ const path2 = accountStorePointerPath(paths.legacyPath);
13228
+ const stage = `${path2}.${journal.id}.tmp`;
13229
+ const bytes = Buffer.from(`${JSON.stringify(pointer, null, 2)}
13230
+ `);
13231
+ await assertOwned();
13232
+ let stageHandle;
13233
+ try {
13234
+ stageHandle = await open(stage, "wx", 384);
13235
+ } catch (error) {
13236
+ if (errno(error) !== "EEXIST")
13237
+ throw error;
13238
+ }
13239
+ if (stageHandle) {
13240
+ try {
13241
+ await stageHandle.writeFile(bytes);
13242
+ await stageHandle.sync();
13243
+ } finally {
13244
+ await stageHandle.close();
13245
+ }
13246
+ }
13247
+ if (!(await secureRead(stage)).equals(bytes))
13248
+ throw new AccountMigrationError("exclusive pointer stage differs");
13249
+ if (!stageHandle)
13250
+ await syncFile(stage);
13251
+ await boundary?.("empty-stage:after-pointer-stage");
13252
+ await syncDirectory(dirname(path2));
13253
+ await boundary?.("empty-stage:after-parent-prelink-sync");
13254
+ await boundary?.("pointer:before-link");
13255
+ await assertOwned();
13256
+ await assertSourceAbsent(paths);
13257
+ if (await exists(path2))
13258
+ throw new AccountMigrationError("foreign or competing pointer publication refuses overwrite");
13259
+ if (await exists(resolveAccountStorePaths(paths.legacyPath).storeDir))
13260
+ throw new AccountMigrationError("foreign logical store directory appeared before publication");
13261
+ try {
13262
+ await link(stage, path2);
13263
+ } catch (error) {
13264
+ if (errno(error) === "EEXIST")
13265
+ throw new AccountMigrationError("foreign or competing pointer publication refuses overwrite");
13266
+ throw new AccountMigrationError("exclusive pointer hard-link publication failed");
13267
+ }
13268
+ await boundary?.("pointer:after-link-before-parent-sync");
13269
+ await syncDirectory(dirname(path2));
13270
+ if (!isDeepStrictEqual(await readPointer(paths.legacyPath), pointer) || !isDeepStrictEqual(await readJournal(paths), journal))
13271
+ throw new AccountMigrationError("pointer publication readback differs");
13272
+ await expectedFreshArtifacts(paths, journal);
13273
+ await currentSuccessor(store, paths, journal);
13274
+ const admission = await readAccountStoreAdmission(paths.legacyPath, modules, options.now, journal.id);
13275
+ if (admission.status !== "active" || !isDeepStrictEqual(admission.receipt, receipt(journal)))
13276
+ throw new AccountMigrationError("published empty generation is not admitted");
13277
+ await boundary?.("pointer:after-sync-before-stage-cleanup");
13278
+ await cleanupPointerStage(paths.legacyPath, pointer, parentLease);
13279
+ await assertOwned();
13280
+ return { status: "completed", receipt: receipt(journal) };
13281
+ });
13282
+ }
13024
13283
  async function allocateGeneration(legacyPath) {
13025
13284
  if (await exists(resolveAccountStorePaths(legacyPath).storeDir))
13026
13285
  throw new AccountMigrationError("foreign logical directory refuses generation allocation");
@@ -13029,13 +13288,16 @@ async function allocateGeneration(legacyPath) {
13029
13288
  await prepareDirectories(paths);
13030
13289
  return paths;
13031
13290
  }
13032
- async function publishGenerationPointer(modules, paths, journal, parentLease, prior, boundary) {
13291
+ async function publishGenerationPointer(modules, paths, journal, parentLease, managementLease, prior, boundary, journalSavedBy) {
13033
13292
  await parentLease.assertOwned();
13293
+ await managementLease.assertOwned();
13034
13294
  const currentJournal = await readJournal(paths);
13035
13295
  if (!currentJournal || currentJournal.id !== journal.id || !isDeepStrictEqual(journalJson(currentJournal), journalJson(journal)))
13036
13296
  throw new AccountMigrationError("publication requires its complete synced canonical journal");
13037
- await syncFile(paths.migrationPath);
13038
- await syncDirectory(paths.storeDir);
13297
+ if (journalSavedBy !== managementLease) {
13298
+ await syncFile(paths.migrationPath);
13299
+ await syncDirectory(paths.storeDir);
13300
+ }
13039
13301
  const pointer = {
13040
13302
  schemaVersion: 1,
13041
13303
  id: journal.id,
@@ -13046,8 +13308,9 @@ async function publishGenerationPointer(modules, paths, journal, parentLease, pr
13046
13308
  const stage = `${path2}.${journal.id}.tmp`;
13047
13309
  const bytes = Buffer.from(`${JSON.stringify(pointer, null, 2)}
13048
13310
  `);
13049
- await exclusiveBytes(stage, bytes, digest(bytes));
13311
+ await exclusiveBytes(stage, bytes, digest(bytes), void 0, true);
13050
13312
  await parentLease.assertOwned();
13313
+ await managementLease.assertOwned();
13051
13314
  await boundary?.("pointer:before-link");
13052
13315
  if (await exists(resolveAccountStorePaths(paths.legacyPath).storeDir))
13053
13316
  throw new AccountMigrationError("foreign logical store directory appeared before publication");
@@ -13079,6 +13342,7 @@ async function publishGenerationPointer(modules, paths, journal, parentLease, pr
13079
13342
  stageName: () => stageName,
13080
13343
  beforeRename: async () => {
13081
13344
  await parentLease.assertOwned();
13345
+ await managementLease.assertOwned();
13082
13346
  if (!isDeepStrictEqual(await readPointer(paths.legacyPath), prior) || (await readJournal(oldPaths))?.status !== "inactive")
13083
13347
  throw new AccountMigrationError("inactive pointer changed before transition");
13084
13348
  await syncFile(`${path2}.${stageName}.tmp`);
@@ -13088,6 +13352,7 @@ async function publishGenerationPointer(modules, paths, journal, parentLease, pr
13088
13352
  await syncDirectory(dirname(path2));
13089
13353
  }
13090
13354
  await parentLease.assertOwned();
13355
+ await managementLease.assertOwned();
13091
13356
  }
13092
13357
  function withParentTopology(modules, legacyPath, body) {
13093
13358
  return modules.fs.withLock(legacyPath, {
@@ -13114,9 +13379,14 @@ async function finishPointerPublication(legacyPath, pointer, lease) {
13114
13379
  const path2 = accountStorePointerPath(legacyPath);
13115
13380
  await syncFile(path2);
13116
13381
  await syncDirectory(dirname(path2));
13382
+ if (await cleanupPointerStage(legacyPath, pointer, lease))
13383
+ await syncDirectory(dirname(path2));
13384
+ }
13385
+ async function cleanupPointerStage(legacyPath, pointer, lease) {
13386
+ const path2 = accountStorePointerPath(legacyPath);
13117
13387
  const stage = `${path2}.${pointer.id}.tmp`;
13118
13388
  if (!await exists(stage))
13119
- return;
13389
+ return false;
13120
13390
  const bytes = await secureRead(stage);
13121
13391
  if (!isDeepStrictEqual(decodeAccountStorePointer(jsonBytes(bytes), legacyPath), pointer))
13122
13392
  throw new AccountMigrationError("pointer stage differs from publication authority");
@@ -13125,7 +13395,7 @@ async function finishPointerPublication(legacyPath, pointer, lease) {
13125
13395
  throw new AccountMigrationError("pointer stage is not the published hard link");
13126
13396
  await lease.assertOwned();
13127
13397
  await unlink(stage);
13128
- await syncDirectory(dirname(path2));
13398
+ return true;
13129
13399
  }
13130
13400
 
13131
13401
  // ../core/dist/account-repository.js
@@ -16442,6 +16712,7 @@ async function fetchWithAgyCliTransport(url, init = {}, options = {}) {
16442
16712
  };
16443
16713
  try {
16444
16714
  options.signal?.addEventListener("abort", abort, { once: true });
16715
+ options.signal?.throwIfAborted();
16445
16716
  socket.write(requestBytes);
16446
16717
  options.onDebug?.(`agy transport request dispatched (${requestBytes.byteLength} bytes)`);
16447
16718
  const { head, leftover } = await waitForHead(socket, timeoutMs, () => {
@@ -16844,6 +17115,15 @@ async function loadCommonAuthStoreModules() {
16844
17115
  }
16845
17116
  var loadCommonAuthPiSlot = memoize(() => Promise.resolve().then(() => (init_pi_slot(), pi_slot_exports)));
16846
17117
 
17118
+ // ../core/dist/credential-redaction.js
17119
+ function maskSensitiveIdentifier(value) {
17120
+ if (typeof value !== "string" || value.length === 0)
17121
+ return "";
17122
+ if (value.length <= 8)
17123
+ return "****";
17124
+ return `${value.slice(0, 4)}****${value.slice(-4)}`;
17125
+ }
17126
+
16847
17127
  // ../core/dist/pi-paths.js
16848
17128
  import { homedir } from "node:os";
16849
17129
  import { dirname as dirname11, join as join6 } from "node:path";
@@ -18439,9 +18719,7 @@ function writeConsoleLog2(level, ...args) {
18439
18719
  }
18440
18720
  }
18441
18721
  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)}`;
18722
+ return maskSensitiveIdentifier(value);
18445
18723
  }
18446
18724
  var SENSITIVE_FIELD_PATTERN = /token|refresh|access|project|fingerprint|deviceId|sessionId|sessionToken|secret|password|apiKey|clientSecret/i;
18447
18725
  function redactSensitiveFields(value) {
@@ -20372,7 +20650,10 @@ function isLostMarkerRaceError2(error) {
20372
20650
  const code2 = error?.code;
20373
20651
  return code2 === "ENOENT" || !windowsPrivateFiles2 && (code2 === "EINVAL" || code2 === "ENOTDIR");
20374
20652
  }
20375
- async function acquireRefreshFileLock2(options) {
20653
+ function acquireRefreshFileLock2(options) {
20654
+ return acquireRefreshFileLockWithClock2({ ...options, now: Date.now });
20655
+ }
20656
+ async function acquireRefreshFileLockWithClock2(options) {
20376
20657
  const lockPath = lockPathFor2(options.path, options.name);
20377
20658
  const legacyOwnerPath = join9(lockPath, "owner.json");
20378
20659
  const ownerId = randomUUID13();
@@ -21306,6 +21587,31 @@ async function readClaustrumEnrollmentStatus2(paths, proposedName) {
21306
21587
  }
21307
21588
  return statusFromState2(state);
21308
21589
  }
21590
+ async function enrollmentAuthority2(paths, proposedName) {
21591
+ let status;
21592
+ try {
21593
+ status = await readClaustrumEnrollmentStatus2(paths, proposedName);
21594
+ } catch (error) {
21595
+ if (!(error instanceof ClaustrumConsumerError2) || error.kind !== "invalid-state" && error.kind !== "invalid-token") {
21596
+ return "unreadable";
21597
+ }
21598
+ try {
21599
+ const stateValue = await readBoundedJson2(paths.statePath);
21600
+ if (stateValue === void 0)
21601
+ return "unreadable";
21602
+ const state = decodeEnrollmentState2(stateValue);
21603
+ return state.phase === "approved" && state.proposedName === proposedName ? "vault" : "unreadable";
21604
+ } catch {
21605
+ return "unreadable";
21606
+ }
21607
+ }
21608
+ if ("proposedName" in status && status.proposedName !== proposedName)
21609
+ return "unreadable";
21610
+ if (status.state === "approved" || status.state === "blocked" && status.code === "missing_token") {
21611
+ return "vault";
21612
+ }
21613
+ return "local";
21614
+ }
21309
21615
  function statusFromState2(state) {
21310
21616
  if (state.phase === "pending") {
21311
21617
  return {
@@ -21546,30 +21852,126 @@ async function resetClaustrumEnrollmentState2(paths, proposedName) {
21546
21852
  }
21547
21853
 
21548
21854
  // src/common-auth-embedded/setup/command-runner.js
21549
- import { execFile } from "node:child_process";
21855
+ import { spawn } from "node:child_process";
21856
+ var STDERR_TAIL_MAX_BYTES = 4 * 1024;
21857
+ var STDOUT_MAX_BYTES = 1024 * 1024;
21858
+ var ByteTail = class {
21859
+ buffer = Buffer.alloc(STDERR_TAIL_MAX_BYTES);
21860
+ start = 0;
21861
+ length = 0;
21862
+ truncated = false;
21863
+ get didTruncate() {
21864
+ return this.truncated;
21865
+ }
21866
+ push(chunk) {
21867
+ if (chunk.length >= STDERR_TAIL_MAX_BYTES) {
21868
+ if (chunk.length > STDERR_TAIL_MAX_BYTES || this.length > 0)
21869
+ this.truncated = true;
21870
+ chunk.copy(this.buffer, 0, chunk.length - STDERR_TAIL_MAX_BYTES);
21871
+ this.start = 0;
21872
+ this.length = STDERR_TAIL_MAX_BYTES;
21873
+ return;
21874
+ }
21875
+ const overflow = Math.max(0, this.length + chunk.length - STDERR_TAIL_MAX_BYTES);
21876
+ if (overflow > 0)
21877
+ this.truncated = true;
21878
+ this.start = (this.start + overflow) % STDERR_TAIL_MAX_BYTES;
21879
+ this.length -= overflow;
21880
+ const writeAt = (this.start + this.length) % STDERR_TAIL_MAX_BYTES;
21881
+ const firstLength = Math.min(chunk.length, STDERR_TAIL_MAX_BYTES - writeAt);
21882
+ chunk.copy(this.buffer, writeAt, 0, firstLength);
21883
+ if (firstLength < chunk.length)
21884
+ chunk.copy(this.buffer, 0, firstLength);
21885
+ this.length += chunk.length;
21886
+ }
21887
+ toString() {
21888
+ const bytes = Buffer.alloc(this.length);
21889
+ const firstLength = Math.min(this.length, STDERR_TAIL_MAX_BYTES - this.start);
21890
+ this.buffer.copy(bytes, 0, this.start, this.start + firstLength);
21891
+ if (firstLength < this.length)
21892
+ this.buffer.copy(bytes, firstLength, 0, this.length - firstLength);
21893
+ let start = 0;
21894
+ while (start < bytes.length) {
21895
+ const byte = bytes[start];
21896
+ if (byte === void 0 || (byte & 192) !== 128)
21897
+ break;
21898
+ start++;
21899
+ }
21900
+ return bytes.subarray(start).toString("utf8");
21901
+ }
21902
+ };
21550
21903
  var defaultCommandRunner = {
21551
21904
  run(file, args, options = {}) {
21552
21905
  return new Promise((resolve13) => {
21553
21906
  const started = performance.now();
21554
21907
  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;
21908
+ const stderr = new ByteTail();
21909
+ const stdout = [];
21910
+ let stdoutLength = 0;
21911
+ let outputExceeded = false;
21912
+ let spawnError = false;
21913
+ let timedOut = false;
21914
+ let child;
21915
+ try {
21916
+ child = spawn(file, [...args], {
21917
+ env: options.env ?? process.env,
21918
+ windowsHide: true,
21919
+ windowsVerbatimArguments: options.windowsVerbatimArguments,
21920
+ stdio: ["ignore", "pipe", "pipe"]
21921
+ });
21922
+ } catch {
21563
21923
  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
21924
+ exitCode: 1,
21925
+ stdout: "",
21926
+ stderr: "",
21927
+ spawnError: true,
21928
+ signal: null,
21929
+ timedOut: false,
21930
+ durationMs: performance.now() - started
21571
21931
  });
21932
+ return;
21933
+ }
21934
+ const timer = timeoutMs > 0 ? setTimeout(() => {
21935
+ timedOut = true;
21936
+ child.kill("SIGTERM");
21937
+ }, timeoutMs) : void 0;
21938
+ child.stdout?.on("data", (chunk) => {
21939
+ const remaining = STDOUT_MAX_BYTES - stdoutLength;
21940
+ const length = Math.min(remaining, chunk.length);
21941
+ if (length > 0) {
21942
+ stdout.push(chunk.subarray(0, length));
21943
+ stdoutLength += length;
21944
+ }
21945
+ if (chunk.length > remaining) {
21946
+ outputExceeded = true;
21947
+ child.kill("SIGTERM");
21948
+ }
21572
21949
  });
21950
+ child.stderr?.on("data", (chunk) => stderr.push(chunk));
21951
+ let settled = false;
21952
+ const settle = (code2, signal) => {
21953
+ if (settled)
21954
+ return;
21955
+ settled = true;
21956
+ if (timer)
21957
+ clearTimeout(timer);
21958
+ resolve13({
21959
+ exitCode: spawnError ? 1 : outputExceeded ? 1 : code2 ?? 1,
21960
+ stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
21961
+ stderr: stderr.toString(),
21962
+ stderrTruncated: stderr.didTruncate,
21963
+ ...spawnError ? { spawnError: true } : {},
21964
+ signal: signal ?? null,
21965
+ timedOut,
21966
+ durationMs: performance.now() - started
21967
+ });
21968
+ };
21969
+ child.once("error", () => {
21970
+ spawnError = true;
21971
+ if (child.pid === void 0)
21972
+ settle(null, null);
21973
+ });
21974
+ child.once("close", (code2, signal) => settle(code2, signal));
21573
21975
  });
21574
21976
  }
21575
21977
  };
@@ -21586,6 +21988,56 @@ function runResolvedCommand(runner, platform, file, args, env3, timeoutMs = 15e3
21586
21988
  return runner.run(file, args, { env: env3, timeoutMs });
21587
21989
  }
21588
21990
 
21991
+ // src/common-auth-embedded/setup/command-error.js
21992
+ var PI_INSTALL_ERROR_MESSAGE = "Pi install failed; run pi install after checking your npm connection.";
21993
+ function utf8Tail(value) {
21994
+ const bytes = Buffer.from(value, "utf8");
21995
+ if (bytes.length <= STDERR_TAIL_MAX_BYTES)
21996
+ return value;
21997
+ let start = bytes.length - STDERR_TAIL_MAX_BYTES;
21998
+ while (start < bytes.length) {
21999
+ const byte = bytes[start];
22000
+ if (byte === void 0 || (byte & 192) !== 128)
22001
+ break;
22002
+ start++;
22003
+ }
22004
+ return bytes.subarray(start).toString("utf8");
22005
+ }
22006
+ function dropPartialLine(tail) {
22007
+ const newline = tail.indexOf("\n");
22008
+ return newline < 0 ? "" : tail.slice(newline + 1);
22009
+ }
22010
+ var SetupCommandError = class extends Error {
22011
+ step = "pi-install";
22012
+ exitCode;
22013
+ signal;
22014
+ stderrTail;
22015
+ constructor(details) {
22016
+ super(PI_INSTALL_ERROR_MESSAGE);
22017
+ this.name = "SetupCommandError";
22018
+ this.exitCode = details.exitCode;
22019
+ this.signal = details.signal;
22020
+ const tail = details.stderrTruncated ? dropPartialLine(details.stderrTail) : details.stderrTail;
22021
+ const redacted = redact2(tail);
22022
+ this.stderrTail = utf8Tail(typeof redacted === "string" ? redacted : "");
22023
+ }
22024
+ };
22025
+ var HOST_LABELS = { opencode: "OpenCode", pi: "Pi" };
22026
+ var OUTCOME_TEXT = {
22027
+ enrolled: "connected to the vault",
22028
+ "not-enrolled": "not connected",
22029
+ unknown: "unknown, check with ck auth status"
22030
+ };
22031
+ function setupEnrollmentLine({ host, outcome }) {
22032
+ return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}`;
22033
+ }
22034
+ var recordedEnrollment = /* @__PURE__ */ new WeakMap();
22035
+ function recordSetupEnrollment(failure, enrollment) {
22036
+ if (typeof failure !== "object" && typeof failure !== "function" || !failure)
22037
+ return;
22038
+ recordedEnrollment.set(failure, Object.freeze(enrollment.map((entry) => Object.freeze({ ...entry }))));
22039
+ }
22040
+
21589
22041
  // src/common-auth-embedded/setup/detect.js
21590
22042
  import { accessSync, constants as constants3, existsSync as existsSync5, readFileSync as readFileSync3, realpathSync, statSync as statSync5 } from "node:fs";
21591
22043
  import { mkdtemp, rm as rm6 } from "node:fs/promises";
@@ -22059,6 +22511,9 @@ async function assertHostsStopped(fence, env3) {
22059
22511
  }
22060
22512
 
22061
22513
  // src/common-auth-embedded/setup/enroll.js
22514
+ var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
22515
+ var HostNotEnrolledError = class extends Error {
22516
+ };
22062
22517
  async function connectSetupHost(plugin, host, io, terminal, fence) {
22063
22518
  const { name, paths: input } = plugin.vault.hosts[host];
22064
22519
  const paths = hostEnrollmentPaths2(input);
@@ -22067,7 +22522,7 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
22067
22522
  connectionFile: plugin.vault.connectionFile,
22068
22523
  handshakeTimeoutMs: 2e3
22069
22524
  }).catch(() => {
22070
- throw new Error("Claustrum connection failed; start ck and rerun setup.");
22525
+ throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.");
22071
22526
  });
22072
22527
  try {
22073
22528
  const manager = new ClaustrumEnrollmentManager2({
@@ -22097,10 +22552,10 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
22097
22552
  return;
22098
22553
  }
22099
22554
  if (status.state !== "pending" && status.state !== "busy")
22100
- throw new Error("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
22555
+ throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
22101
22556
  if (status.state === "pending" && status.requestId && status.requestId !== printedRequest) {
22102
22557
  if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
22103
- throw new Error("Invalid enrollment request id.");
22558
+ throw new HostNotEnrolledError("Invalid enrollment request id.");
22104
22559
  printedRequest = status.requestId;
22105
22560
  printLine2(terminal, "Waiting for approval. In another terminal, run:");
22106
22561
  printLine2(terminal, ` ck auth enroll approve --request-id ${status.requestId} --name ${name}`);
@@ -22108,11 +22563,13 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
22108
22563
  }
22109
22564
  await (io.wait ?? delay)(1e3);
22110
22565
  }
22111
- throw new Error("Claustrum approval is still pending; approve with ck and rerun setup.");
22566
+ throw new HostNotEnrolledError("Claustrum approval is still pending; approve with ck and rerun setup.");
22112
22567
  } catch (error) {
22113
22568
  if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError)
22114
22569
  throw error;
22115
- throw new Error("Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.");
22570
+ if (error instanceof HostNotEnrolledError)
22571
+ throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE);
22572
+ throw new Error(ENROLLMENT_INCOMPLETE_MESSAGE);
22116
22573
  } finally {
22117
22574
  client.close();
22118
22575
  }
@@ -22304,8 +22761,13 @@ async function registerOpenCode(writes, beforeWrite) {
22304
22761
  async function registerPi(plugin, executable, io = {}) {
22305
22762
  const { platform, env: env3 } = setupPaths(io);
22306
22763
  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.");
22764
+ if (result.exitCode !== 0 || result.timedOut)
22765
+ throw new SetupCommandError({
22766
+ exitCode: result.spawnError ? null : result.exitCode,
22767
+ signal: result.signal ?? null,
22768
+ stderrTail: result.stderr,
22769
+ stderrTruncated: result.stderrTruncated ?? false
22770
+ });
22309
22771
  }
22310
22772
 
22311
22773
  // src/common-auth-embedded/setup/command.js
@@ -22353,6 +22815,22 @@ function validatePlugin(plugin) {
22353
22815
  throw new Error("Setup requires lowercase vault names containing only letters, digits and dashes.");
22354
22816
  }
22355
22817
  }
22818
+ async function enrollmentReport(plugin, hosts, recorded) {
22819
+ const report = [];
22820
+ for (const host of hosts) {
22821
+ let outcome = recorded.get(host) ?? "not-enrolled";
22822
+ if (outcome === "unknown") {
22823
+ const { name, paths } = plugin.vault.hosts[host];
22824
+ const authority = await enrollmentAuthority2(hostEnrollmentPaths2(paths), name).catch(() => "unreadable");
22825
+ if (authority === "vault")
22826
+ outcome = "enrolled";
22827
+ else if (authority === "local")
22828
+ outcome = "not-enrolled";
22829
+ }
22830
+ report.push({ host, outcome });
22831
+ }
22832
+ return report;
22833
+ }
22356
22834
  async function runSetup(plugin, argv = [], io = {}) {
22357
22835
  const options = flags(argv);
22358
22836
  validatePlugin(plugin);
@@ -22462,23 +22940,45 @@ ${write.content}`);
22462
22940
  hosts: Object.freeze([...hosts]),
22463
22941
  piAgentDir: detection.pi.directory
22464
22942
  };
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);
22943
+ const enrollment = /* @__PURE__ */ new Map();
22944
+ try {
22945
+ for (const host of hosts) {
22946
+ await stopped();
22947
+ await plugin.beforeSignIn?.(host, context);
22948
+ await stopped();
22949
+ if (useVault) {
22950
+ enrollment.set(host, "unknown");
22951
+ try {
22952
+ await connectSetupHost(plugin, host, io, terminal, stopped);
22953
+ } catch (error) {
22954
+ if (error instanceof HostNotEnrolledError)
22955
+ enrollment.set(host, "not-enrolled");
22956
+ throw error;
22957
+ }
22958
+ enrollment.set(host, "enrolled");
22959
+ } else
22960
+ await plugin.signInLocal(host, context);
22961
+ await stopped();
22962
+ await plugin.beforeRegister?.(host, mode, context);
22963
+ await stopped();
22964
+ if (host === "opencode")
22965
+ await registerOpenCode(writes, stopped);
22966
+ else
22967
+ await registerPi(plugin, detection.pi.executable, io);
22968
+ await stopped();
22969
+ await plugin.migrate(host, context);
22970
+ }
22971
+ } catch (error) {
22972
+ if (enrollment.size === 0)
22973
+ throw error;
22974
+ try {
22975
+ const report = await enrollmentReport(plugin, hosts, enrollment);
22976
+ recordSetupEnrollment(error, report);
22977
+ for (const entry of report)
22978
+ printLine2(terminal, setupEnrollmentLine(entry));
22979
+ } catch {
22980
+ }
22981
+ throw error;
22482
22982
  }
22483
22983
  }
22484
22984
  printLine2(terminal, `${options.dryRun ? "Planned" : "Configured"} ${plugin.displayName} for ${hosts.join(", ")} (${mode}).`);
@@ -23128,7 +23628,7 @@ async function runCli(argv, deps) {
23128
23628
  return 1;
23129
23629
  }
23130
23630
  }
23131
- var execFileAsync = promisify(execFile2);
23631
+ var execFileAsync = promisify(execFile);
23132
23632
  async function openBrowserDefault(url) {
23133
23633
  if (process.platform === "win32") {
23134
23634
  await execFileAsync("cmd", ["/c", "start", "", url]);