-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtelemetry.ts
More file actions
1388 lines (1269 loc) · 46.2 KB
/
telemetry.ts
File metadata and controls
1388 lines (1269 loc) · 46.2 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
/**
* Telemetry for Sentry CLI
*
* Tracks anonymous usage data to improve the CLI:
* - Command execution (which commands run, success/failure)
* - Error tracking (unhandled exceptions)
* - Performance (command duration)
*
* No PII is collected. Opt-out via SENTRY_CLI_NO_TELEMETRY=1 environment variable.
*/
import { chmodSync, statSync } from "node:fs";
// biome-ignore lint/performance/noNamespaceImport: Sentry SDK recommends namespace import
import * as Sentry from "@sentry/node-core/light";
import { isMusl } from "./binary.js";
import {
CLI_VERSION,
getCliEnvironment,
getConfiguredSentryUrl,
SENTRY_CLI_DSN,
} from "./constants.js";
import { getCustomCaCerts } from "./custom-ca.js";
import { isReadonlyError, tryRepairAndRetry } from "./db/schema.js";
import {
type AgentInfo,
detectAgent,
detectAgentFromProcessTree,
} from "./detect-agent.js";
import { getEnv } from "./env.js";
import {
classifySilenced,
enrichEventWithGroupingTags,
reportCliError,
} from "./error-reporting.js";
import { ApiError } from "./errors.js";
import { attachSentryReporter, logger } from "./logger.js";
import { getSentryBaseUrl, isSentrySaasUrl } from "./sentry-urls.js";
import { makeCompressedTransport } from "./telemetry/zstd-transport.js";
import { getRealUsername } from "./utils.js";
export type { Span } from "@sentry/core";
/** Re-imported locally because Span is exported via re-export */
type Span = Sentry.Span;
/**
* Initialize telemetry context with user and instance information.
* Called after Sentry is initialized to set user context and instance tags.
*/
async function initTelemetryContext(): Promise<void> {
try {
// Dynamic imports to avoid circular dependencies and for ES module compatibility
const { getUserInfo } = await import("./db/user.js");
const { getInstanceId } = await import("./db/instance.js");
const user = getUserInfo();
const instanceId = getInstanceId();
if (user) {
Sentry.setUser({ id: user.userId, email: user.email });
}
if (instanceId) {
Sentry.setTag("instance_id", instanceId);
}
} catch (error) {
// Context initialization is not critical - continue without it
// But capture the error for debugging
Sentry.captureException(error);
}
}
/**
* Mark the active session as crashed.
*
* Checks both current scope and isolation scope since processSessionIntegration
* stores the session on the isolation scope. Called when a command error
* propagates through withTelemetry — the SDK auto-marks crashes for truly
* uncaught exceptions (mechanism.handled === false), but command errors need
* explicit marking.
*
* @internal Exported for testing
*/
export function markSessionCrashed(): void {
const session =
Sentry.getCurrentScope().getSession() ??
Sentry.getIsolationScope().getSession();
if (session) {
session.status = "crashed";
}
}
/** Env var that disables CLI telemetry when set to `"1"`. */
export const TELEMETRY_ENV_VAR = "SENTRY_CLI_NO_TELEMETRY";
/** Industry-standard env var for opting out of telemetry (consoledonottrack.com). */
export const DO_NOT_TRACK_ENV_VAR = "DO_NOT_TRACK";
/** Result of resolving the effective telemetry state */
export type TelemetryEffective = {
/** Whether telemetry is enabled after applying all overrides */
enabled: boolean;
/**
* Which layer determined the result:
* - `"env:SENTRY_CLI_NO_TELEMETRY"` — env var opt-out
* - `"env:DO_NOT_TRACK"` — industry-standard opt-out
* - `"preference"` — persistent `sentry cli defaults telemetry` setting
* - `"default"` — no override, telemetry enabled by default
*/
source: string;
};
/**
* Resolve the effective telemetry state with source attribution.
*
* Priority (highest to lowest):
* 1. `SENTRY_CLI_NO_TELEMETRY=1` — explicit CLI env var opt-out
* 2. `DO_NOT_TRACK=1` — industry standard (consoledonottrack.com)
* 3. SQLite persistent preference — `sentry cli defaults telemetry on/off`
* 4. Default: enabled
*
* The DB read is wrapped in try/catch — if the database is uninitialized
* or corrupted, we fall through to the default (enabled).
*/
export function computeTelemetryEffective(): TelemetryEffective {
if (getEnv()[TELEMETRY_ENV_VAR] === "1") {
return { enabled: false, source: `env:${TELEMETRY_ENV_VAR}` };
}
if (getEnv()[DO_NOT_TRACK_ENV_VAR] === "1") {
return { enabled: false, source: `env:${DO_NOT_TRACK_ENV_VAR}` };
}
try {
const { getTelemetryPreference } = require("./db/defaults.js") as {
getTelemetryPreference: () => boolean | undefined;
};
const pref = getTelemetryPreference();
if (pref !== undefined) {
return { enabled: pref, source: "preference" };
}
} catch {
// DB not initialized yet — fall through to default
}
return { enabled: true, source: "default" };
}
/**
* Convenience wrapper: returns just the boolean enabled state.
* Used by `withTelemetry()` and other call sites that only need the decision.
*/
export function isTelemetryEnabled(): boolean {
return computeTelemetryEffective().enabled;
}
/**
* Wrap CLI execution with telemetry tracking.
*
* Creates a Sentry span for the command execution and captures exceptions.
* Session lifecycle is managed by the SDK's processSessionIntegration
* (started during Sentry.init) and a beforeExit handler (registered in
* initSentry) that ends healthy sessions and flushes events. This ensures
* sessions are reliably tracked even for unhandled rejections and other
* paths that bypass this function's try/catch.
*
* Telemetry can be disabled via:
* - `SENTRY_CLI_NO_TELEMETRY=1` environment variable
* - `DO_NOT_TRACK=1` environment variable (consoledonottrack.com)
* - `sentry cli defaults telemetry off` (persistent preference)
*
* @param callback - The CLI execution function to wrap, receives the span for naming
* @returns The result of the callback
*/
export async function withTelemetry<T>(
callback: (span: Span | undefined) => T | Promise<T>,
options?: { libraryMode?: boolean }
): Promise<T> {
const enabled = isTelemetryEnabled();
const client = initSentry(enabled, options);
if (!client?.getOptions().enabled) {
return callback(undefined);
}
// Initialize user and instance context
await initTelemetryContext();
// Flush deferred completion telemetry (queued during __complete fast-path).
// Best-effort: never block CLI execution for telemetry emission.
try {
const { drainCompletionTelemetry } = await import(
"./db/completion-telemetry.js"
);
for (const entry of drainCompletionTelemetry()) {
Sentry.metrics.distribution("completion.duration_ms", entry.durationMs, {
attributes: { command_path: entry.commandPath },
});
Sentry.metrics.distribution(
"completion.result_count",
entry.resultCount,
{ attributes: { command_path: entry.commandPath } }
);
}
} catch {
// Queue flush is non-essential
}
try {
return await Sentry.startSpan(
{ name: "cli.command", op: "cli.command", forceTransaction: true },
async (span) => {
try {
return await callback(span);
} catch (e) {
// Record user API errors (401–499) as span attributes instead of
// exceptions. These are user errors (wrong ID, no access), not CLI
// bugs. Recording on the span lets us detect volume spikes in Discover.
// 400 Bad Request is NOT filtered here — it's a CLI bug.
if (isUserApiError(e)) {
recordApiErrorOnSpan(span, e as ApiError);
}
throw e;
}
}
);
} catch (e) {
// Route through reportCliError so silencing (OutputError, expected-auth
// AuthError, 401–499 ApiError) and fingerprint normalization are applied
// consistently. Silenced errors emit a `cli.error.silenced` metric +
// optional structured log instead of creating a Sentry issue.
reportCliError(e);
// Only mark session crashed for errors that weren't silenced.
// Silenced errors (OutputError, expected AuthError, user 4xx ApiError)
// are expected states — marking them crashed would skew release-health.
if (!classifySilenced(e)) {
markSessionCrashed();
}
throw e;
}
}
/**
* Create a beforeExit handler that ends healthy sessions and flushes events.
*
* The SDK's processSessionIntegration only ends non-OK sessions (crashed/errored).
* This handler complements it by ending OK sessions (clean exit → 'exited')
* and flushing pending events. Includes a re-entry guard since flush is async
* and causes beforeExit to re-fire when complete.
*
* @param client - The Sentry client to flush
* @returns A handler function for process.on("beforeExit")
*
* @internal Exported for testing
*/
export function createBeforeExitHandler(
client: Sentry.LightNodeClient
): () => void {
let isFlushing = false;
return () => {
if (isFlushing) {
return;
}
isFlushing = true;
const session = Sentry.getIsolationScope().getSession();
if (session?.status === "ok") {
Sentry.endSession();
}
// Flush pending events before exit. Convert PromiseLike to Promise
// for proper error handling. The async work causes beforeExit to
// re-fire when complete, which the isFlushing guard handles.
Promise.resolve(client.flush(3000)).catch(() => {
// Ignore flush errors — telemetry should never block CLI exit
});
};
}
/**
* Check if a Sentry event represents an EPIPE error.
*
* EPIPE (errno -32) occurs when writing to a pipe whose reading end has been
* closed. This is normal Unix behavior when CLI output is piped through
* commands like `head`, `less`, or `grep -m1`. These errors are not bugs
* and should be silently dropped from telemetry.
*
* Detects both Bun-style ("EPIPE: broken pipe, write") and Node.js-style
* ("write EPIPE") error messages, plus the structured `node_system_error` context.
*
* @internal Exported for testing
*/
export function isEpipeError(event: Sentry.ErrorEvent): boolean {
// Check exception message for EPIPE
const exceptions = event.exception?.values;
if (exceptions) {
for (const ex of exceptions) {
if (ex.value?.includes("EPIPE")) {
return true;
}
}
}
// Check Node.js system error context (set by the SDK for system errors)
const systemError = event.contexts?.node_system_error as
| { code?: string }
| undefined;
if (systemError?.code === "EPIPE") {
return true;
}
return false;
}
/**
* Check if an error is a user-caused (401–499) API error.
*
* 401–499 errors are user errors — wrong issue IDs, no access, rate limited —
* not CLI bugs. 400 Bad Request is **excluded** because it indicates the CLI
* constructed a malformed API request, which is a code defect.
*
* These should be recorded as span attributes for volume-spike detection in
* Discover, but should NOT be captured as Sentry exceptions.
*
* @internal Exported for testing
*/
export function isUserApiError(error: unknown): boolean {
return error instanceof ApiError && error.status > 400 && error.status < 500;
}
/**
* Record a client API error as span attributes for Discover queryability.
*
* Sets `api_error.status`, `api_error.message`, and optionally `api_error.detail`
* on the span. Must be called before `span.end()`.
*
* @internal Exported for testing
*/
export function recordApiErrorOnSpan(span: Span, error: ApiError): void {
span.setAttribute("api_error.status", error.status);
span.setAttribute("api_error.message", error.message);
if (error.detail) {
span.setAttribute("api_error.detail", error.detail);
}
}
/**
* Integrations to exclude for CLI.
* These add overhead without benefit for short-lived CLI processes.
*/
const EXCLUDED_INTEGRATIONS = new Set([
"Console", // Captures console output - too noisy for CLI
"Context", // Replaced below with cpu: false to avoid os.cpus() crash (CLI-1ED)
"ContextLines", // Reads source files - we rely on uploaded sourcemaps instead
"LocalVariables", // Captures local variables - adds significant overhead
"Modules", // Lists all loaded modules - unnecessary for CLI telemetry
]);
/**
* Integrations to exclude in library mode.
*
* Extends {@link EXCLUDED_INTEGRATIONS} with integrations that register
* global process listeners, monkey-patch builtins, or monitor child
* processes — all of which would pollute the host application's runtime.
*/
const LIBRARY_EXCLUDED_INTEGRATIONS = new Set([
...EXCLUDED_INTEGRATIONS,
"OnUncaughtException", // process.on('uncaughtException')
"OnUnhandledRejection", // process.on('unhandledRejection')
"ProcessSession", // process.on('beforeExit') — anonymous handler, no cleanup
"Http", // diagnostics_channel + trace headers
"NodeFetch", // diagnostics_channel + trace headers
"FunctionToString", // wraps Function.prototype.toString
"ChildProcess", // monitors child processes
"NodeRuntimeMetrics", // runtime metrics timer would keep host event loop alive
]);
/**
* Check whether `util.getSystemErrorMap` exists at setup time.
* Bun does not implement this Node.js API, which the SDK's NodeSystemError
* integration uses in its `processEvent` hook. When missing, the hook crashes
* during event processing instead of sending the error report (CLI-K1).
*
* Checked once at module load so the integration filter is a simple boolean.
*/
const hasGetSystemErrorMap = (() => {
try {
// Dynamic require to avoid bundler issues — the check only matters at runtime
const util = require("node:util") as Record<string, unknown>;
return typeof util.getSystemErrorMap === "function";
} catch {
return false;
}
})();
/** Current beforeExit handler, tracked so it can be replaced on re-init */
let currentBeforeExitHandler: (() => void) | null = null;
/** Match all SaaS regional URLs (us.sentry.io, de.sentry.io, o1234.ingest.us.sentry.io, etc.) */
const SENTRY_SAAS_SUBDOMAIN_RE = /^https:\/\/[^/]*\.sentry\.io(\/|$)/;
/** Match the bare sentry.io domain itself */
const SENTRY_SAAS_ROOT_RE = /^https:\/\/sentry\.io(\/|$)/;
/**
* Build trace propagation targets for Sentry API URLs.
*
* Matches:
* - SaaS: *.sentry.io (all regional URLs like us.sentry.io, de.sentry.io)
* - SaaS: sentry.io itself
* - Self-hosted: the configured SENTRY_HOST/SENTRY_URL if non-SaaS
*
* @internal Exported for testing
*/
export function getSentryTracePropagationTargets(): (string | RegExp)[] {
const targets: (string | RegExp)[] = [
SENTRY_SAAS_SUBDOMAIN_RE,
SENTRY_SAAS_ROOT_RE,
];
// Also match self-hosted Sentry instances
const customUrl = getConfiguredSentryUrl();
if (customUrl && !isSentrySaasUrl(customUrl)) {
targets.push(customUrl);
}
return targets;
}
/**
* Initialize Sentry for telemetry.
*
* @param enabled - Whether telemetry is enabled
* @param options - Optional configuration
* @param options.libraryMode - When true, strips all global-polluting
* integrations (process listeners, HTTP trace headers, Function.prototype
* patches) and disables logs/client reports to avoid timers and beforeExit
* handlers. The caller is responsible for calling `client.flush()` manually.
* @returns The Sentry client, or undefined if initialization failed
*
* @internal Exported for testing
*/
/**
* Set the cli.libc Sentry tag on Linux (musl for Alpine, glibc for most distros).
* No-op on non-Linux — the concept doesn't apply to macOS/Windows.
* Extracted from initSentry to stay under the cognitive complexity limit.
*/
function setLibcTag(): void {
if (process.platform !== "linux") {
return;
}
Sentry.setTag("cli.libc", isMusl() ? "musl" : "glibc");
}
/**
* Set Sentry tags for a detected AI agent.
* Splits structured {@link AgentInfo} into `agent`, `agent.version`, and `agent.role` tags.
*/
function setAgentTags(info: AgentInfo): void {
Sentry.setTag("agent", info.name);
if (info.version) {
Sentry.setTag("agent.version", info.version);
}
if (info.role) {
Sentry.setTag("agent.role", info.role);
}
}
export function initSentry(
enabled: boolean,
options?: { libraryMode?: boolean }
): Sentry.LightNodeClient | undefined {
const libraryMode = options?.libraryMode ?? false;
const environment = getCliEnvironment();
/**
* Ensure frame paths are absolute so Sentry's symbolicator can match them.
*
* Bun compiled binaries with `sourcemap: "linked"` produce relative
* paths like `"dist-bin/bin.js"` in `Error.stack`. The symbolicator's
* `get_release_file_candidate_urls` generates `"~dist-bin/bin.js"` for
* relative paths (missing the `/` after `~`), which never matches
* uploaded artifacts at `"~/dist-bin/bin.js"`. Prepending `/` makes
* the candidate `"~/dist-bin/bin.js"` — a match.
*/
/** True if the path is relative (no leading `/`, no scheme, not `native`). */
function isRelativePath(p: string): boolean {
if (p.startsWith("/") || p === "native") {
return false;
}
return !p.includes("://");
}
function ensureAbsolute(p: string): string {
// Normalize Windows backslashes to forward slashes for sourcemap URL
// matching. Bun on Windows produces paths like "dist-bin\bin.js" in
// Error.stack — the symbolicator expects forward slashes to match
// artifacts at "~/dist-bin/bin.js".
const normalized = p.replaceAll("\\", "/");
return isRelativePath(normalized) ? `/${normalized}` : normalized;
}
function normalizeExceptionFrames(event: Sentry.ErrorEvent): void {
for (const exc of event.exception?.values ?? []) {
for (const frame of exc.stacktrace?.frames ?? []) {
if (frame.abs_path) {
frame.abs_path = ensureAbsolute(frame.abs_path);
}
if (frame.filename) {
frame.filename = ensureAbsolute(frame.filename);
}
}
}
}
function normalizeDebugImages(event: Sentry.ErrorEvent): void {
for (const img of event.debug_meta?.images ?? []) {
if ("code_file" in img && typeof img.code_file === "string") {
img.code_file = ensureAbsolute(img.code_file);
}
}
}
function normalizeFramePaths(event: Sentry.ErrorEvent): void {
normalizeExceptionFrames(event);
normalizeDebugImages(event);
}
// Close the previous client to clean up its internal timers and beforeExit
// handlers (client report flusher interval, log flush listener). Without
// this, re-initializing the SDK (e.g., in tests) leaks setInterval handles
// that keep the event loop alive and prevent the process from exiting.
// close(0) removes listeners synchronously; we don't need to await the flush.
Sentry.getClient()?.close(0);
const client = Sentry.init({
dsn: SENTRY_CLI_DSN,
enabled,
// Compress outgoing envelopes with zstd (level 3) instead of gzip —
// smaller payloads, faster compress/decompress on both sides.
// Automatic gzip fallback when running on Node < 22.15 without the
// `Bun.zstdCompress` polyfill (see script/node-polyfills.ts).
transport: makeCompressedTransport,
// Pass custom CA certificates to the transport for corporate TLS proxies.
// The zstd-transport reads `caCerts` and passes it as `ca:` to
// `http.request()`, and the SDK's fallback `makeNodeTransport` does the same.
transportOptions: { caCerts: getCustomCaCerts() },
// Keep default integrations but filter out ones that add overhead without benefit.
// Important: Don't use defaultIntegrations: false as it may break debug ID support.
// NodeSystemError is excluded on runtimes missing util.getSystemErrorMap (Bun) — CLI-K1.
// Library mode uses the extended exclusion set to avoid polluting the host process.
integrations: (defaults) => {
const excluded = libraryMode
? LIBRARY_EXCLUDED_INTEGRATIONS
: EXCLUDED_INTEGRATIONS;
const filtered = defaults.filter(
(integration) =>
!excluded.has(integration.name) &&
(integration.name !== "NodeSystemError" || hasGetSystemErrorMap)
);
// Re-add Context integration with cpu: false to avoid os.cpus() crash
// on systems where /proc/cpuinfo is not accessible (CLI-1ED).
if (!libraryMode) {
filtered.push(
Sentry.nodeContextIntegration({ device: { cpu: false } })
);
}
// Collect runtime metrics (CPU, memory, event loop) for non-library mode.
// Uses nodeRuntimeMetricsIntegration which degrades gracefully on Bun:
// monitorEventLoopDelay is try/caught, all other APIs are Bun-compatible.
// 5s interval for CLI — most commands complete in <10s.
if (!libraryMode) {
filtered.push(
Sentry.nodeRuntimeMetricsIntegration({ collectionIntervalMs: 5000 })
);
}
return filtered;
},
environment,
// Enable Sentry structured logs for non-exception telemetry (e.g., unexpected input warnings).
// Disabled when telemetry is off or in library mode — the SDK registers
// beforeExit handlers for log flushing that keep the event loop alive.
enableLogs: enabled && !libraryMode,
// Disable client reports when telemetry is off or in library mode — the SDK
// registers a setInterval + beforeExit handler that keep the event loop alive.
...((libraryMode || !enabled) && { sendClientReports: false }),
// Sample all events for CLI telemetry (low volume)
tracesSampleRate: 1,
sampleRate: 1,
release: CLI_VERSION,
// Propagate traces to Sentry API for distributed tracing
tracePropagationTargets: getSentryTracePropagationTargets(),
beforeSendTransaction: (event) => {
// Remove server_name which may contain hostname (PII)
event.server_name = undefined;
return event;
},
beforeSend: (event) => {
// Remove server_name which may contain hostname (PII)
event.server_name = undefined;
// EPIPE errors are expected when stdout is piped and the consumer closes
// early (e.g., `sentry issue list | head`). Not actionable — drop them.
if (isEpipeError(event)) {
return null;
}
// Normalize relative frame paths to absolute. Bun's compiled binaries
// with sourcemap: "linked" produce relative paths like "dist-bin/bin.js"
// in Error.stack. Sentry's symbolicator only matches absolute paths
// when generating tilde-prefixed URL candidates (e.g., "~/dist-bin/bin.js"),
// silently skipping resolution for relative paths.
normalizeFramePaths(event);
// Enrich events with cli_error.* tags for server-side fingerprint rules.
// reportCliError already sets these for command-level errors; this
// catches uncaught exceptions and best-effort background captures.
return enrichEventWithGroupingTags(event);
},
});
// Always remove our own previous handler on re-init.
if (currentBeforeExitHandler) {
process.removeListener("beforeExit", currentBeforeExitHandler);
currentBeforeExitHandler = null;
}
if (client?.getOptions().enabled) {
const isBun = typeof process.versions.bun !== "undefined";
const runtime = isBun ? "bun" : "node";
// LightNodeClient hardcodes runtime to { name: 'node' }. Override it so
// events carry the correct runtime when running as a compiled Bun binary.
const opts = client.getOptions();
opts.runtime = {
name: runtime,
version: isBun ? process.versions.bun : process.version,
};
// Tag whether running as bun binary or node (npm package).
// Kept alongside the SDK's promoted 'runtime' tag for explicit signaling
// and backward compatibility with existing dashboards/alerts.
Sentry.setTag("cli.runtime", runtime);
// Tag whether targeting self-hosted Sentry (not SaaS)
Sentry.setTag("is_self_hosted", !isSentrySaasUrl(getSentryBaseUrl()));
// Tag whether running in an interactive terminal or agent/CI environment
Sentry.setTag("is_tty", !!process.stdout.isTTY);
// Tag the C library variant on Linux (musl vs glibc).
setLibcTag();
// Tag which AI agent (if any) is driving the CLI.
// Env var detection is sync (instant). If no env var matches, fire off
// async process tree detection in the background — it sets the tag
// before the transaction finishes without blocking CLI startup.
const agent = detectAgent();
if (agent) {
setAgentTags(agent);
} else {
detectAgentFromProcessTree()
.then((processAgent) => {
if (processAgent) {
setAgentTags(processAgent);
}
})
.catch((error) => {
logger.withTag("agent").warn("Process tree detection failed:", error);
});
}
// Wire up consola → Sentry log forwarding now that the client is active
attachSentryReporter();
// End healthy sessions and flush events when the event loop drains.
// The SDK's processSessionIntegration starts a session during init and
// registers its own beforeExit handler that ends non-OK (crashed/errored)
// sessions. We complement it by ending OK sessions (clean exit → 'exited')
// and flushing pending events. This covers unhandled rejections and other
// paths that bypass withTelemetry's try/catch.
// Ref: https://nodejs.org/api/process.html#event-beforeexit
//
// Skipped in library mode — the host owns the process lifecycle.
// The library entry point calls client.flush() manually after completion.
if (!libraryMode) {
currentBeforeExitHandler = createBeforeExitHandler(client);
process.on("beforeExit", currentBeforeExitHandler);
}
}
return client;
}
/**
* Set the command name on the telemetry span.
*
* Called by stricli's forCommand context builder with the resolved
* command path (e.g., "auth.login", "issue.list").
*
* @param span - The span to update (from withTelemetry callback)
* @param command - The command name (dot-separated path)
*/
export function setCommandSpanName(
span: Span | undefined,
command: string
): void {
if (span) {
Sentry.updateSpanName(span, command);
}
// Also set as tag for easier filtering in Sentry UI
Sentry.setTag("command", command);
}
/**
* Set organization and project context as tags.
*
* Call this from commands after resolving the target org/project
* to enable filtering by org/project in Sentry.
* Accepts arrays to support multi-project commands.
*
* @param orgs - Organization slugs
* @param projects - Project slugs
*/
export function setOrgProjectContext(orgs: string[], projects: string[]): void {
if (orgs.length > 0) {
Sentry.setTag("sentry.org", orgs.join(","));
}
if (projects.length > 0) {
Sentry.setTag("sentry.project", projects.join(","));
}
}
/**
* Flag names whose values must never be sent to telemetry.
* Values for these flags are replaced with "[REDACTED]" regardless of content.
*/
const SENSITIVE_FLAGS = new Set(["token"]);
/**
* Convert a flag value to a telemetry tag string.
*
* Handles booleans, objects (JSON-serialized to avoid "[object Object]"),
* and primitives. Truncates to 200 chars for Sentry tag limits.
*/
function flagValueToTag(value: unknown): string {
if (typeof value === "boolean") {
return String(value);
}
// Arrays serialize as comma-separated strings (matching existing behavior)
if (Array.isArray(value)) {
return String(value).slice(0, 200);
}
// Non-array objects (e.g., TimeRange) must be JSON-serialized to avoid
// "[object Object]" from String()
if (typeof value === "object" && value !== null) {
return JSON.stringify(value).slice(0, 200);
}
return String(value).slice(0, 200);
}
/**
* Set command flags as telemetry tags.
*
* Converts flag names from camelCase to kebab-case and sets them as tags
* with the `flag.` prefix (e.g., `flag.no-modify-path`).
*
* Only sets tags for flags with non-default/meaningful values:
* - Boolean flags: only when true
* - String/number flags: only when defined and non-empty
* - Array flags: only when non-empty
*
* Sensitive flags (e.g., `--token`) have their values replaced with
* "[REDACTED]" to prevent secrets from reaching telemetry.
*
* Call this at the start of command func() to instrument flag usage.
*
* @param flags - The parsed flags object from Stricli
*
* @example
* ```ts
* async func(this: SentryContext, flags: MyFlags): Promise<void> {
* setFlagContext(flags);
* // ... command implementation
* }
* ```
*/
export function setFlagContext(flags: Record<string, unknown>): void {
for (const [key, value] of Object.entries(flags)) {
// Skip undefined/null values
if (value === undefined || value === null) {
continue;
}
// Skip false booleans (default state)
if (value === false) {
continue;
}
// Skip empty strings
if (value === "") {
continue;
}
// Skip empty arrays
if (Array.isArray(value) && value.length === 0) {
continue;
}
// Convert camelCase to kebab-case for consistency with CLI flag names
const kebabKey = key.replace(/([A-Z])/g, "-$1").toLowerCase();
// Redact sensitive flag values (e.g., API tokens) — never send secrets to telemetry
if (SENSITIVE_FLAGS.has(kebabKey)) {
Sentry.setTag(`flag.${kebabKey}`, "[REDACTED]");
continue;
}
// Set the tag with flag. prefix
Sentry.setTag(`flag.${kebabKey}`, flagValueToTag(value));
}
}
/**
* Set positional arguments as Sentry context.
*
* Stores positional arguments in a structured context for debugging.
* Unlike tags, context is not indexed but provides richer data.
*
* @param args - The positional arguments passed to the command
*/
export function setArgsContext(args: readonly unknown[]): void {
if (args.length === 0) {
return;
}
Sentry.setContext("args", {
values: args.map((arg) =>
typeof arg === "string" ? arg : JSON.stringify(arg)
),
count: args.length,
});
}
/**
* Record a cache hit or miss as a distribution metric (0 or 100).
*
* Emitting 0 for miss and 100 for hit allows computing hit rate as
* `avg(value,cache.hit_rate,distribution,none)` on the tracemetrics
* dashboard — Sentry doesn't support division in widgets, so this
* pre-computed approach gives us percentages directly.
*
* @param cacheName - Identifier for the cache (e.g., "dsn", "project", "region", "http")
* @param hit - Whether the cache lookup was a hit
*/
export function recordCacheHit(cacheName: string, hit: boolean): void {
Sentry.metrics.distribution("cache.hit_rate", hit ? 100 : 0, {
attributes: { cache_name: cacheName },
});
}
/**
* Wrap an operation with a Sentry span for tracing.
*
* Creates a child span under the current active span to track
* operation duration and status. Automatically sets span status
* to OK on success or Error on failure.
*
* Use this generic helper for custom operations, or use the specialized
* helpers (withHttpSpan, withDbSpan, withFsSpan, withSerializeSpan) for
* common operation types.
*
* @param name - Span name (e.g., "scanDirectory", "findProjectRoot")
* @param op - Operation type (e.g., "dsn.scan", "file.read")
* @param fn - Function to execute within the span
* @param attributes - Optional span attributes for additional context
* @returns The result of the function
*/
export function withTracing<T>(
name: string,
op: string,
fn: () => T | Promise<T>,
attributes?: Record<string, string | number | boolean>
): Promise<T> {
return Sentry.startSpan(
{ name, op, attributes, onlyIfParent: true },
async (span) => {
try {
const result = await fn();
span.setStatus({ code: 1 }); // OK
return result;
} catch (error) {
span.setStatus({ code: 2 }); // Error
throw error;
}
}
);
}
/**
* Wrap an operation with a Sentry span, passing the span to the callback.
*
* Like `withTracing`, but passes the span to the callback for cases where
* you need to set attributes or record metrics during execution.
* Automatically sets span status to OK on success or Error on failure,
* unless the callback has already set a status.
*
* @param name - Span name (e.g., "scanDirectory", "findProjectRoot")
* @param op - Operation type (e.g., "dsn.scan", "file.read")
* @param fn - Function to execute, receives the span as argument
* @param attributes - Optional initial span attributes
* @returns The result of the function
*
* @example
* ```ts
* const result = await withTracingSpan(
* "scanDirectory",
* "dsn.scan",
* async (span) => {
* const files = await collectFiles();
* span.setAttribute("files.count", files.length);
* return processFiles(files);
* },
* { "scan.dir": cwd }
* );
* ```
*/
export function withTracingSpan<T>(
name: string,
op: string,
fn: (span: Span) => T | Promise<T>,
attributes?: Record<string, string | number | boolean>
): Promise<T> {
return Sentry.startSpan(
{ name, op, attributes, onlyIfParent: true },
async (span) => {
// Track if callback sets status, so we don't override it
let statusWasSet = false;
const originalSetStatus = span.setStatus.bind(span);
span.setStatus = (...args) => {
statusWasSet = true;
return originalSetStatus(...args);
};
try {
const result = await fn(span);
if (!statusWasSet) {
span.setStatus({ code: 1 }); // OK
}
return result;
} catch (error) {
if (!statusWasSet) {
span.setStatus({ code: 2 }); // Error
}
throw error;
}
}
);
}
/**
* Wrap an HTTP request with a span for tracing.
*
* Creates a child span under the current active span to track
* HTTP request duration and status.
*
* @param method - HTTP method (GET, POST, etc.)
* @param url - Request URL or path
* @param fn - The async function that performs the HTTP request
* @returns The result of the function
*/
export function withHttpSpan<T>(
method: string,
url: string,
fn: () => Promise<T>
): Promise<T> {
return withTracing(`${method} ${url}`, "http.client", fn, {
"http.request.method": method,
"url.path": url,
});
}
/**
* Wrap a database operation with a span for tracing.
*
* Creates a child span under the current active span to track
* database operation duration. This is a synchronous wrapper that
* preserves the sync nature of the callback.
*
* Use this for grouping logical operations (e.g., "clearAuth" which runs
* multiple queries). Individual SQL queries are automatically traced when
* using a database wrapped with `createTracedDatabase`.
*
* @param operation - Name of the operation (e.g., "getAuthToken", "setDefaults")
* @param fn - The function that performs the database operation