@cortexkit/common-auth 0.50.0 → 0.52.0

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',
@@ -3,6 +3,12 @@ export type CacheKeepDecisionInput = {
3
3
  /** All times and the cache lifetime are in milliseconds. */
4
4
  now: number;
5
5
  ttlMs: number;
6
+ /**
7
+ * How long before expiry the warm falls due, so a slow or failed send still
8
+ * has time for retries before the cache lapses. Capped at half the lifetime.
9
+ * Default 30 s, which leaves room for a single send.
10
+ */
11
+ leadMs?: number;
6
12
  lastRealRequestAt: number;
7
13
  lastWarmAt?: number;
8
14
  /** The caller resets the count and costs on every real request. */
@@ -23,7 +23,7 @@ function withinHours(hours, at) {
23
23
  * report a stop for a session that never warmed.
24
24
  */
25
25
  export function decideCacheKeep(input) {
26
- const { mode, now, ttlMs, lastRealRequestAt, lastWarmAt, warmsSinceLastRealRequest, warmCostSoFar, nextWarmCost, rewriteCost, } = input;
26
+ const { mode, now, ttlMs, leadMs = 30_000, lastRealRequestAt, lastWarmAt, warmsSinceLastRealRequest, warmCostSoFar, nextWarmCost, rewriteCost, } = input;
27
27
  if (mode === 'off')
28
28
  return { action: 'stop', reason: 'unsupported' };
29
29
  if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
@@ -40,11 +40,13 @@ export function decideCacheKeep(input) {
40
40
  return { action: 'stop', reason: 'cost-cap' };
41
41
  const last = Math.max(lastRealRequestAt, lastWarmAt ?? lastRealRequestAt);
42
42
  const expiresAt = last + ttlMs;
43
- const due = expiresAt - Math.min(30_000, ttlMs / 2);
43
+ const lead = Math.min(Number.isFinite(leadMs) && leadMs > 0 ? leadMs : 30_000, ttlMs / 2);
44
+ const due = expiresAt - lead;
44
45
  const at = Math.max(now, due);
45
- // Replaying inside the expiry margin risks paying for a cold cache rewrite.
46
+ // Replaying inside the expiry margin risks paying for a cold cache rewrite,
47
+ // so a warm that can no longer start in time stops as a missed deadline.
46
48
  if (at >= expiresAt - Math.min(5_000, ttlMs / 10)) {
47
- return { action: 'stop', reason: 'cost-cap' };
49
+ return { action: 'stop', reason: 'deadline-missed' };
48
50
  }
49
51
  if (mode === 'hours' &&
50
52
  (!withinHours(input.hours, due) || !withinHours(input.hours, at)))
@@ -103,6 +103,13 @@ export interface CacheKeepManagerOptions<M> {
103
103
  ttlMs?: number;
104
104
  /** Warm this long before the cache expires. Default one tick plus 15 s. */
105
105
  leadMs?: number;
106
+ /**
107
+ * How long before expiry a planned warm (a session with a cache plan) falls
108
+ * due, capped at half the cache lifetime. Default 30 s, which leaves room
109
+ * for only one send. Set it longer, for example 5 minutes, when a slow send
110
+ * needs room for retries before the cache lapses.
111
+ */
112
+ planLeadMs?: number;
106
113
  /** Idle bound for main sessions, from their last real request. Default 1 h. */
107
114
  maxIdleWarmMs?: number;
108
115
  /** Idle bound for subagent sessions. Default 30 minutes. */
@@ -199,6 +206,7 @@ export declare class CacheKeepManager<M = undefined> {
199
206
  private readonly log;
200
207
  private readonly ttlMs;
201
208
  private readonly leadMs;
209
+ private readonly planLeadMs;
202
210
  private readonly maxIdleWarmMs;
203
211
  private readonly maxSubagentIdleMs;
204
212
  private readonly tickIntervalMs;
@@ -48,6 +48,7 @@ export class CacheKeepManager {
48
48
  log;
49
49
  ttlMs;
50
50
  leadMs;
51
+ planLeadMs;
51
52
  maxIdleWarmMs;
52
53
  maxSubagentIdleMs;
53
54
  tickIntervalMs;
@@ -75,6 +76,7 @@ export class CacheKeepManager {
75
76
  // One tick of slack so a target that becomes due between ticks is still
76
77
  // warmed before its cache expires.
77
78
  this.leadMs = positive(options.leadMs, this.tickIntervalMs + 15_000);
79
+ this.planLeadMs = options.planLeadMs;
78
80
  this.maxIdleWarmMs = positive(options.maxIdleWarmMs, DEFAULT_MAX_IDLE_WARM_MS);
79
81
  this.maxSubagentIdleMs = positive(options.maxSubagentIdleMs, DEFAULT_MAX_SUBAGENT_IDLE_MS);
80
82
  this.maxTargets = positive(options.maxTargets, DEFAULT_MAX_TARGETS);
@@ -337,7 +339,7 @@ export class CacheKeepManager {
337
339
  cacheExpiresAt: target.cacheExpiresAt,
338
340
  failures: target.failures,
339
341
  });
340
- this.drop(sessionKey, target.plan ? 'cost-cap' : 'expired');
342
+ this.drop(sessionKey, target.plan ? 'deadline-missed' : 'expired');
341
343
  return true;
342
344
  }
343
345
  isCurrent(sessionKey, target) {
@@ -404,6 +406,9 @@ export class CacheKeepManager {
404
406
  : { mode: plan.mode }),
405
407
  now: this.now(),
406
408
  ttlMs: target.ttlMs,
409
+ ...(this.planLeadMs !== undefined
410
+ ? { leadMs: this.planLeadMs }
411
+ : {}),
407
412
  lastRealRequestAt: target.lastRealRequestAt,
408
413
  lastWarmAt: target.lastWarmedAt,
409
414
  warmsSinceLastRealRequest: target.warmCount,
@@ -14,14 +14,14 @@ export interface SessionToolWait {
14
14
  /** Epoch milliseconds when the oldest running plan tool started. */
15
15
  since: number;
16
16
  }
17
- export declare const CACHE_WARM_STOP_REASONS: readonly ['cost-cap', 'count-cap', 'outside-hours', 'session-ended', 'unsupported'];
17
+ export declare const CACHE_WARM_STOP_REASONS: readonly ['cost-cap', 'count-cap', 'deadline-missed', 'outside-hours', 'session-ended', 'unsupported'];
18
18
  /** Billing rejects unknown stop reasons; omit them rather than guessing. */
19
19
  export declare function isCacheWarmStopReason(value: unknown): value is (typeof CACHE_WARM_STOP_REASONS)[number];
20
20
  /**
21
21
  * The stop reasons the llm-runner contract defines today; any other string is
22
22
  * accepted too, for reasons that contract adds later.
23
23
  */
24
- export type CacheWarmStopReason = 'cost-cap' | 'count-cap' | 'outside-hours' | 'session-ended' | 'unsupported' | (string & Record<never, never>);
24
+ export type CacheWarmStopReason = 'cost-cap' | 'count-cap' | 'deadline-missed' | 'outside-hours' | 'session-ended' | 'unsupported' | (string & Record<never, never>);
25
25
  export interface CacheTouchInput {
26
26
  /** Integer epoch milliseconds when the provider answered. */
27
27
  at: number;
@@ -2,6 +2,7 @@ import { routingHandle } from './handle.js';
2
2
  export const CACHE_WARM_STOP_REASONS = [
3
3
  'cost-cap',
4
4
  'count-cap',
5
+ 'deadline-missed',
5
6
  'outside-hours',
6
7
  'session-ended',
7
8
  'unsupported',
@@ -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.50.0",
3
+ "version": "0.52.0",
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": {