-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·1768 lines (1627 loc) · 66.8 KB
/
Copy pathcli.js
File metadata and controls
executable file
·1768 lines (1627 loc) · 66.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* ai-otel-setup
*
* 一行命令配置 Claude Code OTel 上报:
* npx -y ai-otel-setup url=COLLECTOR_HOST
*
* 该 installer **不走 CC plugin 机制**:直接把 hook 脚本铺到
* ~/.claude/cc-otel/,并把 12 个 OTel env + SessionStart hook 注入
* 用户的 ~/.claude/settings.json。安装后 `claude` 立即生效,无需 /plugin install。
*
* 关键约束:
* - 失败时尽量给出可操作信息,不静默
* - settings.json 写之前会备份到 settings.json.bak(每次覆盖,仅保留上一份)
* - 多次运行幂等(按 hook id=team:session-start 去重)
* - 不依赖任何运行时第三方包,只用 Node 标准库
*/
"use strict";
const fs = require("fs");
const path = require("path");
const os = require("os");
const net = require("net");
const crypto = require("crypto");
const { execFileSync, spawn, spawnSync } = require("child_process");
const PKG_VERSION = require("./package.json").version;
// 安装时这台机器的 node 绝对路径,POSIX 上拿来构造 hook command 用。
// Windows 上不再写 node 绝对路径(见 buildHookCommand 注释)。
const NODE_BIN = process.execPath;
// 跨平台 hook 命令构造。
//
// **Windows 上的关键决策(v1.0.9 重构)**:不再写 node 绝对路径,也不再加引号,
// 让 shell 自己按空白 split + 用 PATH lookup node。原因:
// - 写绝对路径如 "C:\Program Files\nodejs\node.exe",PowerShell 5.1(cc/gemini
// 在 Windows 默认 shell)解析时会把外层引号脱掉,按空白把 "C:\Program" 切成
// 一个 token,"Files\nodejs\..." 切成另一个,hook 进程起不来,exit code 1。
// - 用 8.3 短路径 (C:\Progra~1\...) 在 NTFS 8dot3name 禁用的卷上失效,
// 更糟的是 cmd /c for 在某些 locale 下输出会带额外引号,被 installer
// 二次拼装成 ""\"C:\\\"C:\\Program Files\\nodejs\\node.exe\\\"\"" 这种
// 非法嵌套,比原 bug 更难修。
// - 改写 wrapper .cmd / .sh 让用户用别的 shell 接管 → 整体复杂度+30 行,
// 而且 wrapper 路径本身仍可能带空格,治标不治本。
//
// 务实最稳的解:让 shell 自己 PATH 找 node;两个 JS 路径作为 node 参数传入。
// Windows 下统一把反斜杠改成正斜杠:
// - cmd / PowerShell / Node 都能识别 C:/Users/... 路径
// - Git Bash / bash 不会再把 C:\Users\... 里的反斜杠当转义字符吃掉
// 参数路径加双引号,兼容用户名含空格的常见场景。
//
// launch-hook.js 内部还会再做一次 PATH 上探 node、失败时 fallback baked
// execPath 的兜底,所以 PATH 上 node 临时失踪也能起来。
//
// POSIX:保持 quoted 三段格式,shell 行为统一,路径有空格也安全。
function windowsNodeArg(p) {
return `"${String(p).replace(/\\/g, "/")}"`;
}
function buildHookCommand(launcherPath, scriptPath) {
if (process.platform === "win32") {
return `node ${windowsNodeArg(launcherPath)} ${windowsNodeArg(scriptPath)}`;
}
return `"${NODE_BIN}" "${launcherPath}" "${scriptPath}"`;
}
// 把 launcher 模板拷到 hook 同目录,返回 launcher 的绝对路径
function installLauncher(installDir) {
const launcherDest = path.join(installDir, "launch-hook.js");
fs.copyFileSync(path.join(__dirname, "templates", "launch-hook.js"), launcherDest);
fs.chmodSync(launcherDest, 0o755);
fs.copyFileSync(path.join(__dirname, "templates", "logging.js"), path.join(installDir, "logging.js"));
return launcherDest;
}
function writeInstallLog(installDir, tool, endpoint, otelTransport) {
try {
const { logEvent } = require(path.join(installDir, "logging.js"));
logEvent("installer_complete", {
tool,
installerVersion: PKG_VERSION,
endpoint: displayEndpoint(endpoint),
otelTransport,
});
} catch (_) {
// Logging must never break installation.
}
}
const REQUIRED_KEYS = ["url"];
const HOOK_ID = "team:session-start";
// UserPromptSubmit 兜底 hook:复用同一脚本,靠 stdin.hook_event_name 分流;
// 单独 id 是为了让 settings.json 的 SessionStart / UserPromptSubmit 数组各自能按 id 去重
const PROMPT_HOOK_ID = "team:user-prompt-submit";
// Stop hook:CC 每轮返回结束触发,灰度场景用来发 git_snapshot session_end;
// 仍复用 on-session-start.js(按 hook_event_name=Stop 分流),便于幂等去重
const STOP_HOOK_ID = "team:stop";
const OTEL_KEYS = [
"CLAUDE_CODE_ENABLE_TELEMETRY",
"OTEL_METRICS_EXPORTER",
"OTEL_LOGS_EXPORTER",
"OTEL_EXPORTER_OTLP_PROTOCOL",
"OTEL_EXPORTER_OTLP_ENDPOINT",
"OTEL_EXPORTER_OTLP_LOGS_PROTOCOL",
"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
"OTEL_EXPORTER_OTLP_METRICS_PROTOCOL",
"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
"OTEL_LOGS_EXPORT_INTERVAL",
"OTEL_METRIC_EXPORT_INTERVAL",
"OTEL_METRICS_INCLUDE_VERSION",
"OTEL_LOG_USER_PROMPTS",
"OTEL_LOG_TOOL_DETAILS",
"OTEL_LOG_TOOL_CONTENT",
"OTEL_LOG_RAW_API_BODIES",
];
// ---------- argv 解析 ----------
function parseArgs(argv) {
const out = {};
const flat = [];
for (const a of argv) {
if (/^--?[a-z][a-z0-9-]*$/i.test(a)) {
flat.push(a.replace(/^--?/, "") + "=true");
continue;
}
// 兼容 url=x 单 argv 与 url=x 多 argv(保留逗号分隔,便于未来扩展)
for (const part of a.split(",")) {
if (part.trim()) flat.push(part.trim());
}
}
for (const part of flat) {
const idx = part.indexOf("=");
if (idx <= 0) continue;
const k = part.slice(0, idx).trim().toLowerCase();
const v = part.slice(idx + 1).trim();
if (k) out[k] = v;
}
return out;
}
function validateArgs(args) {
const errs = [];
if (truthyFlag(args.http) && truthyFlag(args.grpc)) {
errs.push("--http 与 --grpc 不能同时使用");
}
if (
Object.prototype.hasOwnProperty.call(args, "beta") ||
Object.prototype.hasOwnProperty.call(args, "full-upload") ||
Object.prototype.hasOwnProperty.call(args, "--beta") ||
Object.prototype.hasOwnProperty.call(args, "--full-upload") ||
Object.prototype.hasOwnProperty.call(args, "-beta") ||
Object.prototype.hasOwnProperty.call(args, "-full-upload")
) {
errs.push("--beta / --full-upload 已不再支持:全量数据上报默认开启;如需关闭请使用 --no-full-upload");
}
for (const k of REQUIRED_KEYS) {
if (!args[k]) {
errs.push(`missing required: ${k}`);
continue;
}
if (/\s/.test(args[k])) errs.push(`${k} 不允许包含空格: "${args[k]}"`);
if (args[k].includes(",")) errs.push(`${k} 不允许包含逗号: "${args[k]}"`);
}
return errs;
}
function truthyFlag(value) {
if (value === true) return true;
return /^(1|true|yes|on)$/i.test(String(value || ""));
}
function resolveOtelTransport(args) {
if (truthyFlag(args.http)) return "http";
if (truthyFlag(args.grpc)) return "grpc";
return "http";
}
function normalizeOptionalUrl(raw) {
const value = String(raw || "").trim();
if (!value) return "";
return value.replace(/\/+$/, "");
}
function normalizeOptionalTag(raw) {
const value = String(raw || "").trim();
if (!value) return "";
return value;
}
function deriveRawUploadHost(hostname) {
const host = String(hostname || "").replace(/^\[|\]$/g, "");
if (!host || isIpHost(host) || isLocalHost(host)) return host;
const parts = host.split(".");
if (!parts.length) return host;
if (parts[0].endsWith("-raw-upload")) {
parts[0] = parts[0].replace(/-raw-upload$/, "-upload");
} else if (!parts[0].endsWith("-upload")) {
parts[0] = `${parts[0]}-upload`;
}
return parts.join(".");
}
// local-usage-scanner POST 目标:直接从主 endpoint 派生,独立于 rawUploadUrl
// (历史上 v1.0.31 用 rawUploadUrl 派生 + 端口 8082,导致没传 mongoGrayTag/upload-token 时
// rawUploadUrl 为空 → localUsageUrl 也为空 → scanner 静默 skip。v1.0.32 解耦,让全量装机都可用。)
//
// 派生规则:
// - 域名应用 deriveRawUploadHost 改写(ai-otel.xxx → ai-otel-upload.xxx,与 rawUpload 同 host)
// - 非 IP / 非 localhost:清掉端口(走 ingress 默认 443/80,服务端 8090 在 ingress 后面)
// - IP / localhost:端口固定 8090(直连 raw-upload-server listener,与生产 ingress 同 port)
// - 路径固定 /v1/local-usage
function deriveLocalUsageUrl(endpoint) {
try {
const u = new URL(logsEndpointFromGrpc(endpoint));
u.hostname = deriveRawUploadHost(u.hostname);
if (!isIpHost(u.hostname) && !isLocalHost(u.hostname)) {
u.port = "";
} else {
u.port = "8090";
}
u.pathname = "/v1/local-usage";
u.search = "";
u.hash = "";
return u.toString().replace(/\/+$/, "");
} catch (_) {
return "";
}
}
function rawUploadUrlFromEndpoint(endpoint) {
try {
const logsUrl = new URL(logsEndpointFromGrpc(endpoint));
logsUrl.hostname = deriveRawUploadHost(logsUrl.hostname);
if (!isIpHost(logsUrl.hostname) && !isLocalHost(logsUrl.hostname)) {
logsUrl.port = "";
}
logsUrl.pathname = "/v1/raw-bodies";
logsUrl.search = "";
logsUrl.hash = "";
return logsUrl.toString().replace(/\/+$/, "");
} catch (_) {
return "";
}
}
// ---------- url → endpoint ----------
function isIpHost(host) {
return net.isIP(String(host || "").replace(/^\[|\]$/g, "")) !== 0;
}
function isLocalHost(host) {
const value = String(host || "").replace(/^\[|\]$/g, "").toLowerCase();
return value === "localhost" || value === "127.0.0.1" || value === "::1";
}
function bracketIpv6Host(host) {
const normalized = String(host || "").replace(/^\[|\]$/g, "");
return normalized.includes(":") ? `[${normalized}]` : normalized;
}
function formatRootUrl(protocol, host, port) {
return `${protocol}//${bracketIpv6Host(host)}${port ? ":" + port : ""}`;
}
function resolveEndpoint(rawUrl) {
const input = String(rawUrl || "").trim();
// 用户传完整 URL:保留显式 protocol/port/path;仅在未写 port 时按 IP/域名补默认 gRPC 端口。
if (/^https?:\/\//i.test(input)) {
const url = new URL(input);
if (!url.port) url.port = isIpHost(url.hostname) ? "4317" : "24317";
if (url.pathname === "/" && !url.search && !url.hash) {
return formatRootUrl(url.protocol, url.hostname, url.port);
}
return url.toString();
}
// 用户传裸地址:
// - IP:本地/内网测试形态,OTLP/gRPC = http://IP:4317
// - 域名:生产公网形态,OTLP/gRPC = https://DOMAIN:24317
// 判断只看地址形态,不写入任何具体 host。
const url = new URL(`http://${input}`);
const localOrIp = isIpHost(url.hostname) || isLocalHost(url.hostname);
const port = url.port || (localOrIp ? "4317" : "24317");
return formatRootUrl(localOrIp ? "http:" : "https:", url.hostname, port);
}
function httpRootEndpointFromLogs(logsEndpoint) {
const url = new URL(logsEndpoint);
url.pathname = "/";
url.search = "";
url.hash = "";
return url.origin;
}
function metricsEndpointFromLogs(logsEndpoint) {
const url = new URL(logsEndpoint);
url.pathname = "/v1/metrics";
url.search = "";
url.hash = "";
return url.toString();
}
function tracesEndpointFromLogs(logsEndpoint) {
const url = new URL(logsEndpoint);
url.pathname = "/v1/traces";
url.search = "";
url.hash = "";
return url.toString();
}
function extractHost(endpoint) {
// 从已 resolve 的 endpoint 取 host(不带端口),用于 NO_PROXY
try {
return new URL(endpoint).hostname;
} catch (_) {
return endpoint.replace(/^https?:\/\//i, "").split("/")[0].split(":")[0];
}
}
function displayEndpoint(endpoint) {
try {
const url = new URL(endpoint);
if (!isIpHost(url.hostname)) {
// 生产域名的真实 gRPC 端口只写入配置,不在安装完成日志里暴露。
url.port = "";
if (url.pathname === "/" && !url.search && !url.hash) return url.origin;
return url.toString();
}
} catch (_) {
// 展示失败时沿用原值,不影响安装。
}
return endpoint;
}
function appendNoProxyUrlEntries(entries, endpoint) {
try {
const url = new URL(endpoint);
if (!entries.includes(url.hostname)) entries.push(url.hostname);
const port = url.port || (url.protocol === "https:" ? "443" : url.protocol === "http:" ? "80" : "");
const hostPort = port ? `${url.hostname}:${port}` : "";
if (hostPort && !entries.includes(hostPort)) entries.push(hostPort);
} catch (_) {
const host = extractHost(endpoint);
if (host && !entries.includes(host)) entries.push(host);
}
}
function buildNoProxyEntries(endpoint, otelTransport) {
const entries = [];
appendNoProxyUrlEntries(entries, endpoint);
if (otelTransport === "http") {
appendNoProxyUrlEntries(entries, logsEndpointFromGrpc(endpoint));
}
return entries;
}
function mergeNoProxy(existing, entries) {
// 合并保留用户已有 NO_PROXY 值,仅追加 collector host,去重保序
const list = (existing || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
for (const entry of entries || []) {
if (entry && !list.includes(entry)) list.push(entry);
}
return list.join(",");
}
// ---------- git config 兜底 (跨平台) ----------
//
// hook 进程偶有"压根没跑"的场景(网络/超时/进程崩溃),导致 git.user.email/name 永久丢失。
// 装机时把全局 git config 写到 OTEL_RESOURCE_ATTRIBUTES,CC SDK 自动把 resource attr
// 带到每条 metric/log,service 端在 SessionStore miss 时用它兜底(参见 translator.js
// 的 RESOURCE_FALLBACK_KEYS)。
//
// 跨平台细节:
// - execFileSync(cmd, args):不经过 shell,Win/Mac 行为一致
// - windowsHide:true:Windows 上不弹 cmd 黑窗
// - stdio[2]="ignore":屏蔽 stderr,避免 git 报错刷屏
// - timeout:1000:超时直接当成"读不到",不让 installer 卡住
// - ENOENT (git 没装) / 退出码非 0 (key 没设) 都吞掉返回空串
function readGlobalGitUser() {
function readGitVal(key) {
try {
return execFileSync("git", ["config", "--global", "--get", key], {
encoding: "utf8",
windowsHide: true,
timeout: 1000,
stdio: ["ignore", "pipe", "ignore"],
}).trim();
} catch (_) {
return "";
}
}
return {
name: readGitVal("user.name"),
email: readGitVal("user.email"),
};
}
// ---------- 装机上报:走同一条 OTel 管线 ----------
//
// 历史:原 POST 到 cc-view-server :8081/api/installer/report 直写 Doris。
// otel-prod 部署到公网、cc-view-web 留在内网后,installer 只能跟 OTel collector
// 说话;改成发一条 OTLP/HTTP log(event.name = installer_register),由 forwarder
// 走同一条管线落到 iData,cc-view-server 端从事件表 reduce 出装机记录。
// 这样 installer 命令依旧只暴露一个 url,跟数据上报完全同源。
//
// 设计原则:
// - fire-and-forget:2.5s 超时、不重试、任何失败绝不让安装本身退出非 0
// - 复用 logsEndpointFromGrpc:4317 → 4318,path 自动补 /v1/logs
// - debug 模式下才打错误,正常运行不污染 stdout
function postJsonWithTimeout(targetUrl, payload, timeoutMs) {
return new Promise((resolve, reject) => {
let u;
try {
u = new URL(targetUrl);
} catch (e) {
return reject(e);
}
const isHttps = u.protocol === "https:";
const lib = isHttps ? require("https") : require("http");
const body = Buffer.from(JSON.stringify(payload), "utf8");
const req = lib.request(
{
method: "POST",
hostname: u.hostname,
port: u.port || (isHttps ? 443 : 80),
path: (u.pathname || "/") + (u.search || ""),
headers: {
"Content-Type": "application/json",
"Content-Length": body.length,
},
timeout: timeoutMs,
},
(res) => {
// 排空 body,让 socket 进入 keepalive/释放
res.on("data", () => {});
res.on("end", () => resolve(res.statusCode || 0));
res.on("error", reject);
}
);
req.on("error", reject);
req.on("timeout", () => {
req.destroy(new Error("timeout"));
});
req.write(body);
req.end();
});
}
async function reportInstall(otelEndpoint, gitUser, allResults, debug, fullUpload) {
if (!gitUser || !gitUser.email) {
if (debug) console.error("[ai-otel-setup] 跳过装机上报:无 git user.email");
return;
}
const logsUrl = logsEndpointFromGrpc(otelEndpoint);
if (!logsUrl) return;
const findOk = (tool) =>
allResults.find((r) => r.tool === tool)?.status === "installed";
// OTLP/HTTP log record。translator (lib/translate/installer_register.js) 按
// event.name = "installer_register" 路由到对应 eid,把 git.user.* / hostname
// 经 contextBlocksFromAttrs 落进 user 块,installer_* / os_* / node_version /
// *_cli_detected 走 phase1UdmapFields 白名单进 udmap。
const sessionId = `installer-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const attrs = {
"tool_kind": "installer",
"event.name": "installer_register",
"event.timestamp": new Date().toISOString(),
"session.id": sessionId,
"git.user.email": gitUser.email,
"git.user.name": gitUser.name || "",
"hostname": os.hostname() || "",
"installer_version": PKG_VERSION,
"os_platform": os.platform(),
"os_arch": os.arch(),
"node_version": process.version,
"cc_cli_detected": findOk("claude") ? "1" : "0",
"codex_cli_detected": findOk("codex") ? "1" : "0",
"full_upload": fullUpload ? "1" : "0",
};
const payload = {
resourceLogs: [
{
resource: { attributes: [] },
scopeLogs: [
{
logRecords: [
{
timeUnixNano: `${Date.now()}000000`,
body: { stringValue: "installer_register" },
attributes: Object.entries(attrs).map(([k, v]) => ({
key: k,
value: { stringValue: String(v ?? "") },
})),
},
],
},
],
},
],
};
try {
await postJsonWithTimeout(logsUrl, payload, 2500);
if (debug) console.error("[ai-otel-setup] 装机上报已发送 →", logsUrl);
} catch (e) {
if (debug) {
console.error("[ai-otel-setup] 装机上报失败(不影响安装):", e.message || e);
}
}
}
// ---------- OTEL_RESOURCE_ATTRIBUTES (W3C baggage 风格) ----------
// "k1=urlencoded,k2=urlencoded2" → { k1: "decoded", k2: "decoded2" }
function parseResourceAttrs(s) {
const out = {};
if (!s || typeof s !== "string") return out;
for (const pair of s.split(",")) {
const idx = pair.indexOf("=");
if (idx <= 0) continue;
const k = pair.slice(0, idx).trim();
if (!k) continue;
const raw = pair.slice(idx + 1).trim();
try {
out[k] = decodeURIComponent(raw);
} catch (_) {
out[k] = raw; // decode 失败原样保留,不抛
}
}
return out;
}
function serializeResourceAttrs(obj) {
const parts = [];
for (const [k, v] of Object.entries(obj)) {
if (v === "" || v === null || v === undefined) continue;
parts.push(`${k}=${encodeURIComponent(v)}`);
}
return parts.join(",");
}
// parse-merge-serialize:保留用户自定义 attr(如 region=us-east),仅注入/覆盖 git.user.*
function mergeResourceAttrs(existing, gitUser) {
const attrs = parseResourceAttrs(existing || "");
if (gitUser.email) attrs["git.user.email"] = gitUser.email;
if (gitUser.name) attrs["git.user.name"] = gitUser.name;
attrs["installer_version"] = PKG_VERSION; // CC SDK 自动挂到每条 native OTel 事件的 resource attr
return serializeResourceAttrs(attrs);
}
// ---------- 文件操作 ----------
function readJSONSafe(p) {
try {
if (!fs.existsSync(p)) return {};
const txt = fs.readFileSync(p, "utf8");
if (!txt.trim()) return {};
return JSON.parse(txt);
} catch (e) {
throw new Error(`读取 ${p} 失败:${e.message}`);
}
}
function writeJSONAtomic(p, obj) {
const dir = path.dirname(p);
fs.mkdirSync(dir, { recursive: true });
const tmp = `${p}.tmp.${process.pid}`;
fs.writeFileSync(tmp, JSON.stringify(obj, null, 2) + "\n", "utf8");
fs.renameSync(tmp, p);
}
function backup(p) {
if (!fs.existsSync(p)) return null;
const bak = `${p}.bak`;
fs.copyFileSync(p, bak);
return bak;
}
function removeSessionSeenMarkers(installDir) {
try {
if (!fs.existsSync(installDir)) return 0;
let count = 0;
for (const name of fs.readdirSync(installDir)) {
if (!name.startsWith(".session-seen.")) continue;
try {
fs.unlinkSync(path.join(installDir, name));
count++;
} catch (_) {
// Best effort cleanup.
}
}
return count;
} catch (_) {
return 0;
}
}
// ---------- 合并逻辑 ----------
function buildEnv(template, args, endpoint, otelTransport, rawBodiesDir, fullUpload) {
const env = { ...template.env };
if (otelTransport === "http") {
const logsEndpoint = logsEndpointFromGrpc(endpoint);
env.OTEL_EXPORTER_OTLP_PROTOCOL = "http/protobuf";
env.OTEL_EXPORTER_OTLP_ENDPOINT = httpRootEndpointFromLogs(logsEndpoint);
env.OTEL_EXPORTER_OTLP_LOGS_PROTOCOL = "http/protobuf";
env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT = logsEndpoint;
env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL = "http/protobuf";
env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT = metricsEndpointFromLogs(logsEndpoint);
} else {
env.OTEL_EXPORTER_OTLP_ENDPOINT = endpoint;
}
// fullUpload 默认开启;显式 --no-full-upload 时由 settings.template.json 的安全默认值兜底
// (USER_PROMPTS=0 / TOOL_CONTENT=0 / 不写 RAW_API_BODIES)。
// OTEL_KEYS 在 mergeSettings 里走 "has → overwrite,没有 → delete" 语义,所以
// 切回非 fullUpload 时上一轮残留的 RAW_API_BODIES 会被自动清掉。
if (fullUpload) {
env.OTEL_LOG_USER_PROMPTS = "1";
env.OTEL_LOG_TOOL_CONTENT = "1";
env.OTEL_LOG_RAW_API_BODIES = `file:${rawBodiesDir}`;
}
// OTEL_RESOURCE_ATTRIBUTES 由 mergeSettings 单独处理(parse-merge 用户已有 + 注入 git.user.*)
return env;
}
function mergeSettings(existing, newEnv, hookEntry, promptHookEntry, stopHookEntry, noProxyEntries, gitUser, machineId, fullUpload) {
const merged = { ...existing };
// env:plugin 优先(组织规范不允许个人改红线),但保留用户独有的 env
merged.env = { ...(existing.env || {}) };
for (const k of OTEL_KEYS) {
if (Object.prototype.hasOwnProperty.call(newEnv, k)) merged.env[k] = newEnv[k];
else delete merged.env[k];
}
// OTEL_RESOURCE_ATTRIBUTES:parse-merge 用户已有 attr + 注入 git.user.email/name。
// 不进 OTEL_KEYS(OTEL_KEYS 走 overwrite,会丢掉用户自定义如 region=us-east)。
// 只在 readGlobalGitUser 拿到非空值时写;全空时保持用户已有值不动(包括不删)。
if (gitUser && (gitUser.name || gitUser.email)) {
const ra = mergeResourceAttrs(merged.env.OTEL_RESOURCE_ATTRIBUTES, gitUser);
if (ra) merged.env.OTEL_RESOURCE_ATTRIBUTES = ra;
}
if (machineId) {
const attrs = parseResourceAttrs(merged.env.OTEL_RESOURCE_ATTRIBUTES || "");
attrs["ai_otel.machine_id"] = machineId;
// 全量上报开启:写 ai_otel.mongo_gray=beta(服务端 mongo-full sink 当前仍按此 attr
// 过滤,故 attr 名暂保留)。关闭:显式 delete,让 --no-full-upload 能彻底卸下。
if (fullUpload) attrs["ai_otel.mongo_gray"] = "beta";
else delete attrs["ai_otel.mongo_gray"];
merged.env.OTEL_RESOURCE_ATTRIBUTES = serializeResourceAttrs(attrs);
}
// 兜底用户写坏的 HTTP(S)_PROXY:把 collector host 与 host:port 加进 NO_PROXY,让 OTel gRPC 绕过代理
// 仅追加,不动用户原有的 NO_PROXY 值,也不动 HTTP_PROXY / HTTPS_PROXY
if (noProxyEntries && noProxyEntries.length) {
merged.env.NO_PROXY = mergeNoProxy(merged.env.NO_PROXY, noProxyEntries);
merged.env.no_proxy = mergeNoProxy(merged.env.no_proxy, noProxyEntries);
}
merged.hooks = { ...(existing.hooks || {}) };
const isManagedClaudeHook = (h, expectedId) => {
if (!h) return false;
if (h.id === expectedId) return true;
const hooks = Array.isArray(h.hooks) ? h.hooks : [];
return hooks.some((item) => {
const command = String(item && item.command ? item.command : "");
return command.includes("cc-otel") && command.includes("launch-hook.js") && command.includes("on-session-start.js");
});
};
// hooks.SessionStart:按 id 去重,存在则覆盖,不存在则追加
const sessionStart = Array.isArray(merged.hooks.SessionStart)
? [...merged.hooks.SessionStart]
: [];
const keptSessionStart = sessionStart.filter((h) => !isManagedClaudeHook(h, HOOK_ID));
keptSessionStart.push(hookEntry);
merged.hooks.SessionStart = keptSessionStart;
// hooks.UserPromptSubmit:兜底 hook,按 PROMPT_HOOK_ID 去重,规则同上
if (promptHookEntry) {
const userPromptSubmit = Array.isArray(merged.hooks.UserPromptSubmit)
? [...merged.hooks.UserPromptSubmit]
: [];
const keptUserPromptSubmit = userPromptSubmit.filter((h) => !isManagedClaudeHook(h, PROMPT_HOOK_ID));
keptUserPromptSubmit.push(promptHookEntry);
merged.hooks.UserPromptSubmit = keptUserPromptSubmit;
}
// hooks.Stop:每轮返回结束触发,灰度发 git_snapshot session_end,按 STOP_HOOK_ID 去重
if (stopHookEntry) {
const stop = Array.isArray(merged.hooks.Stop)
? [...merged.hooks.Stop]
: [];
const keptStop = stop.filter((h) => !isManagedClaudeHook(h, STOP_HOOK_ID));
keptStop.push(stopHookEntry);
merged.hooks.Stop = keptStop;
}
return merged;
}
function logsEndpointFromGrpc(endpoint) {
try {
const grpcUrl = new URL(endpoint);
const localOrIp = isIpHost(grpcUrl.hostname) || isLocalHost(grpcUrl.hostname);
const logsUrl = new URL(`${localOrIp ? "http:" : "https:"}//${bracketIpv6Host(grpcUrl.hostname)}`);
if (localOrIp) {
logsUrl.port = !grpcUrl.port || grpcUrl.port === "4317" ? "4318" : grpcUrl.port;
} else if (grpcUrl.port && grpcUrl.port !== "24317") {
logsUrl.port = grpcUrl.port;
}
logsUrl.pathname =
!grpcUrl.pathname || grpcUrl.pathname === "/" ? "/v1/logs" : grpcUrl.pathname;
logsUrl.search = grpcUrl.search;
return logsUrl.toString();
} catch (_) {
return "http://localhost:4318/v1/logs";
}
}
function buildEndpointConfig(endpoint, otelTransport) {
return {
endpoint,
logsEndpoint: logsEndpointFromGrpc(endpoint),
otelTransport,
installerVersion: PKG_VERSION,
packageName: "ai-otel-setup",
};
}
function getOrCreateMachineId(installDir) {
const p = path.join(installDir, "machine-id");
try {
if (fs.existsSync(p)) {
const existing = fs.readFileSync(p, "utf8").trim();
if (existing) return existing;
}
} catch (_) {
// Regenerate below.
}
const id = crypto.randomUUID();
fs.mkdirSync(installDir, { recursive: true });
fs.writeFileSync(p, id + "\n", { mode: 0o600 });
return id;
}
function buildFullEndpointConfig(endpoint, otelTransport, extra = {}) {
return {
...buildEndpointConfig(endpoint, otelTransport),
...extra,
};
}
function installRawUploader(installDir, uploadToken) {
const uploaderDir = path.join(installDir, "raw-uploader");
fs.mkdirSync(uploaderDir, { recursive: true });
const uploaderDest = path.join(installDir, "raw-body-uploader.js");
fs.copyFileSync(path.join(__dirname, "templates", "raw-body-uploader.js"), uploaderDest);
fs.chmodSync(uploaderDest, 0o755);
const tokenPath = path.join(installDir, "raw-upload-token");
if (uploadToken) {
fs.writeFileSync(tokenPath, String(uploadToken).trim() + "\n", { mode: 0o600 });
} else if (fs.existsSync(tokenPath)) {
fs.unlinkSync(tokenPath);
}
}
function launchctlPath() {
try {
return execFileSync("/usr/bin/which", ["launchctl"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
timeout: 1000,
}).trim();
} catch (_) {
return "";
}
}
function installMacRawUploaderTimer(installDir) {
if (process.platform !== "darwin") return { status: "skipped" };
const launchctl = launchctlPath();
if (!launchctl) return { status: "skipped", reason: "launchctl not found" };
const agentsDir = path.join(os.homedir(), "Library", "LaunchAgents");
fs.mkdirSync(agentsDir, { recursive: true });
const plistPath = path.join(agentsDir, "com.ai-otel.raw-uploader.plist");
const uploaderPath = path.join(installDir, "raw-body-uploader.js");
const plist = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.ai-otel.raw-uploader</string>
<key>ProgramArguments</key>
<array>
<string>${escapeXml(NODE_BIN)}</string>
<string>${escapeXml(uploaderPath)}</string>
<string>--once</string>
<string>--max-runtime=25</string>
</array>
<key>StartInterval</key>
<integer>60</integer>
<key>RunAtLoad</key>
<true/>
<key>StandardOutPath</key>
<string>${escapeXml(path.join(installDir, "raw-uploader.out.log"))}</string>
<key>StandardErrorPath</key>
<string>${escapeXml(path.join(installDir, "raw-uploader.err.log"))}</string>
</dict>
</plist>
`;
fs.writeFileSync(plistPath, plist, "utf8");
try {
spawnSync(launchctl, ["unload", plistPath], {
stdio: "ignore",
timeout: 3000,
});
} catch (_) {}
const r = spawnSync(launchctl, ["load", plistPath], {
stdio: "ignore",
timeout: 3000,
});
return {
status: r.status === 0 ? "installed" : "written",
path: plistPath,
};
}
function systemdQuoteArg(arg) {
return `"${String(arg).replace(/(["\\$`])/g, "\\$1")}"`;
}
function installLinuxRawUploaderTimer(installDir) {
if (process.platform !== "linux") return { status: "skipped" };
const systemctl = (() => {
try {
return execFileSync("/usr/bin/which", ["systemctl"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
timeout: 1000,
}).trim();
} catch (_) {
return "";
}
})();
const uploaderPath = path.join(installDir, "raw-body-uploader.js");
const unitName = "ai-otel-raw-uploader";
const userSystemdDir = path.join(os.homedir(), ".config", "systemd", "user");
const servicePath = path.join(userSystemdDir, `${unitName}.service`);
const timerPath = path.join(userSystemdDir, `${unitName}.timer`);
if (systemctl) {
fs.mkdirSync(userSystemdDir, { recursive: true });
const service = `[Unit]
Description=AI OTEL raw body uploader
[Service]
Type=oneshot
ExecStart=${systemdQuoteArg(NODE_BIN)} ${systemdQuoteArg(uploaderPath)} --once --max-runtime=25
`;
const timer = `[Unit]
Description=Run AI OTEL raw body uploader every minute
[Timer]
OnBootSec=30s
OnUnitActiveSec=60s
Unit=${unitName}.service
[Install]
WantedBy=timers.target
`;
fs.writeFileSync(servicePath, service, "utf8");
fs.writeFileSync(timerPath, timer, "utf8");
try {
spawnSync(systemctl, ["--user", "daemon-reload"], { stdio: "ignore", timeout: 5000 });
spawnSync(systemctl, ["--user", "enable", "--now", `${unitName}.timer`], {
stdio: "ignore",
timeout: 8000,
});
return { status: "installed", path: timerPath };
} catch (_) {
// Fall through to crontab fallback below.
}
}
const crontab = (() => {
try {
return execFileSync("/usr/bin/which", ["crontab"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
timeout: 1000,
}).trim();
} catch (_) {
return "";
}
})();
if (!crontab) return { status: "written", reason: "systemctl/crontab not found" };
const cronMarker = "# ai-otel-raw-uploader";
const cronLine = `* * * * * ${systemdQuoteArg(NODE_BIN)} ${systemdQuoteArg(uploaderPath)} --once --max-runtime=25 >/dev/null 2>&1 ${cronMarker}`;
let existing = "";
try {
existing = execFileSync(crontab, ["-l"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
timeout: 3000,
});
} catch (_) {
existing = "";
}
const lines = existing
.split(/\r?\n/)
.map((line) => line.trimEnd())
.filter((line) => line && !line.includes(cronMarker));
lines.push(cronLine);
const payload = lines.join("\n") + "\n";
const r = spawnSync(crontab, ["-"], {
input: payload,
encoding: "utf8",
stdio: ["pipe", "ignore", "ignore"],
timeout: 5000,
});
return {
status: r.status === 0 ? "installed" : "written",
path: "crontab",
};
}
function installWindowsRawUploaderTimer(installDir) {
if (process.platform !== "win32") return { status: "skipped" };
const schtasks = (() => {
try {
return execFileSync("where", ["schtasks"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
shell: true,
timeout: 1000,
windowsHide: true,
})
.split(/\r?\n/)[0]
.trim();
} catch (_) {
return "schtasks";
}
})();
const taskName = "ai-otel-raw-uploader";
const uploaderPath = path.join(installDir, "raw-body-uploader.js").replace(/\\/g, "/");
const nodePath = NODE_BIN.replace(/\\/g, "/");
const taskCommand = `"${nodePath}" "${uploaderPath}" --once --max-runtime=25`;
try {
spawnSync(schtasks, ["/Delete", "/F", "/TN", taskName], {
stdio: "ignore",
shell: true,
timeout: 5000,
windowsHide: true,
});
} catch (_) {}
const r = spawnSync(
schtasks,
["/Create", "/F", "/SC", "MINUTE", "/MO", "1", "/TN", taskName, "/TR", taskCommand],
{
stdio: "ignore",
shell: true,
timeout: 8000,
windowsHide: true,
}
);
return {
status: r.status === 0 ? "installed" : "written",
path: taskName,
};
}
function installRawUploaderTimer(installDir) {
if (process.platform === "darwin") return installMacRawUploaderTimer(installDir);
if (process.platform === "linux") return installLinuxRawUploaderTimer(installDir);
if (process.platform === "win32") return installWindowsRawUploaderTimer(installDir);
return { status: "skipped" };
}
// 卸载之前装机留下的 raw-uploader timer。三种触发场景共用:
// 1. --no-full-upload 装机:每次都跑一次 uninstall,把残留干掉(幂等,没残留就 no-op)
// 2. fullUpload 装机:install 之前先 uninstall(旧的 plist/unit 内容可能旧版本,刷新)
// 3. (未来)显式 cleanup 子命令