Repository navigation
Expand file tree
/
Copy pathstore.ts
More file actions
206 lines (194 loc) · 7.39 KB
/
Copy pathstore.ts
File metadata and controls
206 lines (194 loc) · 7.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { AppError, normalizeError } from '@agent-device/kernel/errors';
import { isRecord } from '@agent-device/kernel/record';
import { runCmd } from '@agent-device/host-kit/command';
import { acquireProcessLock, publishFileSync } from '@agent-device/host-kit/file';
import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process';
import { resolveUserConfigPath } from '../commands/schema/cli-config.ts';
import {
readPluginManifest,
assertUniquePluginProviders,
type PluginManifest,
} from './manifest.ts';
export type PluginSelection = {
installation: string;
version?: string;
options?: Record<string, unknown>;
};
type PluginConfig = Record<string, unknown> & { plugins?: Record<string, PluginSelection> };
export type InstalledPlugin = PluginManifest & { directory: string; selection: PluginSelection };
export function readPluginConfig(env: NodeJS.ProcessEnv): PluginConfig {
const configPath = resolveUserConfigPath(env);
let raw: string;
try {
raw = fs.readFileSync(configPath, 'utf8');
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {};
throw error;
}
let config: PluginConfig;
try {
config = JSON.parse(raw) as PluginConfig;
} catch (error) {
throw new AppError(
'INVALID_ARGS',
`Invalid JSON in config file: ${configPath}`,
{},
error instanceof Error ? error : undefined,
);
}
if (!isRecord(config) || (config.plugins !== undefined && !isRecord(config.plugins))) {
throw new AppError('INVALID_ARGS', 'Plugin config must contain an object');
}
return config;
}
function validatePluginSelection(name: string, selection: PluginSelection): void {
if (
!isPackageName(name) ||
!isRecord(selection) ||
typeof selection.installation !== 'string' ||
!/^[a-f0-9-]{36}$/.test(selection.installation) ||
(selection.version !== undefined && !isVersionSelector(selection.version)) ||
(selection.options !== undefined && !isRecord(selection.options))
) {
throw new AppError('INVALID_ARGS', `Invalid plugin selection: ${name}`);
}
}
export function installedPlugins(env: NodeJS.ProcessEnv): InstalledPlugin[] {
const home = path.dirname(resolveUserConfigPath(env));
return Object.entries(readPluginConfig(env).plugins ?? {}).map(([name, selection]) =>
readInstallation(home, name, selection),
);
}
function readInstallation(home: string, name: string, selection: PluginSelection): InstalledPlugin {
validatePluginSelection(name, selection);
const directory = path.join(home, 'plugins', selection.installation, 'node_modules', name);
const manifest = readPluginManifest(directory);
if (manifest.name !== name)
throw new AppError('INVALID_ARGS', `Plugin package identity mismatch: ${name}`);
return { ...manifest, directory, selection };
}
export function listPlugins(env: NodeJS.ProcessEnv) {
const home = path.dirname(resolveUserConfigPath(env));
return Object.entries(readPluginConfig(env).plugins ?? {}).map(([name, selection]) => {
try {
const manifest = readInstallation(home, name, selection);
return {
name,
version: manifest.version,
provider: manifest.agentDevicePlugin.provider,
compatible: true,
};
} catch (error) {
return { name, compatible: false, error: normalizeError(error) };
}
});
}
type PluginAction = 'add' | 'update' | 'remove';
function parsePluginRequest(action: PluginAction, input: string) {
if (action === 'remove') return { name: input, version: undefined };
const match =
/^(@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)(?:@(.+))?$/.exec(input);
if (!match || !match[1] || (match[2] !== undefined && !isVersionSelector(match[2]))) {
throw new AppError(
'INVALID_ARGS',
'Expected an npm package name, optionally followed by @version or @tag',
);
}
if (action === 'update' && match[2] !== undefined)
throw new AppError('INVALID_ARGS', 'update accepts a package name without a version');
return { name: match[1], version: match[2] };
}
async function stagePlugin(
home: string,
name: string,
version: string | undefined,
env: NodeJS.ProcessEnv,
) {
const installation = crypto.randomUUID();
const project = path.join(home, 'plugins', installation);
fs.mkdirSync(project, { recursive: true, mode: 0o700 });
try {
fs.writeFileSync(
path.join(project, 'package.json'),
JSON.stringify({ private: true, dependencies: { [name]: version ?? 'latest' } }),
);
await runCmd(
'npm',
[
'install',
'--ignore-scripts',
'--no-audit',
'--no-fund',
'--global=false',
'--prefix',
project,
'--workspaces=false',
'--package-lock=true',
],
{ cwd: project, env, timeoutMs: 120_000 },
);
const manifest = readPluginManifest(path.join(project, 'node_modules', name));
if (manifest.name !== name)
throw new AppError('INVALID_ARGS', `Plugin package identity mismatch: ${name}`);
return { installation, project, manifest };
} catch (error) {
fs.rmSync(project, { recursive: true, force: true });
throw error;
}
}
export async function changePlugin(
action: PluginAction,
input: string,
env: NodeJS.ProcessEnv = process.env,
reservedProviders: readonly string[] = [],
): Promise<void> {
const { name, version } = parsePluginRequest(action, input);
const configPath = resolveUserConfigPath(env);
const home = path.dirname(configPath);
fs.mkdirSync(home, { recursive: true, mode: 0o700 });
const release = await acquireProcessLock({
lockDirPath: path.join(home, 'plugins.lock'),
owner: { ...readCurrentOwnerIdentity(), acquiredAtMs: Date.now() },
description: 'plugin installation',
});
let staged: Awaited<ReturnType<typeof stagePlugin>> | undefined;
try {
const config = readPluginConfig(env);
const selections = { ...config.plugins };
const previous = Object.hasOwn(selections, name) ? selections[name] : undefined;
if (previous && action !== 'remove') validatePluginSelection(name, previous);
if (action !== 'add' && !Object.hasOwn(selections, name))
throw new AppError('INVALID_ARGS', `Plugin is not installed: ${name}`);
if (action === 'remove') delete selections[name];
else {
const requested = action === 'update' ? previous?.version : version;
staged = await stagePlugin(home, name, requested, env);
const siblings = Object.entries(selections)
.filter(([other]) => other !== name)
.map(([other, selection]) => readInstallation(home, other, selection));
assertUniquePluginProviders([...siblings, staged.manifest], reservedProviders);
selections[name] = { ...previous, installation: staged.installation, version: requested };
}
publishFileSync({
destination: configPath,
contents: `${JSON.stringify({ ...config, plugins: selections }, null, 2)}\n`,
mode: 0o600,
});
} catch (error) {
if (staged) fs.rmSync(staged.project, { recursive: true, force: true });
throw error;
} finally {
await release();
}
}
function isPackageName(value: string): boolean {
return /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(value);
}
function isVersionSelector(value: unknown): value is string {
return (
typeof value === 'string' && /^[a-zA-Z0-9*^~<>=| .+-]+$/.test(value) && value.trim().length > 0
);
}