@cortexkit/common-auth 0.15.0 → 0.16.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.
@@ -0,0 +1,177 @@
1
+ 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
+ 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;
8
+ function hostName(command) {
9
+ return (HOST_PATTERN.exec(command)?.[1] ??
10
+ (PI_SCRIPT_PATTERN.test(command) ? 'pi' : null));
11
+ }
12
+ export class ProcessInspectionError extends Error {
13
+ code = 'process-inspection-failed';
14
+ step;
15
+ exitCode;
16
+ signal;
17
+ timedOut;
18
+ durationMs;
19
+ constructor(details) {
20
+ super('Process inspection failed; setup cannot prove hosts are stopped.');
21
+ this.name = 'ProcessInspectionError';
22
+ this.step = details.step;
23
+ this.exitCode = details.exitCode;
24
+ this.signal = details.signal;
25
+ this.timedOut = details.timedOut;
26
+ this.durationMs = details.durationMs;
27
+ }
28
+ get refusalText() {
29
+ const outcome = this.timedOut
30
+ ? 'timed out'
31
+ : this.signal
32
+ ? `signal ${this.signal}`
33
+ : this.exitCode === null
34
+ ? 'could not start or complete'
35
+ : this.exitCode === 0
36
+ ? 'invalid output (exit code 0)'
37
+ : `exit code ${this.exitCode}`;
38
+ return `${this.message} ${this.step}: ${outcome} after ${Math.round(this.durationMs)} ms.`;
39
+ }
40
+ }
41
+ export class ProcessFenceViolationError extends Error {
42
+ activeHosts;
43
+ constructor(activeHosts) {
44
+ // Process arguments may contain credentials; report only the recognized host name.
45
+ const safeHosts = activeHosts.map((host) => ({
46
+ pid: host.pid,
47
+ command: hostName(host.command) ?? 'host',
48
+ }));
49
+ super(`OpenCode or Pi processes are currently running:\n${safeHosts.map((host) => ` - PID ${host.pid}: ${host.command}`).join('\n')}\n\nPlease quit all OpenCode, LiteCode, and Pi processes before running setup.`);
50
+ this.activeHosts = safeHosts;
51
+ this.name = 'ProcessFenceViolationError';
52
+ }
53
+ }
54
+ /** List processes before filtering hosts; Windows PID 0 is a valid idle-process row. */
55
+ export async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
56
+ const windows = (options.platform ?? process.platform) === 'win32';
57
+ let inspection = {
58
+ step: windows ? 'tasklist' : 'ps',
59
+ exitCode: null,
60
+ signal: null,
61
+ timedOut: false,
62
+ durationMs: 0,
63
+ };
64
+ const inspect = async (step, file, args, timeoutMs) => {
65
+ const started = performance.now();
66
+ inspection = {
67
+ step,
68
+ exitCode: null,
69
+ signal: null,
70
+ timedOut: false,
71
+ durationMs: 0,
72
+ };
73
+ try {
74
+ const result = await runner.run(file, args, {
75
+ env: options.env,
76
+ timeoutMs,
77
+ });
78
+ inspection = {
79
+ step,
80
+ exitCode: result.exitCode,
81
+ signal: result.signal ?? null,
82
+ timedOut: result.timedOut ?? false,
83
+ durationMs: result.durationMs ?? performance.now() - started,
84
+ };
85
+ return result;
86
+ }
87
+ finally {
88
+ if (inspection.exitCode === null)
89
+ inspection.durationMs = performance.now() - started;
90
+ options.onStep?.({ ...inspection });
91
+ }
92
+ };
93
+ try {
94
+ const result = await inspect(windows ? 'tasklist' : 'ps', windows ? 'tasklist.exe' : 'ps', windows ? ['/fo', 'csv', '/nh'] : ['-eo', 'pid,command']);
95
+ if (result.exitCode !== 0)
96
+ throw new ProcessInspectionError(inspection);
97
+ const processes = [];
98
+ for (const line of result.stdout.split(/\r?\n/)) {
99
+ const trimmed = line.trim();
100
+ if (!trimmed)
101
+ continue;
102
+ let pid;
103
+ let command;
104
+ if (windows) {
105
+ const match = /^"([^"]+)","(\d+)"(?:,|$)/.exec(trimmed);
106
+ if (!match)
107
+ throw new ProcessInspectionError(inspection);
108
+ command = match[1] ?? '';
109
+ pid = Number(match[2]);
110
+ }
111
+ else {
112
+ const match = /^(\d+)\s+(.+)$/.exec(trimmed);
113
+ if (!match) {
114
+ if (/^PID\s+COMMAND$/i.test(trimmed))
115
+ continue;
116
+ throw new ProcessInspectionError(inspection);
117
+ }
118
+ pid = Number(match[1]);
119
+ command = match[2] ?? '';
120
+ }
121
+ if (!Number.isSafeInteger(pid) || pid < 0)
122
+ throw new ProcessInspectionError(inspection);
123
+ processes.push({ pid, command });
124
+ }
125
+ if (!processes.length)
126
+ throw new ProcessInspectionError(inspection);
127
+ // tasklist identifies native hosts, but npm Pi/OpenCode scripts appear as Node or Bun.
128
+ const runtimes = processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command));
129
+ if (windows && runtimes.length) {
130
+ const details = await inspect('CIM', 'powershell.exe', [
131
+ '-NoProfile',
132
+ '-NonInteractive',
133
+ '-Command',
134
+ "$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter \"Name = 'node.exe' OR Name = 'bun.exe'\" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress",
135
+ ], WINDOWS_CIM_TIMEOUT_MS);
136
+ if (details.exitCode !== 0)
137
+ throw new ProcessInspectionError(inspection);
138
+ const value = JSON.parse(details.stdout || 'null');
139
+ const rows = value === null ? [] : Array.isArray(value) ? value : [value];
140
+ const commands = new Map();
141
+ for (const row of rows) {
142
+ if (!row ||
143
+ typeof row !== 'object' ||
144
+ !('ProcessId' in row) ||
145
+ !('CommandLine' in row) ||
146
+ !Number.isSafeInteger(row.ProcessId))
147
+ throw new ProcessInspectionError(inspection);
148
+ if (typeof row.CommandLine === 'string')
149
+ commands.set(Number(row.ProcessId), row.CommandLine);
150
+ else if (runtimes.some((entry) => entry.pid === row.ProcessId))
151
+ throw new ProcessInspectionError(inspection);
152
+ }
153
+ for (const entry of runtimes) {
154
+ // A process absent from the later CIM snapshot already exited.
155
+ entry.command = commands.get(entry.pid) ?? '';
156
+ }
157
+ }
158
+ return processes;
159
+ }
160
+ catch (error) {
161
+ if (error instanceof ProcessInspectionError)
162
+ throw error;
163
+ throw new ProcessInspectionError(inspection);
164
+ }
165
+ }
166
+ export function createProcessFence(runner = defaultCommandRunner, options = {}) {
167
+ return {
168
+ async listRunningHosts(env) {
169
+ return (await listSetupProcesses(runner, { ...options, env })).filter((entry) => entry.pid !== process.pid && hostName(entry.command) !== null);
170
+ },
171
+ };
172
+ }
173
+ export async function assertHostsStopped(fence, env) {
174
+ const active = await fence.listRunningHosts(env);
175
+ if (active.length)
176
+ throw new ProcessFenceViolationError(active);
177
+ }
@@ -0,0 +1,4 @@
1
+ import type { MenuTerminal } from '../auth-menu/terminal.js';
2
+ import type { SetupHost } from './types.js';
3
+ /** Reuse the terminal selector for a toggle list with an explicit final choice. */
4
+ export declare function selectSetupHosts(terminal: MenuTerminal, found: readonly SetupHost[]): Promise<SetupHost[] | null>;
@@ -0,0 +1,26 @@
1
+ import { select } from '../auth-menu/select.js';
2
+ /** Reuse the terminal selector for a toggle list with an explicit final choice. */
3
+ export async function selectSetupHosts(terminal, found) {
4
+ const selected = new Set(found);
5
+ for (;;) {
6
+ const choice = await select(terminal, [
7
+ ...['opencode', 'pi'].map((host) => ({
8
+ value: host,
9
+ label: `[${selected.has(host) ? 'x' : ' '}] ${host === 'opencode' ? 'OpenCode' : 'Pi'}`,
10
+ hint: found.includes(host) ? 'found' : 'not found',
11
+ })),
12
+ { value: 'done', label: 'Continue with selected hosts' },
13
+ ], {
14
+ message: 'Select hosts to set up',
15
+ subtitle: 'Enter toggles a host; choose Continue when ready.',
16
+ });
17
+ if (choice === null)
18
+ return null;
19
+ if (choice === 'done')
20
+ return [...selected];
21
+ if (selected.has(choice))
22
+ selected.delete(choice);
23
+ else
24
+ selected.add(choice);
25
+ }
26
+ }
@@ -0,0 +1,11 @@
1
+ import type { OpenCodeGeneration, SetupIO, SetupPlugin } from './types.js';
2
+ export interface PlannedWrite {
3
+ path: string;
4
+ content: string;
5
+ changed: boolean;
6
+ }
7
+ /** Edit only array entries so unrelated JSONC text, including comments, survives. */
8
+ export declare function updatePluginConfig(text: string, key: 'plugin' | 'plugins', pkg: string, version: string): string;
9
+ export declare function planOpenCodeRegistration(plugin: SetupPlugin, generation: OpenCodeGeneration, io?: SetupIO): PlannedWrite[];
10
+ export declare function registerOpenCode(writes: readonly PlannedWrite[], beforeWrite?: () => Promise<void>): Promise<void>;
11
+ export declare function registerPi(plugin: SetupPlugin, executable: string, io?: SetupIO): Promise<void>;
@@ -0,0 +1,130 @@
1
+ import { applyEdits, createScanner, findNodeAtLocation, modify, parse, parseTree, } from 'jsonc-parser';
2
+ import { defaultCommandRunner, runResolvedCommand } from './command-runner.js';
3
+ import { writeHostConfigAtomic } from './config-write.js';
4
+ import { defaultSetupFileSystem } from './detect.js';
5
+ import { setupPaths } from './paths.js';
6
+ function packageOf(value) {
7
+ const entry = typeof value === 'string'
8
+ ? value
9
+ : Array.isArray(value)
10
+ ? value[0]
11
+ : value && typeof value === 'object' && 'package' in value
12
+ ? value.package
13
+ : null;
14
+ if (typeof entry !== 'string')
15
+ return null;
16
+ const at = entry.indexOf('@', entry.startsWith('@') ? 1 : 0);
17
+ return at < 0 ? entry : entry.slice(0, at);
18
+ }
19
+ function removeArrayEntry(text, key, index) {
20
+ const tree = parseTree(text);
21
+ const array = tree && findNodeAtLocation(tree, [key]);
22
+ const nodes = array?.children ?? [];
23
+ const node = nodes[index];
24
+ if (!node || !array)
25
+ throw new Error('Invalid plugin array edit.');
26
+ const edits = [{ offset: node.offset, length: node.length, content: '' }];
27
+ const removeComma = (start, end) => {
28
+ const scanner = createScanner(text.slice(start, end), true);
29
+ scanner.scan();
30
+ if (text[start + scanner.getTokenOffset()] === ',')
31
+ edits.push({
32
+ offset: start + scanner.getTokenOffset(),
33
+ length: 1,
34
+ content: '',
35
+ });
36
+ };
37
+ // Delete punctuation separately so comments beside other entries are not removed.
38
+ if (index === nodes.length - 1) {
39
+ const previous = nodes[index - 1];
40
+ if (previous)
41
+ removeComma(previous.offset + previous.length, node.offset);
42
+ removeComma(node.offset + node.length, array.offset + array.length - 1);
43
+ }
44
+ else
45
+ removeComma(node.offset + node.length, nodes[index + 1]?.offset ?? node.offset + node.length);
46
+ return applyEdits(text, edits);
47
+ }
48
+ /** Edit only array entries so unrelated JSONC text, including comments, survives. */
49
+ export function updatePluginConfig(text, key, pkg, version) {
50
+ const errors = [];
51
+ const value = parse(text, errors, { allowTrailingComma: true });
52
+ if (errors.length ||
53
+ !value ||
54
+ typeof value !== 'object' ||
55
+ Array.isArray(value))
56
+ throw new Error('Invalid OpenCode config; refusing to overwrite it.');
57
+ const options = {
58
+ formattingOptions: {
59
+ insertSpaces: !/^\t+/m.test(text),
60
+ tabSize: /^([ ]+)"/m.exec(text)?.[1]?.length ?? 2,
61
+ eol: text.includes('\r\n') ? '\r\n' : '\n',
62
+ },
63
+ };
64
+ let output = text;
65
+ const array = value[key];
66
+ if (array !== undefined && !Array.isArray(array))
67
+ throw new Error(`OpenCode ${key} must be an array.`);
68
+ const entries = Array.isArray(array) ? [...array] : [];
69
+ const matches = entries.flatMap((entry, index) => packageOf(entry) === pkg ? [index] : []);
70
+ const entry = `${pkg}@${version}`;
71
+ if (!matches.length) {
72
+ output = applyEdits(output, modify(output, array === undefined ? [key] : [key, entries.length], array === undefined ? [entry] : entry, options));
73
+ }
74
+ else {
75
+ const first = matches[0];
76
+ const previous = entries[first];
77
+ // Preserve options in OpenCode's [package, options] and { package, options } entries.
78
+ const replacement = Array.isArray(previous)
79
+ ? [entry, ...previous.slice(1)]
80
+ : previous && typeof previous === 'object'
81
+ ? { ...previous, package: entry }
82
+ : entry;
83
+ if (JSON.stringify(previous) !== JSON.stringify(replacement))
84
+ output = applyEdits(output, modify(output, [key, first], replacement, options));
85
+ for (const index of matches.slice(1).reverse())
86
+ output = removeArrayEntry(output, key, index);
87
+ }
88
+ const other = key === 'plugin' ? 'plugins' : 'plugin';
89
+ if (Array.isArray(value[other])) {
90
+ const otherEntries = value[other];
91
+ for (let index = otherEntries.length - 1; index >= 0; index--) {
92
+ if (packageOf(otherEntries[index]) === pkg)
93
+ output = removeArrayEntry(output, other, index);
94
+ }
95
+ }
96
+ return output;
97
+ }
98
+ export function planOpenCodeRegistration(plugin, generation, io = {}) {
99
+ const fs = io.fs ?? defaultSetupFileSystem;
100
+ const { path, opencode } = setupPaths(io);
101
+ const key = generation === '2' ? 'plugins' : 'plugin';
102
+ const names = generation === '2' ? ['opencode'] : ['opencode', 'tui'];
103
+ return names.map((name) => {
104
+ const jsonc = path.join(opencode, `${name}.jsonc`);
105
+ const json = path.join(opencode, `${name}.json`);
106
+ const file = fs.exists(jsonc) ? jsonc : fs.exists(json) ? json : jsonc;
107
+ const exists = fs.exists(file);
108
+ const before = exists
109
+ ? fs.readText(file)
110
+ : `${JSON.stringify({ $schema: `https://opencode.ai/${name === 'tui' ? 'tui' : 'config'}.json` }, null, 2)}\n`;
111
+ const content = updatePluginConfig(before, key, plugin.packages.opencode, plugin.version);
112
+ return { path: file, content, changed: !exists || content !== before };
113
+ });
114
+ }
115
+ export async function registerOpenCode(writes, beforeWrite) {
116
+ for (const write of writes) {
117
+ if (!write.changed)
118
+ continue;
119
+ await beforeWrite?.();
120
+ await writeHostConfigAtomic(write.path, write.content, {
121
+ beforeRename: beforeWrite,
122
+ });
123
+ }
124
+ }
125
+ export async function registerPi(plugin, executable, io = {}) {
126
+ const { platform, env } = setupPaths(io);
127
+ const result = await runResolvedCommand(io.runner ?? defaultCommandRunner, platform, executable, ['install', `npm:${plugin.packages.pi}@${plugin.version}`], env);
128
+ if (result.exitCode !== 0)
129
+ throw new Error('Pi install failed; run pi install after checking your npm connection.');
130
+ }
@@ -0,0 +1,93 @@
1
+ import type { MenuTerminal } from '../auth-menu/terminal.js';
2
+ import type { ClaustrumEnrollmentConnection, hostEnrollmentPaths } from '../claustrum/index.js';
3
+ export type SetupHost = 'opencode' | 'pi';
4
+ export type OpenCodeGeneration = '1' | '2' | 'both';
5
+ export type SetupEnvironment = Record<string, string | undefined>;
6
+ /** Provider login, credential migration and vault activation stay in plugin callbacks. */
7
+ export interface SetupPlugin {
8
+ packages: {
9
+ opencode: string;
10
+ pi: string;
11
+ };
12
+ version: string;
13
+ displayName: string;
14
+ slashCommand: string;
15
+ vault: {
16
+ connectionFile: string;
17
+ hosts: Record<SetupHost, {
18
+ name: string;
19
+ paths: Parameters<typeof hostEnrollmentPaths>[0];
20
+ }>;
21
+ };
22
+ signInLocal(host: SetupHost): Promise<void>;
23
+ migrate(host: SetupHost): Promise<void>;
24
+ /** Reject mixed local/vault credentials and activate provider-specific vault access before registration. */
25
+ beforeRegister?(host: SetupHost, mode: 'local' | 'claustrum'): Promise<void>;
26
+ }
27
+ export interface CommandResult {
28
+ exitCode: number;
29
+ stdout: string;
30
+ stderr: string;
31
+ signal?: NodeJS.Signals | null;
32
+ timedOut?: boolean;
33
+ durationMs?: number;
34
+ }
35
+ export interface CommandRunner {
36
+ run(file: string, args: readonly string[], options?: {
37
+ env?: SetupEnvironment;
38
+ timeoutMs?: number;
39
+ windowsVerbatimArguments?: boolean;
40
+ }): Promise<CommandResult>;
41
+ }
42
+ export interface SetupFileSystem {
43
+ exists(path: string): boolean;
44
+ isDirectory(path: string): boolean;
45
+ isFile(path: string): boolean;
46
+ isExecutable(path: string): boolean;
47
+ readText(path: string): string;
48
+ realpath(path: string): string;
49
+ }
50
+ export interface ProcessFence {
51
+ listRunningHosts(env?: SetupEnvironment): Promise<Array<{
52
+ pid: number;
53
+ command: string;
54
+ }>>;
55
+ }
56
+ /** Defaults use the process terminal and environment; overrides are test seams. */
57
+ export interface SetupIO {
58
+ terminal?: MenuTerminal;
59
+ env?: SetupEnvironment;
60
+ platform?: string;
61
+ home?: string;
62
+ cwd?: string;
63
+ fs?: SetupFileSystem;
64
+ runner?: CommandRunner;
65
+ fence?: ProcessFence;
66
+ connect?: (options: {
67
+ connectionFile: string;
68
+ handshakeTimeoutMs: number;
69
+ }) => Promise<ClaustrumEnrollmentConnection>;
70
+ wait?: (ms: number) => Promise<void>;
71
+ }
72
+ export interface HostDetection {
73
+ installed: boolean;
74
+ executable: string | null;
75
+ version: string | null;
76
+ directory: string;
77
+ }
78
+ export interface SetupDetection {
79
+ opencode: HostDetection & {
80
+ generation: '1' | '2' | 'ambiguous';
81
+ };
82
+ pi: HostDetection;
83
+ claustrum: {
84
+ available: boolean;
85
+ executable: string | null;
86
+ };
87
+ }
88
+ export interface SetupResult {
89
+ hosts: SetupHost[];
90
+ dryRun: boolean;
91
+ mode: 'local' | 'claustrum';
92
+ detection: SetupDetection;
93
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.15.0",
3
+ "version": "0.16.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": {
@@ -12,6 +12,10 @@
12
12
  "test/fixtures/*"
13
13
  ],
14
14
  "exports": {
15
+ "./setup": {
16
+ "types": "./dist/setup/index.d.ts",
17
+ "import": "./dist/setup/index.js"
18
+ },
15
19
  "./rpc": {
16
20
  "types": "./dist/rpc/index.d.ts",
17
21
  "import": "./dist/rpc/index.js"
@@ -99,6 +103,7 @@
99
103
  "prepublishOnly": "bun run build",
100
104
  "check:ranges": "bun scripts/check-installed-ranges.mjs",
101
105
  "check:claustrum-floor": "bun scripts/check-claustrum-floor.mjs",
106
+ "check:insula-peer": "bun scripts/check-insula-peer.mjs",
102
107
  "check:opentui-0511": "bun scripts/check-opentui-0511.mjs"
103
108
  },
104
109
  "dependencies": {
@@ -110,6 +115,7 @@
110
115
  "@opentui/solid": ">=0.5.11",
111
116
  "solid-js": "1.9.12",
112
117
  "@cortexkit/claustrum-client": ">=0.6.2",
118
+ "@cortexkit/subc-client": "^0.16.0",
113
119
  "@opencode/plugin": ">=2.0.21"
114
120
  },
115
121
  "peerDependenciesMeta": {
@@ -125,6 +131,9 @@
125
131
  "@cortexkit/claustrum-client": {
126
132
  "optional": true
127
133
  },
134
+ "@cortexkit/subc-client": {
135
+ "optional": true
136
+ },
128
137
  "@opencode/plugin": {
129
138
  "optional": true
130
139
  }
@@ -132,6 +141,7 @@
132
141
  "devDependencies": {
133
142
  "@biomejs/biome": "2.5.14",
134
143
  "@cortexkit/claustrum-client": "0.9.0",
144
+ "@cortexkit/subc-client": "0.16.1",
135
145
  "@earendil-works/pi-coding-agent": "1.0.4",
136
146
  "@opencode/plugin": "2.0.21",
137
147
  "@opentui/core": ">=0.5.12",