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