@volcengine/tls-observer-pi-install 0.0.1
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/LICENCE +13 -0
- package/README.md +70 -0
- package/bin/tls-observer-pi-install.mjs +9 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +649 -0
- package/dist/installer/installer-runner.d.ts +51 -0
- package/package.json +53 -0
- package/src/index.ts +15 -0
- package/src/installer/installer-runner.ts +808 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,649 @@
|
|
|
1
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
2
|
+
import { homedir } 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_PACKAGE_NAME = '@volcengine/tls-observer-pi';
|
|
11
|
+
const DEFAULT_REGISTRY = 'https://registry.npmjs.org';
|
|
12
|
+
const DEFAULT_ENV_TARGET = __rspack_external_node_path_c5b9b54f.join(homedir(), '.pi', 'agent', 'tls-observer-pi.env');
|
|
13
|
+
const DEFAULT_DATA_ROOT = __rspack_external_node_path_c5b9b54f.join(homedir(), '.pi', 'agent', 'tls-observer-pi');
|
|
14
|
+
const DEFAULT_REGION = 'cn-beijing';
|
|
15
|
+
const DEFAULT_PROJECT_NAME = 'pi_observability';
|
|
16
|
+
const DEFAULT_APP_NAME_PREFIX = 'pi-observability';
|
|
17
|
+
const DEFAULT_TLS_ENDPOINT = 'tls-cn-beijing.volces.com';
|
|
18
|
+
const DEFAULT_LOG_APP_TYPE = 'Pi';
|
|
19
|
+
const DEFAULT_TEMPLATE_NAME = 'Pi';
|
|
20
|
+
const LOCAL_PLUGIN_SOURCE_ENV_KEYS = [
|
|
21
|
+
'PI_PLUGIN_SOURCE',
|
|
22
|
+
'PI_TLS_PLUGIN_SOURCE',
|
|
23
|
+
'TRAE_TLS_PLUGIN_SOURCE'
|
|
24
|
+
];
|
|
25
|
+
function readEnvString(key) {
|
|
26
|
+
const value = process.env[key];
|
|
27
|
+
return 'string' == typeof value && value.trim() ? value.trim() : void 0;
|
|
28
|
+
}
|
|
29
|
+
function readEnvBool(key) {
|
|
30
|
+
const value = readEnvString(key);
|
|
31
|
+
return value ? /^(1|true|yes|y|on)$/i.test(value) : false;
|
|
32
|
+
}
|
|
33
|
+
function takeArg(argv, index, flag) {
|
|
34
|
+
const value = argv[index + 1];
|
|
35
|
+
if ('string' != typeof value || value.startsWith('--')) throw new Error(`${flag} requires a value`);
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
38
|
+
function defaultTlsEndpointForRegion(region) {
|
|
39
|
+
return region ? `tls-${region}.volces.com` : DEFAULT_TLS_ENDPOINT;
|
|
40
|
+
}
|
|
41
|
+
function randomSuffix() {
|
|
42
|
+
const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';
|
|
43
|
+
let value = '';
|
|
44
|
+
for(let index = 0; index < 8; index += 1)value += alphabet[randomInt(alphabet.length)];
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
function defaultAppName() {
|
|
48
|
+
return `${DEFAULT_APP_NAME_PREFIX}_${randomSuffix()}`;
|
|
49
|
+
}
|
|
50
|
+
function applyDerivedDefaults(options) {
|
|
51
|
+
if (options.region && !options.tlsEndpoint) options.tlsEndpoint = defaultTlsEndpointForRegion(options.region);
|
|
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 options = {
|
|
57
|
+
help: false,
|
|
58
|
+
nonInteractive: readEnvBool('PI_TLS_INSTALL_NON_INTERACTIVE'),
|
|
59
|
+
force: readEnvBool('PI_TLS_INSTALL_FORCE'),
|
|
60
|
+
beta: readEnvBool('PI_TLS_INSTALL_BETA'),
|
|
61
|
+
dryRun: readEnvBool('PI_TLS_INSTALL_DRY_RUN'),
|
|
62
|
+
skipTlsConfig: readEnvBool('PI_TLS_INSTALL_SKIP_TLS_CONFIG'),
|
|
63
|
+
piBin: readEnvString('PI_TLS_PI_BIN') || readEnvString('PI_BIN') || 'pi',
|
|
64
|
+
registry: readEnvString('PI_TLS_NPM_REGISTRY') || readEnvString('npm_config_registry') || readEnvString('NPM_CONFIG_REGISTRY') || DEFAULT_REGISTRY,
|
|
65
|
+
pluginPackage: readEnvString('PI_TLS_PLUGIN_PACKAGE') || PLUGIN_PACKAGE_NAME,
|
|
66
|
+
pluginVersion: readEnvString('PI_TLS_PLUGIN_VERSION'),
|
|
67
|
+
envTarget: readEnvString('PI_TLS_ENV_TARGET') || DEFAULT_ENV_TARGET,
|
|
68
|
+
dataRoot: readEnvString('PI_TLS_DATA_ROOT') || DEFAULT_DATA_ROOT,
|
|
69
|
+
region: readEnvString('PI_TLS_REGION') || DEFAULT_REGION,
|
|
70
|
+
traceTopicId: readEnvString('PI_TLS_TRACE_TOPIC_ID'),
|
|
71
|
+
apiKey: readEnvString('PI_TLS_API_KEY'),
|
|
72
|
+
ak: readEnvString('PI_TLS_AK'),
|
|
73
|
+
sk: readEnvString('PI_TLS_SK'),
|
|
74
|
+
authMode: readEnvString('PI_TLS_AUTH_MODE') || 'header',
|
|
75
|
+
exportTimeoutMs: readEnvString('PI_TLS_EXPORT_TIMEOUT_MS') || '20000',
|
|
76
|
+
captureContent: readEnvString('PI_TLS_CAPTURE_CONTENT') || '1',
|
|
77
|
+
tlsEndpoint: readEnvString('PI_TLS_ENDPOINT'),
|
|
78
|
+
projectId: readEnvString('PI_TLS_PROJECT_ID'),
|
|
79
|
+
projectName: readEnvString('PI_TLS_PROJECT_NAME'),
|
|
80
|
+
logAppId: readEnvString('PI_TLS_LOG_APP_ID'),
|
|
81
|
+
logAppName: readEnvString('PI_TLS_LOG_APP_NAME'),
|
|
82
|
+
logAppType: readEnvString('PI_TLS_LOG_APP_TYPE') || DEFAULT_LOG_APP_TYPE,
|
|
83
|
+
templateName: readEnvString('PI_TLS_TEMPLATE_NAME') || DEFAULT_TEMPLATE_NAME,
|
|
84
|
+
templateId: readEnvString('PI_TLS_TEMPLATE_ID')
|
|
85
|
+
};
|
|
86
|
+
for(let index = 0; index < argv.length; index += 1){
|
|
87
|
+
const current = argv[index];
|
|
88
|
+
if ('--help' === current || '-h' === current) options.help = true;
|
|
89
|
+
else if ('--non-interactive' === current) options.nonInteractive = true;
|
|
90
|
+
else if ('--force' === current) options.force = true;
|
|
91
|
+
else if ('--beta' === current) options.beta = true;
|
|
92
|
+
else if ('--dry-run' === current) options.dryRun = true;
|
|
93
|
+
else if ('--skip-tls-config' === current) options.skipTlsConfig = true;
|
|
94
|
+
else if ('--pi-bin' === current) options.piBin = takeArg(argv, index++, current);
|
|
95
|
+
else if ('--registry' === current) options.registry = takeArg(argv, index++, current);
|
|
96
|
+
else if ('--plugin-package' === current) options.pluginPackage = takeArg(argv, index++, current);
|
|
97
|
+
else if ('--plugin-version' === current) options.pluginVersion = takeArg(argv, index++, current);
|
|
98
|
+
else if ('--env-target' === current) options.envTarget = takeArg(argv, index++, current);
|
|
99
|
+
else if ('--data-root' === current) options.dataRoot = takeArg(argv, index++, current);
|
|
100
|
+
else if ('--region' === current) options.region = takeArg(argv, index++, current);
|
|
101
|
+
else if ('--trace-topic-id' === current) options.traceTopicId = takeArg(argv, index++, current);
|
|
102
|
+
else if ('--api-key' === current) options.apiKey = takeArg(argv, index++, current);
|
|
103
|
+
else if ('--ak' === current) options.ak = takeArg(argv, index++, current);
|
|
104
|
+
else if ('--sk' === current) options.sk = takeArg(argv, index++, current);
|
|
105
|
+
else if ('--auth-mode' === current) options.authMode = takeArg(argv, index++, current);
|
|
106
|
+
else if ('--export-timeout-ms' === current) options.exportTimeoutMs = takeArg(argv, index++, current);
|
|
107
|
+
else if ('--capture-content' === current) options.captureContent = takeArg(argv, index++, current);
|
|
108
|
+
else if ('--tls-endpoint' === current) options.tlsEndpoint = takeArg(argv, index++, current);
|
|
109
|
+
else if ('--project-id' === current) options.projectId = takeArg(argv, index++, current);
|
|
110
|
+
else if ('--project-name' === current) options.projectName = takeArg(argv, index++, current);
|
|
111
|
+
else if ('--app-name' === current || '--log-app-name' === current) options.logAppName = takeArg(argv, index++, current);
|
|
112
|
+
else if ('--log-app-id' === current) options.logAppId = takeArg(argv, index++, current);
|
|
113
|
+
else if ('--log-app-type' === current) options.logAppType = takeArg(argv, index++, current);
|
|
114
|
+
else if ('--template-name' === current) options.templateName = takeArg(argv, index++, current);
|
|
115
|
+
else if ('--template-id' === current) options.templateId = takeArg(argv, index++, current);
|
|
116
|
+
else throw new Error(`Unknown option: ${current}`);
|
|
117
|
+
}
|
|
118
|
+
return options;
|
|
119
|
+
}
|
|
120
|
+
function printHelp() {
|
|
121
|
+
console.log(`TLS Observer Pi installer
|
|
122
|
+
|
|
123
|
+
Usage:
|
|
124
|
+
tls-observer-pi-install [options]
|
|
125
|
+
npm exec -y --package=@volcengine/tls-observer-pi-install -- tls-observer-pi-install [options]
|
|
126
|
+
|
|
127
|
+
Options:
|
|
128
|
+
--non-interactive Read required inputs from flags/env
|
|
129
|
+
--force Overwrite existing env file
|
|
130
|
+
--beta Install @volcengine/tls-observer-pi@beta instead of @latest
|
|
131
|
+
--dry-run Write env but skip running pi install
|
|
132
|
+
--skip-tls-config Install plugin without writing TLS env
|
|
133
|
+
--pi-bin <path> Pi CLI executable. Default: pi
|
|
134
|
+
--registry <url> NPM registry for plugin package. Default: https://registry.npmjs.org
|
|
135
|
+
--plugin-version <version> Exact plugin version or dist-tag. Overrides --beta
|
|
136
|
+
--region <region> TLS region. Default: cn-beijing
|
|
137
|
+
--tls-endpoint <host> TLS Producer endpoint. Derived from region by default
|
|
138
|
+
--trace-topic-id <id> TLS trace topic ID
|
|
139
|
+
--api-key <value> TLS API Key
|
|
140
|
+
--ak <value> TLS Access Key
|
|
141
|
+
--sk <value> TLS Secret Key
|
|
142
|
+
--project-name <name> TLS Project name for AK/SK auto creation
|
|
143
|
+
--app-name <name> TLS LogApp name for AK/SK auto creation
|
|
144
|
+
--export-timeout-ms <ms> TLS export timeout. Default: 20000
|
|
145
|
+
--capture-content <0|1> Default: 1
|
|
146
|
+
--env-target <path> Default: ~/.pi/agent/tls-observer-pi.env
|
|
147
|
+
--data-root <path> Default: ~/.pi/agent/tls-observer-pi
|
|
148
|
+
|
|
149
|
+
Environment:
|
|
150
|
+
PI_PLUGIN_SOURCE Install a local built plugin package instead of installing from npm
|
|
151
|
+
PI_TLS_PI_BIN Pi CLI executable path when pi is not on PATH
|
|
152
|
+
`);
|
|
153
|
+
}
|
|
154
|
+
function createReadline() {
|
|
155
|
+
return promises.createInterface({
|
|
156
|
+
input: process.stdin,
|
|
157
|
+
output: process.stdout,
|
|
158
|
+
terminal: false
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
async function promptText(rl, message, defaultValue = '') {
|
|
162
|
+
const suffix = defaultValue ? `\n default: ${defaultValue}\n> ` : '\n> ';
|
|
163
|
+
const answer = await rl.question(`${message}${suffix}`);
|
|
164
|
+
return answer.trim() || defaultValue;
|
|
165
|
+
}
|
|
166
|
+
async function promptRequired(rl, message, defaultValue = '') {
|
|
167
|
+
while(true){
|
|
168
|
+
const value = await promptText(rl, message, defaultValue);
|
|
169
|
+
if (value.trim()) return value.trim();
|
|
170
|
+
console.log('This value is required.');
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function setTerminalEcho(enabled) {
|
|
174
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
|
|
175
|
+
try {
|
|
176
|
+
execFileSync('stty', [
|
|
177
|
+
enabled ? 'echo' : '-echo'
|
|
178
|
+
], {
|
|
179
|
+
stdio: [
|
|
180
|
+
'inherit',
|
|
181
|
+
'ignore',
|
|
182
|
+
'ignore'
|
|
183
|
+
]
|
|
184
|
+
});
|
|
185
|
+
return true;
|
|
186
|
+
} catch {
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
async function promptSecret(rl, message, defaultValue = '') {
|
|
191
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return promptRequired(rl, message, defaultValue);
|
|
192
|
+
rl.pause();
|
|
193
|
+
return new Promise((resolve, reject)=>{
|
|
194
|
+
const input = process.stdin;
|
|
195
|
+
let value = '';
|
|
196
|
+
let finished = false;
|
|
197
|
+
const previousRawMode = input.isRaw;
|
|
198
|
+
let echoDisabled = false;
|
|
199
|
+
const suffix = defaultValue ? '\n default: 已设置,回车保留\n> ' : '\n> ';
|
|
200
|
+
function cleanup() {
|
|
201
|
+
input.off('data', onData);
|
|
202
|
+
input.setRawMode(Boolean(previousRawMode));
|
|
203
|
+
if (echoDisabled) setTerminalEcho(true);
|
|
204
|
+
input.pause();
|
|
205
|
+
rl.resume();
|
|
206
|
+
}
|
|
207
|
+
function finish() {
|
|
208
|
+
if (finished) return;
|
|
209
|
+
finished = true;
|
|
210
|
+
cleanup();
|
|
211
|
+
process.stdout.write('\n');
|
|
212
|
+
const resolvedValue = value.trim() || defaultValue;
|
|
213
|
+
if (resolvedValue) resolve(resolvedValue);
|
|
214
|
+
else {
|
|
215
|
+
console.log('This value is required.');
|
|
216
|
+
resolve(promptSecret(rl, message, defaultValue));
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
function onData(buffer) {
|
|
220
|
+
for (const char of buffer.toString('utf8')){
|
|
221
|
+
if (finished) return;
|
|
222
|
+
if ('\u0003' === char) {
|
|
223
|
+
finished = true;
|
|
224
|
+
cleanup();
|
|
225
|
+
reject(new Error('Interrupted'));
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if ('\r' === char || '\n' === char) return void finish();
|
|
229
|
+
if ('\u007f' === char || '\b' === char) {
|
|
230
|
+
if (value.length > 0) {
|
|
231
|
+
value = [
|
|
232
|
+
...value
|
|
233
|
+
].slice(0, -1).join('');
|
|
234
|
+
process.stdout.write('\b \b');
|
|
235
|
+
}
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
value += char;
|
|
239
|
+
process.stdout.write('*');
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
input.resume();
|
|
243
|
+
input.setRawMode(true);
|
|
244
|
+
input.on('data', onData);
|
|
245
|
+
echoDisabled = setTerminalEcho(false);
|
|
246
|
+
process.stdout.write(`${message}${suffix}`);
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
function detectAuthType(options) {
|
|
250
|
+
if (options.apiKey) return 'apiKey';
|
|
251
|
+
if (options.ak || options.sk) return 'aksk';
|
|
252
|
+
}
|
|
253
|
+
function validateBaseTlsConfig(options) {
|
|
254
|
+
const missing = [];
|
|
255
|
+
if (!options.region) missing.push('--region or PI_TLS_REGION');
|
|
256
|
+
const authType = detectAuthType(options);
|
|
257
|
+
if (!authType) missing.push('--api-key or --ak/--sk');
|
|
258
|
+
if ('apiKey' === authType && (options.ak || options.sk)) throw new Error('API Key and AK/SK cannot be used together');
|
|
259
|
+
if ('aksk' === authType && (!options.ak || !options.sk)) missing.push('--ak and --sk');
|
|
260
|
+
if (missing.length > 0) throw new Error(`Missing required TLS config: ${missing.join(', ')}`);
|
|
261
|
+
}
|
|
262
|
+
function validateTlsConfig(options) {
|
|
263
|
+
validateBaseTlsConfig(options);
|
|
264
|
+
const missing = [];
|
|
265
|
+
if (!options.tlsEndpoint) missing.push('--tls-endpoint or --region');
|
|
266
|
+
if (!options.traceTopicId) missing.push('--trace-topic-id or PI_TLS_TRACE_TOPIC_ID');
|
|
267
|
+
if (missing.length > 0) throw new Error(`Missing required TLS config: ${missing.join(', ')}`);
|
|
268
|
+
}
|
|
269
|
+
async function collectInteractiveOptions(options) {
|
|
270
|
+
if (options.nonInteractive) {
|
|
271
|
+
if (!options.skipTlsConfig) {
|
|
272
|
+
applyDerivedDefaults(options);
|
|
273
|
+
validateBaseTlsConfig(options);
|
|
274
|
+
}
|
|
275
|
+
return options;
|
|
276
|
+
}
|
|
277
|
+
const rl = createReadline();
|
|
278
|
+
try {
|
|
279
|
+
console.log('TLS Observer Pi installer');
|
|
280
|
+
options.force = true;
|
|
281
|
+
if (!options.skipTlsConfig) {
|
|
282
|
+
options.region = await promptRequired(rl, 'TLS region', options.region || DEFAULT_REGION);
|
|
283
|
+
applyDerivedDefaults(options);
|
|
284
|
+
const authType = await promptRequired(rl, 'Auth type, apiKey or aksk', detectAuthType(options) || 'apiKey');
|
|
285
|
+
if ('apiKey' === authType) {
|
|
286
|
+
options.traceTopicId = await promptRequired(rl, 'Trace topic ID', options.traceTopicId || '');
|
|
287
|
+
options.apiKey = await promptSecret(rl, 'TLS API Key', options.apiKey || '');
|
|
288
|
+
options.ak = void 0;
|
|
289
|
+
options.sk = void 0;
|
|
290
|
+
} else if ('aksk' === authType) {
|
|
291
|
+
options.projectName = await promptRequired(rl, 'TLS Project name', options.projectName || DEFAULT_PROJECT_NAME);
|
|
292
|
+
options.logAppName = await promptRequired(rl, 'TLS LogApp name', options.logAppName || defaultAppName());
|
|
293
|
+
options.ak = await promptSecret(rl, 'TLS AK', options.ak || '');
|
|
294
|
+
options.sk = await promptSecret(rl, 'TLS SK', options.sk || '');
|
|
295
|
+
options.apiKey = void 0;
|
|
296
|
+
} else throw new Error('Auth type must be apiKey or aksk');
|
|
297
|
+
}
|
|
298
|
+
return options;
|
|
299
|
+
} finally{
|
|
300
|
+
rl.close();
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
function moduleSpecifier(specifier) {
|
|
304
|
+
if (specifier.startsWith('.') || specifier.startsWith('/') || /^[A-Za-z]:[\\/]/.test(specifier)) return pathToFileURL(__rspack_external_node_path_c5b9b54f.resolve(specifier)).href;
|
|
305
|
+
return specifier;
|
|
306
|
+
}
|
|
307
|
+
async function loadOpenapiModule() {
|
|
308
|
+
return import(moduleSpecifier(readEnvString('PI_TLS_OPENAPI_MODULE') || '@volcengine/openapi'));
|
|
309
|
+
}
|
|
310
|
+
function createTlsService(options, openapiModule) {
|
|
311
|
+
if (!openapiModule?.tlsOpenapi?.TlsService) throw new Error('@volcengine/openapi must export tlsOpenapi.TlsService');
|
|
312
|
+
const isAkSk = !options.apiKey;
|
|
313
|
+
const tlsService = new openapiModule.tlsOpenapi.TlsService({
|
|
314
|
+
host: options.tlsEndpoint || defaultTlsEndpointForRegion(options.region),
|
|
315
|
+
region: options.region,
|
|
316
|
+
accessKeyId: isAkSk ? options.ak : 'anonymous',
|
|
317
|
+
secretKey: isAkSk ? options.sk : 'anonymous',
|
|
318
|
+
protocol: 'https:',
|
|
319
|
+
version: '0.3.0'
|
|
320
|
+
});
|
|
321
|
+
const axiosConfig = options.apiKey ? {
|
|
322
|
+
proxy: false,
|
|
323
|
+
headers: {
|
|
324
|
+
'x-tls-anonymous-identity': options.apiKey
|
|
325
|
+
}
|
|
326
|
+
} : {
|
|
327
|
+
proxy: false
|
|
328
|
+
};
|
|
329
|
+
return {
|
|
330
|
+
isAkSk,
|
|
331
|
+
DescribeProjects: (payload)=>tlsService.DescribeProjects(payload, axiosConfig),
|
|
332
|
+
CreateProject: (payload)=>tlsService.CreateProject(payload, axiosConfig),
|
|
333
|
+
DescribeApps: (payload)=>tlsService.createAPI('DescribeApps', {
|
|
334
|
+
method: 'GET'
|
|
335
|
+
})(payload, axiosConfig),
|
|
336
|
+
CreateApp: (payload)=>tlsService.createAPI('CreateApp', {
|
|
337
|
+
method: 'POST'
|
|
338
|
+
})(payload, axiosConfig),
|
|
339
|
+
DescribeLogApps: (payload)=>tlsService.createAPI('DescribeLogApps', {
|
|
340
|
+
method: 'GET'
|
|
341
|
+
})(payload, axiosConfig),
|
|
342
|
+
DescribeTemplates: (payload)=>tlsService.createAPI('DescribeTemplates', {
|
|
343
|
+
method: 'GET'
|
|
344
|
+
})(payload, axiosConfig)
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
async function ensureTemplateId(tlsService, options) {
|
|
348
|
+
if (options.templateId) return options.templateId;
|
|
349
|
+
const response = await tlsService.DescribeTemplates({
|
|
350
|
+
TemplateName: options.templateName,
|
|
351
|
+
PageNumber: 1,
|
|
352
|
+
PageSize: 20
|
|
353
|
+
});
|
|
354
|
+
const template = response.Templates?.find((item)=>item.TemplateName === options.templateName);
|
|
355
|
+
const templateId = String(template?.TemplateId || '').trim();
|
|
356
|
+
if (!templateId) throw new Error(`DescribeTemplates did not return TemplateId for ${options.templateName}. Pass --template-id or --trace-topic-id.`);
|
|
357
|
+
return templateId;
|
|
358
|
+
}
|
|
359
|
+
async function ensureProjectId(tlsService, options) {
|
|
360
|
+
if (options.projectId) return options.projectId;
|
|
361
|
+
const response = await tlsService.DescribeProjects({
|
|
362
|
+
ProjectName: options.projectName,
|
|
363
|
+
PageSize: 100,
|
|
364
|
+
PageNumber: 1
|
|
365
|
+
});
|
|
366
|
+
const project = response.Projects?.find((item)=>item.ProjectName === options.projectName);
|
|
367
|
+
const existingProjectId = String(project?.ProjectId || '').trim();
|
|
368
|
+
if (existingProjectId) return existingProjectId;
|
|
369
|
+
const created = await tlsService.CreateProject({
|
|
370
|
+
ProjectName: options.projectName,
|
|
371
|
+
Description: 'Pi observability',
|
|
372
|
+
Region: options.region
|
|
373
|
+
});
|
|
374
|
+
const projectId = String(created.ProjectId || '').trim();
|
|
375
|
+
if (!projectId) throw new Error('CreateProject succeeded but did not return ProjectId');
|
|
376
|
+
return projectId;
|
|
377
|
+
}
|
|
378
|
+
async function ensureLogApp(tlsService, options, projectId) {
|
|
379
|
+
if (options.logAppId) return options.logAppId;
|
|
380
|
+
const appResponse = await tlsService.DescribeApps({
|
|
381
|
+
AppName: options.logAppName,
|
|
382
|
+
AppType: 'LogApp'
|
|
383
|
+
});
|
|
384
|
+
const total = appResponse.total ?? appResponse.Total ?? 0;
|
|
385
|
+
if (total > 0) {
|
|
386
|
+
const app = appResponse.apps?.[0] || appResponse.Apps?.[0];
|
|
387
|
+
const logAppId = String(app?.Resources?.[0]?.Id || app?.Sources?.[0]?.Id || '').trim();
|
|
388
|
+
if (logAppId) return logAppId;
|
|
389
|
+
}
|
|
390
|
+
const templateId = await ensureTemplateId(tlsService, options);
|
|
391
|
+
const created = await tlsService.CreateApp({
|
|
392
|
+
AppName: options.logAppName,
|
|
393
|
+
AppType: 'LogApp',
|
|
394
|
+
LogAppReq: {
|
|
395
|
+
LogAppName: options.logAppName,
|
|
396
|
+
LogAppType: options.logAppType,
|
|
397
|
+
ProjectId: projectId
|
|
398
|
+
},
|
|
399
|
+
TemplateId: templateId
|
|
400
|
+
});
|
|
401
|
+
const logAppId = String(created.Sources?.[0]?.Id || '').trim();
|
|
402
|
+
if (!logAppId) throw new Error('CreateApp succeeded but did not return Sources[0].Id');
|
|
403
|
+
return logAppId;
|
|
404
|
+
}
|
|
405
|
+
function topicMapFromLogApps(response) {
|
|
406
|
+
const topics = response?.LogApps?.[0]?.RelatedResourceList || [];
|
|
407
|
+
const topicMap = {};
|
|
408
|
+
for (const topic of topics){
|
|
409
|
+
const resourceName = String(topic?.ResourceName || '');
|
|
410
|
+
const topicName = resourceName.split('_').filter(Boolean).at(-1);
|
|
411
|
+
const resourceId = String(topic?.ResourceID || '').trim();
|
|
412
|
+
if (topicName && resourceId) topicMap[topicName] = resourceId;
|
|
413
|
+
}
|
|
414
|
+
return topicMap;
|
|
415
|
+
}
|
|
416
|
+
async function ensureTlsResources(options) {
|
|
417
|
+
applyDerivedDefaults(options);
|
|
418
|
+
if (options.skipTlsConfig || options.dryRun || options.apiKey || options.traceTopicId || !options.ak || !options.sk) return {
|
|
419
|
+
created: false
|
|
420
|
+
};
|
|
421
|
+
const openapiModule = await loadOpenapiModule();
|
|
422
|
+
const tlsService = createTlsService(options, openapiModule);
|
|
423
|
+
const projectId = await ensureProjectId(tlsService, options);
|
|
424
|
+
const logAppId = await ensureLogApp(tlsService, options, projectId);
|
|
425
|
+
options.logAppId = logAppId;
|
|
426
|
+
const logApps = await tlsService.DescribeLogApps({
|
|
427
|
+
PageNumber: 1,
|
|
428
|
+
PageSize: 20,
|
|
429
|
+
LogAppId: logAppId,
|
|
430
|
+
LogAppType: options.logAppType
|
|
431
|
+
});
|
|
432
|
+
const topics = topicMapFromLogApps(logApps);
|
|
433
|
+
if (!options.traceTopicId) options.traceTopicId = topics.trace;
|
|
434
|
+
return {
|
|
435
|
+
created: true,
|
|
436
|
+
logAppId,
|
|
437
|
+
traceTopicId: options.traceTopicId
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
async function pathExists(filePath) {
|
|
441
|
+
try {
|
|
442
|
+
await __rspack_external_node_fs_promises_153e37e0.stat(filePath);
|
|
443
|
+
return true;
|
|
444
|
+
} catch (error) {
|
|
445
|
+
if ('ENOENT' === error.code) return false;
|
|
446
|
+
throw error;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
async function assertPluginRuntime(pluginSource) {
|
|
450
|
+
const entry = __rspack_external_node_path_c5b9b54f.join(pluginSource, 'dist', 'index.js');
|
|
451
|
+
const manifest = __rspack_external_node_path_c5b9b54f.join(pluginSource, 'package.json');
|
|
452
|
+
if (await pathExists(manifest) && await pathExists(entry)) return;
|
|
453
|
+
throw new Error(`Plugin package is missing runtime files: ${pluginSource}. Expected dist/index.js and package.json.`);
|
|
454
|
+
}
|
|
455
|
+
function pluginPackageSpec(options) {
|
|
456
|
+
const version = options.pluginVersion || (options.beta ? 'beta' : 'latest');
|
|
457
|
+
return `${options.pluginPackage}@${version}`;
|
|
458
|
+
}
|
|
459
|
+
function readLocalPluginSourceEnv() {
|
|
460
|
+
for (const key of LOCAL_PLUGIN_SOURCE_ENV_KEYS){
|
|
461
|
+
const value = readEnvString(key);
|
|
462
|
+
if (value) return {
|
|
463
|
+
key,
|
|
464
|
+
value
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
async function findLocalPluginSource() {
|
|
469
|
+
const explicit = readLocalPluginSourceEnv();
|
|
470
|
+
if (!explicit) return;
|
|
471
|
+
const manifest = await readJsonFile(__rspack_external_node_path_c5b9b54f.join(explicit.value, 'package.json'), {});
|
|
472
|
+
const publishDirectory = manifest.publishConfig?.directory;
|
|
473
|
+
const candidates = publishDirectory ? [
|
|
474
|
+
__rspack_external_node_path_c5b9b54f.join(explicit.value, publishDirectory)
|
|
475
|
+
] : [
|
|
476
|
+
explicit.value
|
|
477
|
+
];
|
|
478
|
+
for (const candidate of candidates)try {
|
|
479
|
+
await assertPluginRuntime(candidate);
|
|
480
|
+
return candidate;
|
|
481
|
+
} catch {}
|
|
482
|
+
throw new Error(`${explicit.key} does not point to a built Pi runtime package: ${explicit.value}. Run the plugin build first.`);
|
|
483
|
+
}
|
|
484
|
+
async function readPluginVersion(pluginSource) {
|
|
485
|
+
const manifest = await readJsonFile(__rspack_external_node_path_c5b9b54f.join(pluginSource, 'package.json'), {});
|
|
486
|
+
return manifest.version;
|
|
487
|
+
}
|
|
488
|
+
function piCliEnv(options) {
|
|
489
|
+
return {
|
|
490
|
+
...process.env,
|
|
491
|
+
npm_config_registry: options.registry,
|
|
492
|
+
NPM_CONFIG_REGISTRY: options.registry
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
function commandErrorDetail(error) {
|
|
496
|
+
if (error && 'object' == typeof error && 'stderr' in error) {
|
|
497
|
+
const stderr = String(error.stderr || '').trim();
|
|
498
|
+
if (stderr) return stderr;
|
|
499
|
+
}
|
|
500
|
+
return error instanceof Error ? error.message : String(error);
|
|
501
|
+
}
|
|
502
|
+
async function execPiCli(options, args) {
|
|
503
|
+
try {
|
|
504
|
+
await execFileAsync(options.piBin, args, {
|
|
505
|
+
env: piCliEnv(options)
|
|
506
|
+
});
|
|
507
|
+
} catch (error) {
|
|
508
|
+
if ('ENOENT' === error.code) throw new Error(`Pi CLI executable not found: ${options.piBin}. Install Pi CLI, make it available on PATH, or pass --pi-bin <path> / set PI_TLS_PI_BIN. The installer needs to run "${options.piBin} ${args.join(' ')}".`);
|
|
509
|
+
throw new Error(`Pi CLI command failed: ${options.piBin} ${args.join(' ')}\n${commandErrorDetail(error)}`);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
async function installPlugin(options) {
|
|
513
|
+
const localSource = await findLocalPluginSource();
|
|
514
|
+
const packageSpec = pluginPackageSpec(options);
|
|
515
|
+
const source = localSource || `npm:${packageSpec}`;
|
|
516
|
+
if (options.dryRun) return {
|
|
517
|
+
source,
|
|
518
|
+
target: source,
|
|
519
|
+
packageSpec: localSource ? void 0 : packageSpec,
|
|
520
|
+
version: localSource ? await readPluginVersion(localSource) : void 0,
|
|
521
|
+
dryRun: true
|
|
522
|
+
};
|
|
523
|
+
if (localSource) {
|
|
524
|
+
await execPiCli(options, [
|
|
525
|
+
'install',
|
|
526
|
+
localSource
|
|
527
|
+
]);
|
|
528
|
+
return {
|
|
529
|
+
source: localSource,
|
|
530
|
+
target: localSource,
|
|
531
|
+
version: await readPluginVersion(localSource)
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
await execPiCli(options, [
|
|
535
|
+
'install',
|
|
536
|
+
source
|
|
537
|
+
]);
|
|
538
|
+
return {
|
|
539
|
+
source,
|
|
540
|
+
target: source,
|
|
541
|
+
packageSpec
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
async function readJsonFile(filePath, fallback) {
|
|
545
|
+
try {
|
|
546
|
+
return JSON.parse(await __rspack_external_node_fs_promises_153e37e0.readFile(filePath, 'utf8'));
|
|
547
|
+
} catch (error) {
|
|
548
|
+
if ('ENOENT' === error.code) return fallback;
|
|
549
|
+
throw error;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
async function writeJsonFile(filePath, value, mode) {
|
|
553
|
+
await __rspack_external_node_fs_promises_153e37e0.mkdir(__rspack_external_node_path_c5b9b54f.dirname(filePath), {
|
|
554
|
+
recursive: true
|
|
555
|
+
});
|
|
556
|
+
if (mode) await __rspack_external_node_fs_promises_153e37e0.writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, {
|
|
557
|
+
mode
|
|
558
|
+
});
|
|
559
|
+
else await __rspack_external_node_fs_promises_153e37e0.writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
560
|
+
}
|
|
561
|
+
function envLine(key, value) {
|
|
562
|
+
if (null == value || '' === value) return;
|
|
563
|
+
return `${key}=${String(value)}`;
|
|
564
|
+
}
|
|
565
|
+
function buildTlsEnv(options) {
|
|
566
|
+
const lines = [
|
|
567
|
+
'# Generated by tls-observer-pi installer.',
|
|
568
|
+
'# Keep this file local because it can contain credentials.',
|
|
569
|
+
envLine('PI_TLS_REGION', options.region),
|
|
570
|
+
envLine('PI_TLS_ENDPOINT', options.tlsEndpoint),
|
|
571
|
+
envLine('PI_TLS_TRACE_TOPIC_ID', options.traceTopicId),
|
|
572
|
+
envLine('PI_TLS_API_KEY', options.apiKey),
|
|
573
|
+
envLine('PI_TLS_AK', options.ak),
|
|
574
|
+
envLine('PI_TLS_SK', options.sk),
|
|
575
|
+
envLine('PI_TLS_AUTH_MODE', options.authMode),
|
|
576
|
+
envLine('PI_TLS_EXPORT_TIMEOUT_MS', options.exportTimeoutMs),
|
|
577
|
+
envLine('PI_TLS_CAPTURE_CONTENT', options.captureContent),
|
|
578
|
+
envLine('PI_TLS_DATA_ROOT', options.dataRoot)
|
|
579
|
+
].filter(Boolean);
|
|
580
|
+
return `${lines.join('\n')}\n`;
|
|
581
|
+
}
|
|
582
|
+
async function writeTlsEnv(options) {
|
|
583
|
+
if (options.skipTlsConfig) return null;
|
|
584
|
+
const envTargetExists = await pathExists(options.envTarget);
|
|
585
|
+
if (envTargetExists && !options.force) throw new Error(`TLS env target exists: ${options.envTarget}. Re-run with --force.`);
|
|
586
|
+
await writeJsonFile(__rspack_external_node_path_c5b9b54f.join(options.dataRoot, 'state', 'install.json'), {
|
|
587
|
+
installed_at: new Date().toISOString(),
|
|
588
|
+
plugin_id: PLUGIN_PACKAGE_NAME,
|
|
589
|
+
log_app_id: options.logAppId,
|
|
590
|
+
env_target: options.envTarget
|
|
591
|
+
});
|
|
592
|
+
await __rspack_external_node_fs_promises_153e37e0.mkdir(__rspack_external_node_path_c5b9b54f.dirname(options.envTarget), {
|
|
593
|
+
recursive: true,
|
|
594
|
+
mode: 448
|
|
595
|
+
});
|
|
596
|
+
if (envTargetExists) {
|
|
597
|
+
await __rspack_external_node_fs_promises_153e37e0.chmod(options.envTarget, 384).catch(()=>void 0);
|
|
598
|
+
await __rspack_external_node_fs_promises_153e37e0.rm(options.envTarget, {
|
|
599
|
+
force: true
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
await __rspack_external_node_fs_promises_153e37e0.writeFile(options.envTarget, buildTlsEnv(options), {
|
|
603
|
+
flag: 'wx',
|
|
604
|
+
mode: 384
|
|
605
|
+
});
|
|
606
|
+
await __rspack_external_node_fs_promises_153e37e0.chmod(options.envTarget, 384);
|
|
607
|
+
return options.envTarget;
|
|
608
|
+
}
|
|
609
|
+
function printCompletion({ plugin, envTarget }) {
|
|
610
|
+
console.log('');
|
|
611
|
+
console.log(plugin.dryRun ? 'Dry run complete' : 'Install complete');
|
|
612
|
+
console.log(` Plugin: ${plugin.target}`);
|
|
613
|
+
if (plugin.packageSpec) console.log(` Plugin package: ${plugin.packageSpec}`);
|
|
614
|
+
if (plugin.version) console.log(` Plugin version: ${plugin.version}`);
|
|
615
|
+
console.log(` TLS env: ${envTarget || 'skipped'}`);
|
|
616
|
+
console.log('');
|
|
617
|
+
console.log('数据访问说明');
|
|
618
|
+
console.log('安装后,插件会读取 Pi 运行过程中的会话和生命周期事件');
|
|
619
|
+
console.log('用户请求、模型回复、工具调用记录和 token 用量会整理成诊断数据,上传到你配置的火山引擎 TLS');
|
|
620
|
+
console.log('如配置 API Key 或 AK/SK,凭据只写入本机 env 文件,用于上传鉴权');
|
|
621
|
+
console.log('');
|
|
622
|
+
console.log('Next steps:');
|
|
623
|
+
console.log(' 1. Restart Pi environment.');
|
|
624
|
+
console.log(' 2. Run one Pi turn.');
|
|
625
|
+
console.log(' 3. Check TLS Trace Topic for agent.turn.');
|
|
626
|
+
}
|
|
627
|
+
async function run(argv = process.argv.slice(2)) {
|
|
628
|
+
const parsed = parseCliOptions(argv);
|
|
629
|
+
if (parsed.help) return void printHelp();
|
|
630
|
+
const options = await collectInteractiveOptions(parsed);
|
|
631
|
+
if (!options.skipTlsConfig) {
|
|
632
|
+
const resourceResult = await ensureTlsResources(options);
|
|
633
|
+
if (resourceResult.created && !options.traceTopicId) throw new Error('TLS LogApp was created but trace topic discovery failed. Pass --trace-topic-id.');
|
|
634
|
+
applyDerivedDefaults(options);
|
|
635
|
+
validateTlsConfig(options);
|
|
636
|
+
}
|
|
637
|
+
const plugin = await installPlugin(options);
|
|
638
|
+
const envTarget = await writeTlsEnv(options);
|
|
639
|
+
printCompletion({
|
|
640
|
+
plugin,
|
|
641
|
+
envTarget
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
async function writeEnvFile(options) {
|
|
645
|
+
await writeTlsEnv(options);
|
|
646
|
+
}
|
|
647
|
+
const runInstaller = run;
|
|
648
|
+
const installPiPackage = installPlugin;
|
|
649
|
+
export { applyDerivedDefaults, buildTlsEnv, findLocalPluginSource, installPiPackage, installPlugin, parseCliOptions, pluginPackageSpec, run, runInstaller, validateBaseTlsConfig, validateTlsConfig, writeEnvFile, writeTlsEnv };
|