@cortexkit/common-auth 0.14.2 → 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.
- package/README.md +4 -4
- package/dist/claustrum/consumer.d.ts +33 -3
- package/dist/claustrum/consumer.js +96 -1
- package/dist/claustrum/custody.d.ts +4 -1
- package/dist/claustrum/enrollment.d.ts +3 -2
- package/dist/claustrum/enrollment.js +84 -42
- package/dist/claustrum/index.d.ts +2 -1
- package/dist/claustrum/index.js +5 -3
- package/dist/claustrum/insula.d.ts +69 -0
- package/dist/claustrum/insula.js +152 -0
- package/dist/claustrum/roster.d.ts +13 -0
- package/dist/claustrum/roster.js +28 -2
- package/dist/dump/index.d.ts +4 -3
- package/dist/dump/index.js +39 -12
- package/dist/fs/atomic-write.d.ts +5 -0
- package/dist/fs/atomic-write.js +21 -0
- package/dist/fs/index.d.ts +2 -0
- package/dist/fs/index.js +1 -0
- package/dist/fs/private-files.d.ts +66 -0
- package/dist/fs/private-files.js +302 -0
- package/dist/fs/refresh-file-lock.d.ts +1 -1
- package/dist/fs/refresh-file-lock.js +254 -37
- package/dist/fs/with-lock.d.ts +3 -0
- package/dist/fs/with-lock.js +4 -0
- package/dist/logger/engine.d.ts +6 -8
- package/dist/logger/engine.js +126 -11
- package/dist/pi-slot/slot.d.ts +2 -0
- package/dist/pi-slot/slot.js +34 -6
- package/dist/rpc/port-file.js +30 -8
- package/dist/rpc/rpc-client.js +15 -1
- package/dist/rpc/rpc-server.js +8 -3
- package/dist/setup/command-runner.d.ts +4 -0
- package/dist/setup/command-runner.js +49 -0
- package/dist/setup/command.d.ts +3 -0
- package/dist/setup/command.js +188 -0
- package/dist/setup/config-write.d.ts +11 -0
- package/dist/setup/config-write.js +60 -0
- package/dist/setup/detect.d.ts +6 -0
- package/dist/setup/detect.js +224 -0
- package/dist/setup/enroll.d.ts +4 -0
- package/dist/setup/enroll.js +70 -0
- package/dist/setup/index.d.ts +5 -0
- package/dist/setup/index.js +4 -0
- package/dist/setup/paths.d.ts +11 -0
- package/dist/setup/paths.js +33 -0
- package/dist/setup/process-fence.d.ts +41 -0
- package/dist/setup/process-fence.js +177 -0
- package/dist/setup/prompts.d.ts +4 -0
- package/dist/setup/prompts.js +26 -0
- package/dist/setup/register.d.ts +11 -0
- package/dist/setup/register.js +130 -0
- package/dist/setup/types.d.ts +93 -0
- package/dist/setup/types.js +1 -0
- package/dist/sidebar-file/sidebar-file.d.ts +5 -4
- package/dist/sidebar-file/sidebar-file.js +17 -8
- package/dist/store/mutate.js +2 -2
- package/dist/store/pool.d.ts +1 -0
- package/dist/store/pool.js +3 -0
- package/dist/store/refresh-lock.d.ts +4 -0
- package/dist/store/refresh-lock.js +5 -0
- package/dist/tui-prefs/tui-preferences.js +6 -4
- package/dist/tui-prefs/watcher.d.ts +3 -0
- package/dist/tui-prefs/watcher.js +26 -10
- package/package.json +14 -3
|
@@ -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 {};
|
|
@@ -53,10 +53,11 @@ export interface SidebarFileOptions<T> {
|
|
|
53
53
|
normalize: (parsed: unknown) => T;
|
|
54
54
|
timeoutMs?: number;
|
|
55
55
|
/**
|
|
56
|
-
*
|
|
57
|
-
* to true. Pass false for a directory the user chose (an override
|
|
58
|
-
* whose permissions are theirs to set. A parent this library has to
|
|
59
|
-
* is always created private, either way.
|
|
56
|
+
* POSIX: tighten an existing parent directory to 0o700 before each write.
|
|
57
|
+
* Defaults to true. Pass false for a directory the user chose (an override
|
|
58
|
+
* path), whose permissions are theirs to set. A parent this library has to
|
|
59
|
+
* create is always created private, either way. Windows checks safe ancestry
|
|
60
|
+
* without tightening existing parents, regardless of this option.
|
|
60
61
|
*/
|
|
61
62
|
secureDir?: boolean;
|
|
62
63
|
logger?: {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { chmod, mkdir
|
|
1
|
+
import { chmod, mkdir } from 'node:fs/promises';
|
|
2
2
|
import { dirname } from 'node:path';
|
|
3
3
|
import { LockContentionError, LockOwnershipError, WRITER_LOCK_CONSTANTS, withLock, writeJsonAtomic, } from '../fs/index.js';
|
|
4
|
+
import { ensurePrivateDirectory, PrivateFileError, readPrivateText, windowsPrivateFiles, } from '../fs/private-files.js';
|
|
4
5
|
/** Binds generic persistence to a caller's path and normalization policy. */
|
|
5
6
|
export function createSidebarFile(options) {
|
|
6
7
|
const { path, defaultValue, normalize } = options;
|
|
@@ -17,7 +18,9 @@ export function createSidebarFile(options) {
|
|
|
17
18
|
};
|
|
18
19
|
const readRaw = async () => {
|
|
19
20
|
try {
|
|
20
|
-
|
|
21
|
+
if (windowsPrivateFiles)
|
|
22
|
+
await ensurePrivateDirectory(dirname(path), options.secureDir ?? true);
|
|
23
|
+
return await readPrivateText(path, windowsPrivateFiles);
|
|
21
24
|
}
|
|
22
25
|
catch (error) {
|
|
23
26
|
if (error.code === 'ENOENT')
|
|
@@ -29,7 +32,9 @@ export function createSidebarFile(options) {
|
|
|
29
32
|
try {
|
|
30
33
|
return parse(await readRaw());
|
|
31
34
|
}
|
|
32
|
-
catch {
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error instanceof PrivateFileError)
|
|
37
|
+
throw error;
|
|
33
38
|
return defaultValue;
|
|
34
39
|
}
|
|
35
40
|
};
|
|
@@ -109,11 +114,15 @@ export function createSidebarFile(options) {
|
|
|
109
114
|
const hooks = writeOptions;
|
|
110
115
|
const parent = dirname(path);
|
|
111
116
|
const secureDir = options.secureDir ?? true;
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
+
if (windowsPrivateFiles)
|
|
118
|
+
await ensurePrivateDirectory(parent, secureDir);
|
|
119
|
+
else {
|
|
120
|
+
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
121
|
+
if (secureDir) {
|
|
122
|
+
await chmod(parent, 0o700).catch((error) => {
|
|
123
|
+
options.logger?.warn('sidebar directory permission remediation failed', { error: error instanceof Error ? error.message : String(error) });
|
|
124
|
+
});
|
|
125
|
+
}
|
|
117
126
|
}
|
|
118
127
|
const committed = await withLock(path, lockOptions, async (lock) => {
|
|
119
128
|
const commit = async (value) => ({
|
package/dist/store/mutate.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { readFile } from 'node:fs/promises';
|
|
2
1
|
import { setTimeout as snapshotDelay } from 'node:timers/promises';
|
|
3
2
|
import { AtomicSyncError, syncJsonFile, writeJsonAtomic, writeJsonAtomicTracked, } from '../fs/atomic-write.js';
|
|
3
|
+
import { readPrivateText, windowsPrivateFiles } from '../fs/private-files.js';
|
|
4
4
|
import { LockContentionError, LockOwnershipError } from '../fs/with-lock.js';
|
|
5
5
|
import { PoolOperationError, } from './errors.js';
|
|
6
6
|
import { callFailureHook } from './hooks.js';
|
|
@@ -10,7 +10,7 @@ import { CREDENTIAL_STAMP_KEY, classifyConfig, classifyState, ensureEntries, ent
|
|
|
10
10
|
import { completeTornRows, loadRows } from './torn.js';
|
|
11
11
|
async function readText(path) {
|
|
12
12
|
try {
|
|
13
|
-
return await
|
|
13
|
+
return await readPrivateText(path, windowsPrivateFiles);
|
|
14
14
|
}
|
|
15
15
|
catch (error) {
|
|
16
16
|
if (error.code === 'ENOENT')
|
package/dist/store/pool.d.ts
CHANGED
|
@@ -66,6 +66,7 @@ export interface OpenPoolStoreOptions {
|
|
|
66
66
|
hold?: (point: HoldPoint, rowId: string) => void | Promise<void>;
|
|
67
67
|
onLockEvent?: LockEnvironment['onLockEvent'];
|
|
68
68
|
onLockStep?: LockEnvironment['onLockStep'];
|
|
69
|
+
onRenewalTimer?: LockEnvironment['onRenewalTimer'];
|
|
69
70
|
}
|
|
70
71
|
export type PoolLoad = {
|
|
71
72
|
status: 'ready';
|
package/dist/store/pool.js
CHANGED
|
@@ -60,6 +60,9 @@ export function openPoolStore(options) {
|
|
|
60
60
|
now: options.now ?? Date.now,
|
|
61
61
|
...(options.onLockEvent ? { onLockEvent: options.onLockEvent } : {}),
|
|
62
62
|
...(options.onLockStep ? { onLockStep: options.onLockStep } : {}),
|
|
63
|
+
...(options.onRenewalTimer
|
|
64
|
+
? { onRenewalTimer: options.onRenewalTimer }
|
|
65
|
+
: {}),
|
|
63
66
|
},
|
|
64
67
|
removedIds: memory.removedIds,
|
|
65
68
|
requireCredentialStamps: options.requireCredentialStamps === true,
|
|
@@ -30,6 +30,10 @@ export interface LockEnvironment {
|
|
|
30
30
|
name: string;
|
|
31
31
|
path: string;
|
|
32
32
|
}, step: LockStep) => void | Promise<void>;
|
|
33
|
+
onRenewalTimer?: (lock: {
|
|
34
|
+
name: string;
|
|
35
|
+
path: string;
|
|
36
|
+
}, event: 'scheduled' | 'cancelled') => void;
|
|
33
37
|
}
|
|
34
38
|
export interface HeldLock {
|
|
35
39
|
readonly name: string;
|
|
@@ -45,6 +45,11 @@ export async function acquirePoolLock(spec, defaults, env) {
|
|
|
45
45
|
now: env.now,
|
|
46
46
|
renew: options.renew,
|
|
47
47
|
onContended: () => emit('contended'),
|
|
48
|
+
...(env.onRenewalTimer
|
|
49
|
+
? {
|
|
50
|
+
onRenewalTimer: (event) => env.onRenewalTimer?.({ name: spec.name, path: spec.path }, event),
|
|
51
|
+
}
|
|
52
|
+
: {}),
|
|
48
53
|
...(options.renewIntervalMs !== undefined
|
|
49
54
|
? { renewIntervalMs: options.renewIntervalMs }
|
|
50
55
|
: {}),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { readFile } from 'node:fs/promises';
|
|
2
1
|
import { applyEdits, modify, parse } from 'jsonc-parser';
|
|
3
2
|
import { writeJsonAtomic } from '../fs/atomic-write.js';
|
|
4
3
|
import { WRITER_LOCK_CONSTANTS } from '../fs/lock-constants.js';
|
|
4
|
+
import { PrivateFileError, readPrivateText, windowsPrivateFiles, } from '../fs/private-files.js';
|
|
5
5
|
import { withLock } from '../fs/with-lock.js';
|
|
6
6
|
function isRecord(value) {
|
|
7
7
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
@@ -10,12 +10,14 @@ function isRecord(value) {
|
|
|
10
10
|
export async function readTuiPreferencesFile(file) {
|
|
11
11
|
try {
|
|
12
12
|
const errors = [];
|
|
13
|
-
const root = parse(await
|
|
13
|
+
const root = parse(await readPrivateText(file, windowsPrivateFiles), errors, {
|
|
14
14
|
allowTrailingComma: true,
|
|
15
15
|
});
|
|
16
16
|
return errors.length === 0 && isRecord(root) ? root : {};
|
|
17
17
|
}
|
|
18
|
-
catch {
|
|
18
|
+
catch (error) {
|
|
19
|
+
if (error instanceof PrivateFileError && error.code !== 'ENOENT')
|
|
20
|
+
throw error;
|
|
19
21
|
return {};
|
|
20
22
|
}
|
|
21
23
|
}
|
|
@@ -42,7 +44,7 @@ export function createTuiPreferenceWriter(options) {
|
|
|
42
44
|
await withLock(file, lockOptions, async (lock) => {
|
|
43
45
|
let text;
|
|
44
46
|
try {
|
|
45
|
-
text = await
|
|
47
|
+
text = await readPrivateText(file, windowsPrivateFiles);
|
|
46
48
|
}
|
|
47
49
|
catch (error) {
|
|
48
50
|
if (error.code !== 'ENOENT')
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { type Stats, watch } from 'node:fs';
|
|
2
|
+
import { PrivateFileError } from '../fs/private-files.js';
|
|
2
3
|
type Metadata = Pick<Stats, 'mtimeMs' | 'size' | 'ino' | 'dev'>;
|
|
3
4
|
export interface TuiPreferencesWatchOptions {
|
|
5
|
+
/** Receives PrivateFileError instances for Windows access failures, never file contents. */
|
|
6
|
+
onError?: (error: PrivateFileError) => void;
|
|
4
7
|
watchDirectory?: typeof watch;
|
|
5
8
|
/** Internal filesystem seam; the first subscriber supplies a shared watcher's I/O. */
|
|
6
9
|
fs?: {
|