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