@cortexkit/common-auth 0.51.0 → 0.52.1

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.
@@ -1,4 +1,5 @@
1
1
  import { spawn as defaultSpawn } from 'node:child_process';
2
+ import { win32 } from 'node:path';
2
3
  /** Opens a URL with the platform's opener; false when it could not start. */
3
4
  export function openBrowserForMenu(url, platform = process.platform, spawn = defaultSpawn) {
4
5
  try {
@@ -13,7 +14,9 @@ export function openBrowserForMenu(url, platform = process.platform, spawn = def
13
14
  // opened. It is not detached: a detached PowerShell has no console and
14
15
  // never ran the command on any Windows runner.
15
16
  const command = `Start-Process '${url.replaceAll("'", "''")}'`;
16
- const child = spawn('powershell.exe', [
17
+ // Spawn PowerShell by its system path: a bare name can resolve to a
18
+ // program planted in the current directory or earlier on PATH.
19
+ const child = spawn(win32.resolve(process.env.SystemRoot ?? process.env.windir ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'), [
17
20
  '-NoProfile',
18
21
  '-NonInteractive',
19
22
  '-WindowStyle',
@@ -94,7 +94,7 @@ export class ClaustrumUnreachableError extends ClaustrumConsumerError {
94
94
  */
95
95
  reason;
96
96
  constructor(reason) {
97
- super('unavailable', 'Claustrum scoped operation unavailable');
97
+ super('unavailable', 'Claustrum vault could not be reached');
98
98
  this.name = 'ClaustrumUnreachableError';
99
99
  if (reason === 'host-accessor-missing' || reason === 'host-accessor-failed')
100
100
  this.reason = reason;
@@ -404,7 +404,7 @@ export class ClaustrumScopedCustody {
404
404
  throw error;
405
405
  if (classifyVaultFailure(error) === 'unreachable')
406
406
  throw new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError ? error.reason : undefined);
407
- throw new ClaustrumConsumerError('unavailable', 'Claustrum scoped operation unavailable');
407
+ throw new ClaustrumConsumerError('unavailable', 'Claustrum scoped operation failed');
408
408
  }
409
409
  finally {
410
410
  removeAbortListener?.();
@@ -24,7 +24,9 @@ export function setPrivateFilesBackendForTest(api) {
24
24
  /** The fixed `reason` of a refusal because the Windows native addon did not load. */
25
25
  export const PRIVATE_FILES_UNAVAILABLE_REASON = 'native-addon-unavailable';
26
26
  function privateFilesUnavailable(cause) {
27
- return Object.assign(new Error('Windows private-files native addon is unavailable', { cause }), {
27
+ return Object.assign(new Error('Windows private-files native addon could not be loaded', {
28
+ cause,
29
+ }), {
28
30
  code: 'ERR_PRIVATE_FILES_UNAVAILABLE',
29
31
  reason: PRIVATE_FILES_UNAVAILABLE_REASON,
30
32
  });
@@ -64,7 +64,13 @@ const pi140Pattern = new RegExp([
64
64
  'subscription_sharing_user_unavailable',
65
65
  ].join('|'), 'i');
66
66
  export function hasUnsafeWording(text) {
67
- return (openCode1Patterns.some((pattern) => pattern.test(text)) ||
67
+ // OpenCode 1's session/retry.ts non-API-error branch retries when any of
68
+ // these substrings occurs in the message, even without a retryable flag.
69
+ const lower = text.toLowerCase();
70
+ return (lower.includes('too_many_requests') ||
71
+ lower.includes('exhausted') ||
72
+ lower.includes('unavailable') ||
73
+ openCode1Patterns.some((pattern) => pattern.test(text)) ||
68
74
  pi140Pattern.test(text));
69
75
  }
70
76
  export class UnsafeWordingError extends Error {
@@ -123,6 +123,9 @@ const retryBodyPatterns = [
123
123
  /try your request again|retry your request|resource exhausted|resource_exhausted/i,
124
124
  /\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i,
125
125
  ];
126
+ // OpenCode 1's session/retry.ts non-API-error branch also retries these
127
+ // substrings. Preserve them when compacting diagnostic bodies too.
128
+ const nonApiRetryPattern = /too_many_requests|exhausted|unavailable/i;
126
129
  /** Numeric request ids are quoted from their source lexeme, not a rounded JS number. */
127
130
  function requestIdFromBody(body) {
128
131
  try {
@@ -179,6 +182,9 @@ function projectResponseBody(body, credential) {
179
182
  if (Buffer.byteLength(safe, 'utf8') <= responseBodyLimit)
180
183
  return safe;
181
184
  const markers = retryBodyPatterns.flatMap((pattern) => pattern.exec(safe)?.[0] ?? []);
185
+ const nonApiMarker = nonApiRetryPattern.exec(safe)?.[0];
186
+ if (nonApiMarker)
187
+ markers.push(nonApiMarker);
182
188
  for (const marker of ['FreeUsageLimitError', 'GoUsageLimitError']) {
183
189
  if (safe.includes(marker))
184
190
  markers.push(marker);
@@ -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';
package/dist/rpc/index.js CHANGED
@@ -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,4 @@
1
+ import type { RpcLogChannel } from './index.js';
2
+ /** Internal clock seam; reset the process-wide budget between tests. */
3
+ export declare function resetRpcSweepForTest(clock?: () => number): void;
4
+ export declare function sweepRpcStateOnStart(root: string, activeDir: string, isManagedDir: (name: string) => boolean, log: RpcLogChannel): Promise<void>;
@@ -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
+ }
@@ -10,6 +10,7 @@ import { confirmEnrollmentAccess } from './enrollment-access.js';
10
10
  import { parseSetupFlags, UNAVAILABLE_HOST_MESSAGE } from './flags.js';
11
11
  import { setupPaths } from './paths.js';
12
12
  import { assertHostsStopped, createProcessFence, ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
13
+ import { SetupProcessGuard } from './process-guard.js';
13
14
  import { selectSetupHosts } from './prompts.js';
14
15
  import { planOpenCodeRegistration, registerOpenCode, registerPi, } from './register.js';
15
16
  export const AMBIGUOUS_OPENCODE_MESSAGE = 'Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.';
@@ -120,7 +121,11 @@ export async function runSetup(plugin, argv = [], io = {}) {
120
121
  }
121
122
  const { env, platform } = setupPaths(io);
122
123
  const fence = io.fence ??
123
- createProcessFence(io.runner ?? defaultCommandRunner, { platform });
124
+ createProcessFence(io.runner ?? defaultCommandRunner, {
125
+ platform,
126
+ isFile: io.fs?.isFile.bind(io.fs),
127
+ onProgress: (line) => printLine(terminal, line),
128
+ });
124
129
  const stopped = async () => {
125
130
  try {
126
131
  await assertHostsStopped(fence, env);
@@ -131,6 +136,7 @@ export async function runSetup(plugin, argv = [], io = {}) {
131
136
  throw error;
132
137
  }
133
138
  };
139
+ const guard = new SetupProcessGuard(stopped, io.now);
134
140
  printLine(terminal, 'Checking that OpenCode and Pi are not running…');
135
141
  if (options.dryRun) {
136
142
  try {
@@ -150,8 +156,10 @@ export async function runSetup(plugin, argv = [], io = {}) {
150
156
  printLine(terminal, error.refusalText);
151
157
  }
152
158
  }
153
- else
154
- await stopped();
159
+ else {
160
+ // Refuse before asking questions; the first write can reuse this check.
161
+ await guard.check();
162
+ }
155
163
  if ((options.claustrum || options.enrollOnly) &&
156
164
  !detection.claustrum.available)
157
165
  throw new Error('Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.');
@@ -164,10 +172,10 @@ export async function runSetup(plugin, argv = [], io = {}) {
164
172
  isInteractive(terminal)) {
165
173
  // Not `confirm`: it reads Escape and Ctrl-C as "No", and "No" here means
166
174
  // a local sign-in. Cancelling must stop setup before anything changes.
167
- const choice = await select(terminal, [
175
+ const choice = await guard.step(() => select(terminal, [
168
176
  { label: 'No', value: false },
169
177
  { label: 'Yes', value: true },
170
- ], { message: 'Connect these hosts to the Claustrum vault?' });
178
+ ], { message: 'Connect these hosts to the Claustrum vault?' }));
171
179
  if (choice === null) {
172
180
  printLine(terminal, 'Setup cancelled. Nothing was changed.');
173
181
  return { hosts: [], dryRun: options.dryRun, mode: 'local', detection };
@@ -224,13 +232,15 @@ export async function runSetup(plugin, argv = [], io = {}) {
224
232
  const enrollmentAccess = new Map();
225
233
  try {
226
234
  for (const host of hosts) {
227
- await stopped();
228
- await plugin.beforeSignIn?.(host, context);
229
- await stopped();
235
+ if (plugin.beforeSignIn) {
236
+ // The callback can change credentials or wait for consent.
237
+ await guard.check({ reuse: true });
238
+ await guard.step(() => plugin.beforeSignIn?.(host, context));
239
+ }
230
240
  if (useVault) {
231
241
  enrollment.set(host, 'unknown');
232
242
  try {
233
- const access = await connectSetupHost(plugin, host, io, terminal, stopped);
243
+ const access = await connectSetupHost(plugin, host, io, terminal, guard);
234
244
  if (access)
235
245
  enrollmentAccess.set(host, access);
236
246
  }
@@ -241,19 +251,30 @@ export async function runSetup(plugin, argv = [], io = {}) {
241
251
  }
242
252
  enrollment.set(host, 'enrolled');
243
253
  }
244
- else
245
- await plugin.signInLocal(host, context);
246
- await stopped();
254
+ else {
255
+ // Local sign-in can write credentials and wait for a browser.
256
+ await guard.check({ reuse: true });
257
+ await guard.step(() => plugin.signInLocal(host, context));
258
+ }
247
259
  if (options.enrollOnly)
248
260
  continue;
249
- await plugin.beforeRegister?.(host, mode, context);
250
- await stopped();
261
+ if (plugin.beforeRegister) {
262
+ // Registration callbacks may write provider-specific files.
263
+ await guard.check({ reuse: true });
264
+ await guard.step(() => plugin.beforeRegister?.(host, mode, context));
265
+ }
251
266
  if (host === 'opencode')
252
- await registerOpenCode(writes, stopped);
253
- else
254
- await registerPi(plugin, detection.pi.executable, io);
255
- await stopped();
256
- await plugin.migrate?.(host, context);
267
+ await registerOpenCode(writes, guard);
268
+ else {
269
+ // Pi's CLI writes its plugin registration.
270
+ await guard.check({ reuse: true });
271
+ await guard.step(() => registerPi(plugin, detection.pi.executable, io));
272
+ }
273
+ if (plugin.migrate) {
274
+ // Migration is a plugin callback and may write host credentials.
275
+ await guard.check({ reuse: true });
276
+ await guard.step(() => plugin.migrate?.(host, context));
277
+ }
257
278
  }
258
279
  }
259
280
  catch (error) {
@@ -1,4 +1,5 @@
1
1
  import { type MenuTerminal } from '../auth-menu/terminal.js';
2
+ import { SetupProcessGuard } from './process-guard.js';
2
3
  import type { SetupEnrollmentAccess, SetupHost, SetupIO, SetupPlugin } from './types.js';
3
4
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
4
5
  export declare const UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read \"Upgrading from v0.1.3\" in its release notes first), or run setup without --claustrum to use local accounts.";
@@ -31,4 +32,4 @@ export declare class HostNotEnrolledError extends Error {
31
32
  });
32
33
  }
33
34
  /** Enroll an independently revocable host; plugin callbacks choose its credential store and account permissions. */
34
- export declare function connectSetupHost(plugin: SetupPlugin, host: SetupHost, io: SetupIO, terminal: MenuTerminal, fence: () => Promise<void>): Promise<SetupEnrollmentAccess | undefined>;
35
+ export declare function connectSetupHost(plugin: SetupPlugin, host: SetupHost, io: SetupIO, terminal: MenuTerminal, fence: (() => Promise<void>) | SetupProcessGuard): Promise<SetupEnrollmentAccess | undefined>;
@@ -5,6 +5,7 @@ import { ClaustrumEnrollmentManager, connectClaustrumEnrollmentClient, hostEnrol
5
5
  import { hasVaultHost, VAULT_HOST_CONNECT_REFUSAL } from '../claustrum/host.js';
6
6
  import { confirmEnrollmentAccess, enrollmentAccessLines, } from './enrollment-access.js';
7
7
  import { ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
8
+ import { SetupProcessGuard } from './process-guard.js';
8
9
  const ENROLLMENT_INCOMPLETE_MESSAGE = 'Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.';
9
10
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
10
11
  export const UNSUPPORTED_VAULT_MESSAGE = 'This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.';
@@ -57,7 +58,9 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
57
58
  throw new Error(VAULT_HOST_CONNECT_REFUSAL);
58
59
  const { name, displayName, requestedGrants, grantFallback, paths: input, } = plugin.vault.hosts[host];
59
60
  const paths = hostEnrollmentPaths(input);
60
- await fence();
61
+ const guard = typeof fence === 'function' ? new SetupProcessGuard(fence, io.now) : fence;
62
+ // Fail before connecting; an uninterrupted caller inspection is sufficient.
63
+ await guard.check({ reuse: true });
61
64
  const client = await (io.connect ?? connectClaustrumEnrollmentClient)({
62
65
  connectionFile: plugin.vault.connectionFile,
63
66
  handshakeTimeoutMs: 2000,
@@ -79,11 +82,10 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
79
82
  client,
80
83
  writeTokenFile: async (path, file) => {
81
84
  // Writing the token is what connects the host: check once more.
82
- await fence();
83
- await writeEnrollmentTokenFile(path, file);
85
+ await guard.check();
86
+ await guard.step(() => writeEnrollmentTokenFile(path, file));
84
87
  },
85
88
  });
86
- await fence();
87
89
  const initial = await manager.status();
88
90
  if (initial.state === 'approved') {
89
91
  printLine(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
@@ -100,7 +102,9 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
100
102
  let reportedCode;
101
103
  let failedProposals = 0;
102
104
  for (;;) {
103
- const status = await manager.reconcile();
105
+ // Reconcile may create or update the host's enrollment state.
106
+ await guard.check({ reuse: true });
107
+ const status = await guard.step(() => manager.reconcile());
104
108
  if (status.state === 'approved') {
105
109
  printLine(terminal, `Connected ${host} to Claustrum.`);
106
110
  const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
@@ -153,8 +157,9 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
153
157
  const remaining = deadline - now();
154
158
  if (remaining <= 0)
155
159
  break;
156
- await wait(Math.min(pause, remaining));
157
- await fence();
160
+ await guard.step(() => wait(Math.min(pause, remaining)));
161
+ // Approval waits allow a host to start before the next reconcile.
162
+ await guard.check();
158
163
  }
159
164
  if (printedRequest)
160
165
  throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
@@ -1,6 +1,8 @@
1
1
  import type { CommandRunner, ProcessFence, SetupEnvironment } from './types.js';
2
2
  export interface ProcessInspectionStep {
3
3
  step: 'tasklist' | 'CIM' | 'ps';
4
+ /** The selected CIM interpreter; absent for tasklist and ps. */
5
+ program?: 'pwsh' | 'powershell';
4
6
  exitCode: number | null;
5
7
  signal: NodeJS.Signals | null;
6
8
  timedOut: boolean;
@@ -9,6 +11,7 @@ export interface ProcessInspectionStep {
9
11
  export declare class ProcessInspectionError extends Error implements ProcessInspectionStep {
10
12
  readonly code = "process-inspection-failed";
11
13
  readonly step: ProcessInspectionStep['step'];
14
+ readonly program?: ProcessInspectionStep['program'];
12
15
  readonly exitCode: number | null;
13
16
  readonly signal: NodeJS.Signals | null;
14
17
  readonly timedOut: boolean;
@@ -30,6 +33,10 @@ export declare class ProcessFenceViolationError extends Error {
30
33
  export declare function listSetupProcesses(runner?: CommandRunner, options?: {
31
34
  platform?: string;
32
35
  env?: SetupEnvironment;
36
+ /** Tests can replace the regular-file check for the fixed pwsh location. */
37
+ isFile?: (file: string) => boolean;
38
+ /** Reports before each slow Windows ARM PowerShell 5.1 check. */
39
+ onProgress?: (line: string) => void;
33
40
  onStep?: (details: ProcessInspectionStep) => void;
34
41
  /** False skips the Windows PowerShell query for Node and Bun command lines. */
35
42
  inspectRuntimes?: boolean;
@@ -53,5 +60,7 @@ export declare function listSetupProcesses(runner?: CommandRunner, options?: {
53
60
  export declare function createProcessFence(runner?: CommandRunner, options?: {
54
61
  platform?: string;
55
62
  selfPid?: number;
63
+ isFile?: (file: string) => boolean;
64
+ onProgress?: (line: string) => void;
56
65
  }): ProcessFence;
57
66
  export declare function assertHostsStopped(fence: ProcessFence, env?: SetupEnvironment): Promise<void>;
@@ -1,8 +1,25 @@
1
+ import { statSync } from 'node:fs';
2
+ import { win32 } from 'node:path';
1
3
  import { defaultCommandRunner } from './command-runner.js';
2
- // A cold PowerShell/WMI query took 13.8 s on Windows Server 2022; warm queries
3
- // took less than 0.5 s. This is the product's one-shot latency budget, not a test
4
- // deadline: 45 s is about three times the worst measured cold start.
5
4
  const WINDOWS_CIM_TIMEOUT_MS = 45_000;
5
+ // Native Windows PowerShell 5.1 on ARM took 22–44 s per process query, with
6
+ // one cold CIM timeout at 45.8 s; pwsh took less than a second. See
7
+ // .cortexkit/internal-docs/investigations/windows-arm-process-fence/report.md.
8
+ // Allow about twice the measured worst case only for 5.1 on ARM. If it needs
9
+ // more than 90 s, investigate before raising this budget again.
10
+ const WINDOWS_ARM_POWERSHELL_TIMEOUT_MS = 90_000;
11
+ function isFile(file) {
12
+ try {
13
+ return statSync(file).isFile();
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ // Windows environment names are case-insensitive, including in injected envs.
20
+ function windowsEnv(env, name) {
21
+ return Object.entries(env).find(([key]) => key.toUpperCase() === name.toUpperCase())?.[1];
22
+ }
6
23
  const HOSTS = new Set(['opencode', 'litecode', 'opencode2', 'pi']);
7
24
  const RUNTIMES = new Set(['node', 'bun']);
8
25
  /**
@@ -101,6 +118,7 @@ function hostName(command) {
101
118
  export class ProcessInspectionError extends Error {
102
119
  code = 'process-inspection-failed';
103
120
  step;
121
+ program;
104
122
  exitCode;
105
123
  signal;
106
124
  timedOut;
@@ -109,6 +127,7 @@ export class ProcessInspectionError extends Error {
109
127
  super('Process inspection failed; setup cannot prove hosts are stopped.');
110
128
  this.name = 'ProcessInspectionError';
111
129
  this.step = details.step;
130
+ this.program = details.program;
112
131
  this.exitCode = details.exitCode;
113
132
  this.signal = details.signal;
114
133
  this.timedOut = details.timedOut;
@@ -143,6 +162,12 @@ export class ProcessFenceViolationError extends Error {
143
162
  /** List processes before filtering hosts; Windows PID 0 is a valid idle-process row. */
144
163
  export async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
145
164
  const windows = (options.platform ?? process.platform) === 'win32';
165
+ const env = options.env ?? process.env;
166
+ const system32 = windows
167
+ ? win32.resolve(windowsEnv(env, 'SystemRoot') ??
168
+ windowsEnv(env, 'windir') ??
169
+ 'C:\\Windows', 'System32')
170
+ : '';
146
171
  const selfPid = options.selfPid ?? process.pid;
147
172
  let inspection = {
148
173
  step: windows ? 'tasklist' : 'ps',
@@ -151,10 +176,11 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
151
176
  timedOut: false,
152
177
  durationMs: 0,
153
178
  };
154
- const inspect = async (step, file, args, timeoutMs) => {
179
+ const inspect = async (step, file, args, timeoutMs, program) => {
155
180
  const started = performance.now();
156
181
  inspection = {
157
182
  step,
183
+ ...(program && { program }),
158
184
  exitCode: null,
159
185
  signal: null,
160
186
  timedOut: false,
@@ -167,6 +193,7 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
167
193
  });
168
194
  inspection = {
169
195
  step,
196
+ ...(program && { program }),
170
197
  exitCode: result.exitCode,
171
198
  signal: result.signal ?? null,
172
199
  timedOut: result.timedOut ?? false,
@@ -180,9 +207,26 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
180
207
  options.onStep?.({ ...inspection });
181
208
  }
182
209
  };
210
+ const inspectCim = (args) => {
211
+ const pwsh = win32.resolve(windowsEnv(env, 'ProgramFiles') ?? 'C:\\Program Files', 'PowerShell', '7', 'pwsh.exe');
212
+ const program = (options.isFile ?? isFile)(pwsh) ? 'pwsh' : 'powershell';
213
+ const arm64 = (windowsEnv(env, 'PROCESSOR_ARCHITEW6432') ??
214
+ windowsEnv(env, 'PROCESSOR_ARCHITECTURE'))?.toUpperCase() === 'ARM64';
215
+ const slow = program === 'powershell' && arm64;
216
+ if (slow)
217
+ options.onProgress?.('Checking that OpenCode and Pi are not running. Without PowerShell 7 this can take up to a minute on Windows ARM; installing PowerShell 7 makes it fast.');
218
+ return inspect('CIM', program === 'pwsh'
219
+ ? pwsh
220
+ : win32.resolve(system32, 'WindowsPowerShell', 'v1.0', 'powershell.exe'), args, slow ? WINDOWS_ARM_POWERSHELL_TIMEOUT_MS : WINDOWS_CIM_TIMEOUT_MS, program);
221
+ };
183
222
  try {
184
223
  if (windows && options.hostImagesOnly) {
185
- const details = await inspect('CIM', 'powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_FENCE_QUERY], WINDOWS_CIM_TIMEOUT_MS);
224
+ const details = await inspectCim([
225
+ '-NoProfile',
226
+ '-NonInteractive',
227
+ '-Command',
228
+ WINDOWS_FENCE_QUERY,
229
+ ]);
186
230
  if (details.exitCode !== 0)
187
231
  throw new ProcessInspectionError(inspection);
188
232
  // An empty or truncated answer fails to parse or lacks `complete`, so a
@@ -220,7 +264,7 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
220
264
  }
221
265
  return processes;
222
266
  }
223
- const result = await inspect(windows ? 'tasklist' : 'ps', windows ? 'tasklist.exe' : 'ps', windows ? ['/fo', 'csv', '/nh'] : ['-eo', 'pid,command']);
267
+ const result = await inspect(windows ? 'tasklist' : 'ps', windows ? win32.resolve(system32, 'tasklist.exe') : 'ps', windows ? ['/fo', 'csv', '/nh'] : ['-eo', 'pid,command']);
224
268
  if (result.exitCode !== 0)
225
269
  throw new ProcessInspectionError(inspection);
226
270
  const processes = [];
@@ -256,12 +300,12 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
256
300
  // tasklist identifies native hosts, but npm Pi/OpenCode scripts appear as Node or Bun.
257
301
  const runtimes = processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command));
258
302
  if (windows && runtimes.length && options.inspectRuntimes !== false) {
259
- const details = await inspect('CIM', 'powershell.exe', [
303
+ const details = await inspectCim([
260
304
  '-NoProfile',
261
305
  '-NonInteractive',
262
306
  '-Command',
263
307
  "$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter \"Name = 'node.exe' OR Name = 'bun.exe'\" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress",
264
- ], WINDOWS_CIM_TIMEOUT_MS);
308
+ ]);
265
309
  if (details.exitCode !== 0)
266
310
  throw new ProcessInspectionError(inspection);
267
311
  const value = JSON.parse(details.stdout || 'null');
@@ -0,0 +1,12 @@
1
+ /** Reuse an inspection only while setup has done nothing a running host could observe. */
2
+ export declare class SetupProcessGuard {
3
+ #private;
4
+ private readonly inspect;
5
+ private readonly now;
6
+ constructor(inspect: () => Promise<void>, now?: () => number);
7
+ check(options?: {
8
+ reuse?: boolean;
9
+ }): Promise<void>;
10
+ /** Callbacks, writes and waits can all make an earlier inspection stale. */
11
+ step<T>(run: () => T | Promise<T>): Promise<T>;
12
+ }
@@ -0,0 +1,32 @@
1
+ /** Reuse an inspection only while setup has done nothing a running host could observe. */
2
+ export class SetupProcessGuard {
3
+ inspect;
4
+ now;
5
+ #checkedAt;
6
+ constructor(inspect, now = () => performance.now()) {
7
+ this.inspect = inspect;
8
+ this.now = now;
9
+ }
10
+ async check(options = {}) {
11
+ if (options.reuse && this.#checkedAt !== undefined) {
12
+ const age = this.now() - this.#checkedAt;
13
+ // Slow read-only RPCs must not extend an inspection indefinitely.
14
+ if (age >= 0 && age < 5000)
15
+ return;
16
+ }
17
+ this.#checkedAt = undefined;
18
+ await this.inspect();
19
+ this.#checkedAt = this.now();
20
+ }
21
+ /** Callbacks, writes and waits can all make an earlier inspection stale. */
22
+ async step(run) {
23
+ this.#checkedAt = undefined;
24
+ try {
25
+ return await run();
26
+ }
27
+ finally {
28
+ // A nested token-write check must not escape its enclosing reconcile.
29
+ this.#checkedAt = undefined;
30
+ }
31
+ }
32
+ }
@@ -1,3 +1,4 @@
1
+ import { SetupProcessGuard } from './process-guard.js';
1
2
  import type { OpenCodeGeneration, SetupIO, SetupPlugin } from './types.js';
2
3
  export interface PlannedWrite {
3
4
  path: string;
@@ -9,5 +10,5 @@ export interface PlannedWrite {
9
10
  /** Edit only array entries so unrelated JSONC text, including comments, survives. */
10
11
  export declare function updatePluginConfig(text: string, key: 'plugin' | 'plugins', pkg: string, version: string): string;
11
12
  export declare function planOpenCodeRegistration(plugin: SetupPlugin, generation: OpenCodeGeneration, io?: SetupIO): PlannedWrite[];
12
- export declare function registerOpenCode(writes: readonly PlannedWrite[], beforeWrite?: () => Promise<void>): Promise<void>;
13
+ export declare function registerOpenCode(writes: readonly PlannedWrite[], beforeWrite?: (() => Promise<void>) | SetupProcessGuard): Promise<void>;
13
14
  export declare function registerPi(plugin: SetupPlugin, executable: string, io?: SetupIO): Promise<void>;
@@ -1,3 +1,5 @@
1
+ import { rename } from 'node:fs/promises';
2
+ import { setTimeout as delay } from 'node:timers/promises';
1
3
  import { domainToUnicode } from 'node:url';
2
4
  import { applyEdits, createScanner, findNodeAtLocation, modify, parse, parseTree, } from 'jsonc-parser';
3
5
  import { SetupCommandError } from './command-error.js';
@@ -5,6 +7,7 @@ import { defaultCommandRunner, runResolvedCommand } from './command-runner.js';
5
7
  import { writeHostConfigAtomic } from './config-write.js';
6
8
  import { defaultSetupFileSystem } from './detect.js';
7
9
  import { setupPaths } from './paths.js';
10
+ import { SetupProcessGuard } from './process-guard.js';
8
11
  function specifierOf(value) {
9
12
  const entry = typeof value === 'string'
10
13
  ? value
@@ -193,12 +196,19 @@ export function planOpenCodeRegistration(plugin, generation, io = {}) {
193
196
  });
194
197
  }
195
198
  export async function registerOpenCode(writes, beforeWrite) {
199
+ const guard = typeof beforeWrite === 'function'
200
+ ? new SetupProcessGuard(beforeWrite)
201
+ : beforeWrite;
196
202
  for (const write of writes) {
197
203
  if (!write.changed)
198
204
  continue;
199
- await beforeWrite?.();
200
205
  await writeHostConfigAtomic(write.path, write.content, {
201
- beforeRename: beforeWrite,
206
+ // Only the rename publishes host-readable config; recheck on every retry.
207
+ beforeRename: guard ? () => guard.check({ reuse: true }) : undefined,
208
+ rename: guard
209
+ ? (from, to) => guard.step(() => rename(from, to))
210
+ : undefined,
211
+ wait: guard ? (ms) => guard.step(() => delay(ms)) : undefined,
202
212
  });
203
213
  }
204
214
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.51.0",
3
+ "version": "0.52.1",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {