@volcengine/tls-observer-opencode-install 0.0.3

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