@cortexkit/common-auth 0.16.0 → 0.17.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.
@@ -103,7 +103,12 @@ export interface EnrollmentAncestorOptions {
103
103
  */
104
104
  export declare function refuseWritableAncestor(parent: string, options?: EnrollmentAncestorOptions): Promise<void>;
105
105
  export declare function readClaustrumEnrollmentStatus(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<ClaustrumEnrollmentStatus>;
106
- /** Resolve the host's account mode from its enrollment files without writing. */
106
+ /**
107
+ * Resolve the host's account mode from its enrollment files. It never changes
108
+ * their contents or the host's mode. On Windows, reading them may create a
109
+ * missing private state folder and tighten an enrollment file's permissions to
110
+ * owner-only, as every private-file read there does.
111
+ */
107
112
  export declare function enrollmentAuthority(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<'vault' | 'local' | 'unreadable'>;
108
113
  /**
109
114
  * Read fresh bearer material for one scoped operation; never publish it.
@@ -419,7 +419,12 @@ export async function readClaustrumEnrollmentStatus(paths, proposedName) {
419
419
  }
420
420
  return statusFromState(state);
421
421
  }
422
- /** Resolve the host's account mode from its enrollment files without writing. */
422
+ /**
423
+ * Resolve the host's account mode from its enrollment files. It never changes
424
+ * their contents or the host's mode. On Windows, reading them may create a
425
+ * missing private state folder and tighten an enrollment file's permissions to
426
+ * owner-only, as every private-file read there does.
427
+ */
423
428
  export async function enrollmentAuthority(paths, proposedName) {
424
429
  let status;
425
430
  try {
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { acquireRefreshFileLock, withLock, writeJsonAtomic, } from '../fs/index.js';
3
3
  import { readPrivateText, windowsPrivateFiles } from '../fs/private-files.js';
4
- import { isQuotaMap, mergeQuotaObservation, } from '../quota/index.js';
4
+ import { decodeQuotaMap, mergeQuotaObservation, } from '../quota/index.js';
5
5
  import { ClaustrumConsumerError } from './errors.js';
6
6
  import { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
7
7
  export const DEFAULT_ROUTE_PREFIX = 'vault:';
@@ -210,6 +210,7 @@ function optionalString(value) {
210
210
  return value === undefined || typeof value === 'string';
211
211
  }
212
212
  function decodeRow(value) {
213
+ const quota = isRecord(value) ? decodeQuotaMap(value.quota) : undefined;
213
214
  if (!isRecord(value) ||
214
215
  typeof value.routeId !== 'string' ||
215
216
  typeof value.credentialId !== 'string' ||
@@ -224,11 +225,14 @@ function decodeRow(value) {
224
225
  (value.aliases !== undefined &&
225
226
  (!Array.isArray(value.aliases) ||
226
227
  !value.aliases.every((alias) => typeof alias === 'string'))) ||
227
- (value.quota !== undefined && !isQuotaMap(value.quota)) ||
228
+ (value.quota !== undefined && quota === undefined) ||
228
229
  (value.stale !== undefined && value.stale !== true) ||
229
230
  (value.unclaimed !== undefined && value.unclaimed !== true))
230
231
  return undefined;
231
- return value;
232
+ return {
233
+ ...value,
234
+ ...(quota === undefined ? {} : { quota }),
235
+ };
232
236
  }
233
237
  const SKIPPED_REASONS = new Set([
234
238
  'empty credential id',
@@ -1,5 +1,7 @@
1
1
  export interface QuotaCodec {
2
2
  readonly validate: (value: unknown) => boolean;
3
+ /** Normalize persisted data before validation; older codecs may omit this. */
4
+ readonly decode?: (value: unknown) => unknown;
3
5
  readonly merge: (stored: unknown, observation: unknown) => unknown;
4
6
  }
5
7
  /**
@@ -1,4 +1,4 @@
1
- import { isQuotaMap } from './map.js';
1
+ import { decodeQuotaMap, isQuotaMap } from './map.js';
2
2
  import { mergeQuotaObservation } from './merge.js';
3
3
  /**
4
4
  * The quota codec the account-pool store (the `/store` subpath) takes when it
@@ -8,5 +8,6 @@ import { mergeQuotaObservation } from './merge.js';
8
8
  */
9
9
  export const quotaCodec = Object.freeze({
10
10
  validate: isQuotaMap,
11
+ decode: decodeQuotaMap,
11
12
  merge: mergeQuotaObservation,
12
13
  });
@@ -2,8 +2,8 @@ export type { QuotaCodec } from './codec.js';
2
2
  export { quotaCodec } from './codec.js';
3
3
  export type { QuotaTextForm, QuotaTextOptions } from './format.js';
4
4
  export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from './format.js';
5
- export type { CreditBudgetCleared, CreditBudgetEntry, CreditBudgetReading, QuotaAbsentEntry, QuotaEntry, QuotaMap, QuotaReadingEntry, QuotaRetiredEntry, } from './map.js';
6
- export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, emptyQuotaMap, isQuotaMap, } from './map.js';
5
+ export type { CreditBudgetCleared, CreditBudgetEntry, CreditBudgetReading, QuotaAbsentEntry, QuotaCounter, QuotaEntry, QuotaMap, QuotaReadingEntry, QuotaRetiredEntry, } from './map.js';
6
+ export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, decodeQuotaMap, emptyQuotaMap, isQuotaMap, } from './map.js';
7
7
  export type { ObservedBudget, ObservedPair, ObservedReading, QuotaObservation, } from './merge.js';
8
8
  export { isQuotaObservation, mergeQuotaObservation, QuotaCodecError, } from './merge.js';
9
9
  export type { ExhaustionReset, ProjectedBudget, ProjectedLimit, ProjectedQuota, } from './projection.js';
@@ -1,5 +1,5 @@
1
1
  export { quotaCodec } from './codec.js';
2
2
  export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from './format.js';
3
- export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, emptyQuotaMap, isQuotaMap, } from './map.js';
3
+ export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, decodeQuotaMap, emptyQuotaMap, isQuotaMap, } from './map.js';
4
4
  export { isQuotaObservation, mergeQuotaObservation, QuotaCodecError, } from './merge.js';
5
5
  export { budgetExhaustedResetAt, futureResetAt, projectQuota, readsExhausted, } from './projection.js';
@@ -44,16 +44,27 @@ export interface CreditBudgetCleared {
44
44
  checkedAt: number;
45
45
  }
46
46
  export type CreditBudgetEntry = CreditBudgetReading | CreditBudgetCleared;
47
+ export interface QuotaCounter {
48
+ value: number;
49
+ checkedAt: number;
50
+ }
47
51
  export interface QuotaMap {
48
52
  limits: QuotaEntry[];
49
53
  /** Absent means no observation has reported on the budget yet. */
50
54
  budget?: CreditBudgetEntry;
55
+ /** Provider-named counts, each with its own observation time. */
56
+ counters?: Record<string, QuotaCounter>;
51
57
  }
52
58
  export declare function emptyQuotaMap(): QuotaMap;
53
59
  /** The time an entry speaks for: its reading, retirement or absence time. */
54
60
  export declare function entryTime(entry: QuotaEntry): number;
55
61
  export declare function limitKey(scope: string, label: string): string;
56
62
  export declare function isCreditBudgetEntry(value: unknown): value is CreditBudgetEntry;
63
+ export declare function isQuotaCounters(value: unknown): value is Record<string, QuotaCounter>;
64
+ /** Keep usable counters without letting one malformed count hide a quota map. */
65
+ export declare function readQuotaCounters(value: unknown): Record<string, QuotaCounter> | undefined;
66
+ /** Decode persisted quota, dropping malformed counters but not limit evidence. */
67
+ export declare function decodeQuotaMap(value: unknown): QuotaMap | undefined;
57
68
  /**
58
69
  * True when `value` is a well-formed quota map. Unrecognised top-level keys
59
70
  * are tolerated (and preserved by merge) so a newer writer's additions
package/dist/quota/map.js CHANGED
@@ -83,6 +83,40 @@ export function isCreditBudgetEntry(value) {
83
83
  optional(value, 'remaining', isFiniteNumber) &&
84
84
  optional(value, 'unit', isString));
85
85
  }
86
+ function isQuotaCounter(value) {
87
+ return (isRecord(value) &&
88
+ isFiniteNumber(value.value) &&
89
+ Number.isInteger(value.value) &&
90
+ value.value >= 0 &&
91
+ isFiniteNumber(value.checkedAt));
92
+ }
93
+ export function isQuotaCounters(value) {
94
+ return isRecord(value) && Object.values(value).every(isQuotaCounter);
95
+ }
96
+ /** Keep usable counters without letting one malformed count hide a quota map. */
97
+ export function readQuotaCounters(value) {
98
+ if (!isRecord(value))
99
+ return undefined;
100
+ const entries = Object.entries(value).filter(([, entry]) => isQuotaCounter(entry));
101
+ return entries.length === 0
102
+ ? undefined
103
+ : Object.fromEntries(entries);
104
+ }
105
+ /** Decode persisted quota, dropping malformed counters but not limit evidence. */
106
+ export function decodeQuotaMap(value) {
107
+ // A valid map is returned as the same object, so stored quota keeps the
108
+ // identity it had before counters existed; only a map with a malformed
109
+ // counter is copied without it.
110
+ if (isQuotaMap(value))
111
+ return value;
112
+ if (!isRecord(value))
113
+ return undefined;
114
+ const { counters: rawCounters, ...rest } = value;
115
+ if (!isQuotaMap(rest))
116
+ return undefined;
117
+ const counters = readQuotaCounters(rawCounters);
118
+ return { ...rest, ...(counters === undefined ? {} : { counters }) };
119
+ }
86
120
  /**
87
121
  * True when `value` is a well-formed quota map. Unrecognised top-level keys
88
122
  * are tolerated (and preserved by merge) so a newer writer's additions
@@ -101,5 +135,6 @@ export function isQuotaMap(value) {
101
135
  return false;
102
136
  seen.add(key);
103
137
  }
104
- return optional(value, 'budget', isCreditBudgetEntry);
138
+ return (optional(value, 'budget', isCreditBudgetEntry) &&
139
+ optional(value, 'counters', isQuotaCounters));
105
140
  }
@@ -1,4 +1,4 @@
1
- import { type QuotaMap } from './map.js';
1
+ import { type QuotaCounter, type QuotaMap } from './map.js';
2
2
  export interface ObservedReading {
3
3
  /** Defaults to `all`. */
4
4
  scope?: string;
@@ -32,6 +32,8 @@ export interface QuotaObservation {
32
32
  coverage?: ObservedPair[];
33
33
  /** Absent means the observation says nothing about the budget. */
34
34
  budget?: ObservedBudget;
35
+ /** Each named count uses its own time, independently of limits and budget. */
36
+ counters?: Record<string, QuotaCounter>;
35
37
  }
36
38
  /** Thrown by `mergeQuotaObservation` when either argument is malformed. */
37
39
  export declare class QuotaCodecError extends TypeError {
@@ -11,7 +11,7 @@
11
11
  // no entry gets an absence record. A pair outside the coverage is never
12
12
  // touched, so a header-shaped partial observation (which covers only what it
13
13
  // carries) cannot erase a family limit or the budget.
14
- import { ALL_SCOPE, entryTime, isQuotaMap, limitKey, } from './map.js';
14
+ import { ALL_SCOPE, decodeQuotaMap, entryTime, isQuotaCounters, limitKey, } from './map.js';
15
15
  /** Thrown by `mergeQuotaObservation` when either argument is malformed. */
16
16
  export class QuotaCodecError extends TypeError {
17
17
  constructor(message) {
@@ -83,7 +83,8 @@ export function isQuotaObservation(value) {
83
83
  }
84
84
  if (!coverage.every(isObservedPair))
85
85
  return false;
86
- return value.budget === undefined || isObservedBudget(value.budget);
86
+ return ((value.budget === undefined || isObservedBudget(value.budget)) &&
87
+ (value.counters === undefined || isQuotaCounters(value.counters)));
87
88
  }
88
89
  function compareEntries(left, right) {
89
90
  if (left.scope !== right.scope)
@@ -99,6 +100,16 @@ function mergeBudget(stored, observed, checkedAt) {
99
100
  return stored;
100
101
  return { ...observed, checkedAt };
101
102
  }
103
+ function mergeCounters(stored, observed) {
104
+ const counters = new Map(Object.entries(stored ?? {}));
105
+ for (const [name, counter] of Object.entries(observed ?? {})) {
106
+ const existing = counters.get(name);
107
+ if (existing === undefined || counter.checkedAt >= existing.checkedAt) {
108
+ counters.set(name, counter);
109
+ }
110
+ }
111
+ return counters.size === 0 ? undefined : Object.fromEntries(counters);
112
+ }
102
113
  /**
103
114
  * Applies `observation` to `stored` (undefined for a row with no map yet) and
104
115
  * returns the new map. Pure: neither argument is modified. Throws
@@ -106,13 +117,16 @@ function mergeBudget(stored, observed, checkedAt) {
106
117
  * write rather than persisting a map it could not read back.
107
118
  */
108
119
  export function mergeQuotaObservation(stored, observation) {
109
- if (stored !== undefined && !isQuotaMap(stored)) {
120
+ // Decode the stored map the way reads do, so a malformed counter that reads
121
+ // already hide is dropped here too instead of refusing every later write.
122
+ const decoded = stored === undefined ? undefined : decodeQuotaMap(stored);
123
+ if (stored !== undefined && decoded === undefined) {
110
124
  throw new QuotaCodecError('stored quota map is malformed');
111
125
  }
112
126
  if (!isQuotaObservation(observation)) {
113
127
  throw new QuotaCodecError('quota observation is malformed');
114
128
  }
115
- const base = stored ?? { limits: [] };
129
+ const base = decoded ?? { limits: [] };
116
130
  const at = observation.checkedAt;
117
131
  const entries = new Map();
118
132
  for (const entry of base.limits) {
@@ -152,11 +166,13 @@ export function mergeQuotaObservation(stored, observation) {
152
166
  : { scope, label: pair.label, kind: 'retired', retiredAt: at });
153
167
  }
154
168
  // Keys this module does not recognise are carried over untouched.
155
- const { limits: _limits, budget: _budget, ...unknownKeys } = base;
169
+ const { limits: _limits, budget: _budget, counters: _counters, ...unknownKeys } = base;
156
170
  const budget = mergeBudget(base.budget, observation.budget, at);
171
+ const counters = mergeCounters(base.counters, observation.counters);
157
172
  return {
158
173
  ...unknownKeys,
159
174
  limits: [...entries.values()].sort(compareEntries),
160
175
  ...(budget === undefined ? {} : { budget }),
176
+ ...(counters === undefined ? {} : { counters }),
161
177
  };
162
178
  }
@@ -1,4 +1,4 @@
1
- import { type QuotaMap } from './map.js';
1
+ import { type QuotaCounter, type QuotaMap } from './map.js';
2
2
  export interface ProjectedLimit {
3
3
  scope: string;
4
4
  label: string;
@@ -30,6 +30,7 @@ export interface ProjectedQuota {
30
30
  checkedAt?: number;
31
31
  /** Present only when the stored budget is a reading, not cleared. */
32
32
  budget?: ProjectedBudget;
33
+ counters?: Record<string, QuotaCounter>;
33
34
  }
34
35
  /**
35
36
  * Resolves `map` for a request in `scope` (`all` or a model family). A family
@@ -6,7 +6,7 @@
6
6
  // scope, orders the result the way the primitives expect, and carries each
7
7
  // entry's (scope, label) so a decision names the limit it judged rather than
8
8
  // the position it occupied.
9
- import { ALL_SCOPE, } from './map.js';
9
+ import { ALL_SCOPE, readQuotaCounters, } from './map.js';
10
10
  function project(entry) {
11
11
  if (entry.kind === 'retired') {
12
12
  return {
@@ -94,11 +94,13 @@ export function projectQuota(map, scope = ALL_SCOPE) {
94
94
  ? Math.min(...stamped.map((limit) => limit.checkedAt))
95
95
  : undefined;
96
96
  const budget = map?.budget?.kind === 'reading' ? projectBudget(map.budget) : undefined;
97
+ const counters = readQuotaCounters(map?.counters);
97
98
  return {
98
99
  scope,
99
100
  limits,
100
101
  ...(checkedAt === undefined ? {} : { checkedAt }),
101
102
  ...(budget === undefined ? {} : { budget }),
103
+ ...(counters === undefined ? {} : { counters }),
102
104
  };
103
105
  }
104
106
  /**
@@ -119,7 +119,12 @@ export async function runSetup(plugin, argv = [], io = {}) {
119
119
  printLine(terminal, 'Checking that OpenCode and Pi are not running…');
120
120
  if (options.dryRun) {
121
121
  try {
122
- const active = await fence.listRunningHosts(env);
122
+ const preview = fence.previewRunningHosts
123
+ ? await fence.previewRunningHosts(env)
124
+ : { hosts: await fence.listRunningHosts(env), uncheckedRuntimes: 0 };
125
+ const active = preview.hosts;
126
+ if (preview.uncheckedRuntimes > 0)
127
+ printLine(terminal, 'Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.');
123
128
  const names = new Set(new ProcessFenceViolationError(active).activeHosts.map((host) => host.command.toLowerCase() === 'pi' ? 'Pi' : 'OpenCode'));
124
129
  for (const name of names)
125
130
  printLine(terminal, `${name} is running; setup will ask you to quit it.`);
@@ -148,6 +153,8 @@ export async function runSetup(plugin, argv = [], io = {}) {
148
153
  if (options.dryRun) {
149
154
  printLine(terminal, 'Dry run: no registrations, enrollment, sign-in or migration will be performed.');
150
155
  for (const host of hosts) {
156
+ if (plugin.beforeSignIn)
157
+ printLine(terminal, `Would run beforeSignIn(${host}, ${mode}).`);
151
158
  if (useVault) {
152
159
  const paths = hostEnrollmentPaths(plugin.vault.hosts[host].paths);
153
160
  printLine(terminal, `Would Connect ${host}: write ${paths.statePath} and ${paths.tokenPath}; wait for ck auth enroll approve.`);
@@ -165,21 +172,29 @@ export async function runSetup(plugin, argv = [], io = {}) {
165
172
  printLine(terminal, `Would migrate ${host} using the plugin callback (provider-specific writes).`);
166
173
  }
167
174
  else {
175
+ const context = {
176
+ opencodeGeneration: generation,
177
+ mode,
178
+ hosts: Object.freeze([...hosts]),
179
+ piAgentDir: detection.pi.directory,
180
+ };
168
181
  for (const host of hosts) {
182
+ await stopped();
183
+ await plugin.beforeSignIn?.(host, context);
169
184
  await stopped();
170
185
  if (useVault)
171
186
  await connectSetupHost(plugin, host, io, terminal, stopped);
172
187
  else
173
- await plugin.signInLocal(host);
188
+ await plugin.signInLocal(host, context);
174
189
  await stopped();
175
- await plugin.beforeRegister?.(host, mode);
190
+ await plugin.beforeRegister?.(host, mode, context);
176
191
  await stopped();
177
192
  if (host === 'opencode')
178
193
  await registerOpenCode(writes, stopped);
179
194
  else
180
195
  await registerPi(plugin, detection.pi.executable, io);
181
196
  await stopped();
182
- await plugin.migrate(host);
197
+ await plugin.migrate(host, context);
183
198
  }
184
199
  }
185
200
  printLine(terminal, `${options.dryRun ? 'Planned' : 'Configured'} ${plugin.displayName} for ${hosts.join(', ')} (${mode}).`);
@@ -2,4 +2,4 @@ export { AMBIGUOUS_OPENCODE_MESSAGE, runSetup } from './command.js';
2
2
  export { detectHosts, detectOpenCodeGeneration, findExecutableOnPath, openCodeDesktopMarkers, } from './detect.js';
3
3
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, type ProcessInspectionStep, } from './process-fence.js';
4
4
  export { type PlannedWrite, planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
5
- export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupDetection, SetupEnvironment, SetupFileSystem, SetupHost, SetupIO, SetupPlugin, SetupResult, } from './types.js';
5
+ export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnvironment, SetupFileSystem, SetupHost, SetupIO, SetupPlugin, SetupResult, } from './types.js';
@@ -31,6 +31,8 @@ export declare function listSetupProcesses(runner?: CommandRunner, options?: {
31
31
  platform?: string;
32
32
  env?: SetupEnvironment;
33
33
  onStep?: (details: ProcessInspectionStep) => void;
34
+ /** False skips the Windows PowerShell query for Node and Bun command lines. */
35
+ inspectRuntimes?: boolean;
34
36
  }): Promise<Array<{
35
37
  pid: number;
36
38
  command: string;
@@ -3,11 +3,88 @@ import { defaultCommandRunner } from './command-runner.js';
3
3
  // took less than 0.5 s. This is the product's one-shot latency budget, not a test
4
4
  // deadline: 45 s is about three times the worst measured cold start.
5
5
  const WINDOWS_CIM_TIMEOUT_MS = 45_000;
6
- const HOST_PATTERN = /(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.(?:exe|cmd|bat|m?js))?(?=$|\s|")/i;
7
- const PI_SCRIPT_PATTERN = /(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js(?=$|\s|")/i;
6
+ const HOSTS = new Set(['opencode', 'litecode', 'opencode2', 'pi']);
7
+ const RUNTIMES = new Set(['node', 'bun']);
8
+ const PI_SCRIPT_PATTERN = /(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;
9
+ /** Splits a command line into arguments, keeping double-quoted ones whole. */
10
+ function commandArguments(command) {
11
+ return [...command.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2] ?? '');
12
+ }
13
+ function executableName(argument) {
14
+ return (argument.split(/[/\\]/).pop() ?? '')
15
+ .toLowerCase()
16
+ .replace(/\.(?:exe|cmd|bat|m?js)$/, '');
17
+ }
18
+ // Node and Bun options whose value is the next argument, so that value is not
19
+ // mistaken for the script (`node --require ./preload.cjs …/opencode`).
20
+ const VALUE_OPTIONS = new Set([
21
+ '-r',
22
+ '--require',
23
+ '--import',
24
+ '--loader',
25
+ '--experimental-loader',
26
+ '-C',
27
+ '--conditions',
28
+ '--env-file',
29
+ '--title',
30
+ '--input-type',
31
+ '--preload',
32
+ '--cwd',
33
+ '-c',
34
+ '--config',
35
+ '--tsconfig-override',
36
+ '-d',
37
+ '--define',
38
+ '-l',
39
+ '--main-fields',
40
+ ]);
41
+ // Options that run inline code instead of a script file.
42
+ const INLINE_OPTIONS = new Set(['-e', '--eval', '-p', '--print']);
43
+ /** The script a Node or Bun runtime was started with, if any. */
44
+ function runtimeScript(runtime, args) {
45
+ for (let index = 0; index < args.length; index++) {
46
+ const argument = args[index] ?? '';
47
+ if (argument === '--')
48
+ return args[index + 1];
49
+ if (INLINE_OPTIONS.has(argument))
50
+ return undefined;
51
+ if (argument.startsWith('-')) {
52
+ if (!argument.includes('=') && VALUE_OPTIONS.has(argument))
53
+ index++;
54
+ continue;
55
+ }
56
+ // `bun run <script>` names the script after the subcommand.
57
+ if (runtime === 'bun' && argument === 'run')
58
+ continue;
59
+ return argument;
60
+ }
61
+ return undefined;
62
+ }
63
+ /**
64
+ * Names the host a process runs, judged by what it executes: the program
65
+ * itself, or the script a Node or Bun runtime was started with. Any other
66
+ * argument is ignored, so a shell whose command line merely mentions an
67
+ * `opencode` folder (`bash -c "cd …/opencode && …"`) is not a running host.
68
+ * `ps` prints arguments unquoted, so on macOS and Linux a program or script
69
+ * path containing spaces is not recognized; npm and Bun install OpenCode and Pi
70
+ * under paths without spaces.
71
+ */
8
72
  function hostName(command) {
9
- return (HOST_PATTERN.exec(command)?.[1] ??
10
- (PI_SCRIPT_PATTERN.test(command) ? 'pi' : null));
73
+ const [program, ...rest] = commandArguments(command);
74
+ if (program === undefined)
75
+ return null;
76
+ const name = executableName(program);
77
+ if (HOSTS.has(name))
78
+ return name;
79
+ if (!RUNTIMES.has(name))
80
+ return null;
81
+ const script = runtimeScript(name, rest);
82
+ if (script === undefined)
83
+ return null;
84
+ const scriptName = executableName(script);
85
+ if (HOSTS.has(scriptName))
86
+ return scriptName;
87
+ return PI_SCRIPT_PATTERN.test(script) ? 'pi' : null;
11
88
  }
12
89
  export class ProcessInspectionError extends Error {
13
90
  code = 'process-inspection-failed';
@@ -126,7 +203,7 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
126
203
  throw new ProcessInspectionError(inspection);
127
204
  // tasklist identifies native hosts, but npm Pi/OpenCode scripts appear as Node or Bun.
128
205
  const runtimes = processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command));
129
- if (windows && runtimes.length) {
206
+ if (windows && runtimes.length && options.inspectRuntimes !== false) {
130
207
  const details = await inspect('CIM', 'powershell.exe', [
131
208
  '-NoProfile',
132
209
  '-NonInteractive',
@@ -164,9 +241,25 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
164
241
  }
165
242
  }
166
243
  export function createProcessFence(runner = defaultCommandRunner, options = {}) {
244
+ const isHost = (entry) => entry.pid !== process.pid && hostName(entry.command) !== null;
167
245
  return {
168
246
  async listRunningHosts(env) {
169
- return (await listSetupProcesses(runner, { ...options, env })).filter((entry) => entry.pid !== process.pid && hostName(entry.command) !== null);
247
+ return (await listSetupProcesses(runner, { ...options, env })).filter(isHost);
248
+ },
249
+ async previewRunningHosts(env) {
250
+ const processes = await listSetupProcesses(runner, {
251
+ ...options,
252
+ env,
253
+ inspectRuntimes: false,
254
+ });
255
+ const windows = (options.platform ?? process.platform) === 'win32';
256
+ return {
257
+ hosts: processes.filter(isHost),
258
+ uncheckedRuntimes: windows
259
+ ? processes.filter((entry) => entry.pid !== process.pid &&
260
+ /^(?:node|bun)\.exe$/i.test(entry.command)).length
261
+ : 0,
262
+ };
170
263
  },
171
264
  };
172
265
  }
@@ -3,6 +3,28 @@ import type { ClaustrumEnrollmentConnection, hostEnrollmentPaths } from '../clau
3
3
  export type SetupHost = 'opencode' | 'pi';
4
4
  export type OpenCodeGeneration = '1' | '2' | 'both';
5
5
  export type SetupEnvironment = Record<string, string | undefined>;
6
+ /**
7
+ * What setup decided before calling a plugin callback. The OpenCode generation
8
+ * is the one being registered, after `--opencode` or the interactive choice, so
9
+ * a plugin can sign in the way that generation expects (OpenCode 2 does not
10
+ * read OpenCode 1's login file).
11
+ */
12
+ export interface SetupCallbackContext {
13
+ opencodeGeneration: OpenCodeGeneration;
14
+ mode: 'local' | 'claustrum';
15
+ /**
16
+ * Every host this run sets up, in order, so the first `beforeSignIn` can
17
+ * check conditions across all of them (for example that their storage paths
18
+ * do not overlap) before any host is changed.
19
+ */
20
+ hosts: readonly SetupHost[];
21
+ /**
22
+ * Pi's agent folder, resolved the way Pi itself does (`PI_CODING_AGENT_DIR`,
23
+ * with `~` expanded, else `~/.pi/agent`). Pi's own `auth.json` lives here;
24
+ * use it rather than a plugin path setting, which can point elsewhere.
25
+ */
26
+ piAgentDir: string;
27
+ }
6
28
  /** Provider login, credential migration and vault activation stay in plugin callbacks. */
7
29
  export interface SetupPlugin {
8
30
  packages: {
@@ -19,10 +41,17 @@ export interface SetupPlugin {
19
41
  paths: Parameters<typeof hostEnrollmentPaths>[0];
20
42
  }>;
21
43
  };
22
- signInLocal(host: SetupHost): Promise<void>;
23
- migrate(host: SetupHost): Promise<void>;
44
+ /**
45
+ * Runs for each host on a real run after the host, mode and generation are
46
+ * chosen and before the vault ceremony or `signInLocal`, while nothing has
47
+ * changed yet. Rejecting stops setup for that host, so a plugin can ask for
48
+ * consent or check preconditions before any credential or authority change.
49
+ */
50
+ beforeSignIn?(host: SetupHost, context: SetupCallbackContext): Promise<void>;
51
+ signInLocal(host: SetupHost, context: SetupCallbackContext): Promise<void>;
52
+ migrate(host: SetupHost, context: SetupCallbackContext): Promise<void>;
24
53
  /** Reject mixed local/vault credentials and activate provider-specific vault access before registration. */
25
- beforeRegister?(host: SetupHost, mode: 'local' | 'claustrum'): Promise<void>;
54
+ beforeRegister?(host: SetupHost, mode: 'local' | 'claustrum', context: SetupCallbackContext): Promise<void>;
26
55
  }
27
56
  export interface CommandResult {
28
57
  exitCode: number;
@@ -52,6 +81,20 @@ export interface ProcessFence {
52
81
  pid: number;
53
82
  command: string;
54
83
  }>>;
84
+ /**
85
+ * For a dry run, which must change nothing: the hosts found without starting
86
+ * any program that writes files. On Windows that skips the PowerShell query
87
+ * for Node and Bun command lines (PowerShell writes a startup cache into the
88
+ * user's profile), so Node or Bun processes are only counted. A fence without
89
+ * it is previewed with `listRunningHosts`.
90
+ */
91
+ previewRunningHosts?(env?: SetupEnvironment): Promise<{
92
+ hosts: Array<{
93
+ pid: number;
94
+ command: string;
95
+ }>;
96
+ uncheckedRuntimes: number;
97
+ }>;
55
98
  }
56
99
  /** Defaults use the process terminal and environment; overrides are test seams. */
57
100
  export interface SetupIO {
@@ -49,6 +49,8 @@ export type StoredCredential = (OAuthCredential & {
49
49
  /** Quota codec supplied by `/quota`: the store never interprets the map itself. */
50
50
  export interface QuotaCodec {
51
51
  validate(value: unknown): boolean;
52
+ /** Normalize persisted quota before validation, when the codec supports it. */
53
+ decode?(value: unknown): unknown;
52
54
  merge(stored: unknown | undefined, observation: unknown): unknown;
53
55
  }
54
56
  /**
@@ -420,7 +420,8 @@ function parseEntry(raw, codec) {
420
420
  return undefined;
421
421
  if ('disabledReason' in raw && typeof raw.disabledReason !== 'string')
422
422
  return undefined;
423
- if ('quota' in raw && !codec.validate(raw.quota))
423
+ const quota = 'quota' in raw && codec.decode ? codec.decode(raw.quota) : raw.quota;
424
+ if ('quota' in raw && !codec.validate(quota))
424
425
  return undefined;
425
426
  if ('staged' in raw && !parseReservation(raw.staged))
426
427
  return undefined;
@@ -430,7 +431,7 @@ function parseEntry(raw, codec) {
430
431
  ...(typeof raw.disabledReason === 'string'
431
432
  ? { disabledReason: raw.disabledReason }
432
433
  : {}),
433
- ...('quota' in raw ? { quota: raw.quota } : {}),
434
+ ...('quota' in raw ? { quota } : {}),
434
435
  };
435
436
  }
436
437
  function credentialFor(raw, stateEntry) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.16.0",
3
+ "version": "0.17.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": {