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