@cortexkit/opencode-antigravity-auth 3.1.7 → 3.1.9

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 (136) hide show
  1. package/dist/cli.js +182 -193
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +83 -54
  4. package/dist/index.js +6886 -6346
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +475 -387
  7. package/dist/server.js +3056 -2446
  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.js +1 -1
  11. package/dist/src/common-auth-embedded/claustrum/custody.js +1 -1
  12. package/dist/src/common-auth-embedded/fs/private-files.js +14 -5
  13. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  14. package/dist/src/common-auth-embedded/opencode2/index.js +1 -1
  15. package/dist/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  16. package/dist/src/common-auth-embedded/opencode2/install.js +14 -4
  17. package/dist/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  18. package/dist/src/common-auth-embedded/pi-slot/index.d.ts +1 -1
  19. package/dist/src/common-auth-embedded/pi-slot/index.js +1 -1
  20. package/dist/src/common-auth-embedded/pi-slot/slot.d.ts +6 -9
  21. package/dist/src/common-auth-embedded/pi-slot/slot.js +42 -105
  22. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +66 -16
  23. package/dist/src/common-auth-embedded/routing-accessor/index.js +123 -17
  24. package/dist/src/common-auth-embedded/rpc/index.d.ts +1 -1
  25. package/dist/src/common-auth-embedded/rpc/index.js +1 -1
  26. package/dist/src/common-auth-embedded/rpc/port-file.d.ts +4 -0
  27. package/dist/src/common-auth-embedded/rpc/port-file.js +55 -49
  28. package/dist/src/common-auth-embedded/rpc/rpc-server.js +3 -2
  29. package/dist/src/common-auth-embedded/rpc/startup-sweep.js +32 -0
  30. package/dist/src/common-auth-embedded/source-output.json +77 -68
  31. package/dist/src/common-auth-embedded/store/mutate.js +34 -13
  32. package/dist/src/ga/server/index.d.ts +1 -1
  33. package/dist/src/ga/server/index.d.ts.map +1 -1
  34. package/dist/src/ga/server/index.js +58 -19
  35. package/dist/src/ga/server/index.js.map +1 -1
  36. package/dist/src/plugin/__fixtures__/verified-store.d.ts +1 -1
  37. package/dist/src/plugin/__fixtures__/verified-store.js +3 -3
  38. package/dist/src/plugin/auth-loader.d.ts.map +1 -1
  39. package/dist/src/plugin/auth-loader.js +102 -80
  40. package/dist/src/plugin/auth-loader.js.map +1 -1
  41. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  42. package/dist/src/plugin/fetch-interceptor.js +27 -13
  43. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  44. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  45. package/dist/src/plugin/ga-location-services.js +21 -11
  46. package/dist/src/plugin/ga-location-services.js.map +1 -1
  47. package/dist/src/plugin/index.d.ts.map +1 -1
  48. package/dist/src/plugin/index.js +13 -5
  49. package/dist/src/plugin/index.js.map +1 -1
  50. package/dist/src/plugin/request.d.ts.map +1 -1
  51. package/dist/src/plugin/request.js +2 -2
  52. package/dist/src/plugin/request.js.map +1 -1
  53. package/dist/src/plugin/shared/opencode-retry-hints.d.ts +2 -0
  54. package/dist/src/plugin/shared/opencode-retry-hints.d.ts.map +1 -0
  55. package/dist/src/plugin/shared/opencode-retry-hints.js +22 -0
  56. package/dist/src/plugin/shared/opencode-retry-hints.js.map +1 -0
  57. package/dist/src/plugin/shared/request-services.d.ts +2 -0
  58. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  59. package/dist/src/plugin/shared/request-services.js +410 -112
  60. package/dist/src/plugin/shared/request-services.js.map +1 -1
  61. package/dist/src/plugin/shared/vault-routing-purpose.d.ts +6 -2
  62. package/dist/src/plugin/shared/vault-routing-purpose.d.ts.map +1 -1
  63. package/dist/src/plugin/shared/vault-routing-purpose.js +13 -7
  64. package/dist/src/plugin/shared/vault-routing-purpose.js.map +1 -1
  65. package/dist/src/plugin/shared/vault-routing.d.ts +8 -1
  66. package/dist/src/plugin/shared/vault-routing.d.ts.map +1 -1
  67. package/dist/src/plugin/shared/vault-routing.js +12 -4
  68. package/dist/src/plugin/shared/vault-routing.js.map +1 -1
  69. package/dist/src/plugin/storage.d.ts +1 -0
  70. package/dist/src/plugin/storage.d.ts.map +1 -1
  71. package/dist/src/plugin/storage.js +3 -3
  72. package/dist/src/plugin/storage.js.map +1 -1
  73. package/dist/src/plugin/vault-custody.d.ts +6 -13
  74. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  75. package/dist/src/plugin/vault-custody.js +19 -16
  76. package/dist/src/plugin/vault-custody.js.map +1 -1
  77. package/dist/src/runtime-layout.d.ts.map +1 -1
  78. package/dist/src/runtime-layout.js +5 -2
  79. package/dist/src/runtime-layout.js.map +1 -1
  80. package/dist/src/setup.d.ts.map +1 -1
  81. package/dist/src/setup.js +2 -7
  82. package/dist/src/setup.js.map +1 -1
  83. package/dist/tui-build-map.json +9 -9
  84. package/dist/tui-ga-build-map.json +1 -1
  85. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  86. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  87. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  88. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +66 -16
  89. package/dist/types/src/ga/server/index.d.ts +1 -1
  90. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  91. package/dist/types/src/plugin/auth-loader.d.ts.map +1 -1
  92. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  93. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  94. package/dist/types/src/plugin/index.d.ts.map +1 -1
  95. package/dist/types/src/plugin/request.d.ts.map +1 -1
  96. package/dist/types/src/plugin/shared/opencode-retry-hints.d.ts +2 -0
  97. package/dist/types/src/plugin/shared/opencode-retry-hints.d.ts.map +1 -0
  98. package/dist/types/src/plugin/shared/request-services.d.ts +2 -0
  99. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  100. package/dist/types/src/plugin/shared/vault-routing-purpose.d.ts +6 -2
  101. package/dist/types/src/plugin/shared/vault-routing-purpose.d.ts.map +1 -1
  102. package/dist/types/src/plugin/shared/vault-routing.d.ts +8 -1
  103. package/dist/types/src/plugin/shared/vault-routing.d.ts.map +1 -1
  104. package/dist/types/src/plugin/storage.d.ts +1 -0
  105. package/dist/types/src/plugin/storage.d.ts.map +1 -1
  106. package/dist/types/src/plugin/vault-custody.d.ts +6 -13
  107. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  108. package/dist/types/src/runtime-layout.d.ts.map +1 -1
  109. package/dist/types/src/setup.d.ts.map +1 -1
  110. package/package.json +2 -2
  111. package/src/common-auth-embedded/claustrum/availability.js +1 -1
  112. package/src/common-auth-embedded/claustrum/custody.js +1 -1
  113. package/src/common-auth-embedded/fs/private-files.js +14 -5
  114. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  115. package/src/common-auth-embedded/opencode2/index.js +1 -1
  116. package/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  117. package/src/common-auth-embedded/opencode2/install.js +14 -4
  118. package/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  119. package/src/common-auth-embedded/pi-slot/index.d.ts +1 -1
  120. package/src/common-auth-embedded/pi-slot/index.js +1 -1
  121. package/src/common-auth-embedded/pi-slot/slot.d.ts +6 -9
  122. package/src/common-auth-embedded/pi-slot/slot.js +42 -105
  123. package/src/common-auth-embedded/routing-accessor/index.d.ts +66 -16
  124. package/src/common-auth-embedded/routing-accessor/index.js +123 -17
  125. package/src/common-auth-embedded/rpc/index.d.ts +1 -1
  126. package/src/common-auth-embedded/rpc/index.js +1 -1
  127. package/src/common-auth-embedded/rpc/port-file.d.ts +4 -0
  128. package/src/common-auth-embedded/rpc/port-file.js +55 -49
  129. package/src/common-auth-embedded/rpc/rpc-server.js +3 -2
  130. package/src/common-auth-embedded/rpc/startup-sweep.js +32 -0
  131. package/src/common-auth-embedded/source-output.json +77 -68
  132. package/src/common-auth-embedded/store/mutate.js +34 -13
  133. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +14 -5
  134. package/src/tui-compiled/common-auth-embedded/rpc/port-file.js +55 -49
  135. package/src/tui-raw/common-auth-embedded/fs/private-files.js +14 -5
  136. package/src/tui-raw/common-auth-embedded/rpc/port-file.js +55 -49
@@ -4,6 +4,7 @@
4
4
  * rows. Nothing is persisted here; plugins on routes the runner does not serve
5
5
  * get no turn notes.
6
6
  */
7
+ import { createHash } from 'node:crypto';
7
8
  import { isCacheWarmStopReason, } from './cache-policy.js';
8
9
  import { routingHandle } from './handle.js';
9
10
  export { CACHE_WARM_STOP_REASONS, isCacheWarmStopReason, reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
@@ -22,6 +23,58 @@ function isObject(value) {
22
23
  function isNonEmptyString(value) {
23
24
  return typeof value === 'string' && value.length > 0;
24
25
  }
26
+ function isBoundedControlFreeString(value, maxLength) {
27
+ return (isNonEmptyString(value) &&
28
+ value.length <= maxLength &&
29
+ !/\p{Cc}/u.test(value));
30
+ }
31
+ function isRoutingCode(value) {
32
+ return typeof value === 'string' && /^[a-z0-9._-]{1,64}$/.test(value);
33
+ }
34
+ function continueExhaustion(value) {
35
+ if (!isObject(value) || Array.isArray(value))
36
+ return undefined;
37
+ const { accountId, credentialId, limitWindow, observedAtMs } = value;
38
+ if (!isBoundedControlFreeString(accountId, 256) ||
39
+ !isBoundedControlFreeString(credentialId, 256) ||
40
+ typeof observedAtMs !== 'number' ||
41
+ !Number.isSafeInteger(observedAtMs) ||
42
+ observedAtMs <= 0 ||
43
+ (limitWindow !== 'five_hour' &&
44
+ limitWindow !== 'seven_day' &&
45
+ limitWindow !== 'signed_out'))
46
+ return undefined;
47
+ const exhausted = {
48
+ account: accountId,
49
+ credential_id: credentialId,
50
+ limit_window: limitWindow,
51
+ observed_at_ms: observedAtMs,
52
+ };
53
+ if (limitWindow === 'signed_out') {
54
+ if ('pool' in value || 'resetsAtMs' in value || 'retryAfterS' in value)
55
+ return undefined;
56
+ return exhausted;
57
+ }
58
+ const { pool, resetsAtMs, retryAfterS } = value;
59
+ if ((pool !== undefined && !isRoutingCode(pool)) ||
60
+ (resetsAtMs !== undefined &&
61
+ (typeof resetsAtMs !== 'number' ||
62
+ !Number.isSafeInteger(resetsAtMs) ||
63
+ resetsAtMs <= 0)) ||
64
+ (retryAfterS !== undefined &&
65
+ (typeof retryAfterS !== 'number' ||
66
+ !Number.isFinite(retryAfterS) ||
67
+ retryAfterS < 0)))
68
+ return undefined;
69
+ return {
70
+ ...exhausted,
71
+ ...(pool !== undefined ? { pool } : {}),
72
+ ...(resetsAtMs !== undefined ? { resets_at_ms: resetsAtMs } : {}),
73
+ ...(retryAfterS !== undefined
74
+ ? { retry_after_s: Math.floor(retryAfterS) }
75
+ : {}),
76
+ };
77
+ }
25
78
  function billingCache(value) {
26
79
  if (!isObject(value) || Array.isArray(value))
27
80
  return;
@@ -123,6 +176,24 @@ export function turnNotes(sessionId) {
123
176
  return [];
124
177
  }
125
178
  }
179
+ function candidateView(candidates) {
180
+ const accounts = [];
181
+ for (const { accountId, credentialId } of candidates) {
182
+ if (isNonEmptyString(accountId) &&
183
+ isBoundedControlFreeString(credentialId, 256)) {
184
+ accounts.push({ account_id: accountId, credential_id: credentialId });
185
+ }
186
+ }
187
+ if (accounts.length === 0)
188
+ return undefined;
189
+ const lines = accounts
190
+ .map(({ account_id, credential_id }) => Buffer.from(`${account_id}\t${credential_id}\n`, 'utf8'))
191
+ .sort(Buffer.compare);
192
+ const hash = createHash('sha256');
193
+ for (const line of lines)
194
+ hash.update(line);
195
+ return { view_digest: hash.digest('hex'), accounts };
196
+ }
126
197
  function selectionFor(answer, candidates) {
127
198
  if (!isObject(answer))
128
199
  return undefined;
@@ -156,11 +227,11 @@ function refusalFor(value) {
156
227
  return undefined;
157
228
  }
158
229
  const refused = { code };
159
- const routingCode = value.routing_code;
160
- if (typeof routingCode === 'string' &&
161
- /^[a-z0-9._-]{1,64}$/.test(routingCode)) {
230
+ const { routing_code: routingCode, reason } = value;
231
+ if (isRoutingCode(routingCode))
162
232
  refused.routingCode = routingCode;
163
- }
233
+ if (isRoutingCode(reason))
234
+ refused.reason = reason;
164
235
  const retryAfterSecs = value.retry_after_secs;
165
236
  if (typeof retryAfterSecs === 'number' &&
166
237
  Number.isFinite(retryAfterSecs) &&
@@ -178,6 +249,21 @@ function refusalFor(value) {
178
249
  export async function askRouting(input) {
179
250
  let timer;
180
251
  try {
252
+ const request = {
253
+ provider: input.provider,
254
+ modelId: input.modelId,
255
+ };
256
+ if (input.mode === 'continue') {
257
+ const { requestId } = input;
258
+ if (!isBoundedControlFreeString(requestId, 128))
259
+ return undefined;
260
+ const exhausted = continueExhaustion(input.exhausted);
261
+ if (!exhausted)
262
+ return undefined;
263
+ request.mode = 'continue';
264
+ request.request_id = requestId;
265
+ request.exhausted = exhausted;
266
+ }
181
267
  const handle = routingHandle(input.sessionId);
182
268
  if (!handle)
183
269
  return undefined;
@@ -192,10 +278,6 @@ export async function askRouting(input) {
192
278
  timer = setTimeout(() => resolve(undefined), deadlineMs);
193
279
  timer.unref();
194
280
  });
195
- const request = {
196
- provider: input.provider,
197
- modelId: input.modelId,
198
- };
199
281
  const cap = input.holdWaitMaxS;
200
282
  if (typeof cap === 'number' && Number.isFinite(cap)) {
201
283
  request.hold_wait_max_s = Math.max(0, Math.floor(cap));
@@ -203,12 +285,13 @@ export async function askRouting(input) {
203
285
  if (input.refusals === true)
204
286
  request.refusals = true;
205
287
  const warmCredentialId = input.warmCredentialId;
206
- if (isNonEmptyString(warmCredentialId) &&
207
- warmCredentialId.length <= 256 &&
208
- !/\p{Cc}/u.test(warmCredentialId) &&
288
+ if (isBoundedControlFreeString(warmCredentialId, 256) &&
209
289
  input.candidates.some((candidate) => candidate.credentialId === warmCredentialId)) {
210
290
  request.warm_credential = warmCredentialId;
211
291
  }
292
+ const candidates = candidateView(input.candidates);
293
+ if (candidates)
294
+ request.candidates = candidates;
212
295
  const pending = accountFor.call(handle, request, { deadlineMs });
213
296
  if (!isObject(pending) || typeof pending.then !== 'function')
214
297
  return undefined;
@@ -227,10 +310,10 @@ export async function askRouting(input) {
227
310
  }
228
311
  }
229
312
  /**
230
- * Report a vault request, billing result, plugin wait or turn-note event without
231
- * waiting for routing. Only contract fields are sent, and all accessor failures
232
- * are ignored. Headers must already be limited to rate-limit headers by the
233
- * caller; values are not filtered or redacted here.
313
+ * Report a vault request, account backoff, billing result, plugin wait or
314
+ * turn-note event without waiting for routing. Only contract fields are sent,
315
+ * and all accessor failures are ignored. Headers must already be limited to
316
+ * rate-limit headers by the caller; values are not filtered or redacted here.
234
317
  */
235
318
  export function reportRouting(input) {
236
319
  try {
@@ -244,6 +327,30 @@ export function reportRouting(input) {
244
327
  let payload;
245
328
  if ('kind' in input) {
246
329
  switch (input.kind) {
330
+ case 'transient_backoff': {
331
+ const { accountId, credentialId, retryAtMs, providerCode } = input;
332
+ if (!isNonEmptyString(sessionId) ||
333
+ !isNonEmptyString(accountId) ||
334
+ !Number.isSafeInteger(retryAtMs) ||
335
+ retryAtMs <= 0 ||
336
+ (credentialId !== undefined &&
337
+ !isBoundedControlFreeString(credentialId, 256)) ||
338
+ (providerCode !== undefined &&
339
+ !isBoundedControlFreeString(providerCode, 128)))
340
+ return;
341
+ payload = {
342
+ kind: 'transient_backoff',
343
+ account_id: accountId,
344
+ ...(credentialId !== undefined
345
+ ? { credential_id: credentialId }
346
+ : {}),
347
+ retry_at_ms: retryAtMs,
348
+ ...(providerCode !== undefined
349
+ ? { provider_code: providerCode }
350
+ : {}),
351
+ };
352
+ break;
353
+ }
247
354
  case 'wait': {
248
355
  const { phase, waitId, reason, nextMs, attempt, message, outcome } = input;
249
356
  if (!isNonEmptyString(sessionId) ||
@@ -406,8 +513,7 @@ export function reportRouting(input) {
406
513
  if (window !== '5h' && window !== '7d')
407
514
  return;
408
515
  // An undefined pool means the whole account, as an omitted one does.
409
- if (pool !== undefined &&
410
- (typeof pool !== 'string' || !/^[a-z0-9._-]{1,64}$/.test(pool)))
516
+ if (pool !== undefined && !isRoutingCode(pool))
411
517
  return;
412
518
  payload = {
413
519
  ...identity,
@@ -1,5 +1,5 @@
1
1
  export * from './notifications.js';
2
- export * from './port-file.js';
2
+ export { createManagedRpcStateDirPredicate, type DiscoverPortFileOptions, discoverPortFile, getRpcDir, isManagedRpcStateDir, type PortFileEntry, portFileIdentity, sweepRpcState, writePortFile, } from './port-file.js';
3
3
  export * from './rpc-client.js';
4
4
  export * from './rpc-server.js';
5
5
  export * from './server-registry.js';
@@ -1,5 +1,5 @@
1
1
  export * from './notifications.js';
2
- export * from './port-file.js';
2
+ export { createManagedRpcStateDirPredicate, discoverPortFile, getRpcDir, isManagedRpcStateDir, portFileIdentity, sweepRpcState, writePortFile, } from './port-file.js';
3
3
  export * from './rpc-client.js';
4
4
  export * from './rpc-server.js';
5
5
  export * from './server-registry.js';
@@ -27,6 +27,10 @@ export declare function sweepRpcState(root: string, activeDir: string, isManaged
27
27
  /** Internal seam for replacing a stale record before its identity recheck. */
28
28
  beforeRemove?: (path: string) => void | Promise<void>;
29
29
  }): Promise<void>;
30
+ /** Internal folder cleanup shared by full and throttled startup sweeps. */
31
+ export declare function sweepRpcDirectory(dir: string, log?: RpcLogChannel, options?: PortFileClock & {
32
+ beforeRemove?: (path: string) => void | Promise<void>;
33
+ }, cutoff?: number): Promise<boolean>;
30
34
  export interface DiscoverPortFileOptions extends PortFileClock {
31
35
  /**
32
36
  * Return only the expected PID's entry, or null; never fall back to
@@ -94,9 +94,8 @@ async function removeCorruptPortFile(portFile, log) {
94
94
  export async function writePortFile(dir, entry, options = {}) {
95
95
  // The directory can be removed by another project's sweep between our
96
96
  // mkdir and the first open/rename, so the whole create-then-rename
97
- // unit is retried once on ENOENT. The retry recreates the directory; a
98
- // persistent ENOENT (e.g. permission, read-only parent) will surface on
99
- // the second attempt — failing fast beats an unbounded loop.
97
+ // unit gets up to five attempts on ENOENT. Each retry recreates the
98
+ // directory after a short delay, but persistent removal still surfaces.
100
99
  const writeOnce = async () => {
101
100
  const target = join(dir, `port-${entry.pid}.json`);
102
101
  if (windowsPrivateFiles) {
@@ -136,14 +135,15 @@ export async function writePortFile(dir, entry, options = {}) {
136
135
  }
137
136
  return target;
138
137
  };
139
- try {
140
- return await writeOnce();
141
- }
142
- catch (error) {
143
- if (error.code === 'ENOENT') {
138
+ for (let attempt = 1;; attempt += 1) {
139
+ try {
144
140
  return await writeOnce();
145
141
  }
146
- throw error;
142
+ catch (error) {
143
+ if (error.code !== 'ENOENT' || attempt === 5)
144
+ throw error;
145
+ await new Promise((resolve) => setTimeout(resolve, 25));
146
+ }
147
147
  }
148
148
  }
149
149
  export async function sweepRpcState(root, activeDir, isManagedDir, log, options = {}) {
@@ -163,52 +163,58 @@ export async function sweepRpcState(root, activeDir, isManagedDir, log, options
163
163
  continue;
164
164
  }
165
165
  const dir = join(root, projectDir.name);
166
- let names;
166
+ if (!(await sweepRpcDirectory(dir, log, options, cutoff)))
167
+ continue;
168
+ if (resolve(dir) !== active)
169
+ await rmdir(dir).catch(() => { });
170
+ }
171
+ }
172
+ /** Internal folder cleanup shared by full and throttled startup sweeps. */
173
+ export async function sweepRpcDirectory(dir, log, options = {}, cutoff = staleBefore(options)) {
174
+ let names;
175
+ try {
176
+ names = await readdir(dir);
177
+ }
178
+ catch (error) {
179
+ if (error.code === 'ENOENT')
180
+ return false;
181
+ throw error;
182
+ }
183
+ for (const name of names) {
184
+ if (!name.startsWith('port-') || !name.endsWith('.json'))
185
+ continue;
186
+ const portFile = join(dir, name);
187
+ const info = await stat(portFile).catch(() => undefined);
188
+ let raw;
167
189
  try {
168
- names = await readdir(dir);
190
+ raw = await readPrivateText(portFile);
169
191
  }
170
192
  catch (error) {
171
- if (error.code === 'ENOENT')
172
- continue;
173
- throw error;
193
+ if (error instanceof PrivateFileError && error.code !== 'ENOENT')
194
+ throw error;
195
+ continue;
174
196
  }
175
- for (const name of names) {
176
- if (!name.startsWith('port-') || !name.endsWith('.json'))
177
- continue;
178
- const portFile = join(dir, name);
179
- const info = await stat(portFile).catch(() => undefined);
180
- let raw;
181
- try {
182
- raw = await readPrivateText(portFile);
183
- }
184
- catch (error) {
185
- if (error instanceof PrivateFileError && error.code !== 'ENOENT')
186
- throw error;
187
- continue;
188
- }
189
- if (raw === undefined)
190
- continue;
191
- let parsed;
192
- try {
193
- parsed = JSON.parse(raw);
194
- }
195
- catch {
196
- await removeCorruptPortFile(portFile, log);
197
- continue;
198
- }
199
- if (!isUsablePortFileEntry(parsed, name)) {
200
- await removeCorruptPortFile(portFile, log);
201
- continue;
202
- }
203
- const entry = parsed;
204
- if (!pidAlive(entry.pid))
205
- await unlink(portFile).catch(() => { });
206
- else if (isStalePortFile(entry, info, cutoff))
207
- await removeStalePortFile(portFile, raw, info, options.beforeRemove);
197
+ if (raw === undefined)
198
+ continue;
199
+ let parsed;
200
+ try {
201
+ parsed = JSON.parse(raw);
208
202
  }
209
- if (resolve(dir) !== active)
210
- await rmdir(dir).catch(() => { });
203
+ catch {
204
+ await removeCorruptPortFile(portFile, log);
205
+ continue;
206
+ }
207
+ if (!isUsablePortFileEntry(parsed, name)) {
208
+ await removeCorruptPortFile(portFile, log);
209
+ continue;
210
+ }
211
+ const entry = parsed;
212
+ if (!pidAlive(entry.pid))
213
+ await unlink(portFile).catch(() => { });
214
+ else if (isStalePortFile(entry, info, cutoff))
215
+ await removeStalePortFile(portFile, raw, info, options.beforeRemove);
211
216
  }
217
+ return true;
212
218
  }
213
219
  /** Internal cache validation: probe only the selected file and its PID. */
214
220
  export async function portFileIdentity(dir, entry, options = {}) {
@@ -4,7 +4,8 @@ import { createServer, } from 'node:http';
4
4
  import { join } from 'node:path';
5
5
  import { PrivateFileError, readPrivateText } from '../fs/private-files.js';
6
6
  import { isSessionId, } from './notifications.js';
7
- import { sweepRpcState, writePortFile } from './port-file.js';
7
+ import { writePortFile } from './port-file.js';
8
+ import { sweepRpcStateOnStart } from './startup-sweep.js';
8
9
  /**
9
10
  * Thrown by an `apply`, `drain`, or `parsePending` handler to refuse a request with a 4xx
10
11
  * status. Its message is sent on the wire as `{error: message}`, so it must
@@ -279,7 +280,7 @@ export async function startRpcServer(options) {
279
280
  server.unref();
280
281
  if (options.sweepRoot) {
281
282
  try {
282
- await sweepRpcState(options.sweepRoot, options.dir, options.isManagedDir, log);
283
+ await sweepRpcStateOnStart(options.sweepRoot, options.dir, options.isManagedDir, log);
283
284
  }
284
285
  catch (error) {
285
286
  log.warn('rpc state sweep failed', {
@@ -0,0 +1,32 @@
1
+ import { lstat } from 'node:fs/promises';
2
+ import { basename, dirname, resolve } from 'node:path';
3
+ import { sweepRpcDirectory, sweepRpcState } from './port-file.js';
4
+ const globals = globalThis;
5
+ const key = Symbol.for('common-auth.rpc.startup-sweep');
6
+ globals[key] ??= {};
7
+ const state = globals[key];
8
+ let now = Date.now;
9
+ /** Internal clock seam; reset the process-wide budget between tests. */
10
+ export function resetRpcSweepForTest(clock = Date.now) {
11
+ now = clock;
12
+ delete state.lastSweepAt;
13
+ }
14
+ export async function sweepRpcStateOnStart(root, activeDir, isManagedDir, log) {
15
+ const time = now();
16
+ if (state.lastSweepAt !== undefined && time - state.lastSweepAt < 60_000) {
17
+ // The starting folder still needs corrupt, dead and pre-boot records removed.
18
+ const active = resolve(activeDir);
19
+ if (dirname(active) === resolve(root) &&
20
+ isManagedDir(basename(active)) &&
21
+ (await lstat(active).catch((error) => {
22
+ if (error.code !== 'ENOENT')
23
+ throw error;
24
+ return undefined;
25
+ }))?.isDirectory())
26
+ await sweepRpcDirectory(active, log);
27
+ return;
28
+ }
29
+ // Claim before awaiting I/O so concurrent starts cannot all scan sibling folders.
30
+ state.lastSweepAt = time;
31
+ await sweepRpcState(root, activeDir, isManagedDir, log);
32
+ }