@volcengine/tls-observer-cursor-install 0.0.4
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/CHANGELOG.md +31 -0
- package/README.md +91 -0
- package/bin/tls-observer-cursor-install.mjs +9 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +779 -0
- package/dist/installer/installer-runner.d.ts +2 -0
- package/package.json +40 -0
- package/scripts/sync-plugin.mjs +31 -0
- package/src/index.ts +1 -0
- package/src/installer/installer-runner.ts +942 -0
|
@@ -0,0 +1,942 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { execFile, execFileSync, spawn } from 'node:child_process';
|
|
4
|
+
import { homedir, tmpdir } from 'node:os';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import readline from 'node:readline/promises';
|
|
8
|
+
import { randomInt } from 'node:crypto';
|
|
9
|
+
|
|
10
|
+
type AnyRecord = Record<string, any>;
|
|
11
|
+
|
|
12
|
+
type TlsServiceClient = {
|
|
13
|
+
isAkSk: boolean;
|
|
14
|
+
DescribeProjects: (payload: AnyRecord) => Promise<AnyRecord>;
|
|
15
|
+
CreateProject: (payload: AnyRecord) => Promise<AnyRecord>;
|
|
16
|
+
DescribeApps: (payload: AnyRecord) => Promise<AnyRecord>;
|
|
17
|
+
CreateApp: (payload: AnyRecord) => Promise<AnyRecord>;
|
|
18
|
+
DescribeLogApps: (payload: AnyRecord) => Promise<AnyRecord>;
|
|
19
|
+
DescribeTemplates: (payload: AnyRecord) => Promise<AnyRecord>;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
type OpenapiModule = {
|
|
23
|
+
tlsOpenapi?: {
|
|
24
|
+
TlsService?: new (options: AnyRecord) => AnyRecord;
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
type InstallOptions = {
|
|
29
|
+
help: boolean;
|
|
30
|
+
nonInteractive: boolean;
|
|
31
|
+
force: boolean;
|
|
32
|
+
beta: boolean;
|
|
33
|
+
skipTlsConfig: boolean;
|
|
34
|
+
advancedPaths: boolean;
|
|
35
|
+
registry: string;
|
|
36
|
+
pluginPackage: string;
|
|
37
|
+
pluginVersion?: string;
|
|
38
|
+
hooksPath: string;
|
|
39
|
+
pluginTarget: string;
|
|
40
|
+
envTarget: string;
|
|
41
|
+
dataRoot: string;
|
|
42
|
+
region?: string;
|
|
43
|
+
otelEndpoint?: string;
|
|
44
|
+
traceTopicId?: string;
|
|
45
|
+
apiKey?: string;
|
|
46
|
+
ak?: string;
|
|
47
|
+
sk?: string;
|
|
48
|
+
authMode: string;
|
|
49
|
+
exportTimeoutMs: string;
|
|
50
|
+
exportTimeoutRetries: string;
|
|
51
|
+
captureContent: string;
|
|
52
|
+
tlsEndpoint?: string;
|
|
53
|
+
projectId?: string;
|
|
54
|
+
projectName?: string;
|
|
55
|
+
logAppId?: string;
|
|
56
|
+
logAppName?: string;
|
|
57
|
+
logAppType: string;
|
|
58
|
+
templateName: string;
|
|
59
|
+
templateId?: string;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
type PluginInstallResult = {
|
|
63
|
+
source: string;
|
|
64
|
+
target: string;
|
|
65
|
+
packageSpec?: string;
|
|
66
|
+
version?: string;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const execFileAsync = promisify(execFile);
|
|
70
|
+
const PLUGIN_NAME = 'tls-observer-cursor';
|
|
71
|
+
const PLUGIN_PACKAGE_NAME = '@volcengine/tls-observer-cursor';
|
|
72
|
+
const DEFAULT_REGISTRY = 'https://registry.npmjs.org';
|
|
73
|
+
const DEFAULT_HOOKS_PATH = path.join(homedir(), '.cursor', 'hooks.json');
|
|
74
|
+
const DEFAULT_INSTALL_ROOT = path.join(homedir(), '.cursor', PLUGIN_NAME);
|
|
75
|
+
const DEFAULT_ENV_TARGET = path.join(homedir(), '.cursor', 'tls-observer-cursor.env');
|
|
76
|
+
const DEFAULT_PLUGIN_TARGET = path.join(DEFAULT_INSTALL_ROOT, 'plugin');
|
|
77
|
+
const DEFAULT_DATA_ROOT = path.join(homedir(), '.cursor', 'plugins', 'data', 'tls-observer-cursor');
|
|
78
|
+
const DEFAULT_REGION = 'cn-beijing';
|
|
79
|
+
const DEFAULT_PROJECT_NAME = 'cursor_observability';
|
|
80
|
+
const DEFAULT_APP_NAME_PREFIX = 'cursor-observability';
|
|
81
|
+
const DEFAULT_TLS_ENDPOINT = 'tls-cn-beijing.volces.com';
|
|
82
|
+
const DEFAULT_LOG_APP_TYPE = 'Cursor';
|
|
83
|
+
const DEFAULT_TEMPLATE_NAME = 'Cursor';
|
|
84
|
+
const CURSOR_HOOK_EVENTS = [
|
|
85
|
+
['beforeSubmitPrompt', 30],
|
|
86
|
+
['stop', 120],
|
|
87
|
+
['sessionEnd', 30],
|
|
88
|
+
] as const;
|
|
89
|
+
|
|
90
|
+
type CursorHooksFile = AnyRecord & {
|
|
91
|
+
version?: number;
|
|
92
|
+
hooks?: Record<string, unknown>;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
type HookEventConfig = {
|
|
96
|
+
eventName: string;
|
|
97
|
+
timeout: number;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
function readEnvString(key: string): string | undefined {
|
|
101
|
+
const value = process.env[key];
|
|
102
|
+
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function readEnvBool(key: string): boolean {
|
|
106
|
+
const value = readEnvString(key);
|
|
107
|
+
return value ? /^(1|true|yes|y|on)$/i.test(value) : false;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function takeArg(argv: string[], index: number, flag: string): string {
|
|
111
|
+
const value = argv[index + 1];
|
|
112
|
+
if (typeof value !== 'string' || value.startsWith('--')) {
|
|
113
|
+
throw new Error(`${flag} requires a value`);
|
|
114
|
+
}
|
|
115
|
+
return value;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function defaultTlsEndpointForRegion(region?: string): string {
|
|
119
|
+
return region ? `tls-${region}.volces.com` : DEFAULT_TLS_ENDPOINT;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function randomSuffix(): string {
|
|
123
|
+
const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';
|
|
124
|
+
let value = '';
|
|
125
|
+
for (let index = 0; index < 8; index += 1) value += alphabet[randomInt(alphabet.length)];
|
|
126
|
+
return value;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function defaultAppName(): string {
|
|
130
|
+
return `${DEFAULT_APP_NAME_PREFIX}_${randomSuffix()}`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function applyDerivedDefaults(options: InstallOptions): void {
|
|
134
|
+
if (options.region) {
|
|
135
|
+
if (!options.tlsEndpoint && !options.otelEndpoint) {
|
|
136
|
+
options.tlsEndpoint = defaultTlsEndpointForRegion(options.region);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (!options.projectName && !options.projectId) options.projectName = DEFAULT_PROJECT_NAME;
|
|
140
|
+
if (!options.logAppName) options.logAppName = defaultAppName();
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function parseCliOptions(argv: string[] = process.argv.slice(2)): InstallOptions {
|
|
144
|
+
const options = {
|
|
145
|
+
help: false,
|
|
146
|
+
nonInteractive: readEnvBool('CURSOR_TLS_INSTALL_NON_INTERACTIVE'),
|
|
147
|
+
force: readEnvBool('CURSOR_TLS_INSTALL_FORCE'),
|
|
148
|
+
beta: readEnvBool('CURSOR_TLS_INSTALL_BETA'),
|
|
149
|
+
skipTlsConfig: readEnvBool('CURSOR_TLS_INSTALL_SKIP_TLS_CONFIG'),
|
|
150
|
+
advancedPaths: readEnvBool('CURSOR_TLS_INSTALL_ADVANCED_PATHS'),
|
|
151
|
+
registry:
|
|
152
|
+
readEnvString('CURSOR_TLS_NPM_REGISTRY') ||
|
|
153
|
+
readEnvString('npm_config_registry') ||
|
|
154
|
+
readEnvString('NPM_CONFIG_REGISTRY') ||
|
|
155
|
+
DEFAULT_REGISTRY,
|
|
156
|
+
pluginPackage: readEnvString('CURSOR_TLS_PLUGIN_PACKAGE') || PLUGIN_PACKAGE_NAME,
|
|
157
|
+
pluginVersion: readEnvString('CURSOR_TLS_PLUGIN_VERSION'),
|
|
158
|
+
hooksPath: readEnvString('CURSOR_HOOKS_PATH') || DEFAULT_HOOKS_PATH,
|
|
159
|
+
pluginTarget:
|
|
160
|
+
readEnvString('CURSOR_TLS_PLUGIN_TARGET') ||
|
|
161
|
+
readEnvString('CURSOR_PLUGIN_TARGET') ||
|
|
162
|
+
DEFAULT_PLUGIN_TARGET,
|
|
163
|
+
envTarget: readEnvString('CURSOR_TLS_ENV_TARGET') || DEFAULT_ENV_TARGET,
|
|
164
|
+
dataRoot: readEnvString('CURSOR_TLS_DATA_ROOT') || DEFAULT_DATA_ROOT,
|
|
165
|
+
region: readEnvString('CURSOR_TLS_REGION') || DEFAULT_REGION,
|
|
166
|
+
otelEndpoint: readEnvString('CURSOR_TLS_OTEL_ENDPOINT'),
|
|
167
|
+
traceTopicId: readEnvString('CURSOR_TLS_TRACE_TOPIC_ID'),
|
|
168
|
+
apiKey: readEnvString('CURSOR_TLS_API_KEY'),
|
|
169
|
+
ak: readEnvString('CURSOR_TLS_AK'),
|
|
170
|
+
sk: readEnvString('CURSOR_TLS_SK'),
|
|
171
|
+
authMode: readEnvString('CURSOR_TLS_AUTH_MODE') || 'header',
|
|
172
|
+
exportTimeoutMs: readEnvString('CURSOR_TLS_EXPORT_TIMEOUT_MS') || '20000',
|
|
173
|
+
exportTimeoutRetries: readEnvString('CURSOR_TLS_EXPORT_TIMEOUT_RETRIES') || '1',
|
|
174
|
+
captureContent: readEnvString('CURSOR_TLS_CAPTURE_CONTENT') || '1',
|
|
175
|
+
tlsEndpoint: readEnvString('CURSOR_TLS_ENDPOINT'),
|
|
176
|
+
projectId: readEnvString('CURSOR_TLS_PROJECT_ID'),
|
|
177
|
+
projectName: readEnvString('CURSOR_TLS_PROJECT_NAME'),
|
|
178
|
+
logAppId: readEnvString('CURSOR_TLS_LOG_APP_ID'),
|
|
179
|
+
logAppName: readEnvString('CURSOR_TLS_LOG_APP_NAME'),
|
|
180
|
+
logAppType: readEnvString('CURSOR_TLS_LOG_APP_TYPE') || DEFAULT_LOG_APP_TYPE,
|
|
181
|
+
templateName: readEnvString('CURSOR_TLS_TEMPLATE_NAME') || DEFAULT_TEMPLATE_NAME,
|
|
182
|
+
templateId: readEnvString('CURSOR_TLS_TEMPLATE_ID'),
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
186
|
+
const current = argv[index];
|
|
187
|
+
if (current === '--help' || current === '-h') options.help = true;
|
|
188
|
+
else if (current === '--non-interactive') options.nonInteractive = true;
|
|
189
|
+
else if (current === '--force') options.force = true;
|
|
190
|
+
else if (current === '--beta') options.beta = true;
|
|
191
|
+
else if (current === '--skip-tls-config') options.skipTlsConfig = true;
|
|
192
|
+
else if (current === '--advanced-paths') options.advancedPaths = true;
|
|
193
|
+
else if (current === '--registry') options.registry = takeArg(argv, index++, current);
|
|
194
|
+
else if (current === '--plugin-package') options.pluginPackage = takeArg(argv, index++, current);
|
|
195
|
+
else if (current === '--plugin-version') options.pluginVersion = takeArg(argv, index++, current);
|
|
196
|
+
else if (current === '--hooks-path') options.hooksPath = takeArg(argv, index++, current);
|
|
197
|
+
else if (current === '--plugin-target') options.pluginTarget = takeArg(argv, index++, current);
|
|
198
|
+
else if (current === '--env-target') options.envTarget = takeArg(argv, index++, current);
|
|
199
|
+
else if (current === '--data-root') options.dataRoot = takeArg(argv, index++, current);
|
|
200
|
+
else if (current === '--region') options.region = takeArg(argv, index++, current);
|
|
201
|
+
else if (current === '--otel-endpoint') options.otelEndpoint = takeArg(argv, index++, current);
|
|
202
|
+
else if (current === '--trace-topic-id') options.traceTopicId = takeArg(argv, index++, current);
|
|
203
|
+
else if (current === '--api-key') options.apiKey = takeArg(argv, index++, current);
|
|
204
|
+
else if (current === '--ak') options.ak = takeArg(argv, index++, current);
|
|
205
|
+
else if (current === '--sk') options.sk = takeArg(argv, index++, current);
|
|
206
|
+
else if (current === '--auth-mode') options.authMode = takeArg(argv, index++, current);
|
|
207
|
+
else if (current === '--export-timeout-ms') options.exportTimeoutMs = takeArg(argv, index++, current);
|
|
208
|
+
else if (current === '--export-timeout-retries')
|
|
209
|
+
options.exportTimeoutRetries = takeArg(argv, index++, current);
|
|
210
|
+
else if (current === '--capture-content') options.captureContent = takeArg(argv, index++, current);
|
|
211
|
+
else if (current === '--tls-endpoint') options.tlsEndpoint = takeArg(argv, index++, current);
|
|
212
|
+
else if (current === '--project-id') options.projectId = takeArg(argv, index++, current);
|
|
213
|
+
else if (current === '--project-name') options.projectName = takeArg(argv, index++, current);
|
|
214
|
+
else if (current === '--app-name' || current === '--log-app-name')
|
|
215
|
+
options.logAppName = takeArg(argv, index++, current);
|
|
216
|
+
else if (current === '--log-app-id') options.logAppId = takeArg(argv, index++, current);
|
|
217
|
+
else if (current === '--log-app-type') options.logAppType = takeArg(argv, index++, current);
|
|
218
|
+
else if (current === '--template-name') options.templateName = takeArg(argv, index++, current);
|
|
219
|
+
else if (current === '--template-id') options.templateId = takeArg(argv, index++, current);
|
|
220
|
+
else throw new Error(`Unknown option: ${current}`);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return options;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function printHelp(): void {
|
|
227
|
+
console.log(`TLS Observer Cursor installer
|
|
228
|
+
|
|
229
|
+
Usage:
|
|
230
|
+
tls-observer-cursor-install [options]
|
|
231
|
+
npm exec -y --package=@volcengine/tls-observer-cursor-install -- tls-observer-cursor-install [options]
|
|
232
|
+
|
|
233
|
+
Options:
|
|
234
|
+
--non-interactive Read required inputs from flags/env
|
|
235
|
+
--force Overwrite existing plugin/env files
|
|
236
|
+
--beta Install @volcengine/tls-observer-cursor@beta instead of @latest
|
|
237
|
+
--skip-tls-config Install plugin without writing TLS env
|
|
238
|
+
--advanced-paths Prompt for Cursor path overrides
|
|
239
|
+
--registry <url> NPM registry for plugin package. Default: https://registry.npmjs.org
|
|
240
|
+
--plugin-version <version> Exact plugin version or dist-tag. Overrides --beta
|
|
241
|
+
--region <region> TLS region. Default: cn-beijing
|
|
242
|
+
--tls-endpoint <host> TLS Producer endpoint. Derived from region by default
|
|
243
|
+
--otel-endpoint <url> Deprecated legacy endpoint alias
|
|
244
|
+
--trace-topic-id <id> TLS trace topic ID
|
|
245
|
+
--api-key <value> TLS API Key
|
|
246
|
+
--ak <value> TLS Access Key
|
|
247
|
+
--sk <value> TLS Secret Key
|
|
248
|
+
--project-name <name> TLS Project name for AK/SK auto creation
|
|
249
|
+
--app-name <name> TLS LogApp name for AK/SK auto creation
|
|
250
|
+
--capture-content <0|1> Default: 1
|
|
251
|
+
--hooks-path <path> Default: ~/.cursor/hooks.json
|
|
252
|
+
--plugin-target <path> Default: ~/.cursor/tls-observer-cursor/plugin
|
|
253
|
+
--env-target <path> Default: ~/.cursor/tls-observer-cursor.env
|
|
254
|
+
--data-root <path> Default: ~/.cursor/plugins/data/tls-observer-cursor
|
|
255
|
+
`);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function createReadline(): readline.Interface {
|
|
259
|
+
return readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false });
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async function promptText(rl: readline.Interface, message: string, defaultValue = ''): Promise<string> {
|
|
263
|
+
const suffix = defaultValue ? `\n default: ${defaultValue}\n> ` : '\n> ';
|
|
264
|
+
const answer = await rl.question(`${message}${suffix}`);
|
|
265
|
+
return answer.trim() || defaultValue;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async function promptRequired(rl: readline.Interface, message: string, defaultValue = ''): Promise<string> {
|
|
269
|
+
while (true) {
|
|
270
|
+
const value = await promptText(rl, message, defaultValue);
|
|
271
|
+
if (value.trim()) return value.trim();
|
|
272
|
+
console.log('This value is required.');
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function setTerminalEcho(enabled: boolean): boolean {
|
|
277
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
|
|
278
|
+
try {
|
|
279
|
+
execFileSync('stty', [enabled ? 'echo' : '-echo'], {
|
|
280
|
+
stdio: ['inherit', 'ignore', 'ignore'],
|
|
281
|
+
});
|
|
282
|
+
return true;
|
|
283
|
+
} catch {
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async function promptSecret(rl: readline.Interface, message: string, defaultValue = ''): Promise<string> {
|
|
289
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
290
|
+
return promptRequired(rl, message, defaultValue);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
rl.pause();
|
|
294
|
+
return new Promise<string>((resolve, reject) => {
|
|
295
|
+
const input = process.stdin;
|
|
296
|
+
let value = '';
|
|
297
|
+
let finished = false;
|
|
298
|
+
const previousRawMode = input.isRaw;
|
|
299
|
+
let echoDisabled = false;
|
|
300
|
+
const suffix = defaultValue ? '\n default: 已设置,回车保留\n> ' : '\n> ';
|
|
301
|
+
|
|
302
|
+
function cleanup(): void {
|
|
303
|
+
input.off('data', onData);
|
|
304
|
+
input.setRawMode(Boolean(previousRawMode));
|
|
305
|
+
if (echoDisabled) setTerminalEcho(true);
|
|
306
|
+
input.pause();
|
|
307
|
+
rl.resume();
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function finish(): void {
|
|
311
|
+
if (finished) return;
|
|
312
|
+
finished = true;
|
|
313
|
+
cleanup();
|
|
314
|
+
process.stdout.write('\n');
|
|
315
|
+
const resolvedValue = value.trim() || defaultValue;
|
|
316
|
+
if (resolvedValue) {
|
|
317
|
+
resolve(resolvedValue);
|
|
318
|
+
} else {
|
|
319
|
+
console.log('This value is required.');
|
|
320
|
+
resolve(promptSecret(rl, message, defaultValue));
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function onData(buffer: Buffer): void {
|
|
325
|
+
for (const char of buffer.toString('utf8')) {
|
|
326
|
+
if (finished) return;
|
|
327
|
+
if (char === '\u0003') {
|
|
328
|
+
finished = true;
|
|
329
|
+
cleanup();
|
|
330
|
+
reject(new Error('Interrupted'));
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if (char === '\r' || char === '\n') {
|
|
334
|
+
finish();
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
if (char === '\u007f' || char === '\b') {
|
|
338
|
+
if (value.length > 0) {
|
|
339
|
+
value = [...value].slice(0, -1).join('');
|
|
340
|
+
process.stdout.write('\b \b');
|
|
341
|
+
}
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
value += char;
|
|
345
|
+
process.stdout.write('*');
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
input.resume();
|
|
350
|
+
input.setRawMode(true);
|
|
351
|
+
input.on('data', onData);
|
|
352
|
+
echoDisabled = setTerminalEcho(false);
|
|
353
|
+
process.stdout.write(`${message}${suffix}`);
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function detectAuthType(options: InstallOptions): 'apiKey' | 'aksk' | undefined {
|
|
358
|
+
if (options.apiKey) return 'apiKey';
|
|
359
|
+
if (options.ak || options.sk) return 'aksk';
|
|
360
|
+
return undefined;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function validateBaseTlsConfig(options: InstallOptions): void {
|
|
364
|
+
const missing: string[] = [];
|
|
365
|
+
if (!options.region) missing.push('--region or CURSOR_TLS_REGION');
|
|
366
|
+
const authType = detectAuthType(options);
|
|
367
|
+
if (!authType) missing.push('--api-key or --ak/--sk');
|
|
368
|
+
if (authType === 'apiKey' && (options.ak || options.sk)) {
|
|
369
|
+
throw new Error('API Key and AK/SK cannot be used together');
|
|
370
|
+
}
|
|
371
|
+
if (authType === 'aksk' && (!options.ak || !options.sk)) missing.push('--ak and --sk');
|
|
372
|
+
if (missing.length > 0) throw new Error(`Missing required TLS config: ${missing.join(', ')}`);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function validateTlsConfig(options: InstallOptions): void {
|
|
376
|
+
validateBaseTlsConfig(options);
|
|
377
|
+
const missing: string[] = [];
|
|
378
|
+
if (!options.tlsEndpoint && !options.otelEndpoint) {
|
|
379
|
+
missing.push('--tls-endpoint, --region, or legacy --otel-endpoint');
|
|
380
|
+
}
|
|
381
|
+
if (!options.traceTopicId) missing.push('--trace-topic-id or CURSOR_TLS_TRACE_TOPIC_ID');
|
|
382
|
+
if (missing.length > 0) throw new Error(`Missing required TLS config: ${missing.join(', ')}`);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function collectInteractiveOptions(options: InstallOptions): Promise<InstallOptions> {
|
|
386
|
+
if (options.nonInteractive) {
|
|
387
|
+
if (!options.skipTlsConfig) {
|
|
388
|
+
applyDerivedDefaults(options);
|
|
389
|
+
validateBaseTlsConfig(options);
|
|
390
|
+
}
|
|
391
|
+
return options;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
const rl = createReadline();
|
|
395
|
+
try {
|
|
396
|
+
console.log('TLS Observer Cursor installer');
|
|
397
|
+
if (options.advancedPaths) {
|
|
398
|
+
options.hooksPath = await promptRequired(rl, 'Cursor hooks path', options.hooksPath);
|
|
399
|
+
options.pluginTarget = await promptRequired(rl, 'Cursor plugin target', options.pluginTarget);
|
|
400
|
+
options.envTarget = await promptRequired(rl, 'TLS env output path', options.envTarget);
|
|
401
|
+
options.dataRoot = await promptRequired(rl, 'Plugin data root', options.dataRoot);
|
|
402
|
+
}
|
|
403
|
+
options.force = true;
|
|
404
|
+
if (!options.skipTlsConfig) {
|
|
405
|
+
options.region = await promptRequired(rl, 'TLS region', options.region || DEFAULT_REGION);
|
|
406
|
+
applyDerivedDefaults(options);
|
|
407
|
+
const authType = await promptRequired(
|
|
408
|
+
rl,
|
|
409
|
+
'Auth type, apiKey or aksk',
|
|
410
|
+
detectAuthType(options) || 'apiKey',
|
|
411
|
+
);
|
|
412
|
+
if (authType === 'apiKey') {
|
|
413
|
+
options.traceTopicId = await promptRequired(rl, 'Trace topic ID', options.traceTopicId || '');
|
|
414
|
+
options.apiKey = await promptSecret(rl, 'TLS API Key', options.apiKey || '');
|
|
415
|
+
options.ak = undefined;
|
|
416
|
+
options.sk = undefined;
|
|
417
|
+
} else if (authType === 'aksk') {
|
|
418
|
+
options.projectName = await promptRequired(
|
|
419
|
+
rl,
|
|
420
|
+
'TLS Project name',
|
|
421
|
+
options.projectName || DEFAULT_PROJECT_NAME,
|
|
422
|
+
);
|
|
423
|
+
options.logAppName = await promptRequired(
|
|
424
|
+
rl,
|
|
425
|
+
'TLS LogApp name',
|
|
426
|
+
options.logAppName || defaultAppName(),
|
|
427
|
+
);
|
|
428
|
+
options.ak = await promptSecret(rl, 'TLS AK', options.ak || '');
|
|
429
|
+
options.sk = await promptSecret(rl, 'TLS SK', options.sk || '');
|
|
430
|
+
options.apiKey = undefined;
|
|
431
|
+
} else {
|
|
432
|
+
throw new Error('Auth type must be apiKey or aksk');
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return options;
|
|
436
|
+
} finally {
|
|
437
|
+
rl.close();
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function moduleSpecifier(specifier: string): string {
|
|
442
|
+
if (specifier.startsWith('.') || specifier.startsWith('/') || /^[A-Za-z]:[\\/]/.test(specifier)) {
|
|
443
|
+
return pathToFileURL(path.resolve(specifier)).href;
|
|
444
|
+
}
|
|
445
|
+
return specifier;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
async function loadOpenapiModule(): Promise<OpenapiModule> {
|
|
449
|
+
return import(moduleSpecifier(readEnvString('CURSOR_TLS_OPENAPI_MODULE') || '@volcengine/openapi'));
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function createTlsService(options: InstallOptions, openapiModule: OpenapiModule): TlsServiceClient {
|
|
453
|
+
if (!openapiModule?.tlsOpenapi?.TlsService) {
|
|
454
|
+
throw new Error('@volcengine/openapi must export tlsOpenapi.TlsService');
|
|
455
|
+
}
|
|
456
|
+
const isAkSk = !options.apiKey;
|
|
457
|
+
const tlsService = new openapiModule.tlsOpenapi.TlsService({
|
|
458
|
+
host: options.tlsEndpoint || defaultTlsEndpointForRegion(options.region),
|
|
459
|
+
region: options.region,
|
|
460
|
+
accessKeyId: isAkSk ? options.ak : 'anonymous',
|
|
461
|
+
secretKey: isAkSk ? options.sk : 'anonymous',
|
|
462
|
+
protocol: 'https:',
|
|
463
|
+
version: '0.3.0',
|
|
464
|
+
});
|
|
465
|
+
const axiosConfig = options.apiKey
|
|
466
|
+
? { proxy: false, headers: { 'x-tls-anonymous-identity': options.apiKey } }
|
|
467
|
+
: { proxy: false };
|
|
468
|
+
|
|
469
|
+
return {
|
|
470
|
+
isAkSk,
|
|
471
|
+
DescribeProjects: (payload: AnyRecord) => tlsService.DescribeProjects(payload, axiosConfig),
|
|
472
|
+
CreateProject: (payload: AnyRecord) => tlsService.CreateProject(payload, axiosConfig),
|
|
473
|
+
DescribeApps: (payload: AnyRecord) =>
|
|
474
|
+
tlsService.createAPI('DescribeApps', { method: 'GET' })(payload, axiosConfig),
|
|
475
|
+
CreateApp: (payload: AnyRecord) =>
|
|
476
|
+
tlsService.createAPI('CreateApp', { method: 'POST' })(payload, axiosConfig),
|
|
477
|
+
DescribeLogApps: (payload: AnyRecord) =>
|
|
478
|
+
tlsService.createAPI('DescribeLogApps', { method: 'GET' })(payload, axiosConfig),
|
|
479
|
+
DescribeTemplates: (payload: AnyRecord) =>
|
|
480
|
+
tlsService.createAPI('DescribeTemplates', { method: 'GET' })(payload, axiosConfig),
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
async function ensureTemplateId(tlsService: TlsServiceClient, options: InstallOptions): Promise<string> {
|
|
485
|
+
if (options.templateId) return options.templateId;
|
|
486
|
+
const response = await tlsService.DescribeTemplates({
|
|
487
|
+
TemplateName: options.templateName,
|
|
488
|
+
PageNumber: 1,
|
|
489
|
+
PageSize: 20,
|
|
490
|
+
});
|
|
491
|
+
const template = response.Templates?.find((item: AnyRecord) => item.TemplateName === options.templateName);
|
|
492
|
+
const templateId = String(template?.TemplateId || '').trim();
|
|
493
|
+
if (!templateId) {
|
|
494
|
+
throw new Error(
|
|
495
|
+
`DescribeTemplates did not return TemplateId for ${options.templateName}. Pass --template-id or --trace-topic-id.`,
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
return templateId;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
async function ensureProjectId(tlsService: TlsServiceClient, options: InstallOptions): Promise<string> {
|
|
502
|
+
if (options.projectId) return options.projectId;
|
|
503
|
+
const response = await tlsService.DescribeProjects({
|
|
504
|
+
ProjectName: options.projectName,
|
|
505
|
+
PageSize: 100,
|
|
506
|
+
PageNumber: 1,
|
|
507
|
+
});
|
|
508
|
+
const project = response.Projects?.find((item: AnyRecord) => item.ProjectName === options.projectName);
|
|
509
|
+
const existingProjectId = String(project?.ProjectId || '').trim();
|
|
510
|
+
if (existingProjectId) return existingProjectId;
|
|
511
|
+
const created = await tlsService.CreateProject({
|
|
512
|
+
ProjectName: options.projectName,
|
|
513
|
+
Description: 'Cursor observability',
|
|
514
|
+
Region: options.region,
|
|
515
|
+
});
|
|
516
|
+
const projectId = String(created.ProjectId || '').trim();
|
|
517
|
+
if (!projectId) throw new Error('CreateProject succeeded but did not return ProjectId');
|
|
518
|
+
return projectId;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
async function ensureLogApp(
|
|
522
|
+
tlsService: TlsServiceClient,
|
|
523
|
+
options: InstallOptions,
|
|
524
|
+
projectId: string,
|
|
525
|
+
): Promise<string> {
|
|
526
|
+
if (options.logAppId) return options.logAppId;
|
|
527
|
+
const appResponse = await tlsService.DescribeApps({
|
|
528
|
+
AppName: options.logAppName,
|
|
529
|
+
AppType: 'LogApp',
|
|
530
|
+
});
|
|
531
|
+
const total = appResponse.total ?? appResponse.Total ?? 0;
|
|
532
|
+
if (total > 0) {
|
|
533
|
+
const app = appResponse.apps?.[0] || appResponse.Apps?.[0];
|
|
534
|
+
const logAppId = String(app?.Resources?.[0]?.Id || app?.Sources?.[0]?.Id || '').trim();
|
|
535
|
+
if (logAppId) return logAppId;
|
|
536
|
+
}
|
|
537
|
+
const templateId = await ensureTemplateId(tlsService, options);
|
|
538
|
+
const created = await tlsService.CreateApp({
|
|
539
|
+
AppName: options.logAppName,
|
|
540
|
+
AppType: 'LogApp',
|
|
541
|
+
LogAppReq: {
|
|
542
|
+
LogAppName: options.logAppName,
|
|
543
|
+
LogAppType: options.logAppType,
|
|
544
|
+
ProjectId: projectId,
|
|
545
|
+
},
|
|
546
|
+
TemplateId: templateId,
|
|
547
|
+
});
|
|
548
|
+
const logAppId = String(created.Sources?.[0]?.Id || '').trim();
|
|
549
|
+
if (!logAppId) throw new Error('CreateApp succeeded but did not return Sources[0].Id');
|
|
550
|
+
return logAppId;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function topicMapFromLogApps(response: AnyRecord): Record<string, string> {
|
|
554
|
+
const topics = response?.LogApps?.[0]?.RelatedResourceList || [];
|
|
555
|
+
const topicMap: Record<string, string> = {};
|
|
556
|
+
for (const topic of topics) {
|
|
557
|
+
const resourceName = String(topic?.ResourceName || '');
|
|
558
|
+
const topicName = resourceName.split('_').filter(Boolean).at(-1);
|
|
559
|
+
const resourceId = String(topic?.ResourceID || '').trim();
|
|
560
|
+
if (topicName && resourceId) topicMap[topicName] = resourceId;
|
|
561
|
+
}
|
|
562
|
+
return topicMap;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
async function ensureTlsResources(
|
|
566
|
+
options: InstallOptions,
|
|
567
|
+
): Promise<{ created: boolean; logAppId?: string; traceTopicId?: string }> {
|
|
568
|
+
applyDerivedDefaults(options);
|
|
569
|
+
if (options.skipTlsConfig || options.apiKey || options.traceTopicId || !options.ak || !options.sk) {
|
|
570
|
+
return { created: false };
|
|
571
|
+
}
|
|
572
|
+
const openapiModule = await loadOpenapiModule();
|
|
573
|
+
const tlsService = createTlsService(options, openapiModule);
|
|
574
|
+
const projectId = await ensureProjectId(tlsService, options);
|
|
575
|
+
|
|
576
|
+
const logAppId = await ensureLogApp(tlsService, options, projectId);
|
|
577
|
+
options.logAppId = logAppId;
|
|
578
|
+
const logApps = await tlsService.DescribeLogApps({
|
|
579
|
+
PageNumber: 1,
|
|
580
|
+
PageSize: 20,
|
|
581
|
+
LogAppId: logAppId,
|
|
582
|
+
LogAppType: options.logAppType,
|
|
583
|
+
});
|
|
584
|
+
|
|
585
|
+
const topics = topicMapFromLogApps(logApps);
|
|
586
|
+
if (!options.traceTopicId) options.traceTopicId = topics.trace;
|
|
587
|
+
return { created: true, logAppId, traceTopicId: options.traceTopicId };
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
async function pathExists(filePath: string): Promise<boolean> {
|
|
591
|
+
try {
|
|
592
|
+
await fs.stat(filePath);
|
|
593
|
+
return true;
|
|
594
|
+
} catch (error) {
|
|
595
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
|
|
596
|
+
throw error;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
async function assertPluginRuntime(pluginSource: string): Promise<void> {
|
|
601
|
+
const hooks = path.join(pluginSource, 'hooks', 'hooks.json');
|
|
602
|
+
const entry = path.join(pluginSource, 'dist', 'index.js');
|
|
603
|
+
const manifest = path.join(pluginSource, 'package.json');
|
|
604
|
+
if ((await pathExists(manifest)) && (await pathExists(hooks)) && (await pathExists(entry))) return;
|
|
605
|
+
throw new Error(
|
|
606
|
+
`Plugin package is missing runtime files: ${pluginSource}. Expected dist/index.js, hooks/hooks.json, and package.json.`,
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
function pluginPackagePath(tempRoot: string, packageName: string): string {
|
|
611
|
+
return path.join(tempRoot, 'node_modules', ...packageName.split('/'));
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function pluginPackageSpec(options: InstallOptions): string {
|
|
615
|
+
const version = options.pluginVersion || (options.beta ? 'beta' : 'latest');
|
|
616
|
+
return `${options.pluginPackage}@${version}`;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
async function installPluginPackageToTemp(options: InstallOptions): Promise<{
|
|
620
|
+
root: string;
|
|
621
|
+
source: string;
|
|
622
|
+
packageSpec: string;
|
|
623
|
+
}> {
|
|
624
|
+
const root = await fs.mkdtemp(path.join(tmpdir(), 'tls-observer-cursor-plugin-'));
|
|
625
|
+
const packageSpec = pluginPackageSpec(options);
|
|
626
|
+
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
|
627
|
+
const args = [
|
|
628
|
+
'install',
|
|
629
|
+
'--prefix',
|
|
630
|
+
root,
|
|
631
|
+
'--ignore-scripts',
|
|
632
|
+
'--no-audit',
|
|
633
|
+
'--no-fund',
|
|
634
|
+
'--omit=dev',
|
|
635
|
+
'--registry',
|
|
636
|
+
options.registry,
|
|
637
|
+
packageSpec,
|
|
638
|
+
];
|
|
639
|
+
|
|
640
|
+
try {
|
|
641
|
+
await execFileAsync(npm, args, { timeout: 120_000 });
|
|
642
|
+
} catch (error) {
|
|
643
|
+
const detail =
|
|
644
|
+
error && typeof error === 'object' && 'stderr' in error
|
|
645
|
+
? String((error as { stderr?: unknown }).stderr || '')
|
|
646
|
+
: error instanceof Error
|
|
647
|
+
? error.message
|
|
648
|
+
: String(error);
|
|
649
|
+
throw new Error(`Failed to install plugin package ${packageSpec} from ${options.registry}: ${detail}`);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
const source = pluginPackagePath(root, options.pluginPackage);
|
|
653
|
+
await assertPluginRuntime(source);
|
|
654
|
+
return { root, source, packageSpec };
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
async function writeHookWrapper(options: InstallOptions): Promise<void> {
|
|
658
|
+
const source = [
|
|
659
|
+
'#!/usr/bin/env node',
|
|
660
|
+
`process.env.CURSOR_TLS_ENV_FILE ??= ${JSON.stringify(options.envTarget)};`,
|
|
661
|
+
"await import('./dist/index.js');",
|
|
662
|
+
'',
|
|
663
|
+
].join('\n');
|
|
664
|
+
await fs.writeFile(path.join(options.pluginTarget, 'run-hook.mjs'), source, { mode: 0o755 });
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
async function findLocalPluginSource(): Promise<string | undefined> {
|
|
668
|
+
const explicit = readEnvString('CURSOR_PLUGIN_SOURCE');
|
|
669
|
+
if (!explicit) return undefined;
|
|
670
|
+
const manifest = await readJsonFile<{ publishConfig?: { directory?: string } }>(
|
|
671
|
+
path.join(explicit, 'package.json'),
|
|
672
|
+
{},
|
|
673
|
+
);
|
|
674
|
+
const publishDirectory = manifest.publishConfig?.directory;
|
|
675
|
+
const candidates = publishDirectory ? [path.join(explicit, publishDirectory)] : [explicit];
|
|
676
|
+
for (const candidate of candidates) {
|
|
677
|
+
try {
|
|
678
|
+
await assertPluginRuntime(candidate);
|
|
679
|
+
return candidate;
|
|
680
|
+
} catch {
|
|
681
|
+
// Continue so the final error includes the env var value.
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
throw new Error(
|
|
685
|
+
`CURSOR_PLUGIN_SOURCE does not point to a built runtime package: ${explicit}. Run the plugin build first.`,
|
|
686
|
+
);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
async function readPluginVersion(pluginSource: string): Promise<string | undefined> {
|
|
690
|
+
const manifest = await readJsonFile<{ version?: string }>(path.join(pluginSource, 'package.json'), {});
|
|
691
|
+
return manifest.version;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
async function installPlugin(options: InstallOptions): Promise<PluginInstallResult> {
|
|
695
|
+
if ((await pathExists(options.pluginTarget)) && !options.force) {
|
|
696
|
+
throw new Error(`Plugin target exists: ${options.pluginTarget}. Re-run with --force.`);
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
const localSource = await findLocalPluginSource();
|
|
700
|
+
const tempInstall = localSource ? undefined : await installPluginPackageToTemp(options);
|
|
701
|
+
const source = localSource || tempInstall!.source;
|
|
702
|
+
|
|
703
|
+
await fs.rm(options.pluginTarget, { recursive: true, force: true });
|
|
704
|
+
await fs.mkdir(path.dirname(options.pluginTarget), { recursive: true });
|
|
705
|
+
await fs.mkdir(options.pluginTarget, { recursive: true });
|
|
706
|
+
const runtimeEntries = ['dist', 'hooks', 'README.md', 'package.json'] as const;
|
|
707
|
+
try {
|
|
708
|
+
for (const entry of runtimeEntries) {
|
|
709
|
+
await fs.cp(path.join(source, entry), path.join(options.pluginTarget, entry), { recursive: true });
|
|
710
|
+
}
|
|
711
|
+
await writeHookWrapper(options);
|
|
712
|
+
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
|
713
|
+
console.log('插件依赖安装中,请稍后...');
|
|
714
|
+
try {
|
|
715
|
+
await new Promise<void>((resolve, reject) => {
|
|
716
|
+
const child = spawn(npm, ['install', '--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund'], {
|
|
717
|
+
cwd: options.pluginTarget,
|
|
718
|
+
stdio: 'inherit',
|
|
719
|
+
});
|
|
720
|
+
const timer = setTimeout(() => {
|
|
721
|
+
child.kill();
|
|
722
|
+
reject(new Error(`npm install timed out after 120s`));
|
|
723
|
+
}, 120_000);
|
|
724
|
+
child.on('exit', (code) => {
|
|
725
|
+
clearTimeout(timer);
|
|
726
|
+
if (code === 0) resolve();
|
|
727
|
+
else reject(new Error(`npm install exited with code ${code}`));
|
|
728
|
+
});
|
|
729
|
+
child.on('error', reject);
|
|
730
|
+
});
|
|
731
|
+
} catch (error) {
|
|
732
|
+
const detail =
|
|
733
|
+
error && typeof error === 'object' && 'stderr' in error
|
|
734
|
+
? String((error as { stderr?: unknown }).stderr || '')
|
|
735
|
+
: error instanceof Error
|
|
736
|
+
? error.message
|
|
737
|
+
: String(error);
|
|
738
|
+
throw new Error(`Failed to install plugin dependencies at ${options.pluginTarget}: ${detail}`);
|
|
739
|
+
}
|
|
740
|
+
return {
|
|
741
|
+
source,
|
|
742
|
+
target: options.pluginTarget,
|
|
743
|
+
packageSpec: tempInstall?.packageSpec,
|
|
744
|
+
version: await readPluginVersion(source),
|
|
745
|
+
};
|
|
746
|
+
} finally {
|
|
747
|
+
if (tempInstall) await fs.rm(tempInstall.root, { recursive: true, force: true });
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
async function readJsonFile<T>(filePath: string, fallback: T): Promise<T> {
|
|
752
|
+
try {
|
|
753
|
+
return JSON.parse(await fs.readFile(filePath, 'utf8')) as T;
|
|
754
|
+
} catch (error) {
|
|
755
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return fallback;
|
|
756
|
+
throw error;
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
async function writeJsonFile(filePath: string, value: unknown, mode?: number): Promise<void> {
|
|
761
|
+
await fs.mkdir(path.dirname(filePath), { recursive: true });
|
|
762
|
+
if (mode) {
|
|
763
|
+
await fs.writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, { mode });
|
|
764
|
+
} else {
|
|
765
|
+
await fs.writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
function commandQuote(value: string): string {
|
|
770
|
+
if (process.platform === 'win32') return `"${value.replace(/"/g, '\\"')}"`;
|
|
771
|
+
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
function hookCommand(options: InstallOptions): string {
|
|
775
|
+
const nodeBin = commandQuote(process.execPath);
|
|
776
|
+
const wrapper = commandQuote(path.join(options.pluginTarget, 'run-hook.mjs'));
|
|
777
|
+
return `${nodeBin} ${wrapper}`;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
function isManagedHookEntry(entry: unknown): boolean {
|
|
781
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return false;
|
|
782
|
+
const command = String((entry as AnyRecord).command || '');
|
|
783
|
+
return (
|
|
784
|
+
command.includes(PLUGIN_NAME) ||
|
|
785
|
+
command.includes(PLUGIN_PACKAGE_NAME) ||
|
|
786
|
+
command.includes('CURSOR_TLS_OBSERVER_ROOT')
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function fallbackHookEvents(): HookEventConfig[] {
|
|
791
|
+
return CURSOR_HOOK_EVENTS.map(([eventName, timeout]) => ({ eventName, timeout }));
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
function parseHookEventsManifest(value: unknown): HookEventConfig[] {
|
|
795
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return [];
|
|
796
|
+
const hooks = (value as AnyRecord).hooks;
|
|
797
|
+
if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks)) return [];
|
|
798
|
+
|
|
799
|
+
const events: HookEventConfig[] = [];
|
|
800
|
+
for (const [eventName, entries] of Object.entries(hooks)) {
|
|
801
|
+
if (!Array.isArray(entries) || entries.length === 0) continue;
|
|
802
|
+
const firstEntry = entries.find((entry) => entry && typeof entry === 'object' && !Array.isArray(entry));
|
|
803
|
+
const timeout = Number((firstEntry as AnyRecord | undefined)?.timeout);
|
|
804
|
+
events.push({
|
|
805
|
+
eventName,
|
|
806
|
+
timeout: Number.isFinite(timeout) && timeout > 0 ? timeout : 30,
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
return events;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
async function readHookEvents(options: InstallOptions): Promise<HookEventConfig[]> {
|
|
813
|
+
const manifestPath = path.join(options.pluginTarget, 'hooks', 'hooks.json');
|
|
814
|
+
const manifest = await readJsonFile<unknown>(manifestPath, {});
|
|
815
|
+
const events = parseHookEventsManifest(manifest);
|
|
816
|
+
return events.length > 0 ? events : fallbackHookEvents();
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
async function writeHooks(options: InstallOptions): Promise<void> {
|
|
820
|
+
const hooksFile = await readJsonFile<CursorHooksFile>(options.hooksPath, {});
|
|
821
|
+
if (!hooksFile.version) hooksFile.version = 1;
|
|
822
|
+
if (!hooksFile.hooks || typeof hooksFile.hooks !== 'object' || Array.isArray(hooksFile.hooks)) {
|
|
823
|
+
hooksFile.hooks = {};
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
const command = hookCommand(options);
|
|
827
|
+
const currentHookEvents = await readHookEvents(options);
|
|
828
|
+
|
|
829
|
+
for (const [eventName, existing] of Object.entries(hooksFile.hooks)) {
|
|
830
|
+
if (!Array.isArray(existing)) continue;
|
|
831
|
+
const unmanagedEntries = existing.filter((entry) => !isManagedHookEntry(entry));
|
|
832
|
+
if (unmanagedEntries.length > 0) {
|
|
833
|
+
hooksFile.hooks[eventName] = unmanagedEntries;
|
|
834
|
+
} else {
|
|
835
|
+
delete hooksFile.hooks[eventName];
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
for (const { eventName, timeout } of currentHookEvents) {
|
|
840
|
+
const existing = hooksFile.hooks[eventName];
|
|
841
|
+
const entries = Array.isArray(existing) ? existing.filter((entry) => !isManagedHookEntry(entry)) : [];
|
|
842
|
+
entries.push({ command, timeout });
|
|
843
|
+
hooksFile.hooks[eventName] = entries;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
await writeJsonFile(options.hooksPath, hooksFile);
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
function envLine(key: string, value?: string | null): string | undefined {
|
|
850
|
+
if (value === undefined || value === null || value === '') return undefined;
|
|
851
|
+
return `${key}=${String(value)}`;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
function buildTlsEnv(options: InstallOptions): string {
|
|
855
|
+
const lines = [
|
|
856
|
+
'# Generated by tls-observer-cursor installer.',
|
|
857
|
+
'# Keep this file local because it can contain credentials.',
|
|
858
|
+
envLine('CURSOR_TLS_REGION', options.region),
|
|
859
|
+
envLine('CURSOR_TLS_ENDPOINT', options.tlsEndpoint),
|
|
860
|
+
envLine('CURSOR_TLS_OTEL_ENDPOINT', options.otelEndpoint),
|
|
861
|
+
envLine('CURSOR_TLS_TRACE_TOPIC_ID', options.traceTopicId),
|
|
862
|
+
envLine('CURSOR_TLS_API_KEY', options.apiKey),
|
|
863
|
+
envLine('CURSOR_TLS_AK', options.ak),
|
|
864
|
+
envLine('CURSOR_TLS_SK', options.sk),
|
|
865
|
+
envLine('CURSOR_TLS_AUTH_MODE', options.authMode),
|
|
866
|
+
envLine('CURSOR_TLS_EXPORT_TIMEOUT_MS', options.exportTimeoutMs),
|
|
867
|
+
envLine('CURSOR_TLS_EXPORT_TIMEOUT_RETRIES', options.exportTimeoutRetries),
|
|
868
|
+
envLine('CURSOR_TLS_CAPTURE_CONTENT', options.captureContent),
|
|
869
|
+
envLine('CURSOR_TLS_DATA_ROOT', options.dataRoot),
|
|
870
|
+
].filter(Boolean);
|
|
871
|
+
return `${lines.join('\n')}\n`;
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
async function writeTlsEnv(options: InstallOptions): Promise<string | null> {
|
|
875
|
+
if (options.skipTlsConfig) return null;
|
|
876
|
+
if ((await pathExists(options.envTarget)) && !options.force) {
|
|
877
|
+
throw new Error(`TLS env target exists: ${options.envTarget}. Re-run with --force.`);
|
|
878
|
+
}
|
|
879
|
+
await writeJsonFile(path.join(options.dataRoot, 'state', 'install.json'), {
|
|
880
|
+
installed_at: new Date().toISOString(),
|
|
881
|
+
plugin_name: PLUGIN_NAME,
|
|
882
|
+
plugin_target: options.pluginTarget,
|
|
883
|
+
hooks_path: options.hooksPath,
|
|
884
|
+
env_target: options.envTarget,
|
|
885
|
+
});
|
|
886
|
+
await fs.mkdir(path.dirname(options.envTarget), { recursive: true });
|
|
887
|
+
await fs.writeFile(options.envTarget, buildTlsEnv(options), { mode: 0o600 });
|
|
888
|
+
return options.envTarget;
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
function printCompletion({
|
|
892
|
+
plugin,
|
|
893
|
+
hooksPath,
|
|
894
|
+
envTarget,
|
|
895
|
+
}: {
|
|
896
|
+
plugin: PluginInstallResult;
|
|
897
|
+
hooksPath: string;
|
|
898
|
+
envTarget: string | null;
|
|
899
|
+
}): void {
|
|
900
|
+
console.log('');
|
|
901
|
+
console.log('Install complete');
|
|
902
|
+
console.log(` Plugin: ${plugin.target}`);
|
|
903
|
+
if (plugin.packageSpec) console.log(` Plugin package: ${plugin.packageSpec}`);
|
|
904
|
+
if (plugin.version) console.log(` Plugin version: ${plugin.version}`);
|
|
905
|
+
console.log(` Hooks: ${hooksPath}`);
|
|
906
|
+
console.log(` TLS env: ${envTarget || 'skipped'}`);
|
|
907
|
+
console.log('');
|
|
908
|
+
console.log('数据访问说明');
|
|
909
|
+
console.log('安装后,插件会读取会话文件');
|
|
910
|
+
console.log(
|
|
911
|
+
'会话文件中的用户请求、模型回复、工具调用记录和 token 用量会整理成诊断数据,上传到你配置的火山引擎 TLS',
|
|
912
|
+
);
|
|
913
|
+
console.log('如配置 API Key 或 AK/SK,凭据只写入本机 env 文件,用于上传鉴权');
|
|
914
|
+
console.log('');
|
|
915
|
+
console.log('Next steps:');
|
|
916
|
+
console.log(' 1. Restart Cursor.');
|
|
917
|
+
console.log(' 2. Run one Cursor turn.');
|
|
918
|
+
console.log(' 3. Check TLS Trace Topic for agent.turn.');
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
async function run(argv: string[] = process.argv.slice(2)): Promise<void> {
|
|
922
|
+
const parsed = parseCliOptions(argv);
|
|
923
|
+
if (parsed.help) {
|
|
924
|
+
printHelp();
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
927
|
+
const options = await collectInteractiveOptions(parsed);
|
|
928
|
+
if (!options.skipTlsConfig) {
|
|
929
|
+
const resourceResult = await ensureTlsResources(options);
|
|
930
|
+
if (resourceResult.created && !options.traceTopicId) {
|
|
931
|
+
throw new Error('TLS LogApp was created but trace topic discovery failed. Pass --trace-topic-id.');
|
|
932
|
+
}
|
|
933
|
+
applyDerivedDefaults(options);
|
|
934
|
+
validateTlsConfig(options);
|
|
935
|
+
}
|
|
936
|
+
const plugin = await installPlugin(options);
|
|
937
|
+
await writeHooks(options);
|
|
938
|
+
const envTarget = await writeTlsEnv(options);
|
|
939
|
+
printCompletion({ plugin, hooksPath: options.hooksPath, envTarget });
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
export { run };
|